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/lib/spaceship/connect_api/models/build_delivery.rb
spaceship/lib/spaceship/connect_api/models/build_delivery.rb
require_relative '../model' module Spaceship class ConnectAPI class BuildDelivery include Spaceship::ConnectAPI::Model attr_accessor :cf_build_version attr_accessor :cf_build_short_version_string attr_accessor :platform attr_accessor :uploaded_date attr_mapping({ "cfBundleVersion" => "cf_build_version", "cfBundleShortVersionString" => "cf_build_short_version_string", "platform" => "platform", "uploadedDate" => "uploaded_date" }) def self.type return "buildDeliveries" end # # API # def self.all(client: nil, app_id: nil, version: nil, build_number: nil) client ||= Spaceship::ConnectAPI resps = client.get_build_deliveries( app_id: app_id, filter: { cfBundleShortVersionString: version, cfBundleVersion: build_number }, limit: 1 ).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/bundle_id_capability.rb
spaceship/lib/spaceship/connect_api/models/bundle_id_capability.rb
require_relative '../model' module Spaceship class ConnectAPI class BundleIdCapability include Spaceship::ConnectAPI::Model attr_accessor :capability_type attr_accessor :settings attr_mapping({ "capabilityType" => "capability_type", "settings" => "settings" }) module Type ACCESS_WIFI_INFORMATION = "ACCESS_WIFI_INFORMATION" APP_ATTEST = "APP_ATTEST" APP_GROUPS = "APP_GROUPS" APPLE_PAY = "APPLE_PAY" ASSOCIATED_DOMAINS = "ASSOCIATED_DOMAINS" AUTOFILL_CREDENTIAL_PROVIDER = "AUTOFILL_CREDENTIAL_PROVIDER" CLASSKIT = "CLASSKIT" ICLOUD = "ICLOUD" USERNOTIFICATIONS_COMMUNICATION = "USERNOTIFICATIONS_COMMUNICATION" NETWORK_CUSTOM_PROTOCOL = "NETWORK_CUSTOM_PROTOCOL" DATA_PROTECTION = "DATA_PROTECTION" EXTENDED_VIRTUAL_ADDRESSING = "EXTENDED_VIRTUAL_ADDRESSING" FAMILY_CONTROLS = "FAMILY_CONTROLS" FILEPROVIDER_TESTINGMODE = "FILEPROVIDER_TESTINGMODE" FONT_INSTALLATION = "FONT_INSTALLATION" GAME_CENTER = "GAME_CENTER" GROUP_ACTIVITIES = "GROUP_ACTIVITIES" HEALTHKIT = "HEALTHKIT" HEALTHKIT_RECALIBRATE_ESTIMATES = "HEALTHKIT_RECALIBRATE_ESTIMATES" HLS_INTERSTITIAL_PREVIEW = "HLS_INTERSTITIAL_PREVIEW" HOMEKIT = "HOMEKIT" HOT_SPOT = "HOT_SPOT" IN_APP_PURCHASE = "IN_APP_PURCHASE" INTER_APP_AUDIO = "INTER_APP_AUDIO" COREMEDIA_HLS_LOW_LATENCY = "COREMEDIA_HLS_LOW_LATENCY" MDM_MANAGED_ASSOCIATED_DOMAINS = "MDM_MANAGED_ASSOCIATED_DOMAINS" MAPS = "MAPS" MULTIPATH = "MULTIPATH" NETWORK_EXTENSIONS = "NETWORK_EXTENSIONS" NFC_TAG_READING = "NFC_TAG_READING" PERSONAL_VPN = "PERSONAL_VPN" PUSH_NOTIFICATIONS = "PUSH_NOTIFICATIONS" APPLE_ID_AUTH = "APPLE_ID_AUTH" SIRIKIT = "SIRIKIT" SYSTEM_EXTENSION_INSTALL = "SYSTEM_EXTENSION_INSTALL" USERNOTIFICATIONS_TIMESENSITIVE = "USERNOTIFICATIONS_TIMESENSITIVE" USER_MANAGEMENT = "USER_MANAGEMENT" WALLET = "WALLET" WIRELESS_ACCESSORY_CONFIGURATION = "WIRELESS_ACCESSORY_CONFIGURATION" # Additional Capabilities CARPLAY_PLAYABLE_CONTENT = "CARPLAY_PLAYABLE_CONTENT" CARPLAY_MESSAGING = "CARPLAY_MESSAGING" CARPLAY_NAVIGATION = "CARPLAY_NAVIGATION" CARPLAY_VOIP = "CARPLAY_VOIP" CRITICAL_ALERTS = "CRITICAL_ALERTS" HOTSPOT_HELPER_MANAGED = "HOTSPOT_HELPER_MANAGED" DRIVERKIT = "DRIVERKIT" DRIVERKIT_ENDPOINT_SECURITY = "DRIVERKIT_ENDPOINT_SECURITY" DRIVERKIT_HID_DEVICE = "DRIVERKIT_HID_DEVICE" DRIVERKIT_NETWORKING = "DRIVERKIT_NETWORKING" DRIVERKIT_SERIAL = "DRIVERKIT_SERIAL" DRIVERKIT_HID_EVENT_SERVICE = "DRIVERKIT_HID_EVENT_SERVICE" DRIVERKIT_HID = "DRIVERKIT_HID" IPAD_CAMERA_MULTITASKING = "IPAD_CAMERA_MULTITASKING" SFUNIVERSALLINK_API = "SFUNIVERSALLINK_API" VP9_DECODER = "VP9_DECODER" # App Services MUSIC_KIT = "MUSIC_KIT" SHAZAM_KIT = "SHAZAM_KIT" # Undocumented as of 2020-06-09 MARZIPAN = "MARZIPAN" # Catalyst # Undocumented as of 2025-10-15 DECLARED_AGE_RANGE = "DECLARED_AGE_RANGE" end module Settings ICLOUD_VERSION = "ICLOUD_VERSION" DATA_PROTECTION_PERMISSION_LEVEL = "DATA_PROTECTION_PERMISSION_LEVEL" APPLE_ID_AUTH_APP_CONSENT = "APPLE_ID_AUTH_APP_CONSENT" GAME_CENTER_SETTING = "GAME_CENTER_SETTING" end module Options XCODE_5 = "XCODE_5" XCODE_6 = "XCODE_6" COMPLETE_PROTECTION = "COMPLETE_PROTECTION" PROTECTED_UNLESS_OPEN = "PROTECTED_UNLESS_OPEN" PROTECTED_UNTIL_FIRST_USER_AUTH = "PROTECTED_UNTIL_FIRST_USER_AUTH" PRIMARY_APP_CONSENT = "PRIMARY_APP_CONSENT" GAME_CENTER_MAC = "GAME_CENTER_MAC" GAME_CENTER_IOS = "GAME_CENTER_IOS" end def self.type return "bundleIdCapabilities" end # # Helpers # def is_type?(type) # JWT session returns type under "capability_type" attribute # Web session returns type under "id" attribute but with "P7GJR49W72_" prefixed return capability_type == type || id.end_with?(type) end # # API # def self.all(client: nil, bundle_id_id:, limit: nil) client ||= Spaceship::ConnectAPI resp = client.get_bundle_id_capabilities(bundle_id_id: bundle_id_id, limit: limit).all_pages return resp.flat_map(&:to_models) end def self.create(client: nil, bundle_id_id:, capability_type:, settings: []) client ||= Spaceship::ConnectAPI resp = client.post_bundle_id_capability(bundle_id_id: bundle_id_id, capability_type: capability_type, settings: settings) return resp.to_models.first end def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI client.delete_bundle_id_capability(bundle_id_capability_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_build_metric.rb
spaceship/lib/spaceship/connect_api/models/beta_build_metric.rb
require_relative '../model' module Spaceship class ConnectAPI class BetaBuildMetric include Spaceship::ConnectAPI::Model attr_accessor :install_count attr_accessor :crash_count attr_accessor :invite_count attr_accessor :seven_day_tester_count attr_mapping({ "installCount" => "install_count", "crashCount" => "crash_count", "inviteCount" => "invite_count", "sevenDayTesterCount" => "seven_day_tester_count" }) def self.type return "betaBuildMetrics" 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.rb
spaceship/lib/spaceship/connect_api/models/app_preview.rb
require_relative '../model' require_relative '../file_uploader' require 'spaceship/globals' require 'digest/md5' module Spaceship class ConnectAPI class AppPreview include Spaceship::ConnectAPI::Model attr_accessor :file_size attr_accessor :file_name attr_accessor :source_file_checksum attr_accessor :preview_frame_time_code attr_accessor :mime_type attr_accessor :video_url attr_accessor :preview_image attr_accessor :upload_operations attr_accessor :asset_delivery_state attr_accessor :upload attr_mapping({ "fileSize" => "file_size", "fileName" => "file_name", "sourceFileChecksum" => "source_file_checksum", "previewFrameTimeCode" => "preview_frame_time_code", "mimeType" => "mime_type", "videoUrl" => "video_url", "previewImage" => "preview_image", "uploadOperations" => "upload_operations", "assetDeliveryState" => "asset_delivery_state", "uploaded" => "uploaded" }) def self.type return "appPreviews" end def complete? (asset_delivery_state || {})["state"] == "COMPLETE" end # # API # def self.get(client: nil, app_preview_id: nil) client ||= Spaceship::ConnectAPI client.get_app_preview(app_preview_id: app_preview_id).first end # Creates an AppPreview in an AppPreviewSet # Setting the optional frame_time_code will force polling until video is done processing # @param app_preview_set_id The AppPreviewSet id # @param path The path of the file # @param frame_time_code The time code for the preview still frame (ex: "00:00:07:01") def self.create(client: nil, app_preview_set_id: nil, path: nil, wait_for_processing: true, frame_time_code: nil) 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 preview = client.post_app_preview( app_preview_set_id: app_preview_set_id, attributes: post_attributes ).first # Upload the file upload_operations = preview.upload_operations Spaceship::ConnectAPI::FileUploader.upload(upload_operations, bytes) # Update file uploading complete patch_attributes = { uploaded: true, sourceFileChecksum: Digest::MD5.hexdigest(bytes) } begin preview = client.patch_app_preview( app_preview_id: preview.id, attributes: patch_attributes ).first rescue => error puts("Failed to patch app preview. Update may have gone through so verifying") if Spaceship::Globals.verbose? preview = Spaceship::ConnectAPI::AppPreview.get(client: client, app_preview_id: preview.id) raise error unless preview.complete? end # Poll for video processing completion to set still frame time wait_for_processing = true unless frame_time_code.nil? if wait_for_processing loop do unless preview.video_url.nil? puts("Preview processing complete!") if Spaceship::Globals.verbose? preview = preview.update(attributes: { previewFrameTimeCode: frame_time_code }) puts("Updated preview frame time code!") if Spaceship::Globals.verbose? break end sleep_time = 30 puts("Waiting #{sleep_time} seconds before checking status of processing...") if Spaceship::Globals.verbose? sleep(sleep_time) preview = Spaceship::ConnectAPI::AppPreview.get(client: client, app_preview_id: preview.id) end end preview end def update(client: nil, attributes: nil) client ||= Spaceship::ConnectAPI attributes = reverse_attr_mapping(attributes) client.patch_app_preview(app_preview_id: id, attributes: attributes).first end def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI client.delete_app_preview(app_preview_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.rb
spaceship/lib/spaceship/connect_api/models/app_info.rb
require_relative '../model' module Spaceship class ConnectAPI class AppInfo include Spaceship::ConnectAPI::Model attr_accessor :app_store_state attr_accessor :state attr_accessor :app_store_age_rating attr_accessor :brazil_age_rating attr_accessor :kids_age_band attr_accessor :primary_category attr_accessor :primary_subcategory_one attr_accessor :primary_subcategory_two attr_accessor :secondary_category attr_accessor :secondary_subcategory_one attr_accessor :secondary_subcategory_two # 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 State ACCEPTED = "ACCEPTED" DEVELOPER_REJECTED = "DEVELOPER_REJECTED" IN_REVIEW = "IN_REVIEW" PENDING_RELEASE = "PENDING_RELEASE" PREPARE_FOR_SUBMISSION = "PREPARE_FOR_SUBMISSION" READY_FOR_DISTRIBUTION = "READY_FOR_DISTRIBUTION" READY_FOR_REVIEW = "READY_FOR_REVIEW" REJECTED = "REJECTED" REPLACED_WITH_NEW_INFO = "REPLACED_WITH_NEW_INFO" WAITING_FOR_REVIEW = "WAITING_FOR_REVIEW" end module AppStoreAgeRating FOUR_PLUS = "FOUR_PLUS" end attr_mapping({ "appStoreState" => "app_store_state", "state" => "state", "appStoreAgeRating" => "app_store_age_rating", "brazilAgeRating" => "brazil_age_rating", "kidsAgeBand" => "kids_age_band", "primaryCategory" => "primary_category", "primarySubcategoryOne" => "primary_subcategory_one", "primarySubcategoryTwo" => "primary_subcategory_two", "secondaryCategory" => "secondary_category", "secondarySubcategoryOne" => "secondary_subcategory_one", "secondarySubcategoryTwo" => "secondary_subcategory_two" }) ESSENTIAL_INCLUDES = [ "primaryCategory", "primarySubcategoryOne", "primarySubcategoryTwo", "secondaryCategory", "secondarySubcategoryOne", "secondarySubcategoryTwo" ].join(",") def self.type return "appInfos" end # # API # def update(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI client.patch_app_info(app_info_id: id).first end def update_categories(client: nil, category_id_map: nil) client ||= Spaceship::ConnectAPI client.patch_app_info_categories(app_info_id: id, category_id_map: category_id_map).first end def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI client.delete_app_info(app_info_id: id) end # # Age Rating Declaration # def fetch_age_rating_declaration(client: nil) client ||= Spaceship::ConnectAPI resp = client.get_age_rating_declaration(app_info_id: id) return resp.to_models.first end # # App Info Localizations # def create_app_info_localization(client: nil, attributes: nil) client ||= Spaceship::ConnectAPI resp = client.post_app_info_localization(app_info_id: id, attributes: attributes) return resp.to_models.first end def get_app_info_localizations(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI resp = client.get_app_info_localizations(app_info_id: id, filter: filter, includes: includes, limit: limit, sort: sort) 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/device.rb
spaceship/lib/spaceship/connect_api/models/device.rb
require_relative '../../connect_api' module Spaceship class ConnectAPI class Device include Spaceship::ConnectAPI::Model attr_accessor :device_class attr_accessor :model attr_accessor :name attr_accessor :platform attr_accessor :status attr_accessor :udid attr_accessor :added_date attr_mapping({ "deviceClass" => "device_class", "model" => "model", "name" => "name", "platform" => "platform", "status" => "status", "udid" => "udid", "addedDate" => "added_date" }) module DeviceClass APPLE_WATCH = "APPLE_WATCH" IPAD = "IPAD" IPHONE = "IPHONE" IPOD = "IPOD" APPLE_TV = "APPLE_TV" MAC = "MAC" APPLE_VISION_PRO = "APPLE_VISION_PRO" # As of 2024-03-08, this is not _officially_ supported by App Store Connect API (according to API docs)—yet still used in the API responses APPLE_SILICON_MAC = "APPLE_SILICON_MAC" INTEL_MAC = "INTEL_MAC" end module Status ENABLED = "ENABLED" DISABLED = "DISABLED" end def self.type return "devices" end def enabled? return status == Status::ENABLED 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_devices(filter: filter, includes: includes, fields: fields, limit: limit, sort: sort).all_pages return resps.flat_map(&:to_models) end # @param platform [String] The provisioning profile's platform (i.e. ios, tvos, macos, catalyst). # @param include_mac_in_profiles [Bool] Whether to include macs in iOS provisioning profiles. false by default. # @param client [ConnectAPI] ConnectAPI client. # @return (Device) List of enabled devices. def self.devices_for_platform(platform: nil, include_mac_in_profiles: false, client: nil) platform = platform.to_sym include_mac_in_profiles &&= platform == :ios device_platform = case platform when :osx, :macos, :mac Spaceship::ConnectAPI::Platform::MAC_OS when :ios, :tvos, :xros, :visionos Spaceship::ConnectAPI::Platform::IOS when :catalyst Spaceship::ConnectAPI::Platform::MAC_OS end device_platforms = [ device_platform ] device_classes = case platform when :ios [ Spaceship::ConnectAPI::Device::DeviceClass::IPAD, Spaceship::ConnectAPI::Device::DeviceClass::IPHONE, Spaceship::ConnectAPI::Device::DeviceClass::IPOD, Spaceship::ConnectAPI::Device::DeviceClass::APPLE_WATCH, Spaceship::ConnectAPI::Device::DeviceClass::APPLE_VISION_PRO ] when :tvos [ Spaceship::ConnectAPI::Device::DeviceClass::APPLE_TV ] when :macos, :catalyst [ Spaceship::ConnectAPI::Device::DeviceClass::MAC, Spaceship::ConnectAPI::Device::DeviceClass::APPLE_SILICON_MAC, Spaceship::ConnectAPI::Device::DeviceClass::INTEL_MAC ] else [] end if include_mac_in_profiles device_classes << Spaceship::ConnectAPI::Device::DeviceClass::APPLE_SILICON_MAC device_platforms << Spaceship::ConnectAPI::Platform::MAC_OS end filter = { status: Spaceship::ConnectAPI::Device::Status::ENABLED } filter[:platform] = device_platforms.uniq.join(',') unless device_platforms.empty? devices = Spaceship::ConnectAPI::Device.all( client: client, filter: filter ) unless device_classes.empty? devices.select! do |device| # App Store Connect API return MAC in device_class instead of APPLE_SILICON_MAC for Silicon Macs. # The difference between old MAC and APPLE_SILICON_MAC is provisioning uuid. # Intel-based provisioning UUID: 01234567-89AB-CDEF-0123-456789ABCDEF. # arm64-based provisioning UUID: 01234567-89ABCDEF12345678. # Workaround is to include macs having: # * 25 chars length and only one hyphen in provisioning UUID. if include_mac_in_profiles && device.device_class == Spaceship::ConnectAPI::Device::DeviceClass::MAC next device.udid.length == 25 && device.udid.count('-') == 1 end device_classes.include?(device.device_class) end end devices end # @param client [ConnectAPI] ConnectAPI client. # @param platform [String] The platform of the device. # @param include_disabled [Bool] Whether to include disable devices. false by default. # @return (Device) Find a device based on the UDID of the device. nil if no device was found. def self.find_by_udid(device_udid, client: nil, include_disabled: false) self.all(client: client).find do |device| device.udid.casecmp(device_udid) == 0 && (include_disabled ? true : device.enabled?) end end # @param client [ConnectAPI] ConnectAPI client. # @param name [String] The name to be assigned to the device, if it needs to be created. # @param platform [String] The platform of the device. # @return (Device) Find a device based on the UDID of the device. If no device was found, nil if no device was found. def self.find_or_create(device_udid, client: nil, name: nil, platform: nil) existing = self.find_by_udid(device_udid, client: client) return existing if existing return self.create(client: client, name: name, platform: platform, udid: device_udid) end # @param client [ConnectAPI] ConnectAPI client. # @param name [String] The name to be assigned to the device. # @param platform [String] The platform of the device. # @param udid [String] The udid of the device being created. # @return (Device) Find a device based on the UDID of the device. nil if no device was found. def self.create(client: nil, name: nil, platform: nil, udid: nil) client ||= Spaceship::ConnectAPI resp = client.post_device(name: name, platform: platform, udid: udid) return resp.to_models.first end # @param device_udid [String] Device Provisioning UDID that needs to be modified. # @param client [ConnectAPI] ConnectAPI client. # @param enabled [Boolean] New enabled value. true - if device must be enabled, `false` - to disable device. nil if no status change needed. # @param new_name [String] A new name for the device. nil if no name change needed. # @return (Device) Modified device based on the UDID of the device. nil if no device was found. def self.modify(device_udid, client: nil, enabled: nil, new_name: nil) client ||= Spaceship::ConnectAPI existing = self.find_by_udid(device_udid, client: client, include_disabled: true) return nil if existing.nil? enabled = existing.enabled? if enabled.nil? new_name ||= existing.name return existing if existing.name == new_name && existing.enabled? == enabled new_status = enabled ? Status::ENABLED : Status::DISABLED resp = client.patch_device(id: existing.id, new_name: new_name, status: new_status) return resp.to_models.first end # @param device_udid [String] Device Provisioning UDID that needs to be enabled. # @param client [ConnectAPI] ConnectAPI client. # @return (Device) Modified device based on the UDID of the device. nil if no device was found. def self.enable(device_udid, client: nil) self.modify(device_udid, client: client, enabled: true) end # @param device_udid [String] Device Provisioning UDID that needs to be disabled. # @param client [ConnectAPI] ConnectAPI client. # @return (Device) Modified device based on the UDID of the device. nil if no device was found. def self.disable(device_udid, client: nil) self.modify(device_udid, client: client, enabled: false) end # @param device_udid [String] Device Provisioning UDID that needs to be renamed. # @param new_name [String] A new name for the device. # @param client [ConnectAPI] ConnectAPI client. # @return (Device) Modified device based on the UDID of the device. nil if no device was found. def self.rename(device_udid, new_name, client: nil) self.modify(device_udid, client: client, new_name: new_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/models/territory_availability.rb
spaceship/lib/spaceship/connect_api/models/territory_availability.rb
require_relative '../model' module Spaceship class ConnectAPI class TerritoryAvailability include Spaceship::ConnectAPI::Model attr_accessor :available attr_accessor :content_statuses attr_accessor :pre_order_enabled attr_accessor :pre_order_publish_date attr_accessor :release_date module ContentStatus AVAILABLE = "AVAILABLE" AVAILABLE_FOR_PREORDER_ON_DATE = "AVAILABLE_FOR_PREORDER_ON_DATE" PROCESSING_TO_NOT_AVAILABLE = "PROCESSING_TO_NOT_AVAILABLE" PROCESSING_TO_AVAILABLE = "PROCESSING_TO_AVAILABLE" PROCESSING_TO_PRE_ORDER = "PROCESSING_TO_PRE_ORDER" AVAILABLE_FOR_SALE_UNRELEASED_APP = "AVAILABLE_FOR_SALE_UNRELEASED_APP" PREORDER_ON_UNRELEASED_APP = "PREORDER_ON_UNRELEASED_APP" AVAILABLE_FOR_PREORDER = "AVAILABLE_FOR_PREORDER" MISSING_RATING = "MISSING_RATING" CANNOT_SELL_RESTRICTED_RATING = "CANNOT_SELL_RESTRICTED_RATING" BRAZIL_REQUIRED_TAX_ID = "BRAZIL_REQUIRED_TAX_ID" MISSING_GRN = "MISSING_GRN" UNVERIFIED_GRN = "UNVERIFIED_GRN" CANNOT_SELL_SEVENTEEN_PLUS_APPS = "CANNOT_SELL_SEVENTEEN_PLUS_APPS" CANNOT_SELL_SEXUALLY_EXPLICIT = "CANNOT_SELL_SEXUALLY_EXPLICIT" CANNOT_SELL_NON_IOS_GAMES = "CANNOT_SELL_NON_IOS_GAMES" CANNOT_SELL_SEVENTEEN_PLUS_GAMES = "CANNOT_SELL_SEVENTEEN_PLUS_GAMES" CANNOT_SELL_FREQUENT_INTENSE_GAMBLING = "CANNOT_SELL_FREQUENT_INTENSE_GAMBLING" CANNOT_SELL_CASINO = "CANNOT_SELL_CASINO" CANNOT_SELL_CASINO_WITHOUT_GRAC = "CANNOT_SELL_CASINO_WITHOUT_GRAC" CANNOT_SELL_CASINO_WITHOUT_AGE_VERIFICATION = "CANNOT_SELL_CASINO_WITHOUT_AGE_VERIFICATION" CANNOT_SELL_FREQUENT_INTENSE_ALCOHOL_TOBACCO_DRUGS = "CANNOT_SELL_FREQUENT_INTENSE_ALCOHOL_TOBACCO_DRUGS" CANNOT_SELL_FREQUENT_INTENSE_VIOLENCE = "CANNOT_SELL_FREQUENT_INTENSE_VIOLENCE" CANNOT_SELL_FREQUENT_INTENSE_SEXUAL_CONTENT_NUDITY = "CANNOT_SELL_FREQUENT_INTENSE_SEXUAL_CONTENT_NUDITY" CANNOT_SELL_INFREQUENT_MILD_ALCOHOL_TOBACCO_DRUGS = "CANNOT_SELL_INFREQUENT_MILD_ALCOHOL_TOBACCO_DRUGS" CANNOT_SELL_INFREQUENT_MILD_SEXUAL_CONTENT_NUDITY = "CANNOT_SELL_INFREQUENT_MILD_SEXUAL_CONTENT_NUDITY" CANNOT_SELL_ADULT_ONLY = "CANNOT_SELL_ADULT_ONLY" CANNOT_SELL_FREQUENT_INTENSE = "CANNOT_SELL_FREQUENT_INTENSE" CANNOT_SELL_FREQUENT_INTENSE_WITHOUT_GRAC = "CANNOT_SELL_FREQUENT_INTENSE_WITHOUT_GRAC" CANNOT_SELL_GAMBLING_CONTESTS = "CANNOT_SELL_GAMBLING_CONTESTS" CANNOT_SELL_GAMBLING = "CANNOT_SELL_GAMBLING" CANNOT_SELL_CONTESTS = "CANNOT_SELL_CONTESTS" CANNOT_SELL = "CANNOT_SELL" end attr_mapping({ available: 'available', contentStatuses: 'content_statuses', preOrderEnabled: 'pre_order_enabled', preOrderPublishDate: 'pre_order_publish_date', releaseDate: 'release_date' }) def self.type return 'territoryAvailabilities' 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_user.rb
spaceship/lib/spaceship/connect_api/models/custom_app_user.rb
require_relative '../model' module Spaceship class ConnectAPI class CustomAppUser include Spaceship::ConnectAPI::Model attr_accessor :apple_id attr_mapping({ "appleId" => "apple_id" }) def self.type return "customAppUsers" end # # API # def self.all(app_id: nil, filter: {}, includes: nil, limit: nil, sort: nil) resps = Spaceship::ConnectAPI.get_custom_app_users( 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, apple_id: nil) return Spaceship::ConnectAPI.post_custom_app_user(app_id: app_id, apple_id: apple_id).first end def delete! Spaceship::ConnectAPI.delete_custom_app_user(custom_app_user_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/resolution_center_message.rb
spaceship/lib/spaceship/connect_api/models/resolution_center_message.rb
require_relative '../model' require_relative './actor' require_relative './review_rejection' module Spaceship class ConnectAPI class ResolutionCenterMessage include Spaceship::ConnectAPI::Model attr_accessor :message_body attr_accessor :created_date attr_accessor :rejections attr_accessor :from_actor attr_mapping({ messageBody: 'message_body', createdDate: 'created_date', # includes rejections: 'rejections', fromActor: 'from_actor' }) def self.type return 'resolutionCenterMessages' 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/territory.rb
spaceship/lib/spaceship/connect_api/models/territory.rb
require_relative '../model' module Spaceship class ConnectAPI class Territory include Spaceship::ConnectAPI::Model attr_accessor :currency attr_mapping({ "currency" => "currency" }) def self.type return "territories" end # # API # def self.all(client: nil, filter: {}, includes: nil, limit: 180, sort: nil) client ||= Spaceship::ConnectAPI resps = client.get_territories(filter: {}, includes: nil, limit: nil, sort: nil).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/certificate.rb
spaceship/lib/spaceship/connect_api/models/certificate.rb
require_relative '../../connect_api' require 'openssl' module Spaceship class ConnectAPI class Certificate include Spaceship::ConnectAPI::Model attr_accessor :certificate_content attr_accessor :display_name attr_accessor :expiration_date attr_accessor :name attr_accessor :platform attr_accessor :serial_number attr_accessor :certificate_type attr_accessor :requester_email attr_accessor :requester_first_name attr_accessor :requester_last_name attr_mapping({ "certificateContent" => "certificate_content", "displayName" => "display_name", "expirationDate" => "expiration_date", "name" => "name", "platform" => "platform", "serialNumber" => "serial_number", "certificateType" => "certificate_type", "requesterEmail" => "requester_email", "requesterFirstName" => "requester_first_name", "requesterLastName" => "requester_last_name" }) module CertificateType DEVELOPMENT = "DEVELOPMENT" DISTRIBUTION = "DISTRIBUTION" IOS_DEVELOPMENT = "IOS_DEVELOPMENT" IOS_DISTRIBUTION = "IOS_DISTRIBUTION" MAC_APP_DISTRIBUTION = "MAC_APP_DISTRIBUTION" MAC_INSTALLER_DISTRIBUTION = "MAC_INSTALLER_DISTRIBUTION" MAC_APP_DEVELOPMENT = "MAC_APP_DEVELOPMENT" DEVELOPER_ID_KEXT = "DEVELOPER_ID_KEXT" DEVELOPER_ID_APPLICATION = "DEVELOPER_ID_APPLICATION" DEVELOPER_ID_APPLICATION_G2 = "DEVELOPER_ID_APPLICATION_G2" # As of 2021-11-09, this is only available with Apple ID auth DEVELOPER_ID_INSTALLER = "DEVELOPER_ID_INSTALLER" end def self.type return "certificates" end def valid? return false if expiration_date.nil? || expiration_date.empty? Time.parse(expiration_date) > Time.now end # Create a new cert signing request that can be used to # generate a new certificate # @example # Create a new certificate signing request # csr, pkey = Spaceship.certificate.create_certificate_signing_request # # # Use the signing request to create a new distribution certificate # Spaceship.certificate.production.create!(csr: csr) def self.create_certificate_signing_request key = OpenSSL::PKey::RSA.new(2048) csr = OpenSSL::X509::Request.new csr.version = 0 csr.subject = OpenSSL::X509::Name.new([ ['CN', 'PEM', OpenSSL::ASN1::UTF8STRING] ]) csr.public_key = key.public_key csr.sign(key, OpenSSL::Digest::SHA256.new) return [csr, key] end # # API # # Certificate types not supported by the App Store Connect API. # https://api.appstoreconnect.apple.com/v1/certificates?filter[certificateType]=DEVELOPER_ID_APPLICATION_G2 # Radar: FB21181137. UNSUPPORTED_CERTIFICATE_TYPE_FILTERS = [ CertificateType::DEVELOPER_ID_APPLICATION_G2 ] def self.all(client: nil, filter: {}, includes: nil, fields: nil, limit: Spaceship::ConnectAPI::MAX_OBJECTS_PER_PAGE_LIMIT, sort: nil) client ||= Spaceship::ConnectAPI new_filter = filter.dup has_unsupported_cert_types_filter = filter[:certificateType] && UNSUPPORTED_CERTIFICATE_TYPE_FILTERS.any? { |type| filter[:certificateType].include?(type) } # If the filter contains unsupported certificate types: # - remove the certificateType filter completely and fetch all certificates # - filter fetched certificates later by the given certificate types if has_unsupported_cert_types_filter new_filter[:certificateType] = nil end new_filter.compact! resps = client.get_certificates(filter: new_filter, includes: includes, fields: fields, limit: limit, sort: sort).all_pages certs = resps.flat_map(&:to_models) if has_unsupported_cert_types_filter # Filter fetched certificates by the given certificate types if we encountered unsupported certificate types in the filter previously. certs.select! do |cert| filter[:certificateType].include?(cert.certificate_type) end end return certs end def self.create(client: nil, certificate_type: nil, csr_content: nil) client ||= Spaceship::ConnectAPI attributes = { certificateType: certificate_type, csrContent: csr_content } resp = client.post_certificate(attributes: attributes) return resp.to_models.first end def self.get(client: nil, certificate_id: nil, includes: nil) client ||= Spaceship::ConnectAPI resp = client.get_certificate(certificate_id: certificate_id, includes: includes) return resp.to_models.first end def delete!(client: nil) client ||= Spaceship::ConnectAPI client.delete_certificate(certificate_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/build_bundle_file_sizes.rb
spaceship/lib/spaceship/connect_api/models/build_bundle_file_sizes.rb
require_relative '../model' module Spaceship class ConnectAPI class BuildBundleFileSizes include Spaceship::ConnectAPI::Model attr_accessor :device_model attr_accessor :os_version attr_accessor :download_bytes attr_accessor :install_bytes attr_mapping({ "deviceModel" => "device_model", "osVersion" => "os_version", "downloadBytes" => "download_bytes", "installBytes" => "install_bytes" }) def self.type return "buildBundleFileSizes" end # # API # def self.all(client: nil, build_bundle_id: nil, limit: 30) client ||= Spaceship::ConnectAPI resps = client.get_build_bundles_build_bundle_file_sizes(build_bundle_id: build_bundle_id).all_pages 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_app_localization.rb
spaceship/lib/spaceship/connect_api/models/beta_app_localization.rb
require_relative '../model' module Spaceship class ConnectAPI class BetaAppLocalization include Spaceship::ConnectAPI::Model attr_accessor :feedback_email attr_accessor :marketing_url attr_accessor :privacy_policy_url attr_accessor :tv_os_privacy_policy attr_accessor :description attr_accessor :locale attr_mapping({ "feedbackEmail" => "feedback_email", "marketingUrl" => "marketing_url", "privacyPolicyUrl" => "privacy_policy_url", "tvOsPrivacyPolicy" => "tv_os_privacy_policy", "description" => "description", "locale" => "locale" }) def self.type return "betaAppLocalizations" 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_attachment.rb
spaceship/lib/spaceship/connect_api/models/app_store_review_attachment.rb
require_relative '../model' require_relative '../file_uploader' require 'digest/md5' module Spaceship class ConnectAPI class AppStoreReviewAttachment include Spaceship::ConnectAPI::Model attr_accessor :file_name attr_accessor :source_file_checksum attr_accessor :upload_operations attr_accessor :asset_delivery_state attr_accessor :uploaded attr_mapping({ "fileName" => "file_name", "sourceFileChecksum" => "source_file_checksum", "uploadOperations" => "upload_operations", "assetDeliveryState" => "asset_delivery_state", "uploaded" => "uploaded" }) def self.type return "appStoreReviewAttachments" end # # API # def self.create(client: nil, app_store_review_detail_id: nil, path: nil) 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 attachment = client.post_app_store_review_attachment( app_store_review_detail_id: app_store_review_detail_id, attributes: post_attributes ).to_models.first # Upload the file upload_operations = attachment.upload_operations Spaceship::ConnectAPI::FileUploader.upload(upload_operations, bytes) # Update file uploading complete patch_attributes = { uploaded: true, sourceFileChecksum: Digest::MD5.hexdigest(bytes) } client.patch_app_store_review_attachment( app_store_review_attachment_id: attachment.id, attributes: patch_attributes ).to_models.first end def delete!(client: nil, filter: {}, includes: nil, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI client.delete_app_store_review_attachment(app_store_review_attachment_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/user.rb
spaceship/lib/spaceship/connect_api/models/user.rb
require_relative '../model' module Spaceship class ConnectAPI class User include Spaceship::ConnectAPI::Model attr_accessor :username attr_accessor :first_name attr_accessor :last_name attr_accessor :email attr_accessor :preferred_currency_territory attr_accessor :agreed_to_terms attr_accessor :roles attr_accessor :all_apps_visible attr_accessor :provisioning_allowed attr_accessor :email_vetting_required attr_accessor :notifications attr_accessor :visible_apps attr_mapping({ "username" => "username", "firstName" => "first_name", "lastName" => "last_name", "email" => "email", "preferredCurrencyTerritory" => "preferred_currency_territory", "agreedToTerms" => "agreed_to_terms", "roles" => "roles", "allAppsVisible" => "all_apps_visible", "provisioningAllowed" => "provisioning_allowed", "emailVettingRequired" => "email_vetting_required", "notifications" => "notifications", "visibleApps" => "visible_apps" }) ESSENTIAL_INCLUDES = [ "visibleApps" ].join(",") def self.type return "users" end module UserRole ADMIN = "ADMIN" FINANCE = "FINANCE" TECHNICAL = "TECHNICAL" SALES = "SALES" MARKETING = "MARKETING" DEVELOPER = "DEVELOPER" ACCOUNT_HOLDER = "ACCOUNT_HOLDER" READ_ONLY = "READ_ONLY" APP_MANAGER = "APP_MANAGER" ACCESS_TO_REPORTS = "ACCESS_TO_REPORTS" CUSTOMER_SUPPORT = "CUSTOMER_SUPPORT" end # # API # def self.all(client: nil, filter: {}, includes: ESSENTIAL_INCLUDES, limit: nil, sort: nil) client ||= Spaceship::ConnectAPI resps = client.get_users(filter: filter, includes: includes).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 # @param client [ConnectAPI] ConnectAPI client. # @param all_apps_visible [Boolean] If all apps must be visible to a user. true - if a user must see all apps, you must not provide visible_app_ids, `false` - a user must see only a limited list of apps, and you must provide visible_app_ids. nil if no change is needed. # @param provisioning_allowed [Bool] If a user with a Developer or App Manager role must have access to Certificates, Identifiers & Profiles. true - if a user must be able to create new certificates and provisioning profiles, `false` - otherwise. nil if no change is needed. # @param roles [Array] Array of strings describing user roles. You can use defined constants in the UserRole, or refer to the Apple Documentation https://developer.apple.com/documentation/appstoreconnectapi/userrole . Pass nil if no change is needed. # @param visible_app_ids [Array] Array of strings with application identifiers the user needs access to. nil if no apps change is needed or user must have access to all apps. # @return (User) Modified user. def update(client: nil, all_apps_visible: nil, provisioning_allowed: nil, roles: nil, visible_app_ids: nil) client ||= Spaceship::ConnectAPI all_apps_visible = all_apps_visible.nil? ? self.all_apps_visible : all_apps_visible provisioning_allowed = provisioning_allowed.nil? ? self.provisioning_allowed : provisioning_allowed roles ||= self.roles visible_app_ids ||= self.visible_apps.map(&:id) resp = client.patch_user( user_id: self.id, all_apps_visible: all_apps_visible, provisioning_allowed: provisioning_allowed, roles: roles, visible_app_ids: visible_app_ids ) return resp.to_models.first end def delete!(client: nil) client ||= Spaceship::ConnectAPI client.delete_user(user_id: id) end def get_visible_apps(client: nil, limit: nil) client ||= Spaceship::ConnectAPI resp = client.get_user_visible_apps(user_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/testflight/testflight.rb
spaceship/lib/spaceship/connect_api/testflight/testflight.rb
require 'spaceship/connect_api/testflight/client' module Spaceship class ConnectAPI module TestFlight module API module Version V1 = "v1" end def test_flight_request_client=(test_flight_request_client) @test_flight_request_client = test_flight_request_client end def test_flight_request_client return @test_flight_request_client if @test_flight_request_client raise TypeError, "You need to instantiate this module with test_flight_request_client" end # # apps # def get_apps(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/apps", params) end def get_app(app_id: nil, includes: nil) params = test_flight_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil) test_flight_request_client.get("#{Version::V1}/apps/#{app_id}", params) end # # betaAppLocalizations # def get_beta_app_localizations(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaAppLocalizations", params) end def post_beta_app_localizations(app_id: nil, attributes: {}) body = { data: { attributes: attributes, type: "betaAppLocalizations", relationships: { app: { data: { type: "apps", id: app_id } } } } } test_flight_request_client.post("#{Version::V1}/betaAppLocalizations", body) end def patch_beta_app_localizations(localization_id: nil, attributes: {}) body = { data: { attributes: attributes, id: localization_id, type: "betaAppLocalizations" } } test_flight_request_client.patch("#{Version::V1}/betaAppLocalizations/#{localization_id}", body) end # # betaAppReviewDetails # def get_beta_app_review_detail(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaAppReviewDetails", params) end def patch_beta_app_review_detail(app_id: nil, attributes: {}) body = { data: { attributes: attributes, id: app_id, type: "betaAppReviewDetails" } } test_flight_request_client.patch("#{Version::V1}/betaAppReviewDetails/#{app_id}", body) end # # betaAppReviewSubmissions # def get_beta_app_review_submissions(filter: {}, includes: nil, limit: nil, sort: nil, cursor: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort, cursor: cursor) test_flight_request_client.get("#{Version::V1}/betaAppReviewSubmissions", params) end def post_beta_app_review_submissions(build_id: nil) body = { data: { type: "betaAppReviewSubmissions", relationships: { build: { data: { type: "builds", id: build_id } } } } } test_flight_request_client.post("#{Version::V1}/betaAppReviewSubmissions", body) end def delete_beta_app_review_submission(beta_app_review_submission_id: nil) params = test_flight_request_client.build_params(filter: nil, includes: nil, limit: nil, sort: nil, cursor: nil) test_flight_request_client.delete("#{Version::V1}/betaAppReviewSubmissions/#{beta_app_review_submission_id}", params) end # # betaBuildLocalizations # def get_beta_build_localizations(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaBuildLocalizations", params) end def post_beta_build_localizations(build_id: nil, attributes: {}) body = { data: { attributes: attributes, type: "betaBuildLocalizations", relationships: { build: { data: { type: "builds", id: build_id } } } } } test_flight_request_client.post("#{Version::V1}/betaBuildLocalizations", body) end def patch_beta_build_localizations(localization_id: nil, feedbackEmail: nil, attributes: {}) body = { data: { attributes: attributes, id: localization_id, type: "betaBuildLocalizations" } } test_flight_request_client.patch("#{Version::V1}/betaBuildLocalizations/#{localization_id}", body) end # # betaBuildMetrics # def get_beta_build_metrics(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaBuildMetrics", params) end # # betaGroups # def get_beta_groups(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaGroups", params) end def add_beta_groups_to_build(build_id: nil, beta_group_ids: []) body = { data: beta_group_ids.map do |id| { type: "betaGroups", id: id } end } test_flight_request_client.post("#{Version::V1}/builds/#{build_id}/relationships/betaGroups", body) end def delete_beta_groups_from_build(build_id: nil, beta_group_ids: []) body = { data: beta_group_ids.map do |id| { type: "betaGroups", id: id } end } test_flight_request_client.delete("#{Version::V1}/builds/#{build_id}/relationships/betaGroups", nil, body) end def create_beta_group(app_id: 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) if is_internal_group has_access_to_all_builds = true if has_access_to_all_builds.nil? else # Access to all builds is only for internal groups has_access_to_all_builds = nil end body = { data: { attributes: { name: group_name, isInternalGroup: is_internal_group, hasAccessToAllBuilds: has_access_to_all_builds, # Undocumented of 2021-08-02 in ASC API docs and ASC Open API spec. This is the default behavior on App Store Connect and does work with both Apple ID and API Token publicLinkEnabled: public_link_enabled, publicLinkLimit: public_link_limit, publicLinkLimitEnabled: public_link_limit_enabled }, relationships: { app: { data: { id: app_id, type: "apps" }, }, }, type: "betaGroups", }, } test_flight_request_client.post("#{Version::V1}/betaGroups", body) end def patch_group(group_id: nil, attributes: {}) body = { data: { attributes: attributes, id: group_id, type: "betaGroups" } } test_flight_request_client.patch("#{Version::V1}/betaGroups/#{group_id}", body) end def delete_beta_group(group_id: nil) raise "group_id is nil" if group_id.nil? test_flight_request_client.delete("#{Version::V1}/betaGroups/#{group_id}") end def get_builds_for_beta_group(group_id: nil) raise "group_id is nil" if group_id.nil? test_flight_request_client.get("#{Version::V1}/betaGroups/#{group_id}/builds") end # # betaTesters # def get_beta_testers(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaTesters", params) end # beta_testers - [{email: "", firstName: "", lastName: ""}] def post_bulk_beta_tester_assignments(beta_group_id: nil, beta_testers: nil) beta_testers || [] beta_testers.map do |tester| tester[:errors] = [] end body = { data: { attributes: { betaTesters: beta_testers }, relationships: { betaGroup: { data: { type: "betaGroups", id: beta_group_id } } }, type: "bulkBetaTesterAssignments" } } test_flight_request_client.post("#{Version::V1}/bulkBetaTesterAssignments", body) end # attributes - {email: "", firstName: "", lastName: ""} def post_beta_tester_assignment(beta_group_ids: [], attributes: {}) body = { data: { attributes: attributes, relationships: { betaGroups: { data: beta_group_ids.map do |id| { type: "betaGroups", id: id } end } }, type: "betaTesters" } } test_flight_request_client.post("#{Version::V1}/betaTesters", body) end def add_beta_tester_to_group(beta_group_id: nil, beta_tester_ids: nil) beta_tester_ids || [] body = { data: beta_tester_ids.map do |id| { type: "betaTesters", id: id } end } test_flight_request_client.post("#{Version::V1}/betaGroups/#{beta_group_id}/relationships/betaTesters", body) end def delete_beta_tester_from_apps(beta_tester_id: nil, app_ids: []) body = { data: app_ids.map do |id| { type: "apps", id: id } end } test_flight_request_client.delete("#{Version::V1}/betaTesters/#{beta_tester_id}/relationships/apps", nil, body) end def delete_beta_tester_from_beta_groups(beta_tester_id: nil, beta_group_ids: []) body = { data: beta_group_ids.map do |id| { type: "betaGroups", id: id } end } test_flight_request_client.delete("#{Version::V1}/betaTesters/#{beta_tester_id}/relationships/betaGroups", nil, body) end def delete_beta_testers_from_app(beta_tester_ids: [], app_id: nil) body = { data: beta_tester_ids.map do |id| { type: "betaTesters", id: id } end } test_flight_request_client.delete("#{Version::V1}/apps/#{app_id}/relationships/betaTesters", nil, body) end def add_beta_tester_to_builds(beta_tester_id: nil, build_ids: []) body = { data: build_ids.map do |id| { type: "builds", id: id } end } test_flight_request_client.post("#{Version::V1}/betaTesters/#{beta_tester_id}/relationships/builds", body) end def add_beta_testers_to_build(build_id: nil, beta_tester_ids: []) body = { data: beta_tester_ids.map do |id| { type: "betaTesters", id: id } end } test_flight_request_client.post("#{Version::V1}/builds/#{build_id}/relationships/individualTesters", body) end def delete_beta_testers_from_build(build_id: nil, beta_tester_ids: []) body = { data: beta_tester_ids.map do |id| { type: "betaTesters", id: id } end } test_flight_request_client.delete("#{Version::V1}/builds/#{build_id}/relationships/individualTesters", nil, body) end # # betaTesterMetrics # def get_beta_tester_metrics(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaTesterMetrics", params) end # # buildBundles # def get_build_bundles_build_bundle_file_sizes(build_bundle_id:, limit: nil) params = test_flight_request_client.build_params(filter: nil, includes: nil, limit: limit, sort: nil, cursor: nil) test_flight_request_client.get("#{Version::V1}/buildBundles/#{build_bundle_id}/buildBundleFileSizes", params) end # # builds # def get_builds(filter: {}, includes: "buildBetaDetail,betaBuildMetrics", limit: 10, sort: "uploadedDate", cursor: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort, cursor: cursor) test_flight_request_client.get("#{Version::V1}/builds", params) end def get_build(build_id: nil, app_store_version_id: nil, includes: nil) if build_id params = test_flight_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil, cursor: nil) return test_flight_request_client.get("#{Version::V1}/builds/#{build_id}", params) elsif app_store_version_id params = test_flight_request_client.build_params(filter: nil, includes: includes, limit: nil, sort: nil, cursor: nil) return test_flight_request_client.get("#{Version::V1}/appStoreVersions/#{app_store_version_id}/build", params) else return nil end end def patch_builds(build_id: nil, attributes: {}) body = { data: { attributes: attributes, id: build_id, type: "builds" } } test_flight_request_client.patch("#{Version::V1}/builds/#{build_id}", body) end # # buildBetaDetails # def get_build_beta_details(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/buildBetaDetails", params) end def patch_build_beta_details(build_beta_details_id: nil, attributes: {}) body = { data: { attributes: attributes, id: build_beta_details_id, type: "buildBetaDetails" } } test_flight_request_client.patch("#{Version::V1}/buildBetaDetails/#{build_beta_details_id}", body) end # # buildDeliveries # def get_build_deliveries(app_id:, filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/apps/#{app_id}/buildDeliveries", params) end # # preReleaseVersions # def get_pre_release_versions(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/preReleaseVersions", params) end # # betaFeedbacks (private API as of end 2019) # def get_beta_feedback(filter: {}, includes: nil, limit: nil, sort: nil) params = test_flight_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) test_flight_request_client.get("#{Version::V1}/betaFeedbacks", params) end def delete_beta_feedback(feedback_id: nil) raise "Feedback id is nil" if feedback_id.nil? test_flight_request_client.delete("#{Version::V1}/betaFeedbacks/#{feedback_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/testflight/client.rb
spaceship/lib/spaceship/connect_api/testflight/client.rb
require_relative '../api_client' require_relative './testflight' require_relative '../../tunes/tunes_client' module Spaceship class ConnectAPI module TestFlight 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::TestFlight::API) self.test_flight_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/users/users.rb
spaceship/lib/spaceship/connect_api/users/users.rb
require 'spaceship/connect_api/users/client' module Spaceship class ConnectAPI module Users module API module Version V1 = "v1" end def users_request_client=(users_request_client) @users_request_client = users_request_client end def users_request_client return @users_request_client if @users_request_client raise TypeError, "You need to instantiate this module with users_request_client" end # # users # # Get list of users def get_users(filter: {}, includes: nil, limit: nil, sort: nil) params = users_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) users_request_client.get("#{Version::V1}/users", params) end # Delete existing user def delete_user(user_id: nil) users_request_client.delete("#{Version::V1}/users/#{user_id}") end # Update existing user def patch_user(user_id:, all_apps_visible:, provisioning_allowed:, roles:, visible_app_ids:) body = { data: { type: 'users', id: user_id, attributes: { allAppsVisible: all_apps_visible, provisioningAllowed: provisioning_allowed, roles: roles }, relationships: { visibleApps: { data: visible_app_ids.map do |app_id| { type: "apps", id: app_id } end } } } } # Avoid API error: You cannot set visible apps for this user because the user's roles give them access to all apps. body[:data].delete(:relationships) if all_apps_visible users_request_client.patch("#{Version::V1}/users/#{user_id}", body) end # Add app permissions for user # @deprecated Use {#post_user_visible_apps} instead. def add_user_visible_apps(user_id: nil, app_ids: nil) post_user_visible_apps(user_id: user_id, app_ids: app_ids) end def post_user_visible_apps(user_id: nil, app_ids: nil) body = { data: app_ids.map do |app_id| { type: "apps", id: app_id } end } users_request_client.post("#{Version::V1}/users/#{user_id}/relationships/visibleApps", body) end # Replace app permissions for user def patch_user_visible_apps(user_id: nil, app_ids: nil) body = { data: app_ids.map do |app_id| { type: "apps", id: app_id } end } users_request_client.patch("#{Version::V1}/users/#{user_id}/relationships/visibleApps", body) end # Remove app permissions for user def delete_user_visible_apps(user_id: nil, app_ids: nil) body = { data: app_ids.map do |app_id| { type: "apps", id: app_id } end } params = nil users_request_client.delete("#{Version::V1}/users/#{user_id}/relationships/visibleApps", params, body) end # Get app permissions for user def get_user_visible_apps(user_id: id, limit: nil) params = users_request_client.build_params(filter: {}, includes: nil, limit: limit, sort: nil) users_request_client.get("#{Version::V1}/users/#{user_id}/visibleApps", params) end # # invitations (invited users) # # Get all invited users def get_user_invitations(filter: {}, includes: nil, limit: nil, sort: nil) params = users_request_client.build_params(filter: filter, includes: includes, limit: limit, sort: sort) users_request_client.get("#{Version::V1}/userInvitations", params) end # Invite new users to App Store Connect def post_user_invitation(email: nil, first_name: nil, last_name: nil, roles: [], provisioning_allowed: nil, all_apps_visible: nil, visible_app_ids: []) body = { data: { type: "userInvitations", attributes: { email: email, firstName: first_name, lastName: last_name, roles: roles, provisioningAllowed: provisioning_allowed, allAppsVisible: all_apps_visible }, relationships: { visibleApps: { data: visible_app_ids.map do |id| { id: id, type: "apps" } end } } } } # Avoid API error: You cannot set visible apps for this user because the user's roles give them access to all apps. body[:data].delete(:relationships) if all_apps_visible users_request_client.post("#{Version::V1}/userInvitations", body) end # Remove invited user from team (not yet accepted) def delete_user_invitation(user_invitation_id: nil) users_request_client.delete("#{Version::V1}/userInvitations/#{user_invitation_id}") end # Get all app permissions for invited user def get_user_invitation_visible_apps(user_invitation_id: id, limit: nil) params = users_request_client.build_params(filter: {}, includes: nil, limit: limit, sort: nil) users_request_client.get("#{Version::V1}/userInvitations/#{user_invitation_id}/visibleApps", params) 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/users/client.rb
spaceship/lib/spaceship/connect_api/users/client.rb
require_relative '../api_client' require_relative './users' require_relative '../../tunes/tunes_client' module Spaceship class ConnectAPI module Users 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::Users::API) self.users_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/portal/portal_base.rb
spaceship/lib/spaceship/portal/portal_base.rb
require_relative '../base' module Spaceship class PortalBase < Spaceship::Base class << self def client require_relative 'spaceship' ( @client or Spaceship::Portal.client or raise "Please login using `Spaceship::Portal.login('user', 'password')`" ) 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/portal/app_service.rb
spaceship/lib/spaceship/portal/app_service.rb
module Spaceship module Portal # Represents a single application service (its state to be more precise) on the Apple Dev Portal class AppService # @return (String) The identifier used by the Dev Portal to represent this service # @example # "homeKit" attr_accessor :service_id # @return (Object) The current value for this service # @example # false attr_accessor :value # @return (String) The service URI for this service # @example # "account/ios/identifiers/updateService.action" attr_accessor :service_uri def initialize(service_id, value) @service_id = service_id @value = value if @service_id == "push" # Push notifications have a special URI @service_uri = "account/ios/identifiers/updatePushService.action" else # Default service URI @service_uri = "account/ios/identifiers/updateService.action" end end def self.new_service(id, values: { on: true, off: false }) m = Module.new values.each do |k, v| m.define_singleton_method(k) do AppService.new(id, v) end end return m end AccessWifi = AppService.new_service("AWEQ28MY3E") AppGroup = AppService.new_service("APG3427HIY") ApplePay = AppService.new_service("OM633U5T5G") AssociatedDomains = AppService.new_service("SKC3T5S89Y") ClassKit = AppService.new_service("PKTJAN2017") AutoFillCredential = AppService.new_service("CPEQ28MX4E") DataProtection = AppService.new_service("dataProtection", values: { off: "", complete: "complete", unless_open: "unlessopen", until_first_auth: "untilfirstauth" }) GameCenter = AppService.new_service("gameCenter") HealthKit = AppService.new_service("HK421J6T7P") HomeKit = AppService.new_service("homeKit") Hotspot = AppService.new_service("HSC639VEI8") Cloud = AppService.new_service("iCloud") CloudKit = AppService.new_service("cloudKitVersion", values: { xcode5_compatible: 1, cloud_kit: 2 }) InAppPurchase = AppService.new_service("inAppPurchase") InterAppAudio = AppService.new_service("IAD53UNK2F") Multipath = AppService.new_service("MP49FN762P") NetworkExtension = AppService.new_service("NWEXT04537") NFCTagReading = AppService.new_service("NFCTRMAY17") PersonalVPN = AppService.new_service("V66P55NK2I") Passbook = AppService.new_service("passbook") PushNotification = AppService.new_service("push") SiriKit = AppService.new_service("SI015DKUHP") VPNConfiguration = AppService.new_service("V66P55NK2I") Wallet = AppService.new_service("passbook") WirelessAccessory = AppService.new_service("WC421J6T7P") constants.each do |c| name = c.to_s .gsub(/([A-Z0-9]+)([A-Z][a-z])/, '\1_\2') # ABBRVString -> ABBRV_String .gsub(/([a-z0-9])([A-Z])/, '\1_\2') # CamelCase -> Camel_Case .downcase self.class.send(:define_method, name) do AppService.const_get(c) end end def ==(other) self.class == other.class && self.service_id == other.service_id && self.value == other.value && self.service_uri == other.service_uri 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/portal/provisioning_profile.rb
spaceship/lib/spaceship/portal/provisioning_profile.rb
require_relative 'app' require_relative 'device' require_relative 'certificate' require_relative 'provisioning_profile_template' module Spaceship module Portal # Represents a provisioning profile of the Apple Dev Portal # # NOTE: If the environment variable `SPACESHIP_AVOID_XCODE_API` is present when using this class, all requests will be made via Apple developer portal API. # In the default case, this class will use the Xcode API for fetching provisioning profiles. This is an optimization that results in 1 query for all Profiles vs 1+N queries. class ProvisioningProfile < PortalBase # @return (String) The ID generated by the Dev Portal # You'll probably not really need this value # @example # "2MAY7NPHAA" attr_accessor :id # @return (String) The UDID of this provisioning profile # This value is used for example for code signing # It is also contained in the actual profile # @example # "23d7df3b-9767-4e85-a1ea-1df4d8f32fec" attr_accessor :uuid # @return (DateTime) The date and time of when the profile # expires. # @example # #<DateTime: 2015-11-25T22:45:50+00:00 ((2457352j,81950s,0n),+0s,2299161j)> attr_accessor :expires # @return (String) The profile distribution type. You probably want to # use the class type to detect the profile type instead of this string. # @example AppStore Profile # "store" # @example AdHoc Profile # "adhoc" # @example Development Profile # "limited" # @example Mac Developer ID Profile # "direct" attr_accessor :distribution_method # @return (String) The name of this profile # @example # "com.krausefx.app AppStore" attr_accessor :name # @return (String) The status of this profile # @example Active (profile is fine) # "Active" # @example Expired (time ran out) # "Expired" # @example Invalid (e.g. code signing identity not available any more) # "Invalid" attr_accessor :status # @return (String) The type of the profile (development or distribution). # You'll probably not need this value # @example Distribution # "iOS Distribution" # @example Development # "iOS Development" attr_accessor :type # @return (String) This will always be "2" # @example # "2" attr_accessor :version # @return (String) The supported platform for this profile # @example # "ios" attr_accessor :platform # @return (String) The supported sub_platform for this profile # @example # "tvOS" attr_accessor :sub_platform # No information about this attribute attr_accessor :managing_app # A reference to the app this profile is for. # You can then easily access the value directly # @return (App) The app this profile is for # # @example Example Value # <Spaceship::Portal::App # @app_id="2UMR2S6PAA" # @name="App Name" # @platform="ios" # @prefix="5A997XSAAA" # @bundle_id="com.krausefx.app" # @is_wildcard=false # @dev_push_enabled=false # @prod_push_enabled=false> # # @example Usage # profile.app.name attr_accessor :app # @return (Array) A list of certificates used for this profile # @example Example Value # [ # <Spaceship::Portal::Certificate::Production # @status=nil # @id="XC5PH8D4AA" # @name="iOS Distribution" # @created=nil # @expires=#<DateTime: 2015-11-25T22:45:50+00:00 ((2457352j,81950s,0n),+0s,2299161j)> # @owner_type="team" # @owner_name=nil # @owner_id=nil # @type_display_id="R58UK2EWAA">] # ] # # @example Usage # profile.certificates.first.id attr_accessor :certificates # @return (Array) A list of devices this profile is enabled for. # This will always be [] for AppStore profiles # # @example Example Value # <Spaceship::Portal::Device # @id="WXQ7V239BE" # @name="Grahams iPhone 4s" # @udid="ba0ac7d70f7a14c6fa02ef0e02f4fe9c5178e2f7" # @platform="ios" # @status="c">] # # @example Usage # profile.devices.first.name attr_accessor :devices # This is the second level request, which is done before creating the object # this includes information about the devices and the certificates # more information on this issue https://github.com/fastlane/fastlane/issues/6137 attr_accessor :profile_details # @return (Bool) Does the profile use a template (has extended entitlements)? # # @example # false attr_accessor :is_template_profile # @return (Spaceship::Portal::ProvisioningProfileTemplate) # Model representation of the provisioning profile template. # This will be always nil if is_template_profile returns false # # @example Example Value # <Spaceship::Portal::ProvisioningProfileTemplate # @template_description="Subscription Service iOS (dist)", # @entitlements=nil, # @purpose_description="Generic Provisioning Profile Template for App: com.apple.smoot.subscriptionservice", # @purpose_display_name="Subscription Service iOS (dist)", # @purpose_name="Subscription Service iOS (dist)", # @version=1> # # @example Usage # profile.template.purpose_display_name attr_accessor :template attr_mapping({ 'provisioningProfileId' => :id, 'UUID' => :uuid, 'dateExpire' => :expires, 'distributionMethod' => :distribution_method, 'name' => :name, 'status' => :status, 'type' => :type, 'version' => :version, 'proProPlatform' => :platform, 'proProSubPlatform' => :sub_platform, 'managingApp' => :managing_app, 'appId' => :app, 'isTemplateProfile' => :is_template_profile, 'template' => :template }) class << self # @return (String) The profile type used for web requests to the Dev Portal # @example # "limited" # "store" # "adhoc" # "inhouse" def type raise "You cannot create a ProvisioningProfile without a type. Use a subclass." end # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) # available values of `distributionMethod` at this point: ['adhoc', 'store', 'limited', 'direct', 'inhouse'] klass = case attrs['distributionMethod'] when 'limited' Development when 'store' AppStore when 'adhoc' AdHoc when 'inhouse' InHouse when 'direct' Direct # Mac-only else raise "Can't find class '#{attrs['distributionMethod']}'" end # Parse the dates # rubocop:disable Style/RescueModifier attrs['dateExpire'] = (Time.parse(attrs['dateExpire']) rescue attrs['dateExpire']) # rubocop:enable Style/RescueModifier # When a profile is created with a template name, the response # (provisioning profiles info) already contains the data about # template, which is used to instantiate the # ProvisioningProfileTemplate model. # Doing so saves an API call needed to fetch profile details. # # Verify if `attrs` contains the info needed to instantiate a template. # If not, the template will be lazily loaded. if attrs['profile'] && attrs['profile']['description'] attrs['template'] = ProvisioningProfileTemplate.factory(attrs['template']) end klass.client = @client obj = klass.new(attrs) return obj end # @return (String) The human readable name of this profile type. # @example # "AppStore" # "AdHoc" # "Development" # "InHouse" def pretty_type name.split('::').last end # Create a new provisioning profile # @param name (String): The name of the provisioning profile on the Dev Portal # @param bundle_id (String): The app identifier, this parameter is required # @param certificate (Certificate): The certificate that should be used with this # provisioning profile. You can also pass an array of certificates to this method. This will # only work for development profiles # @param devices (Array) (optional): An array of Device objects that should be used in this profile. # It is recommend to not pass devices as spaceship will automatically add all devices for AdHoc # and Development profiles and add none for AppStore and Enterprise Profiles # @param mac (Bool) (optional): Pass true if you're making a Mac provisioning profile # @param sub_platform (String) Used to create tvOS profiles at the moment. Value should equal 'tvOS' or nil. # @param template_name (String) (optional): The name of the provisioning profile template. # The value can be found by inspecting the Entitlements drop-down when creating/editing a # provisioning profile in Developer Portal. # @return (ProvisioningProfile): The profile that was just created def create!(name: nil, bundle_id: nil, certificate: nil, devices: [], mac: false, sub_platform: nil, template_name: nil) raise "Missing required parameter 'bundle_id'" if bundle_id.to_s.empty? raise "Missing required parameter 'certificate'. e.g. use `Spaceship::Portal::Certificate::Production.all.first`" if certificate.to_s.empty? app = Spaceship::Portal::App.find(bundle_id, mac: mac) raise "Could not find app with bundle id '#{bundle_id}'" unless app raise "Invalid sub_platform #{sub_platform}, valid values are tvOS" if !sub_platform.nil? && sub_platform != 'tvOS' # Fill in sensible default values name ||= [bundle_id, self.pretty_type].join(' ') if self == AppStore || self == InHouse || self == Direct # Distribution Profiles MUST NOT have devices devices = [] end certificate_parameter = certificate.collect(&:id) if certificate.kind_of?(Array) certificate_parameter ||= [certificate.id] # Fix https://github.com/KrauseFx/fastlane/issues/349 certificate_parameter = certificate_parameter.first if certificate_parameter.count == 1 if devices.nil? || devices.count == 0 if self == Development || self == AdHoc # For Development and AdHoc we usually want all compatible devices by default if mac devices = Spaceship::Portal::Device.all_macs elsif sub_platform == 'tvOS' devices = Spaceship::Portal::Device.all_apple_tvs else devices = Spaceship::Portal::Device.all_ios_profile_devices end end end profile = client.with_retry do client.create_provisioning_profile!(name, self.type, app.app_id, certificate_parameter, devices.map(&:id), mac: mac, sub_platform: sub_platform, template_name: template_name) end self.new(profile) end # @return (Array) Returns all profiles registered for this account # If you're calling this from a subclass (like AdHoc), this will # only return the profiles that are of this type # @param mac (Bool) (optional): Pass true to get all Mac provisioning profiles # @param xcode (Bool) (optional): Pass true to include Xcode managed provisioning profiles def all(mac: false, xcode: false) if ENV['SPACESHIP_AVOID_XCODE_API'] profiles = client.provisioning_profiles(mac: mac) else profiles = client.provisioning_profiles_via_xcode_api(mac: mac) end # transform raw data to class instances profiles.map! { |profile| self.factory(profile) } # filter out the profiles managed by xcode unless xcode profiles.delete_if(&:managed_by_xcode?) end return profiles if self == ProvisioningProfile return profiles.select { |profile| profile.class == self } end # @return (Array) Returns all profiles registered for this account # If you're calling this from a subclass (like AdHoc), this will # only return the profiles that are of this type def all_tvos profiles = all(mac: false) tv_os_profiles = [] profiles.each do |tv_os_profile| if tv_os_profile.tvos? tv_os_profiles << tv_os_profile end end return tv_os_profiles end # @return (Array) Returns an array of provisioning # profiles matching the bundle identifier # Returns [] if no profiles were found # This may also contain invalid or expired profiles def find_by_bundle_id(bundle_id: nil, mac: false, sub_platform: nil) raise "Missing required parameter 'bundle_id'" if bundle_id.to_s.empty? raise "Invalid sub_platform #{sub_platform}, valid values are tvOS" if !sub_platform.nil? && sub_platform != 'tvOS' find_tvos_profiles = sub_platform == 'tvOS' all(mac: mac).find_all do |profile| profile.app.bundle_id == bundle_id && profile.tvos? == find_tvos_profiles end end end # Represents a Development profile from the Dev Portal class Development < ProvisioningProfile def self.type 'limited' end end # Represents an AppStore profile from the Dev Portal class AppStore < ProvisioningProfile def self.type 'store' end end # Represents an AdHoc profile from the Dev Portal class AdHoc < ProvisioningProfile def self.type 'adhoc' end end # Represents an Enterprise InHouse profile from the Dev Portal class InHouse < ProvisioningProfile def self.type 'inhouse' end end # Represents a Mac Developer ID profile from the Dev Portal class Direct < ProvisioningProfile def self.type 'direct' end end # Download the current provisioning profile. This will *not* store # the provisioning profile on the file system. Instead this method # will return the content of the profile. # @return (String) The content of the provisioning profile # You'll probably want to store it on the file system # @example # File.write("path.mobileprovision", profile.download) def download client.download_provisioning_profile(self.id, mac: mac?) end # Delete the provisioning profile def delete! client.delete_provisioning_profile!(self.id, mac: mac?) end # Repair an existing provisioning profile # alias to update! # @return (ProvisioningProfile) A new provisioning profile, as # the repair method will generate a profile with a new ID def repair! update! end # Updates the provisioning profile from the local data # e.g. after you added new devices to the profile # This will also update the code signing identity if necessary # @return (ProvisioningProfile) A new provisioning profile, as # the repair method will generate a profile with a new ID def update! # sigh handles more specific filtering and validation steps that make this logic OK # # This is the minimum protection needed for people using spaceship directly unless certificate_valid? if mac? if self.kind_of?(Development) self.certificates = [Spaceship::Portal::Certificate::MacDevelopment.all.first] elsif self.kind_of?(Direct) self.certificates = [Spaceship::Portal::Certificate::DeveloperIdApplication.all.first] else self.certificates = [Spaceship::Portal::Certificate::MacAppDistribution.all.first] end else if self.kind_of?(Development) self.certificates = [Spaceship::Portal::Certificate::Development.all.first] elsif self.kind_of?(InHouse) self.certificates = [Spaceship::Portal::Certificate::InHouse.all.first] else self.certificates = [Spaceship::Portal::Certificate::Production.all.first] end end end client.with_retry do client.repair_provisioning_profile!( id, name, distribution_method, app.app_id, certificates.map(&:id), devices.map(&:id), mac: mac?, sub_platform: tvos? ? 'tvOS' : nil, template_name: is_template_profile ? template.purpose_name : nil ) end # We need to fetch the provisioning profile again, as the ID changes profile = Spaceship::Portal::ProvisioningProfile.all(mac: mac?).find do |p| p.name == self.name # we can use the name as it's valid end return profile end # Is the certificate of this profile available? # @return (Bool) is the certificate valid? def certificate_valid? return false if (certificates || []).count == 0 certificates.each do |c| if Spaceship::Portal::Certificate.all(mac: mac?).collect(&:id).include?(c.id) return true end end return false end # @return (Bool) Is the current provisioning profile valid? # To also verify the certificate call certificate_valid? 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 > self.expires is_valid = status == 'Active' && !expired return is_valid end # @return (Bool) Is this profile managed by Xcode? def managed_by_xcode? managing_app == 'Xcode' end # @return (Bool) Is this a Mac provisioning profile? def mac? platform == 'mac' end # @return (Bool) Is this a tvos provisioning profile? def tvos? sub_platform == 'tvOS' end def devices if (@devices || []).empty? @devices = (self.profile_details["devices"] || []).collect do |device| Device.set_client(client).factory(device) end end @devices end def certificates if (@certificates || []).empty? @certificates = (profile_details["certificates"] || []).collect do |cert| Certificate.set_client(client).factory(cert) end end @certificates end def app if raw_data.key?('appId') app_attributes = raw_data['appId'] else app_attributes = profile_details['appId'] end App.set_client(client).new(app_attributes) end # This is an expensive operation as it triggers a new request def profile_details # Since 15th September 2016 certificates and devices are hidden behind another request # see https://github.com/fastlane/fastlane/issues/6137 for more information @profile_details ||= client.provisioning_profile_details(provisioning_profile_id: self.id, mac: mac?) end # Lazily instantiates the provisioning profile template model # # @return (Bool) The template model if the provisioning profile has a # template or nil if provisioning profile doesn't have a template def template return nil unless is_template_profile @template ||= ProvisioningProfileTemplate.factory(profile_details['template']) end # @return (String) The name of the template (as displayed in Dev Portal) # or nil if provisioning profile doesn't have a template def template_name is_template_profile ? template.purpose_display_name : nil 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/portal/passbook.rb
spaceship/lib/spaceship/portal/passbook.rb
require_relative 'portal_base' module Spaceship module Portal # Represents an Passbook ID from the Developer Portal class Passbook < PortalBase # @return (String) The identifier of this passbook, provided by the Dev Portal # @example # "RGAWZGXSAA" attr_accessor :passbook_id # @return (String) The name you provided for this passbook # @example # "Spaceship" attr_accessor :name # @return (String) the supported platform of this passbook # @example # "ios" attr_accessor :platform # Prefix provided by the Dev Portal # @example # "5A997XSHK2" attr_accessor :prefix # @return (String) The bundle_id (passbook) of passbook id # @example # "web.com.krausefx.app" attr_accessor :bundle_id # @return (String) Status of the passbook # @example # "current" attr_accessor :status attr_mapping( 'passTypeId' => :passbook_id, 'name' => :name, 'prefix' => :prefix, 'identifier' => :bundle_id, 'status' => :status ) class << self # @return (Array) Returns all passbook available for this account def all client.passbooks.map { |pass_type| self.new(pass_type) } end # Creates a new Passbook ID on the Apple Dev Portal # # @param bundle_id [String] the bundle id (Passbook_id) of the passbook # @param name [String] the name of the Passbook # @return (Passbook) The Passbook you just created def create!(bundle_id: nil, name: nil) new_passbook = client.create_passbook!(name, bundle_id) self.new(new_passbook) end # Find a specific Passbook ID based on the bundle_id # @return (Passbook) The passbook you're looking for. This is nil if the passbook can't be found. def find(bundle_id) all.find do |passbook| passbook.bundle_id == bundle_id end end end # Delete this Passbook ID. # @return (Passbook) The passbook you just deleted def delete! client.delete_passbook!(passbook_id) self 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/portal/merchant.rb
spaceship/lib/spaceship/portal/merchant.rb
require_relative 'portal_base' module Spaceship module Portal # Represents a Merchant ID from the Developer Portal class Merchant < PortalBase # @return (String) The identifier of this merchant, provided by the Dev Portal # @example # "LM1UX73BAC" attr_accessor :merchant_id # @return (String) The name you provided for this merchant # @example # "Spaceship Production" attr_accessor :name # @return (String) the supported platform of this merchant # @example # "ios" attr_accessor :platform # Prefix provided by the Dev Portal # @example # "5A9972XTK2" attr_accessor :prefix # @return (String) The bundle_id (merchant identifier) of merchant id # @example # "merchant.com.krausefx.app.production" attr_accessor :bundle_id # @return (String) Status of the merchant # @example # "current" attr_accessor :status attr_mapping( 'omcId' => :merchant_id, 'name' => :name, 'prefix' => :prefix, 'identifier' => :bundle_id, 'status' => :status ) class << self # @param mac [Bool] Fetches Mac merchant if true # @return (Array) Returns all merchants available for this account def all(mac: false) client.merchants(mac: mac).map { |merchant| new(merchant) } end # Creates a new Merchant on the Apple Dev Portal # # @param bundle_id [String] the bundle id (merchant_identifier) of the merchant # @param name [String] the name of the Merchant # @param mac [Bool] is this a Mac Merchant? # @return (Merchant) The Merchant you just created def create!(bundle_id: nil, name: nil, mac: false) new_merchant = client.create_merchant!(name, bundle_id, mac: mac) new(new_merchant) end # Find a specific Merchant ID based on the bundle_id # @param mac [Bool] Searches Mac merchants if true # @return (Merchant) The Merchant you're looking for. This is nil if the merchant can't be found. def find(bundle_id, mac: false) all(mac: mac).find do |merchant| merchant.bundle_id == bundle_id end end end # Delete this Merchant # @return (Merchant) The merchant you just deleted def delete! client.delete_merchant!(merchant_id, mac: mac?) self end # @return (Bool) Is this a Mac merchant? def mac? platform == 'mac' 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/portal/legacy_wrapper.rb
spaceship/lib/spaceship/portal/legacy_wrapper.rb
require_relative 'certificate' require_relative 'provisioning_profile' require_relative 'device' require_relative 'app' require_relative 'app_group' require_relative 'passbook' require_relative 'website_push' require_relative 'app_service' require_relative 'merchant' module Spaceship Certificate = Spaceship::Portal::Certificate ProvisioningProfile = Spaceship::Portal::ProvisioningProfile Device = Spaceship::Portal::Device App = Spaceship::Portal::App AppGroup = Spaceship::Portal::AppGroup Passbook = Spaceship::Portal::Passbook WebsitePush = Spaceship::Portal::WebsitePush AppService = Spaceship::Portal::AppService Merchant = Spaceship::Portal::Merchant end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/portal/app_group.rb
spaceship/lib/spaceship/portal/app_group.rb
require_relative 'portal_base' module Spaceship module Portal # Represents an app group of the Apple Dev Portal class AppGroup < PortalBase # @return (String) The identifier assigned to this group # @example # "group.com.example.application" attr_accessor :group_id # @return (String) The prefix assigned to this group # @example # "9J57U9392R" attr_accessor :prefix # @return (String) The name of this group # @example # "App Group" attr_accessor :name # @return (String) Status of the group # @example # "current" attr_accessor :status # @return (String) The identifier of this app group, provided by the Dev Portal # @example # "2MAY7NPHAA" attr_accessor :app_group_id attr_mapping( 'applicationGroup' => :app_group_id, 'name' => :name, 'prefix' => :prefix, 'identifier' => :group_id, 'status' => :status ) class << self # @return (Array) Returns all app groups available for this account def all client.app_groups.map { |group| self.factory(group) } end # Creates a new App Group on the Apple Dev Portal # # @param group_id [String] the identifier to assign to this group # @param name [String] the name of the group # @return (AppGroup) The group you just created def create!(group_id: nil, name: nil) new_group = client.create_app_group!(name, group_id) self.new(new_group) end # Find a specific App Group group_id # @return (AppGroup) The app group you're looking for. This is nil if the app group can't be found. def find(group_id) all.find do |group| group.group_id == group_id end end end # Delete this app group # @return (AppGroup) The app group you just deleted def delete! client.delete_app_group!(app_group_id) self 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/portal/spaceship.rb
spaceship/lib/spaceship/portal/spaceship.rb
require_relative 'portal_client' require_relative 'app_service' module Spaceship module Portal class << self # This client stores the default client when using the lazy syntax # Spaceship.app instead of using the spaceship launcher attr_accessor :client # 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::Portal::Client) The client the login method was called for def login(user = nil, password = nil) @client = PortalClient.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 # Helper methods for managing multiple instances of spaceship # @return (Class) Access the apps for the spaceship def app Spaceship::Portal::App.set_client(@client) end # @return (Class) Access the pass types for the spaceship def passbook Spaceship::Portal::Passbook.set_client(@client) end # @return (Class) Access the website pushes for the spaceship def website_push Spaceship::Portal::WebsitePush.set_client(@client) end # @return (Class) Access the app groups for the spaceship def app_group Spaceship::Portal::AppGroup.set_client(@client) end # @return (Class) Access app services for the spaceship def app_service Spaceship::Portal::AppService end # @return (Class) Access the iCloud Containers for the spaceship def cloud_container Spaceship::Portal::CloudContainer.set_client(@client) end # @return (Class) Access the devices for the spaceship def device Spaceship::Portal::Device.set_client(@client) end # @return (Class) Access the certificates for the spaceship def certificate Spaceship::Portal::Certificate.set_client(@client) end # @return (Class) Access the provisioning profiles for the spaceship def provisioning_profile Spaceship::Portal::ProvisioningProfile.set_client(@client) end # @return (Class) Access the merchants for the spaceship def merchant Spaceship::Portal::Merchant.set_client(@client) end end end # Legacy code to support `Spaceship.app` without `Portal` class << self def login(user = nil, password = nil) Spaceship::Portal.login(user, password) end def select_team(team_id: nil, team_name: nil) Spaceship::Portal.select_team(team_id: team_id, team_name: team_name) end def app Spaceship::Portal.app end def passbook Spaceship::Portal.passbook end def website_push Spaceship::Portal.website_push end def app_group Spaceship::Portal.app_group end def app_service Spaceship::Portal.app_service end def cloud_container Spaceship::Portal.cloud_container end def device Spaceship::Portal.device end def certificate Spaceship::Portal.certificate end def provisioning_profile Spaceship::Portal.provisioning_profile end def client Spaceship::Portal.client end def merchant Spaceship::Portal.merchant 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/portal/website_push.rb
spaceship/lib/spaceship/portal/website_push.rb
require_relative 'portal_base' module Spaceship module Portal # Represents an Website Push ID from the Developer Portal class WebsitePush < PortalBase # @return (String) The identifier of this website push, provided by the Dev Portal # @example # "RGAWZGXSAA" attr_accessor :website_id # @return (String) The name you provided for this website push # @example # "Spaceship" attr_accessor :name # @return (String) the supported platform of this website push # @example # "ios" attr_accessor :platform # Prefix provided by the Dev Portal # @example # "5A997XSHK2" attr_accessor :prefix # @return (String) The bundle_id (website identifier) of website push id # @example # "web.com.krausefx.app" attr_accessor :bundle_id # @return (String) Status of the website push # @example # "current" attr_accessor :status attr_mapping( 'websitePushId' => :website_id, 'name' => :name, 'prefix' => :prefix, 'identifier' => :bundle_id, 'status' => :status ) alias app_id website_id # must be after attr_mapping class << self # @param mac [Bool] Fetches Mac website push if true # @return (Array) Returns all website push available for this account def all(mac: false) client.website_push(mac: mac).map { |website_push| self.new(website_push) } end # Creates a new Website Push ID on the Apple Dev Portal # # @param bundle_id [String] the bundle id (website_push_identifier) of the website push # @param name [String] the name of the Website Push # @param mac [Bool] is this a Mac Website Push? # @return (Website Push) The Website Push you just created def create!(bundle_id: nil, name: nil, mac: false) new_website_push = client.create_website_push!(name, bundle_id, mac: mac) self.new(new_website_push) end # Find a specific Website Push ID based on the bundle_id # @param mac [Bool] Searches Mac website pushes if true # @return (Website Push) The website push you're looking for. This is nil if the website push can't be found. def find(bundle_id, mac: false) all(mac: mac).find do |website_push| website_push.bundle_id == bundle_id end end end # Delete this Website Push ID. # @return (Website Push) The website you just deleted def delete! client.delete_website_push!(website_id, mac: mac?) self end # @return (Bool) Is this a Mac website push? def mac? platform == 'mac' 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/portal/key.rb
spaceship/lib/spaceship/portal/key.rb
require_relative 'portal_base' module Spaceship module Portal class Key < PortalBase ## # data model for managing JWT tokens or "Keys" as the ADP refers to them APNS_ID = 'U27F4V844T' DEVICE_CHECK_ID = 'DQ8HTZ7739' MUSIC_KIT_ID = '6A7HVUVQ3M' attr_accessor :id attr_accessor :name attr_mapping({ 'keyId' => :id, 'keyName' => :name, 'services' => :services, 'canDownload' => :can_download, 'canRevoke' => :can_revoke }) def self.all keys = client.list_keys keys.map do |key| new(key) end end def self.find(id) key = client.get_key(id: id) new(key) end ## # Creates a new JWT / Key for making requests to services. # # @param name [String] the name of the key # @param apns [Bool] whether the key should be able to make APNs requests # @param device_check [Bool] whether the key should be able to make DeviceCheck requests # @param music_id [String] the Music Id id (the autogenerated id, not the user specified identifier "music.com.etc...") def self.create(name: nil, apns: nil, device_check: nil, music_id: nil) service_config = {} service_config[APNS_ID] = [] if apns service_config[DEVICE_CHECK_ID] = [] if device_check service_config[MUSIC_KIT_ID] = [music_id] if music_id key = client.create_key!(name: name, service_configs: service_config) new(key) end def revoke! client.revoke_key!(id: id) end def download client.download_key(id: id) end def services raw_data['services'] || reload super end def service_configs_for(service_id) if (service = find_service(service_id)) service['configurations'] end end def has_apns? has_service?(APNS_ID) end def has_music_kit? has_service?(MUSIC_KIT_ID) end def has_device_check? has_service?(DEVICE_CHECK_ID) end def reload self.raw_data = self.class.find(id).raw_data end private def find_service(service_id) services.find do |service| service['id'] == service_id end end def has_service?(service_id) find_service(service_id) != nil 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/portal/provisioning_profile_template.rb
spaceship/lib/spaceship/portal/provisioning_profile_template.rb
require_relative 'portal_base' module Spaceship module Portal class ProvisioningProfileTemplate < PortalBase ## # Data model representing a provisioning profile template # @return (String) Template's description # @example # "Subscription Service iOS (dist)" attr_accessor :template_description # @return (String) Template's purpose description # @example # "Generic Provisioning Profile Template for App: com.apple.smoot.subscriptionservice" attr_accessor :purpose_description # @return (String) Template's purpose name displayed in Dev Portal # @example # "Subscription Service iOS (dist)" attr_accessor :purpose_display_name # @return (String) Template's purpose name # @example # "Subscription Service iOS (dist)" attr_accessor :purpose_name # @return (String) Template version # @example # "1" attr_accessor :version # @return (Array) A list of extended entitlement IDs defined by the template # This is almost always nil :shrug_emoticon: # @example # nil # @example # ["com.apple.smoot.subscriptionservice"] attr_accessor :entitlements attr_mapping({ 'description' => :template_description, 'purposeDescription' => :purpose_description, 'purposeDisplayName' => :purpose_display_name, 'purposeName' => :purpose_name, 'version' => :version, 'entitlements' => :entitlements }) 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/portal/invite.rb
spaceship/lib/spaceship/portal/invite.rb
require_relative 'portal_base' module Spaceship module Portal class Invite < PortalBase # @return (String) Invite Id attr_accessor :invite_id # @return (String) Inviter name attr_accessor :inviter_name # @return (String) Recipient Email Address attr_accessor :email_address # @return (String) Role (member, admin or agent) attr_accessor :type # @return (String) Invite creation date attr_accessor :created # @return (String) Invite expiration date attr_accessor :expires attr_mapping( 'inviteId' => :invite_id, 'inviterName' => :inviter_name, 'recipientEmail' => :email_address, 'recipientRole' => :type, 'dateCreated' => :created, 'dateExpires' => :expires ) class << self def factory(attrs) begin attrs['dateCreated'] = Time.at(attrs['dateCreated'] / 1000).utc rescue NoMethodError # if attrs['dateCreated'] does not implement / rescue TypeError # if Time.at receives an invalid type end begin attrs['dateExpires'] = Time.at(attrs['dateExpires'] / 1000).utc rescue NoMethodError rescue TypeError end attrs['recipientRole'] = attrs['recipientRole'].downcase return self.new(attrs) 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/portal/portal_client.rb
spaceship/lib/spaceship/portal/portal_client.rb
require_relative '../client' require_relative 'app' require_relative 'app_group' require_relative 'cloud_container' require_relative 'device' require_relative 'merchant' require_relative 'passbook' require_relative 'provisioning_profile' require_relative 'certificate' require_relative 'website_push' require_relative 'persons' module Spaceship # rubocop:disable Metrics/ClassLength class PortalClient < Spaceship::Client ##################################################### # @!group Init and Login ##################################################### PROTOCOL_VERSION = Spaceship::Client::PROTOCOL_VERSION def self.hostname "https://developer.apple.com/services-account/#{PROTOCOL_VERSION}/" end def send_login_request(user, password) response = send_shared_login_request(user, password) return response if self.cookie.include?("myacinfo") # When the user has 2 step enabled, we might have to call this method again # This only occurs when the user doesn't have a team on App Store Connect # For 2 step verification we use the App Store Connect back-end # which is enough to get the DES... cookie, however we don't get a valid # myacinfo cookie at that point. That means, after getting the DES... cookie # we have to send the login request again. This will then get us a valid myacinfo # cookie, additionally to the DES... cookie return send_shared_login_request(user, password) end # @return (Array) A list of all available teams def teams return @teams if @teams req = request(:post, "account/listTeams.action") @teams = parse_response(req, 'teams').sort_by do |team| [ team['name'], team['teamId'] ] end 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 if teams.count == 0 raise "User '#{user}' does not have access to any teams with an active membership" end @current_team_id ||= teams[0]['teamId'] end # Shows a team selection for the user in the terminal. This should not be # called on CI systems # # @param team_id (String) (optional): The ID of a Developer Portal team # @param team_name (String) (optional): The name of a Developer Portal team def select_team(team_id: nil, team_name: nil) @current_team_id = self.UI.select_team(team_id: team_id, team_name: team_name) end # Set a new team ID which will be used from now on def team_id=(team_id) @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 # Is the current session from an Enterprise In House account? def in_house? return @in_house unless @in_house.nil? @in_house = (team_information['type'] == 'In-House') end def platform_slug(mac) if mac 'mac' else 'ios' end end private :platform_slug def list_pending_agreements(language: "en") r = request(:post) do |req| req.url("account/listPendingAgreements") req.body = { teamId: team_id, languageIsoCode: language }.to_json req.headers['Content-Type'] = 'application/json' end return parse_response(r) end ##################################################### # @!group Apps ##################################################### def apps(mac: false) paging do |page_number| r = request(:post, "account/#{platform_slug(mac)}/identifiers/listAppIds.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(r, 'appIds') end end def details_for_app(app) r = request(:post, "account/#{platform_slug(app.mac?)}/identifiers/getAppIdDetail.action", { teamId: team_id, appIdId: app.app_id }) parse_response(r, 'appId') end def update_service_for_app(app, service) ensure_csrf(Spaceship::Portal::App) request(:post, service.service_uri, { teamId: team_id, displayId: app.app_id, featureType: service.service_id, featureValue: service.value }) details_for_app(app) end def associate_groups_with_app(app, groups) ensure_csrf(Spaceship::Portal::AppGroup) request(:post, 'account/ios/identifiers/assignApplicationGroupToAppId.action', { teamId: team_id, appIdId: app.app_id, displayId: app.app_id, applicationGroups: groups.map(&:app_group_id) }) details_for_app(app) end def associate_cloud_containers_with_app(app, containers) ensure_csrf(Spaceship::Portal::CloudContainer) request(:post, 'account/ios/identifiers/assignCloudContainerToAppId.action', { teamId: team_id, appIdId: app.app_id, cloudContainers: containers.map(&:cloud_container) }) details_for_app(app) end def associate_merchants_with_app(app, merchants, mac) ensure_csrf(Spaceship::Portal::Merchant) request(:post, "account/#{platform_slug(mac)}/identifiers/assignOMCToAppId.action", { teamId: team_id, appIdId: app.app_id, omcIds: merchants.map(&:merchant_id) }) details_for_app(app) end def valid_name_for(input) latinized = input.to_slug.transliterate latinized = latinized.gsub(/[^0-9A-Za-z\d\s]/, '') # remove non-valid characters # Check if the input string was modified, since it might be empty now # (if it only contained non-latin symbols) or the duplicate of another app if latinized != input latinized << " " latinized << Digest::MD5.hexdigest(input) end latinized end def create_app!(type, name, bundle_id, mac: false, enable_services: {}) # We moved the ensure_csrf to the top of this method # as we got some users with issues around creating new apps # https://github.com/fastlane/fastlane/issues/5813 ensure_csrf(Spaceship::Portal::App) ident_params = case type.to_sym when :explicit { type: 'explicit', identifier: bundle_id, inAppPurchase: 'on', gameCenter: 'on' } when :wildcard { type: 'wildcard', identifier: bundle_id } end params = { name: valid_name_for(name), teamId: team_id } params.merge!(ident_params) enable_services.each do |k, v| params[v.service_id.to_sym] = v.value end r = request(:post, "account/#{platform_slug(mac)}/identifiers/addAppId.action", params) parse_response(r, 'appId') end def delete_app!(app_id, mac: false) ensure_csrf(Spaceship::Portal::App) r = request(:post, "account/#{platform_slug(mac)}/identifiers/deleteAppId.action", { teamId: team_id, appIdId: app_id }) parse_response(r) end def update_app_name!(app_id, name, mac: false) ensure_csrf(Spaceship::Portal::App) r = request(:post, "account/#{platform_slug(mac)}/identifiers/updateAppIdName.action", { teamId: team_id, appIdId: app_id, name: valid_name_for(name) }) parse_response(r, 'appId') end ##################################################### # @!group Passbook ##################################################### def passbooks paging do |page_number| r = request(:post, "account/ios/identifiers/listPassTypeIds.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(r, 'passTypeIdList') end end def create_passbook!(name, bundle_id) ensure_csrf(Spaceship::Portal::Passbook) r = request(:post, "account/ios/identifiers/addPassTypeId.action", { name: name, identifier: bundle_id, teamId: team_id }) parse_response(r, 'passTypeId') end def delete_passbook!(passbook_id) ensure_csrf(Spaceship::Portal::Passbook) r = request(:post, "account/ios/identifiers/deletePassTypeId.action", { teamId: team_id, passTypeId: passbook_id }) parse_response(r) end ##################################################### # @!group Website Push ##################################################### def website_push(mac: false) paging do |page_number| r = request(:post, "account/#{platform_slug(mac)}/identifiers/listWebsitePushIds.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(r, 'websitePushIdList') end end def create_website_push!(name, bundle_id, mac: false) ensure_csrf(Spaceship::Portal::WebsitePush) r = request(:post, "account/#{platform_slug(mac)}/identifiers/addWebsitePushId.action", { name: name, identifier: bundle_id, teamId: team_id }) parse_response(r, 'websitePushId') end def delete_website_push!(website_id, mac: false) ensure_csrf(Spaceship::Portal::WebsitePush) r = request(:post, "account/#{platform_slug(mac)}/identifiers/deleteWebsitePushId.action", { teamId: team_id, websitePushId: website_id }) parse_response(r) end ##################################################### # @!group Merchant ##################################################### def merchants(mac: false) paging do |page_number| r = request(:post, "account/#{platform_slug(mac)}/identifiers/listOMCs.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(r, 'identifierList') end end def create_merchant!(name, bundle_id, mac: false) ensure_csrf(Spaceship::Portal::Merchant) r = request(:post, "account/#{platform_slug(mac)}/identifiers/addOMC.action", { name: name, identifier: bundle_id, teamId: team_id }) parse_response(r, 'omcId') end def delete_merchant!(merchant_id, mac: false) ensure_csrf(Spaceship::Portal::Merchant) r = request(:post, "account/#{platform_slug(mac)}/identifiers/deleteOMC.action", { teamId: team_id, omcId: merchant_id }) parse_response(r) end ##################################################### # @!group App Groups ##################################################### def app_groups paging do |page_number| r = request(:post, 'account/ios/identifiers/listApplicationGroups.action', { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(r, 'applicationGroupList') end end def create_app_group!(name, group_id) ensure_csrf(Spaceship::Portal::AppGroup) r = request(:post, 'account/ios/identifiers/addApplicationGroup.action', { name: valid_name_for(name), identifier: group_id, teamId: team_id }) parse_response(r, 'applicationGroup') end def delete_app_group!(app_group_id) ensure_csrf(Spaceship::Portal::AppGroup) r = request(:post, 'account/ios/identifiers/deleteApplicationGroup.action', { teamId: team_id, applicationGroup: app_group_id }) parse_response(r) end ##################################################### # @!group Cloud Containers ##################################################### def cloud_containers paging do |page_number| r = request(:post, 'account/cloudContainer/listCloudContainers.action', { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) result = parse_response(r, 'cloudContainerList') csrf_cache[Spaceship::Portal::CloudContainer] = self.csrf_tokens result end end def create_cloud_container!(name, identifier) ensure_csrf(Spaceship::Portal::CloudContainer) r = request(:post, 'account/cloudContainer/addCloudContainer.action', { name: valid_name_for(name), identifier: identifier, teamId: team_id }) parse_response(r, 'cloudContainer') end ##################################################### # @!group Team ##################################################### def team_members response = request(:post) do |req| req.url("/services-account/#{PROTOCOL_VERSION}/account/getTeamMembers") req.body = { teamId: team_id }.to_json req.headers['Content-Type'] = 'application/json' end parse_response(response) end def team_invited response = request(:post) do |req| req.url("/services-account/#{PROTOCOL_VERSION}/account/getInvites") req.body = { teamId: team_id }.to_json req.headers['Content-Type'] = 'application/json' end parse_response(response) end def team_set_role(team_member_id, role) ensure_csrf(Spaceship::Portal::Persons) response = request(:post) do |req| req.url("/services-account/#{PROTOCOL_VERSION}/account/setTeamMemberRoles") req.body = { teamId: team_id, role: role, teamMemberIds: [team_member_id] }.to_json req.headers['Content-Type'] = 'application/json' end parse_response(response) end def team_remove_member!(team_member_id) ensure_csrf(Spaceship::Portal::Persons) response = request(:post) do |req| req.url("/services-account/#{PROTOCOL_VERSION}/account/removeTeamMembers") req.body = { teamId: team_id, teamMemberIds: [team_member_id] }.to_json req.headers['Content-Type'] = 'application/json' end parse_response(response) end def team_invite(email, role) ensure_csrf(Spaceship::Portal::Persons) response = request(:post) do |req| req.url("/services-account/#{PROTOCOL_VERSION}/account/sendInvites") req.body = { invites: [ { recipientEmail: email, recipientRole: role } ], teamId: team_id }.to_json req.headers['Content-Type'] = 'application/json' end parse_response(response) end ##################################################### # @!group Devices ##################################################### def devices(mac: false, include_disabled: false) paging do |page_number| r = request(:post, "account/#{platform_slug(mac)}/device/listDevices.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc', includeRemovedDevices: include_disabled }) result = parse_response(r, 'devices') csrf_cache[Spaceship::Portal::Device] = self.csrf_tokens result end end def devices_by_class(device_class, include_disabled: false) paging do |page_number| r = request(:post, 'account/ios/device/listDevices.action', { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc', deviceClasses: device_class, includeRemovedDevices: include_disabled }) parse_response(r, 'devices') end end def create_device!(device_name, device_id, mac: false) ensure_csrf(Spaceship::Portal::Device) req = request(:post, "account/#{platform_slug(mac)}/device/addDevices.action", { teamId: team_id, deviceClasses: mac ? 'mac' : 'iphone', deviceNumbers: device_id, deviceNames: device_name, register: 'single' }) devices = parse_response(req, 'devices') return devices.first unless devices.empty? validation_messages = parse_response(req, 'validationMessages').map { |message| message["validationUserMessage"] }.compact.uniq raise UnexpectedResponse.new, validation_messages.join('\n') unless validation_messages.empty? raise UnexpectedResponse.new, "Couldn't register new device, got this: #{parse_response(req)}" end def disable_device!(device_id, device_udid, mac: false) request(:post, "https://developer.apple.com/services-account/#{PROTOCOL_VERSION}/account/#{platform_slug(mac)}/device/deleteDevice.action", { teamId: team_id, deviceId: device_id }) end def enable_device!(device_id, device_udid, mac: false) req = request(:post, "https://developer.apple.com/services-account/#{PROTOCOL_VERSION}/account/#{platform_slug(mac)}/device/enableDevice.action", { teamId: team_id, displayId: device_id, deviceNumber: device_udid }) parse_response(req, 'device') end ##################################################### # @!group Certificates ##################################################### def certificates(types, mac: false) paging do |page_number| r = request(:post, "account/#{platform_slug(mac)}/certificate/listCertRequests.action", { teamId: team_id, types: types.join(','), pageNumber: page_number, pageSize: page_size, sort: 'certRequestStatusCode=asc' }) parse_response(r, 'certRequests') end end def create_certificate!(type, csr, app_id = nil, mac = false) ensure_csrf(Spaceship::Portal::Certificate) r = request(:post, "account/#{platform_slug(mac)}/certificate/submitCertificateRequest.action", { teamId: team_id, type: type, csrContent: csr, appIdId: app_id, # optional specialIdentifierDisplayId: app_id, # For requesting Web Push certificates }) parse_response(r, 'certRequest') end def download_certificate(certificate_id, type, mac: false) { type: type, certificate_id: certificate_id }.each { |k, v| raise "#{k} must not be nil" if v.nil? } r = request(:get, "account/#{platform_slug(mac)}/certificate/downloadCertificateContent.action", { teamId: team_id, certificateId: certificate_id, type: type }) a = parse_response(r) if r.success? && a.include?("Apple Inc") return a else raise UnexpectedResponse.new, "Couldn't download certificate, got this instead: #{a}" end end def revoke_certificate!(certificate_id, type, mac: false) ensure_csrf(Spaceship::Portal::Certificate) r = request(:post, "account/#{platform_slug(mac)}/certificate/revokeCertificate.action", { teamId: team_id, certificateId: certificate_id, type: type }) parse_response(r, 'certRequests') end ##################################################### # @!group Provisioning Profiles ##################################################### def provisioning_profiles(mac: false) paging do |page_number| req = request(:post, "account/#{platform_slug(mac)}/profile/listProvisioningProfiles.action", { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc', includeInactiveProfiles: true, onlyCountLists: true }) result = parse_response(req, 'provisioningProfiles') csrf_cache[Spaceship::Portal::ProvisioningProfile] = self.csrf_tokens result end end ## # this endpoint is used by Xcode to fetch provisioning profiles. # The response is an xml plist but has the added benefit of containing the appId of each provisioning profile. # # Use this method over `provisioning_profiles` if possible because no secondary API calls are necessary to populate the ProvisioningProfile data model. def provisioning_profiles_via_xcode_api(mac: false) req = request(:post) do |r| r.url("https://developerservices2.apple.com/services/#{PROTOCOL_VERSION}/#{platform_slug(mac)}/listProvisioningProfiles.action") r.params = { teamId: team_id, includeInactiveProfiles: true, includeExpiredProfiles: true, onlyCountLists: true } end result = parse_response(req, 'provisioningProfiles') csrf_cache[Spaceship::Portal::ProvisioningProfile] = self.csrf_tokens result end def provisioning_profile_details(provisioning_profile_id: nil, mac: false) r = request(:post, "account/#{platform_slug(mac)}/profile/getProvisioningProfile.action", { teamId: team_id, provisioningProfileId: provisioning_profile_id }) parse_response(r, 'provisioningProfile') end def create_provisioning_profile!(name, distribution_method, app_id, certificate_ids, device_ids, mac: false, sub_platform: nil, template_name: nil) ensure_csrf(Spaceship::Portal::ProvisioningProfile) do fetch_csrf_token_for_provisioning end params = { teamId: team_id, provisioningProfileName: name, appIdId: app_id, distributionType: distribution_method, certificateIds: certificate_ids, deviceIds: device_ids } params[:subPlatform] = sub_platform if sub_platform # if `template_name` is nil, Default entitlements will be used params[:template] = template_name if template_name r = request(:post, "account/#{platform_slug(mac)}/profile/createProvisioningProfile.action", params) parse_response(r, 'provisioningProfile') end def download_provisioning_profile(profile_id, mac: false) ensure_csrf(Spaceship::Portal::ProvisioningProfile) do fetch_csrf_token_for_provisioning end r = request(:get, "account/#{platform_slug(mac)}/profile/downloadProfileContent", { teamId: team_id, provisioningProfileId: profile_id }) a = parse_response(r) if r.success? && a.include?("DOCTYPE plist PUBLIC") return a else raise UnexpectedResponse.new, "Couldn't download provisioning profile, got this instead: #{a}" end end def delete_provisioning_profile!(profile_id, mac: false) fetch_csrf_token_for_provisioning r = request(:post, "account/#{platform_slug(mac)}/profile/deleteProvisioningProfile.action", { teamId: team_id, provisioningProfileId: profile_id }) parse_response(r) end def repair_provisioning_profile!(profile_id, name, distribution_method, app_id, certificate_ids, device_ids, mac: false, sub_platform: nil, template_name: nil) fetch_csrf_token_for_provisioning params = { teamId: team_id, provisioningProfileId: profile_id, provisioningProfileName: name, appIdId: app_id, distributionType: distribution_method, certificateIds: certificate_ids.join(','), deviceIds: device_ids } params[:subPlatform] = sub_platform if sub_platform # if `template_name` is nil, Default entitlements will be used params[:template] = template_name if template_name r = request(:post, "account/#{platform_slug(mac)}/profile/regenProvisioningProfile.action", params) parse_response(r, 'provisioningProfile') end ##################################################### # @!group Keys ##################################################### def list_keys paging do |page_number| response = request(:post, 'account/auth/key/list', { teamId: team_id, pageNumber: page_number, pageSize: page_size, sort: 'name=asc' }) parse_response(response, 'keys') end end def get_key(id: nil) response = request(:post, 'account/auth/key/get', { teamId: team_id, keyId: id }) # response contains a list of keys with 1 item parse_response(response, 'keys').first end def download_key(id: nil) response = request(:get, 'account/auth/key/download', { teamId: team_id, keyId: id }) parse_response(response) end def create_key!(name: nil, service_configs: nil) fetch_csrf_token_for_keys params = { name: name, serviceConfigurations: service_configs, teamId: team_id } response = request(:post, 'account/auth/key/create') do |req| req.headers['Content-Type'] = 'application/json' req.body = params.to_json end # response contains a list of keys with 1 item parse_response(response, 'keys').first end def revoke_key!(id: nil) fetch_csrf_token_for_keys response = request(:post, 'account/auth/key/revoke', { teamId: team_id, keyId: id }) parse_response(response) end private # This is a cache of entity type (App, AppGroup, Certificate, Device) to csrf_tokens def csrf_cache @csrf_cache ||= {} end # Ensures that there are csrf tokens for the appropriate entity type # Relies on store_csrf_tokens to set csrf_tokens to the appropriate value # then stores that in the correct place in cache # This method also takes a block, if you want to send a custom request, instead of # calling `.all` on the given klass. This is used for provisioning profiles. def ensure_csrf(klass) if csrf_cache[klass] self.csrf_tokens = csrf_cache[klass] return end self.csrf_tokens = nil # If we directly create a new resource (e.g. app) without querying anything before # we don't have a valid csrf token, that's why we have to do at least one request block_given? ? yield : klass.all csrf_cache[klass] = self.csrf_tokens end # We need a custom way to fetch the csrf token for the provisioning profile requests, since # we use a separate API endpoint (host of Xcode API) to fetch the provisioning profiles # All we do is fetch one profile (if exists) to get a valid csrf token with its time stamp # This method is being called from all requests that modify, create or downloading provisioning # profiles. # Source https://github.com/fastlane/fastlane/issues/5903 def fetch_csrf_token_for_provisioning(mac: false) response = request(:post, "account/#{platform_slug(mac)}/profile/listProvisioningProfiles.action", { teamId: team_id, pageNumber: 1, pageSize: 1, sort: 'name=asc' }) parse_response(response, 'provisioningProfiles') return nil end def fetch_csrf_token_for_keys response = request(:post, 'account/auth/key/list', { teamId: team_id, pageNumber: 1, pageSize: 1, sort: 'name=asc' }) parse_response(response, 'keys') return nil 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/portal/app.rb
spaceship/lib/spaceship/portal/app.rb
require_relative 'portal_base' require_relative 'app_group' require_relative 'cloud_container' module Spaceship module Portal # Represents an App ID from the Developer Portal class App < PortalBase # @return (String) The identifier of this app, provided by the Dev Portal # @example # "RGAWZGXSAA" attr_accessor :app_id # @return (String) The name you provided for this app # @example # "Spaceship" attr_accessor :name # @return (String) the supported platform of this app # @example # "ios" attr_accessor :platform # Prefix provided by the Dev Portal # @example # "5A997XSHK2" attr_accessor :prefix # @return (String) The bundle_id (app identifier) of your app # @example # "com.krausefx.app" attr_accessor :bundle_id # @return (Bool) Is this app a wildcard app (e.g. com.krausefx.*) attr_accessor :is_wildcard # @return (Hash) Feature details attr_accessor :features # @return (Array) List of enabled services attr_accessor :enable_services # @return (Bool) Development Push Enabled? attr_accessor :dev_push_enabled # @return (Bool) Production Push Enabled? attr_accessor :prod_push_enabled # @return (Fixnum) Number of associated app groups attr_accessor :app_groups_count # @return (Fixnum) Number of associated cloud containers attr_accessor :cloud_containers_count # @return (Fixnum) Number of associated identifiers attr_accessor :identifiers_count # @return (Array of Spaceship::Portal::AppGroup) Associated groups attr_accessor :associated_groups # @return (Array of Spaceship::Portal::CloudContainer) Associated cloud containers attr_accessor :associated_cloud_containers attr_mapping( 'appIdId' => :app_id, 'name' => :name, 'appIdPlatform' => :platform, 'prefix' => :prefix, 'identifier' => :bundle_id, 'isWildCard' => :is_wildcard, 'features' => :features, 'enabledFeatures' => :enable_services, 'isDevPushEnabled' => :dev_push_enabled, 'isProdPushEnabled' => :prod_push_enabled, 'associatedApplicationGroupsCount' => :app_groups_count, 'associatedCloudContainersCount' => :cloud_containers_count, 'associatedIdentifiersCount' => :identifiers_count, 'associatedCloudContainers' => :associated_cloud_containers ) class << self # @param mac [Bool] Fetches Mac apps if true # @return (Array) Returns all apps available for this account def all(mac: false) client.apps(mac: mac).map { |app| self.new(app) } end # Creates a new App ID on the Apple Dev Portal # # if bundle_id ends with '*' then it is a wildcard id otherwise, it is an explicit id # @param bundle_id [String] the bundle id (app_identifier) of the app associated with this provisioning profile # @param name [String] the name of the App # @param mac [Bool] is this a Mac app? # @return (App) The app you just created def create!(bundle_id: nil, name: nil, mac: false, enable_services: {}) if bundle_id.end_with?('*') type = :wildcard else type = :explicit end new_app = client.create_app!(type, name, bundle_id, mac: mac, enable_services: enable_services) self.new(new_app) end # Find a specific App ID based on the bundle_id # @param mac [Bool] Searches Mac apps if true # @return (App) The app you're looking for. This is nil if the app can't be found. def find(bundle_id, mac: false) raise "`bundle_id` parameter must not be nil" if bundle_id.nil? found_app = all(mac: mac).find do |app| app if app.bundle_id.casecmp(bundle_id) == 0 end # Find catalyst enabled mac apps (look for mac first and then iOS) if !found_app && mac found_app = all(mac: false).find do |app| app if app.bundle_id.casecmp(bundle_id) == 0 end end found_app end end def associated_groups return unless raw_data['associatedApplicationGroups'] @associated_groups ||= raw_data['associatedApplicationGroups'].map do |info| Spaceship::Portal::AppGroup.new(info) end end def associated_cloud_containers return unless raw_data['associatedCloudContainers'] @associated_cloud_containers ||= raw_data['associatedCloudContainers'].map do |info| Spaceship::Portal::CloudContainer.new(info) end end # Delete this App ID. This action will most likely fail if the App ID is already in the store # or there are active profiles # @return (App) The app you just deleted def delete! client.delete_app!(app_id, mac: mac?) self end # Update name of this App ID. # @return (App) The app you updated. This is nil if the app can't be found def update_name!(name, mac: false) app = client.update_app_name!(app_id, name, mac: mac) self.class.factory(app) end # Fetch a specific App ID details based on the bundle_id # @return (App) The app you're looking for. This is nil if the app can't be found. def details app = client.details_for_app(self) self.class.factory(app) end # Associate specific groups with this app # @return (App) The updated detailed app. This is nil if the app couldn't be found def associate_groups(groups) raise "`associate_groups` not available for Mac apps" if mac? app = client.associate_groups_with_app(self, groups) self.class.factory(app) end # Associate specific iCloud Containers with this app # @return (App) The updated detailed app. This is nil if the app couldn't be found. def associate_cloud_containers(containers) raise "`associate_cloud_containers` not available for Mac apps" if mac? app = client.associate_cloud_containers_with_app(self, containers) self.class.factory(app) end # Associate specific merchants with this app # @return (App) The updated detailed app. This is nil if the app couldn't be found def associate_merchants(merchants) app = client.associate_merchants_with_app(self, merchants, mac?) self.class.factory(app) end # Update a service for the app with given AppService object # @return (App) The updated detailed app. This is nil if the app couldn't be found def update_service(service) raise "`update_service` not implemented for Mac apps" if mac? app = client.update_service_for_app(self, service) self.class.factory(app) end # @return (Bool) Is this a Mac app? def mac? platform == 'mac' 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/portal/portal.rb
spaceship/lib/spaceship/portal/portal.rb
require 'spaceship/portal/portal_base' require 'spaceship/portal/app' require 'spaceship/portal/website_push' require 'spaceship/portal/app_group' require 'spaceship/portal/app_service' require 'spaceship/portal/certificate' require 'spaceship/portal/cloud_container' require 'spaceship/portal/device' require 'spaceship/portal/provisioning_profile' require 'spaceship/portal/portal_client' require 'spaceship/portal/persons' require 'spaceship/portal/person' require 'spaceship/portal/key' require 'spaceship/portal/provisioning_profile_template' require 'spaceship/portal/merchant' require 'spaceship/portal/passbook' require 'spaceship/portal/invite'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/portal/cloud_container.rb
spaceship/lib/spaceship/portal/cloud_container.rb
require_relative 'portal_base' module Spaceship module Portal # Represents an iCloud Container of the Apple Dev Portal class CloudContainer < PortalBase # @return (String) The identifier assigned to this container # @example # "iCloud.com.example.application" attr_accessor :identifier # @return (String) The prefix assigned to this container # @example # "9J57U9392R" attr_accessor :prefix # @return (String) The name of this container # @example # "iCloud com example application" attr_accessor :name # @return (String) Status of the container # @example # "current" attr_accessor :status # @return (String) The identifier of this iCloud container, provided by the Dev Portal # @example # "2MAY7NPHAA" attr_accessor :cloud_container # @return (Bool) Is the container editable? attr_accessor :can_edit # @return (Bool) Is the container deletable? attr_accessor :can_delete attr_mapping( 'identifier' => :identifier, 'prefix' => :prefix, 'name' => :name, 'cloudContainer' => :cloud_container, 'status' => :status, 'canEdit' => :can_edit, 'canDelete' => :can_delete ) class << self # @return (Array) Returns all iCloud containers available for this account def all client.cloud_containers.map { |container| self.factory(container) } end # Creates a new iCloud Container on the Apple Dev Portal # # @param identifier [String] the identifier to assign to this container # @param name [String] the name of the container # @return (CloudContainer) The container you just created def create!(identifier: nil, name: nil) new_container = client.create_cloud_container!(name, identifier) self.new(new_container) end # Find a specific iCloud Container identifier # @return (CloudContainer) The iCloud Container you're looking for. This is nil if the container can't be found. def find(identifier) all.find do |container| container.identifier == identifier 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/portal/person.rb
spaceship/lib/spaceship/portal/person.rb
require_relative 'portal_base' module Spaceship module Portal class Person < PortalBase # @return (String) Person Id attr_accessor :person_id # @return (String) First name attr_accessor :firstname # @return (String) Last name attr_accessor :lastname # @return (String) Email Address attr_accessor :email_address # @return (String) Developer status (active, inactive) attr_accessor :developer_status # @return (String) Joined Date attr_accessor :joined # @return (String) Id in Team scope attr_accessor :team_member_id # @return (String) Role (member, admin or agent) attr_accessor :type attr_mapping( 'personId' => :person_id, 'firstName' => :firstname, 'lastName' => :lastname, 'email' => :email_address, 'developerStatus' => :developer_status, 'dateJoined' => :joined, 'teamMemberId' => :team_member_id ) def remove! client.team_remove_member!(team_member_id) end def change_role(role) client.team_set_role(team_member_id, role) end class << self def factory(attrs) begin attrs['dateJoined'] = Time.parse(attrs['dateJoined']) rescue TypeError # Raised if we start getting integer timestamps rescue ArgumentError # Raised if the string's format can't be parsed end return self.new(attrs) 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/portal/device.rb
spaceship/lib/spaceship/portal/device.rb
require_relative 'portal_base' module Spaceship module Portal # Represents a device from the Apple Developer Portal class Device < PortalBase # @return (String) The ID given from the developer portal. You'll probably not need it. # @example # "XJXGVS46MW" attr_accessor :id # @return (String) The name of the device, must be 50 characters or less. # @example # "Felix Krause's iPhone 6" attr_accessor :name # @return (String) The UDID of the device # @example # "4c24a7ee5caaa4847f49aaab2d87483053f53b65" attr_accessor :udid # @return (String) The platform of the device. This is probably always "ios" # @example # "ios" attr_accessor :platform # @return (String) Status of the device. "c" for enabled devices, "r" for disabled devices. # @example # "c" attr_accessor :status # @return (String) Model (can be nil) # @example # 'iPhone 6', 'iPhone 4 GSM' attr_accessor :model # @return (String) Device type # @example # 'watch' - Apple Watch # 'ipad' - iPad # 'iphone' - iPhone # 'ipod' - iPod # 'tvOS' - Apple TV attr_accessor :device_type attr_mapping({ 'deviceId' => :id, 'name' => :name, 'deviceNumber' => :udid, 'devicePlatform' => :platform, 'status' => :status, 'deviceClass' => :device_type, 'model' => :model }) class << self # @param mac [Bool] Fetches Mac devices if true # @param include_disabled [Bool] Whether to include disable devices. false by default. # @return (Array) Returns all devices registered for this account def all(mac: false, include_disabled: false) client.devices(mac: mac, include_disabled: include_disabled).map { |device| self.factory(device) } end # @return (Array) Returns all Apple TVs registered for this account def all_apple_tvs client.devices_by_class('tvOS').map { |device| self.factory(device) } end # @return (Array) Returns all Watches registered for this account def all_watches client.devices_by_class('watch').map { |device| self.factory(device) } end # @return (Array) Returns all iPads registered for this account def all_ipads client.devices_by_class('ipad').map { |device| self.factory(device) } end # @return (Array) Returns all iPhones registered for this account def all_iphones client.devices_by_class('iphone').map { |device| self.factory(device) } end # @return (Array) Returns all iPods registered for this account def all_ipod_touches client.devices_by_class('ipod').map { |device| self.factory(device) } end # @return (Array) Returns all Macs registered for this account def all_macs all(mac: true) end # @return (Array) Returns all devices that can be used for iOS profiles (all devices except TVs) def all_ios_profile_devices all.reject { |device| device.device_type == "tvOS" } end # @return (Array) Returns all devices matching the provided profile_type def all_for_profile_type(profile_type) if profile_type.include?("tvOS") Spaceship::Portal::Device.all_apple_tvs elsif profile_type.include?("Mac") Spaceship::Portal::Device.all_macs else Spaceship::Portal::Device.all_ios_profile_devices end end # @param mac [Bool] Searches for Macs if true # @param include_disabled [Bool] Whether to include disable devices. false by default. # @return (Device) Find a device based on the ID of the device. *Attention*: # This is *not* the UDID. nil if no device was found. def find(device_id, mac: false, include_disabled: false) all(mac: mac, include_disabled: include_disabled).find do |device| device.id == device_id end end # @param mac [Bool] Searches for Macs if true # @param include_disabled [Bool] Whether to include disable devices. false by default. # @return (Device) Find a device based on the UDID of the device. nil if no device was found. def find_by_udid(device_udid, mac: false, include_disabled: false) all(mac: mac, include_disabled: include_disabled).find do |device| device.udid.casecmp(device_udid) == 0 end end # @param mac [Bool] Searches for Macs if true # @param include_disabled [Bool] Whether to include disable devices. false by default. # @return (Device) Find a device based on its name. nil if no device was found. def find_by_name(device_name, mac: false, include_disabled: false) all(mac: mac, include_disabled: include_disabled).find do |device| device.name == device_name end end # Register a new device to this account # @param name (String) (required): The name of the new device # @param udid (String) (required): The UDID of the new device # @param mac (Bool) (optional): Pass Mac if device is a Mac # @example # Spaceship.device.create!(name: "Felix Krause's iPhone 6", udid: "4c24a7ee5caaa4847f49aaab2d87483053f53b65") # @return (Device): The newly created device def create!(name: nil, udid: nil, mac: false) # Check whether the user has passed in a UDID and a name unless udid && name raise "You cannot create a device without a device_id (UDID) and name" end raise "Device name must be 50 characters or less. \"#{name}\" has a #{name.length} character length." if name.length > 50 # Find the device by UDID, raise an exception if it already exists existing = self.find_by_udid(udid, mac: mac) return existing if existing # It is valid to have the same name for multiple devices device = client.create_device!(name, udid, mac: mac) # Update self with the new device self.new(device) end end def enabled? return self.status == "c" end def disabled? return self.status == "r" end # Enable current device. def enable! unless enabled? attr = client.enable_device!(self.id, self.udid, mac: self.platform == 'mac') initialize(attr) end end # Disable current device. This will invalidate all provisioning profiles that use this device. def disable! if enabled? client.disable_device!(self.id, self.udid, mac: self.platform == 'mac') # disable request doesn't return device json, so we assume that the new status is "r" if response succeeded self.status = "r" 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/portal/persons.rb
spaceship/lib/spaceship/portal/persons.rb
require_relative 'person' require_relative 'invite' module Spaceship module Portal class Persons < PortalBase class << self def all members = client.team_members all_members = [] member = factory_member(members["members"], "member") admins = factory_member(members["admins"], "admin") agent = factory_member(members["agent"], "agent") all_members.concat(member) all_members.concat(admins) all_members << agent return all_members end def invited return factory_invite(client.team_invited["invites"]) end def factory_invite(invitees) if invitees.kind_of?(Hash) return Spaceship::Portal::Invite.factory(invitees) end final_invitees = [] invitees.each do |invitee| final_invitees << Spaceship::Portal::Invite.factory(invitee) end return final_invitees end def factory_member(members, type) if members.kind_of?(Hash) attrs = members attrs[:type] = type return Spaceship::Portal::Person.factory(attrs) end final_members = [] members.each do |member| attrs = member attrs[:type] = type final_members << Spaceship::Portal::Person.factory(attrs) end return final_members end def find(email) all.each do |member| if member.email_address == email return member end end return nil end def invite(email, role) client.team_invite(email, role) 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/portal/certificate.rb
spaceship/lib/spaceship/portal/certificate.rb
require 'openssl' require_relative 'app' require_relative 'website_push' module Spaceship module Portal # Represents a certificate from the Apple Developer Portal. # # This can either be a code signing identity or a push profile class Certificate < PortalBase # @return (String) The ID given from the developer portal. You'll probably not need it. # @example # "P577TH3PAA" attr_accessor :id # @return (String) The name of the certificate # @example Company # "SunApps GmbH" # @example Push Profile # "Apple Push Services" attr_accessor :name # @return (String) Status of the certificate # @example # "Issued" attr_accessor :status # @return (Date) The date and time when the certificate was created # @example # 2015-04-01 21:24:00 UTC attr_accessor :created # @return (Date) The date and time when the certificate will expire # @example # 2016-04-01 21:24:00 UTC attr_accessor :expires # @return (String) The owner type that defines if it's a push profile # or a code signing identity # # @example Code Signing Identity # "team" # @example Push Certificate # "bundle" attr_accessor :owner_type # @return (String) The name of the owner # # @example Code Signing Identity (usually the company name) # "SunApps Gmbh" # @example Push Certificate (the bundle identifier) # "tools.fastlane.app" attr_accessor :owner_name # @return (String) The ID of the owner, that can be used to # fetch more information # @example # "75B83SPLAA" attr_accessor :owner_id # Indicates the type of this certificate # which is automatically used to determine the class of # the certificate. Available values listed in CERTIFICATE_TYPE_IDS # @return (String) The type of the certificate # @example Production Certificate # "R58UK2EWSO" # @example Development Certificate # "5QPB9NHCEI" attr_accessor :type_display_id # @return (Bool) Whether or not the certificate can be downloaded attr_accessor :can_download attr_mapping({ 'certificateId' => :id, 'name' => :name, 'statusString' => :status, 'dateCreated' => :created, 'expirationDate' => :expires, 'ownerType' => :owner_type, 'ownerName' => :owner_name, 'ownerId' => :owner_id, 'certificateTypeDisplayId' => :type_display_id, 'canDownload' => :can_download }) ##################################################### # Certs are not associated with apps ##################################################### # An Apple development code signing certificate used for development environment class AppleDevelopment < Certificate; end # An Apple distribution code signing certificate used for distribution environment class AppleDistribution < Certificate; end # A development code signing certificate used for development environment class Development < Certificate; end # A production code signing certificate used for distribution environment class Production < Certificate; end # An In House code signing certificate used for enterprise distributions class InHouse < Certificate; end # A Mac development code signing certificate used for development environment class MacDevelopment < Certificate; end # A Mac production code signing certificate for building .app bundles class MacAppDistribution < Certificate; end # A Mac production code signing certificate for building .pkg installers class MacInstallerDistribution < Certificate; end # A Mac Developer ID signing certificate for building .app bundles class DeveloperIdApplication < Certificate; end # A Mac Developer ID signing certificate for building .pkg installers class DeveloperIdInstaller < Certificate; end ##################################################### # Certs that are specific for one app ##################################################### # Abstract class for push certificates. Check out the subclasses # DevelopmentPush, ProductionPush, WebsitePush and VoipPush class PushCertificate < Certificate; end # A push notification certificate for development environment class DevelopmentPush < PushCertificate; end # A push notification certificate for production environment class ProductionPush < PushCertificate; end # A push notification certificate for websites class WebsitePush < PushCertificate def self.portal_type Spaceship::Portal::WebsitePush end end # A push notification certificate for the VOIP environment class VoipPush < PushCertificate; end # Passbook certificate class Passbook < Certificate; end # ApplePay certificate class ApplePay < Certificate; end # ApplePayMerchantIdentity certificate class ApplePayMerchantIdentity < Certificate; end # A Mac push notification certificate for development environment class MacDevelopmentPush < PushCertificate; end # A Mac push notification certificate for production environment class MacProductionPush < PushCertificate; end APPLE_CERTIFICATE_TYPE_IDS = { "83Q87W3TGH" => AppleDevelopment, "WXV89964HE" => AppleDistribution } IOS_CERTIFICATE_TYPE_IDS = { "5QPB9NHCEI" => Development, "R58UK2EWSO" => Production, "9RQEK7MSXA" => InHouse, "LA30L5BJEU" => Certificate, "JKG5JZ54H7" => DevelopmentPush, "UPV3DW712I" => ProductionPush, "Y3B2F3TYSI" => Passbook, "3T2ZP62QW8" => WebsitePush, "E5D663CMZW" => VoipPush, "4APLUP237T" => ApplePay, "MD8Q2VRT6A" => ApplePayMerchantIdentity } OLDER_IOS_CERTIFICATE_TYPES = [ "3BQKVH9I2X", # old ProductionPush "BKLRAVXMGM", # old DevelopmentPush # those are also sent by the browser, but not sure what they represent: "T44PTHVNID", "DZQUP8189Y", "FGQUP4785Z", "S5WE21TULA", "FUOY7LWJET" ] MAC_CERTIFICATE_TYPE_IDS = { "749Y1QAGU7" => MacDevelopment, "HXZEUKP0FP" => MacAppDistribution, "2PQI8IDXNH" => MacInstallerDistribution, "OYVN2GW35E" => DeveloperIdInstaller, "W0EURJRMC5" => DeveloperIdApplication, "CDZ7EMXIZ1" => MacProductionPush, "HQ4KP3I34R" => MacDevelopmentPush, "DIVN2GW3XT" => DeveloperIdApplication } CERTIFICATE_TYPE_IDS = APPLE_CERTIFICATE_TYPE_IDS .merge(IOS_CERTIFICATE_TYPE_IDS) .merge(MAC_CERTIFICATE_TYPE_IDS) # Class methods class << self # Create a new cert signing request that can be used to # generate a new certificate # @example # Create a new certificate signing request # csr, pkey = Spaceship.certificate.create_certificate_signing_request # # # Use the signing request to create a new distribution certificate # Spaceship.certificate.production.create!(csr: csr) def create_certificate_signing_request key = OpenSSL::PKey::RSA.new(2048) csr = OpenSSL::X509::Request.new csr.version = 0 csr.subject = OpenSSL::X509::Name.new([ ['CN', 'PEM', OpenSSL::ASN1::UTF8STRING] ]) csr.public_key = key.public_key csr.sign(key, OpenSSL::Digest::SHA256.new) return [csr, key] end # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) # Example: # => {"name"=>"iOS Distribution: SunApps GmbH", # "certificateId"=>"XC5PH8DAAA", # "serialNumber"=>"797E732CCE8B7AAA", # "status"=>"Issued", # "statusCode"=>0, # "expirationDate"=>#<DateTime: 2015-11-25T22:45:50+00:00 ((2457352j,81950s,0n),+0s,2299161j)>, # "certificatePlatform"=>"ios", # "certificateType"=> # {"certificateTypeDisplayId"=>"R58UK2EAAA", # "name"=>"iOS Distribution", # "platform"=>"ios", # "permissionType"=>"distribution", # "distributionType"=>"store", # "distributionMethod"=>"app", # "ownerType"=>"team", # "daysOverlap"=>364, # "maxActive"=>2}} if attrs['certificateType'] # On some accounts this is nested, so we need to flatten it attrs.merge!(attrs['certificateType']) attrs.delete('certificateType') end # Parse the dates # rubocop:disable Style/RescueModifier attrs['expirationDate'] = (Time.parse(attrs['expirationDate']) rescue attrs['expirationDate']) attrs['dateCreated'] = (Time.parse(attrs['dateCreated']) rescue attrs['dateCreated']) # rubocop:enable Style/RescueModifier # Here we go klass = CERTIFICATE_TYPE_IDS[attrs['certificateTypeDisplayId']] klass ||= Certificate klass.client = @client klass.new(attrs) end # @param mac [Bool] Fetches Mac certificates if true. (Ignored if called from a subclass) # @return (Array) Returns all certificates of this account. # If this is called from a subclass of Certificate, this will # only include certificates matching the current type. def all(mac: false) if self == Certificate # are we the base-class? type_ids = mac ? MAC_CERTIFICATE_TYPE_IDS : IOS_CERTIFICATE_TYPE_IDS type_ids = APPLE_CERTIFICATE_TYPE_IDS.merge(type_ids) types = type_ids.keys types += OLDER_IOS_CERTIFICATE_TYPES unless mac else types = [CERTIFICATE_TYPE_IDS.key(self)] mac = MAC_CERTIFICATE_TYPE_IDS.values.include?(self) end client.certificates(types, mac: mac).map do |cert| factory(cert) end end # @param mac [Bool] Searches Mac certificates if true # @return (Certificate) Find a certificate based on the ID of the certificate. def find(certificate_id, mac: false) all(mac: mac).find do |c| c.id == certificate_id end end # Generate a new certificate based on a code certificate signing request # @param csr (OpenSSL::X509::Request) (required): The certificate signing request to use. Get one using # `create_certificate_signing_request` # @param bundle_id (String) (optional): The app identifier this certificate is for. # This value is only needed if you create a push profile. For normal code signing # certificates, you must only pass a certificate signing request. # @example # # Create a new certificate signing request # csr, pkey = Spaceship::Certificate.create_certificate_signing_request # # # Use the signing request to create a new distribution certificate # Spaceship::Certificate::Production.create!(csr: csr) # @return (Certificate): The newly created certificate def create!(csr: nil, bundle_id: nil) type = CERTIFICATE_TYPE_IDS.key(self) mac = MAC_CERTIFICATE_TYPE_IDS.include?(type) # look up the app_id by the bundle_id if bundle_id app = portal_type.set_client(client).find(bundle_id) raise "Could not find app with bundle id '#{bundle_id}'" unless app app_id = app.app_id end # ensure csr is a OpenSSL::X509::Request csr = OpenSSL::X509::Request.new(csr) if csr.kind_of?(String) # if this succeeds, we need to save the .cer and the private key in keychain access or wherever they go in linux response = client.create_certificate!(type, csr.to_pem, app_id, mac) # munge the response to make it work for the factory response['certificateTypeDisplayId'] = response['certificateType']['certificateTypeDisplayId'] self.new(response) end # Default portal class to use when finding by bundle_id # @return (Class): The class this type of certificate belongs to def portal_type Spaceship::Portal::App end end # instance methods # @return (String) Download the raw data of the certificate without parsing def download_raw client.download_certificate(id, type_display_id, mac: mac?) end # @return (OpenSSL::X509::Certificate) Downloads and parses the certificate def download OpenSSL::X509::Certificate.new(download_raw) end # Revoke the certificate. You shouldn't use this method probably. def revoke! client.revoke_certificate!(id, type_display_id, mac: mac?) end # @return (Bool): Is this certificate a push profile for apps? def is_push? self.kind_of?(PushCertificate) end # @return (Bool) Is this a Mac profile? def mac? MAC_CERTIFICATE_TYPE_IDS.include?(type_display_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/portal/ui/select_team.rb
spaceship/lib/spaceship/portal/ui/select_team.rb
module Spaceship class Client class UserInterface # Shows the UI to select a team # @example teams value: # [{"status"=>"active", # "teamId"=>"5A997XAAAA", # "type"=>"Company/Organization", # "extendedTeamAttributes"=>{}, # "teamAgent"=>{ # "personId"=>15534241111, # "firstName"=>"Felix", # "lastName"=>"Krause", # "email"=>"spaceship@krausefx.com", # "developerStatus"=>"active", # "teamMemberId"=>"5Y354CXAAA"}, # "memberships"=> # [{"membershipId"=>"HJ5WHYC5CE", # "membershipProductId"=>"ds1", # "status"=>"active", # "inDeviceResetWindow"=>false, # "inRenewalWindow"=>false, # "dateStart"=>"11/20/14 07:59", # "dateExpire"=>"11/20/15 07:59", # "platform"=>"ios", # "availableDeviceSlots"=>100, # "name"=>"iOS Developer Program"}], # "currentTeamMember"=> # {"personId"=>nil, "firstName"=>nil, "lastName"=>nil, "email"=>nil, "developerStatus"=>nil, "privileges"=>{}, "roles"=>["TEAM_ADMIN"], "teamMemberId"=>"HQR8N4GAAA"}, # "name"=>"Company GmbH"}, # {...} # ] # rubocop:disable Require/MissingRequireStatement def self.ci? if Object.const_defined?("FastlaneCore") && FastlaneCore.const_defined?("Helper") return FastlaneCore::Helper.ci? end return false end def self.interactive? if Object.const_defined?("FastlaneCore") && FastlaneCore.const_defined?("UI") return FastlaneCore::UI.interactive? end return true end # rubocop:enable Require/MissingRequireStatement def select_team(team_id: nil, team_name: nil) teams = client.teams if teams.count == 0 puts("No teams available on the Developer Portal") puts("You must accept an invitation to a team for it to be available") puts("To learn more about teams and how to use them visit https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/ManagingYourTeam/ManagingYourTeam.html") raise "Your account is in no teams" end team_id = (team_id || ENV['FASTLANE_TEAM_ID'] || '').strip team_name = (team_name || ENV['FASTLANE_TEAM_NAME'] || '').strip if team_id.length > 0 # User provided a value, let's see if it's valid teams.each_with_index do |team, i| # There are 2 different values - one from the login page one from the Dev Team Page return team['teamId'] if team['teamId'].strip == team_id return team['teamId'] if team['currentTeamMember']['teamMemberId'].to_s.strip == team_id end # Better message to inform user of misconfiguration as Apple now provides less friendly error as of 2019-02-12 # This is especially important as Developer Portal team IDs are deprecated and should be replaced with App Store Connect teamIDs # "Access Unavailable - You currently don't have access to this membership resource. Contact your team's Account Holder, Josh Holtz, or an Admin." # https://github.com/fastlane/fastlane/issues/14228 puts("Couldn't find team with ID '#{team_id}'. Make sure your are using the correct App Store Connect team ID and have the proper permissions for this team") end if team_name.length > 0 # User provided a value, let's see if it's valid teams.each_with_index do |team, i| return team['teamId'] if team['name'].strip == team_name end # Better message to inform user of misconfiguration as Apple now provides less friendly error as of 2019-02-12 # "Access Unavailable - You currently don't have access to this membership resource. Contact your team's Account Holder, Josh Holtz, or an Admin." # https://github.com/fastlane/fastlane/issues/14228 puts("Couldn't find team with Name '#{team_name}. Make sure you have the proper permissions for this team'") end return teams[0]['teamId'] if teams.count == 1 # user is just in one team unless self.class.interactive? puts("Multiple teams found on the Developer Portal, Your Terminal is running in non-interactive mode! Cannot continue from here.") puts("Please check that you set FASTLANE_TEAM_ID or FASTLANE_TEAM_NAME to the right value.") puts("Available Teams:") teams.each_with_index do |team, i| puts("#{i + 1}) #{team['teamId']} \"#{team['name']}\" (#{team['type']})") end raise "Multiple Teams found; unable to choose, terminal not interactive!" end # User Selection loop do # Multiple teams, user has to select puts("Multiple teams found on the " + "Developer Portal".yellow + ", please enter the number of the team you want to use: ") teams.each_with_index do |team, i| puts("#{i + 1}) #{team['teamId']} \"#{team['name']}\" (#{team['type']})") end selected = ($stdin.gets || '').strip.to_i - 1 team_to_use = teams[selected] if selected >= 0 return team_to_use['teamId'] if team_to_use 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/tunes/build_train.rb
spaceship/lib/spaceship/tunes/build_train.rb
require_relative 'tunes_base' require_relative 'errors' require_relative 'build' module Spaceship module Tunes # Represents a build train of builds from App Store Connect # A build train is all builds for a given version number with different build numbers class BuildTrain < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application this train is for attr_accessor :application # @return (Spaceship::Tunes::VersionSet) A reference to the version set # this train is for attr_accessor :version_set # @return (Array) An array of all builds that are inside this train (Spaceship::Tunes::Build) attr_reader :builds # @return (String) The version number of this train attr_reader :version_string # @return (String) Platform (e.g. "ios") attr_reader :platform # @return (Bool) Is external beta testing enabled for this train? Only one train can have enabled testing. attr_reader :external_testing_enabled # @return (Bool) Is internal beta testing enabled for this train? Only one train can have enabled testing. attr_reader :internal_testing_enabled # @return (Array) An array of all processing builds that are inside this train (Spaceship::Tunes::Build) # Does not include invalid builds. # I never got this to work to properly try and debug this attr_reader :processing_builds # @return (Array) An array of all invalid builds that are inside this train attr_reader :invalid_builds attr_mapping( 'application' => 'application', 'versionString' => :version_string, 'platform' => :platform, 'externalTesting.value' => :external_testing_enabled, 'internalTesting.value' => :internal_testing_enabled ) class << self # @param application (Spaceship::Tunes::Application) The app this train is for # @param app_id (String) The unique Apple ID of this app def all(application, app_id, platform: nil) trains = [] trains += client.build_trains(app_id, 'internal', platform: platform)['trains'] trains += client.build_trains(app_id, 'external', platform: platform)['trains'] result = {} trains.each do |attrs| attrs[:application] = application current = self.factory(attrs) if (!platform.nil? && current.platform == platform) || platform.nil? result[current.version_string] = current end end result end end # Setup all the builds and processing builds def setup super @builds = (self.raw_data['builds'] || []).collect do |attrs| attrs[:build_train] = self Tunes::Build.factory(attrs) end @invalid_builds = @builds.select do |build| build.processing_state == 'processingFailed' || build.processing_state == 'invalidBinary' end # This step may not be necessary anymore - it seems as if every processing build will be caught by the # @builds.each below, but not every processing build makes it to buildsInProcessing, so this is redundant @processing_builds = (self.raw_data['buildsInProcessing'] || []).collect do |attrs| attrs[:build_train] = self Tunes::Build.factory(attrs) end # since buildsInProcessing appears empty, fallback to also including processing state from @builds @builds.each do |build| # What combination of attributes constitutes which state is pretty complicated. The table below summarizes # what I've observed, but there's no reason to believe there aren't more states I just haven't seen yet. # The column headers are qualitative states of a given build, and the first column is the observed attributes # of that build. # NOTE: Some of the builds in the build_trains.json fixture do not follow these rules. I don't know if that is # because those examples are older, and the iTC API has changed, or if their format is still a possibility. # The second part of the OR clause in the line below exists so that those suspicious examples continue to be # accepted for unit tests. # +---------------------+-------------------+-------------------+-----------------+--------------------+---------+ # | | just after upload | normal processing | invalid binary | processing failed | success | # +---------------------+-------------------+-------------------+-----------------+--------------------+---------+ # | build.processing = | true | true | true | true | false | # | build.valid = | false | true | false | true | true | # | .processing_state = | "processing" | "processing" | "invalidBinary" | "processingFailed" | nil | # +---------------------+-------------------+-------------------+-----------------+--------------------+---------+ if build.processing_state == 'processing' || (build.processing && build.processing_state != 'invalidBinary' && build.processing_state != 'processingFailed') @processing_builds << build end end self.version_set = self.application.version_set_for_platform(self.platform) end # @return (Spaceship::Tunes::Build) The latest build for this train, sorted by upload time. def latest_build @builds.max_by(&:upload_date) end # @param (testing_type) internal or external def update_testing_status!(new_value, testing_type, build = nil) build ||= latest_build if testing_type == 'external' platform = build ? build.platform : self.application.platform testing_key = "#{testing_type}Testing" data = client.build_trains(self.application.apple_id, testing_type, platform: platform) # Delete the irrelevant trains and update the relevant one to enable testing data['trains'].delete_if do |train| if train['versionString'] != version_string true else train[testing_key]['value'] = new_value # also update the builds train['builds'].delete_if do |b| if b[testing_key].nil? true elsif build && b["buildVersion"] == build.build_version b[testing_key]['value'] = new_value false elsif b[testing_key]['value'] == true b[testing_key]['value'] = false false else true end end false end end begin result = client.update_build_trains!(application.apple_id, testing_type, data) rescue Spaceship::Tunes::Error => ex if ex.to_s.include?("You must provide an answer for this question") # This is a very common error message that's raised by TestFlight # We want to show a nicer error message with instructions on how # to resolve the underlying issue # https://github.com/fastlane/fastlane/issues/1873 # https://github.com/fastlane/fastlane/issues/4002 error_message = [""] # to have a nice new-line in the beginning error_message << "TestFlight requires you to provide the answer to the encryption question" error_message << "to provide the reply, please add the following to your Info.plist file" error_message << "" error_message << "<key>ITSAppUsesNonExemptEncryption</key><false/>" error_message << "" error_message << "Afterwards re-build your app and try again" error_message << "App Store Connect reported: '#{ex}'" raise error_message.join("\n") else raise ex end end self.internal_testing_enabled = new_value if testing_type == 'internal' self.external_testing_enabled = new_value if testing_type == 'external' result 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/tunes/iap_family_list.rb
spaceship/lib/spaceship/tunes/iap_family_list.rb
require_relative 'iap_family_details' module Spaceship module Tunes class IAPFamilyList < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # @return (String) the family name attr_accessor :name # @return (Integer) the Family Id attr_accessor :family_id attr_mapping({ 'id' => :family_id, 'name.value' => :name }) # return a editable family object def edit attrs = client.load_iap_family(app_id: application.apple_id, family_id: self.family_id) attrs[:application] = application Tunes::IAPFamilyDetails.new(attrs) 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/tunes/device_type.rb
spaceship/lib/spaceship/tunes/device_type.rb
require_relative "display_family" module Spaceship module Tunes # identifiers of devices that App Store Connect accepts screenshots for class DeviceType def self.types warn("Spaceship::Tunes::DeviceType has been deprecated, use Spaceship::Tunes::DisplayFamily instead. (https://github.com/fastlane/fastlane/pull/14574).") return DisplayFamily.all.map(&:name) end def self.exists?(type) types.include?(type) 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/tunes/iap_family_details.rb
spaceship/lib/spaceship/tunes/iap_family_details.rb
require_relative 'tunes_base' module Spaceship module Tunes class IAPFamilyDetails < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # @return (String) the family name attr_accessor :name # @return (Integer) the family id attr_accessor :family_id # @return (Array) all linked in-app purchases of this family attr_accessor :linked_iaps # @return (Integer) amount of linked in-app purchases of this family (read-only) attr_accessor :iap_count # @return (Array) of all in-app purchase family details attr_accessor :family_details attr_mapping({ 'id' => :family_id, 'name.value' => :name, 'activeAddOns' => :linked_iaps, 'totalActiveAddOns' => :iap_count, 'details.value' => :family_details }) # @return (Hash) localized names def versions parsed_versions = {} raw_versions = raw_data["details"]["value"] raw_versions.each do |version| language = version["value"]["localeCode"]["value"] parsed_versions[language.to_sym] = { subscription_name: version["value"]["subscriptionName"]["value"], name: version["value"]["name"]["value"], id: version["value"]["id"], status: version["value"]["status"] } end return parsed_versions end # transforms user-set versions to iTC ones def versions=(value = {}) if value.kind_of?(Array) # input that comes from iTC api return end new_versions = [] value.each do |language, current_version| new_versions << { "value" => { "subscriptionName" => { "value" => current_version[:subscription_name] }, "name" => { "value" => current_version[:name] }, "localeCode" => { "value" => language }, "id" => current_version[:id] } } end raw_data.set(["details"], { "value" => new_versions }) end # modify existing family def save! # Transform localization versions back to original format. versions_array = [] versions.each do |language_code, value| versions_array << { "value" => { "subscriptionName" => { "value" => value[:subscription_name] }, "name" => { "value" => value[:name] }, "localeCode" => { "value" => language_code.to_s }, "id" => value[:id] } } end raw_data.set(["details"], { "value" => versions_array }) client.update_iap_family!(app_id: application.apple_id, family_id: self.family_id, data: raw_data) 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/tunes/developer_response.rb
spaceship/lib/spaceship/tunes/developer_response.rb
require_relative 'tunes_base' module Spaceship module Tunes class DeveloperResponse < TunesBase attr_reader :id attr_reader :response attr_reader :last_modified attr_reader :hidden attr_reader :state attr_accessor :application attr_accessor :review_id attr_mapping({ 'responseId' => :id, 'response' => :response, 'lastModified' => :last_modified, 'isHidden' => :hidden, 'pendingState' => :state }) 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/tunes/iap_families.rb
spaceship/lib/spaceship/tunes/iap_families.rb
require_relative 'iap_family_list' module Spaceship module Tunes class IAPFamilies < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # Create a new Purchase Family # a freshly created family has to have at least one product. # the product will be created, and versions/pricing_intervals and so on # should be set by subsequent edit. # @param name (String) Familyname # @param product_id (String) New Product's id # @param reference_name (String) Reference name of the new product # @param versions (Hash) Localized Family names # @example # versions: { # 'de-DE': { # subscription_name: "Subname German", # name: 'App Name German', # }, # 'da': { # subscription_name: "Subname DA", # name: 'App Name DA', # } # } def create!(name: nil, product_id: nil, reference_name: nil, versions: {}) versions_array = [] versions.each do |language_code, value| versions_array << { value: { subscriptionName: { value: value[:subscription_name] }, name: { value: value[:name] }, localeCode: { value: language_code.to_s } } } end client.create_iap_family(app_id: self.application.apple_id, name: name, product_id: product_id, reference_name: reference_name, versions: versions_array) end # returns a list of all available subscription groups/families of the current In-App-Purchase def all r = client.iap_families(app_id: self.application.apple_id) return_families = [] r.each do |family| attrs = family attrs[:application] = self.application loaded_family = Tunes::IAPFamilyList.factory(attrs) return_families << loaded_family end return_families end # find a specific family # @param family_id (String) Family Id def find(family_id) all.each do |family| if family.family_id == family_id return family end end return nil 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/tunes/application.rb
spaceship/lib/spaceship/tunes/application.rb
require_relative '../test_flight/group' require_relative '../test_flight/build' require_relative 'app_analytics' require_relative 'app_details' require_relative 'app_ratings' require_relative 'app_submission' require_relative 'app_version' require_relative 'app_version_generated_promocodes' require_relative 'app_version_history' require_relative 'build_train' require_relative 'iap' require_relative 'tunes_base' require_relative 'version_set' module Spaceship module Tunes class Application < TunesBase # @return (String) The App identifier of this app, provided by App Store Connect # @example # "1013943394" attr_accessor :apple_id # @return (String) The name you provided for this app (in the default language) # @example # "Spaceship App" attr_accessor :name # @return (String) The SKU (Stock keeping unit) you provided for this app for internal tracking # @example # "1435592086" attr_accessor :vendor_id # @return (String) The bundle_id (app identifier) of your app # @example # "com.krausefx.app" attr_accessor :bundle_id # @return (String) Last modified attr_accessor :last_modified # @return (Integer) The number of issues provided by App Store Connect attr_accessor :issues_count # @return (String) The URL to a low resolution app icon of this app (340x340px). Might be nil # @example # "https://is1-ssl.mzstatic.com/image/thumb/Purple7/v4/cd/a3/e2/cda3e2ac-4034-c6af-ee0c-3e4d9a0bafaa/pr_source.png/340x340bb-80.png" # @example # nil attr_accessor :app_icon_preview_url # @return (Array) An array of all versions sets attr_accessor :version_sets attr_mapping( 'adamId' => :apple_id, 'name' => :name, 'vendorId' => :vendor_id, 'bundleId' => :bundle_id, 'lastModifiedDate' => :last_modified, 'issuesCount' => :issues_count, 'iconUrl' => :app_icon_preview_url ) class << self # @return (Array) Returns all apps available for this account def all client.applications.map { |application| self.factory(application) } end # @return (Spaceship::Tunes::Application) Returns the application matching the parameter # as either the App ID or the bundle identifier def find(identifier, mac: false) all.find do |app| ((app.apple_id && app.apple_id.casecmp(identifier.to_s) == 0) || (app.bundle_id && app.bundle_id.casecmp(identifier.to_s) == 0)) && app.version_sets.any? { |v| (mac ? ["osx"] : ["ios", "xros", "appletvos"]).include?(v.platform) } end end # Creates a new application on App Store Connect # @param name (String): The name of your app as it will appear on the App Store. # This can't be longer than 255 characters. # @param primary_language (String): If localized app information isn't available in an # App Store territory, the information from your primary language will be used instead. # @param version *DEPRECATED: Use `ensure_version!` method instead* # (String): The version number is shown on the App Store and should match the one you used in Xcode. # @param sku (String): A unique ID for your app that is not visible on the App Store. # @param bundle_id (String): The bundle ID must match the one you used in Xcode. It # can't be changed after you submit your first build. # @param company_name (String): The company name or developer name to display on the App Store for your apps. # It cannot be changed after you create your first app. # @param platform (String): Platform one of (ios,osx) # should it be an ios or an osx app def create!(name: nil, primary_language: nil, version: nil, sku: nil, bundle_id: nil, bundle_id_suffix: nil, company_name: nil, platform: nil, platforms: nil, itunes_connect_users: nil) puts("The `version` parameter is deprecated. Use `ensure_version!` method instead") if version client.create_application!(name: name, primary_language: primary_language, sku: sku, bundle_id: bundle_id, bundle_id_suffix: bundle_id_suffix, company_name: company_name, platform: platform, platforms: platforms, itunes_connect_users: itunes_connect_users) end def available_bundle_ids(platform: nil) client.get_available_bundle_ids(platform: platform) end end ##################################################### # @!group Getting information ##################################################### def version_set_for_platform(platform) version_sets.each do |version_set| return version_set if version_set.platform == platform end nil end # @return (Spaceship::Tunes::AppVersion) Receive the version that is currently live on the # App Store. You can't modify all values there, so be careful. def live_version(platform: nil) Spaceship::Tunes::AppVersion.find(self, self.apple_id, true, platform: platform) end # @return (Spaceship::Tunes::AppVersion) Receive the version that can fully be edited def edit_version(platform: nil) Spaceship::Tunes::AppVersion.find(self, self.apple_id, false, platform: platform) end # @return (Spaceship::Tunes::AppVersion) This will return the `edit_version` if available # and fallback to the `live_version`. Use this to just access the latest data def latest_version(platform: nil) edit_version(platform: platform) || live_version(platform: platform) end # @return (String) An URL to this specific resource. You can enter this URL into your browser def url "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/#{self.apple_id}" end def analytics if self.live_version.nil? raise 'Analytics are only available for live apps.' end attrs = {} attrs[:apple_id] = self.apple_id Spaceship::Tunes::AppAnalytics.factory(attrs) end # @return (Hash) Contains the reason for rejection. # if everything is alright, the result will be # `{"sectionErrorKeys"=>[], "sectionInfoKeys"=>[], "sectionWarningKeys"=>[], "replyConstraints"=>{"minLength"=>1, "maxLength"=>4000}, "appNotes"=>{"threads"=>[]}, "betaNotes"=>{"threads"=>[]}, "appMessages"=>{"threads"=>[]}}` def resolution_center client.get_resolution_center(apple_id, platform) end def reply_resolution_center(app_id, platform, thread_id, version_id, version_number, from, message_body) client.post_resolution_center(app_id, platform, thread_id, version_id, version_number, from, message_body) end def ratings(version_id: '', storefront: '') attrs = client.get_ratings(apple_id, platform, version_id, storefront) attrs[:application] = self Tunes::AppRatings.new(attrs) end def platforms platforms = [] version_sets.each do |version_set| platforms << version_set.platform end platforms end def type if self.version_sets.nil? raise 'The application has no version sets and Spaceship does not know what to do here.' end if self.version_sets.length == 1 version_sets[0].platform end platform = Spaceship::Tunes::AppVersionCommon.find_platform(raw_data['versionSets']) platform['type'] end # kept for backward compatibility # tries to guess the platform of the currently submitted apps # note that as ITC now supports multiple app types, this might break # if your app supports more than one def platform if self.version_sets.nil? raise 'The application has no version sets and Spaceship does not know what to do here.' end if self.version_sets.length == 1 version_sets[0].platform elsif self.platforms == %w(ios appletvos) 'ios' end Spaceship::Tunes::AppVersionCommon.find_platform(raw_data['versionSets'])['platformString'] end def details attrs = client.app_details(apple_id) attrs[:application] = self Tunes::AppDetails.factory(attrs) end def versions_history ensure_not_a_bundle versions = client.versions_history(apple_id, platform) versions.map do |attrs| attrs[:application] = self Tunes::AppVersionHistory.factory(attrs) end end ##################################################### # @!group Modifying ##################################################### # Create a new version of your app # Since we have stored the outdated raw_data, we need to refresh this object # otherwise `edit_version` will return nil def create_version!(version_number, platform: nil) if edit_version(platform: platform) raise "Cannot create a new version for this app as there already is an `edit_version` available" end client.create_version!(apple_id, version_number, platform.nil? ? 'ios' : platform) # Future: implemented -reload method 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_number, platform: nil) if (e = edit_version(platform: platform)) if e.version.to_s != version_number.to_s # Update an existing version e.version = version_number e.save! return true end return false else create_version!(version_number, platform: platform) return true end end def reject_version_if_possible! can_reject = edit_version.can_reject_version if can_reject client.reject!(apple_id, edit_version.version_id) end return can_reject end # set the price tier. This method doesn't require `save` to be called def update_price_tier!(price_tier) client.update_price_tier!(self.apple_id, price_tier) end # The current price tier def price_tier client.price_tier(self.apple_id) end # set the availability. This method doesn't require `save` to be called def update_availability!(availability) client.update_availability!(self.apple_id, availability) end # The current availability. def availability client.availability(self.apple_id) end ##################################################### # @!group in_app_purchases ##################################################### # Get base In-App-Purchases object def in_app_purchases attrs = {} attrs[:application] = self Tunes::IAP.factory(attrs) end ##################################################### # @!group Builds ##################################################### # TestFlight: A reference to all the build trains # @return [Hash] a hash, the version number and platform being the key def build_trains(platform: nil) TestFlight::BuildTrains.all(app_id: self.apple_id, platform: platform || self.platform) end # The numbers of all build trains that were uploaded # @return [Array] An array of train version numbers def all_build_train_numbers(platform: nil) return self.build_trains(platform: platform || self.platform).versions end # Receive the build details for a specific build # useful if the app is not listed in the TestFlight build list # which might happen if you don't use TestFlight # This is used to receive dSYM files from Apple def all_builds_for_train(train: nil, platform: nil) return TestFlight::Build.builds_for_train(app_id: self.apple_id, platform: platform || self.platform, train_version: train) end # @return [Array] This will return an array of *all* processing builds # this include pre-processing or standard processing def all_processing_builds(platform: nil) return TestFlight::Build.all_processing_builds(app_id: self.apple_id, platform: platform || self.platform) end def tunes_all_build_trains(app_id: nil, platform: nil) resp = client.all_build_trains(app_id: apple_id, platform: platform) trains = resp["trains"] or [] trains.map do |attrs| attrs['application'] = self Tunes::BuildTrain.factory(attrs) end end def tunes_all_builds_for_train(train: nil, platform: nil) resp = client.all_builds_for_train(app_id: apple_id, train: train, platform: platform) items = resp["items"] or [] items.map do |attrs| attrs['apple_id'] = apple_id Tunes::Build.factory(attrs) end end def tunes_build_details(train: nil, build_number: nil, platform: nil) resp = client.build_details(app_id: apple_id, train: train, build_number: build_number, platform: platform) resp['apple_id'] = apple_id Tunes::BuildDetails.factory(resp) end # Get all builds that are already processed for all build trains # You can either use the return value (array) or pass a block def builds(platform: nil) all = TestFlight::Build.all(app_id: self.apple_id, platform: platform || self.platform) return all unless block_given? all.each { |build| yield(build) } end ##################################################### # @!group Submit for Review ##################################################### def create_submission(platform: nil) version = self.latest_version(platform: platform) if version.nil? raise "Could not find a valid version to submit for review" end Spaceship::Tunes::AppSubmission.create(self, version, platform: platform) end # Cancels all ongoing TestFlight beta submission for this application def cancel_all_testflight_submissions! self.builds do |build| begin build.cancel_beta_review! rescue # We really don't care about any errors here end end true end ##################################################### # @!group release ##################################################### def release! version = self.edit_version if version.nil? raise "Could not find a valid version to release" end version.release! end ##################################################### # @!group release to all users ##################################################### def release_to_all_users! version = self.live_version if version.nil? raise "Could not find a valid version to release" end version.release_to_all_users! end ##################################################### # @!group General ##################################################### def setup super @version_sets = (self.raw_data['versionSets'] || []).map do |attrs| attrs[:application] = self Tunes::VersionSet.factory(attrs) end end ##################################################### # @!group Testers ##################################################### def default_external_group TestFlight::Group.default_external_group(app_id: self.apple_id) end ##################################################### # @!group Promo codes ##################################################### def promocodes data = client.app_promocodes(app_id: self.apple_id) data.map do |attrs| Tunes::AppVersionPromocodes.factory(attrs) end end def promocodes_history data = client.app_promocodes_history(app_id: self.apple_id) data.map do |attrs| Tunes::AppVersionGeneratedPromocodes.factory(attrs) end end # private to module def ensure_not_a_bundle # we only support applications raise "We do not support BUNDLE types right now" if self.type == 'BUNDLE' 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/tunes/app_version_ref.rb
spaceship/lib/spaceship/tunes/app_version_ref.rb
require_relative 'tunes_base' module Spaceship module Tunes class AppVersionRef < TunesBase attr_accessor :sso_token_for_image attr_accessor :sso_token_for_video attr_mapping( 'ssoTokenForImage' => :sso_token_for_image, 'ssoTokenForVideo' => :sso_token_for_video ) 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/tunes/app_details.rb
spaceship/lib/spaceship/tunes/app_details.rb
require_relative 'errors' require_relative 'language_item' require_relative 'tunes_base' module Spaceship module Tunes class AppDetails < TunesBase attr_accessor :application #### # Localized values #### # @return (Array) Raw access the all available languages. You shouldn't use it probably attr_accessor :languages # @return (Hash) A hash representing the app name in all languages attr_reader :name # @return (Hash) A hash representing the subtitle in all languages attr_reader :subtitle # @return (Hash) A hash representing the privacy URL in all languages attr_reader :privacy_url # @return (Hash) A hash representing the privacy URL in all languages for Apple TV attr_reader :apple_tv_privacy_policy # Categories (e.g. MZGenre.Business) attr_accessor :primary_category attr_accessor :primary_first_sub_category attr_accessor :primary_second_sub_category attr_accessor :secondary_category attr_accessor :secondary_first_sub_category attr_accessor :secondary_second_sub_category attr_accessor :primary_locale_code attr_accessor :available_primary_locale_codes attr_mapping( 'localizedMetadata.value' => :languages, 'primaryCategory.value' => :primary_category, 'primaryFirstSubCategory.value' => :primary_first_sub_category, 'primarySecondSubCategory.value' => :primary_second_sub_category, 'secondaryCategory.value' => :secondary_category, 'secondaryFirstSubCategory.value' => :secondary_first_sub_category, 'secondarySecondSubCategory.value' => :secondary_second_sub_category, 'primaryLocaleCode.value' => :primary_locale_code, 'availablePrimaryLocaleCodes' => :available_primary_locale_codes ) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) obj = self.new(attrs) obj.unfold_languages return obj end end # Prefill name, privacy url def unfold_languages { name: :name, subtitle: :subtitle, privacyPolicyUrl: :privacy_url, privacyPolicy: :apple_tv_privacy_policy }.each do |json, attribute| instance_variable_set("@#{attribute}".to_sym, LanguageItem.new(json, languages)) end end # Push all changes that were made back to App Store Connect def save! client.update_app_details!(application.apple_id, raw_data) rescue Spaceship::Tunes::Error => ex if ex.to_s == "operation_failed" # That's alright, we get this error message if nothing has changed else raise ex end end # Custom Setters # def primary_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end def primary_first_sub_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end def primary_second_sub_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end def secondary_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end def secondary_first_sub_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end def secondary_second_sub_category=(value) value = prefix_apps(value) value = prefix_mzgenre(value) super(value) end ##################################################### # @!group General ##################################################### def setup; end private def prefix_mzgenre(value) value.include?("MZGenre") ? value : "MZGenre.#{value}" end def prefix_apps(value) return value unless value.include?("Stickers") value.include?("Apps") ? value : "Apps.#{value}" 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/tunes/member.rb
spaceship/lib/spaceship/tunes/member.rb
require_relative 'tunes_base' require_relative 'application' module Spaceship module Tunes class Member < TunesBase attr_accessor :email_address attr_accessor :firstname attr_accessor :lastname attr_accessor :username attr_accessor :not_accepted_invitation attr_accessor :user_id attr_mapping( 'emailAddress.value' => :email_address, 'firstName.value' => :firstname, 'lastName.value' => :lastname, 'userName' => :username, 'dsId' => :user_id ) ROLES = { admin: 'admin', app_manager: 'appmanager', sales: 'sales', developer: 'developer', marketing: 'marketing', reports: 'reports' } def roles parsed_roles = [] raw_data["roles"].each do |role| parsed_roles << role["value"]["name"] end return parsed_roles end def admin? roles.include?(ROLES[:admin]) end def app_manager? roles.include?(ROLES[:app_manager]) end def preferred_currency currency_base = raw_data["preferredCurrency"]["value"] return { name: currency_base["name"], code: currency_base["currencyCode"], country: currency_base["countryName"], country_code: currency_base["countryCode"] } end def selected_apps parsed_apps = [] all_apps = Application.all raw_data["userSoftwares"]["value"]["grantedSoftwareAdamIds"].each do |app_id| parsed_apps << all_apps.select { |app| app.apple_id == app_id } end return parsed_apps.flatten end def not_accepted_invitation return true if raw_data["activationExpiry"] return false end def has_all_apps selected_apps.length == 0 end def delete! client.delete_member!(self.user_id, self.email_address) end def resend_invitation client.reinvite_member(self.email_address) 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/tunes/app_analytics.rb
spaceship/lib/spaceship/tunes/app_analytics.rb
require_relative 'tunes_base' module Spaceship module Tunes class AppAnalytics < TunesBase # @return (Integer) The app ID to grab analytics for attr_accessor :apple_id class << self def factory(attrs) return self.new(attrs) end end # App Store / Impressions Unique Devices def app_impressions start_t, end_t = time_last_7_days app_impressions_interval(start_t, end_t) end # App Store / Product Page Views Unique Devices def app_views start_t, end_t = time_last_7_days app_views_interval(start_t, end_t) end # Sales / App Units def app_units start_t, end_t = time_last_7_days app_units_interval(start_t, end_t) end # Sales / In-App Purchases def app_in_app_purchases start_t, end_t = time_last_7_days app_in_app_purchases_interval(start_t, end_t) end # Sales / Sales def app_sales start_t, end_t = time_last_7_days app_sales_interval(start_t, end_t) end # Sales / Paying Users def app_paying_users start_t, end_t = time_last_7_days app_paying_users_interval(start_t, end_t) end # Usage / Installations def app_installs start_t, end_t = time_last_7_days app_installs_interval(start_t, end_t) end # Usage / Sessions def app_sessions start_t, end_t = time_last_7_days app_sessions_interval(start_t, end_t) end # Usage / Active Devices def app_active_devices start_t, end_t = time_last_7_days app_active_devices_interval(start_t, end_t) end # Usage / Active Devices 30 Days def app_active_last_30_days start_t, end_t = time_last_7_days app_active_last_30_days_interval(start_t, end_t) end # Usage / Crashes def app_crashes start_t, end_t = time_last_7_days app_crashes_interval(start_t, end_t) end def app_measure_interval(start_t, end_t, measure, view_by = nil) client.time_series_analytics([apple_id], [measure], start_t, end_t, "DAY", view_by) end def app_impressions_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['impressionsTotal'], start_t, end_t, "DAY", view_by) end def app_units_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['units'], start_t, end_t, "DAY", view_by) end def app_views_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['pageViewCount'], start_t, end_t, "DAY", view_by) end def app_in_app_purchases_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['iap'], start_t, end_t, "DAY", view_by) end def app_sales_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['sales'], start_t, end_t, "DAY", view_by) end def app_paying_users_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['payingUsers'], start_t, end_t, "DAY", view_by) end def app_installs_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['installs'], start_t, end_t, "DAY", view_by) end def app_sessions_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['sessions'], start_t, end_t, "DAY", view_by) end def app_active_devices_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['activeDevices'], start_t, end_t, "DAY", view_by) end def app_active_last_30_days_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['rollingActiveDevices'], start_t, end_t, "DAY", view_by) end def app_crashes_interval(start_t, end_t, view_by = nil) client.time_series_analytics([apple_id], ['crashes'], start_t, end_t, "DAY", view_by) end def time_last_7_days time = Time.now past = time - (60 * 60 * 24 * 7) end_t = time.strftime("%Y-%m-%dT00:00:00Z") start_t = past.strftime("%Y-%m-%dT00:00:00Z") return start_t, end_t end def time_last_30_days time = Time.now past = time - (60 * 60 * 24 * 30) end_t = time.strftime("%Y-%m-%dT00:00:00Z") start_t = past.strftime("%Y-%m-%dT00:00:00Z") return start_t, end_t end def time_last_90_days time = Time.now past = time - (60 * 60 * 24 * 90) end_t = time.strftime("%Y-%m-%dT00:00:00Z") start_t = past.strftime("%Y-%m-%dT00:00:00Z") return start_t, end_t 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/tunes/errors.rb
spaceship/lib/spaceship/tunes/errors.rb
require_relative '../errors' module Spaceship module Tunes # ITunesConnectError is only thrown when App Store Connect raises an exception class Error < BasicPreferredInfoError end # raised if the server failed to save temporarily class TemporaryError < Spaceship::Tunes::Error end # raised if the server failed to save, and it might be caused by an invisible server error class PotentialServerError < Spaceship::Tunes::Error 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/tunes/sandbox_tester.rb
spaceship/lib/spaceship/tunes/sandbox_tester.rb
require_relative 'tunes_base' module Spaceship module Tunes class SandboxTester < TunesBase # @return (String) The email of this sandbox tester # @example # "tester@spaceship.com" attr_accessor :email # @return (String) The first name of this tester # @example # "Cary" attr_accessor :first_name # @return (String) The last name of this tester # @example # "Bennett" attr_accessor :last_name # @return (String) The two-letter country code of this tester # @example # "US" attr_accessor :country attr_mapping( 'emailAddress.value' => :email, 'firstName.value' => :first_name, 'lastName.value' => :last_name, 'storeFront.value' => :country ) def self.url { index: "ra/users/iap", create: "ra/users/iap/add", delete: "ra/users/iap/delete" } end def self.all client.sandbox_testers(self).map { |tester| self.new(tester) } end def self.create!(email: nil, password: nil, first_name: 'Test', last_name: 'Test', country: 'US') data = client.create_sandbox_tester!( tester_class: self, email: email, password: password, first_name: first_name, last_name: last_name, country: country ) self.new(data) end def self.delete!(emails) client.delete_sandbox_testers!(self, emails) end def self.delete_all! delete!(self.all.map(&:email)) end ##################################################### # @!group Subclasses ##################################################### # Delete current tester def delete! client.delete_tester!(self) 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/tunes/build_details.rb
spaceship/lib/spaceship/tunes/build_details.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents the details of a build class BuildDetails < TunesBase # @return (String) The App identifier of this app, provided by App Store Connect # @example # '1013943394' attr_accessor :apple_id # @return (Integer) Upload date of build as UNIX timestamp # @example 1563813377000 attr_accessor :upload_date # @return (String) State of the build/binary # @example 'ITC.apps.preReleaseBuildStatus.Validated' attr_accessor :binary_state # @return (String) Name of uploaded file # @example 'MyApp.ipa' attr_accessor :file_name # @return (String) SDK used to build app # @example '13A340' attr_accessor :build_sdk # @return (String) Platform # @example '13A340' attr_accessor :build_platform # @return (String) Bundle ID of build # @example 'com.sample.app' attr_accessor :bundle_id # @return (String) Name of app # @example 'Test App' attr_accessor :app_name # @return (String) Supported architectures of the build # @example 'armv7, arm64' attr_accessor :supported_architectures # @return (String) Localizations of the build # @example 'English' attr_accessor :localizations # @return (Boolean) Is this a Newsstand app? # @example false attr_accessor :newsstand_app # @return (Boolean) Does the build contain an app icon? # @example true attr_accessor :prerendered_icon_flag # @return [Hash] containing all entitlements for all targets # @example 'Sample.app/Sample: {'com.apple.developer.team-identifier': 'ABC123DEF456'}' attr_accessor :entitlements # @return (String) Platform of the app # @example 'ios' attr_accessor :app_platform # @return (String) Device Requirements / Device Protocols attr_accessor :device_protocols # @return (String) Version code of the build # @example '4' attr_accessor :cf_bundle_version # @return (String) Version code of the build train # @example '1.6' attr_accessor :cf_bundle_short_version # @return (String) Minimum iOS Version # @example '9.3' attr_accessor :min_os_version # @return (String) Enabled Device Family # @example 'iPhone / iPod touch, iPad'' attr_accessor :device_families # @return (String) Required Capabilities # @example 'armv7' attr_accessor :capabilities # @return (Int) Compressed File Size in bytes # @example '9365224' attr_accessor :size_in_bytes # @return (Hash) Estimated App Store file sizes for all devices in bytes attr_accessor :sizes_in_bytes # @return (Hash) Estimated App Store file sizes for all devices in bytes attr_accessor :sizes_in_bytes_with_device_loc # @return (Boolean) Contains On Demand Resources # @example false attr_accessor :contains_odr # @return (Integer) Number of Asset packs # @example 0 attr_accessor :number_of_asset_packs # @return (Boolean) Includes Symbols # @example true attr_accessor :include_symbols # @return (Boolean) App Uses Non-Exempt Encryption (Optional) # @example null attr_accessor :use_encryption_in_plist # @return (Boolean) App Encryption Export Compliance Code (Optional) # @example null attr_accessor :export_compliance_code_value_in_plist # @return (Boolean) Includes Stickers # @example false attr_accessor :has_stickers # @return (Boolean) Includes iMessage App # @example false attr_accessor :has_messages_extension # @return (Boolean) // Not sure what this is for # @example false attr_accessor :launch_prohibited # @return (Boolean) Uses SiriKit # @example false attr_accessor :uses_synapse # @return (Boolean) App uses Location Services # @example false attr_accessor :uses_location_background_mode # @return (String) Link to the dSYM file (not always available) # @example build/***.****.*****.*****-1.0.0-2647.dSYM.zip attr_accessor :dsym_url # @return (Boolean) Watch-Only App # @example false attr_accessor :watch_only attr_mapping( 'apple_id' => :apple_id, 'uploadDate' => :upload_date, 'binaryState' => :binary_state, 'fileName' => :file_name, 'buildSdk' => :build_sdk, 'buildPlatform' => :build_platform, 'bundleId' => :bundle_id, 'appName' => :app_name, 'supportedArchitectures' => :supported_architectures, 'localizations' => :localizations, 'newsstandApp' => :newsstand_app, 'prerenderedIconFlag' => :prerendered_icon_flag, 'entitlements' => :entitlements, 'appPlatform' => :app_platform, 'deviceProtocols' => :device_protocols, 'cfBundleVersion' => :cf_bundle_version, 'cfBundleShortVersion' => :cf_bundle_short_version, 'minOsVersion' => :min_os_version, 'deviceFamilies' => :device_families, 'capabilities' => :capabilities, 'sizeInBytes' => :size_in_bytes, 'sizesInBytes' => :sizes_in_bytes, 'sizesInBytesWithDeviceLoc' => :sizes_in_bytes_with_device_loc, 'containsODR' => :contains_odr, 'numberOfAssetPacks' => :number_of_asset_packs, 'includesSymbols' => :include_symbols, 'useEncryptionInPlist' => :use_encryption_in_plist, 'exportComplianceCodeValueInPlist' => :export_compliance_code_value_in_plist, 'hasStickers' => :has_stickers, 'hasMessagesExtension' => :has_messages_extension, 'launchProhibited' => :launch_prohibited, 'usesSynapse' => :uses_synapse, 'usesLocationBackgroundMode' => :uses_location_background_mode, 'dsymurl' => :dsym_url, 'watchOnly' => :watch_only ) 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/tunes/members.rb
spaceship/lib/spaceship/tunes/members.rb
require_relative 'member' module Spaceship module Tunes class Members < TunesBase class << self def all response = client.members return_members = [] response.each do |member| return_members << Tunes::Member.factory(member) end return_members end def find(email) all.each do |member| if member.email_address.casecmp?(email) return member end end return nil end def create!(firstname: nil, lastname: nil, email_address: nil, roles: [], apps: []) client.create_member!(firstname: firstname, lastname: lastname, email_address: email_address, roles: roles, apps: apps) end def update_member_roles!(member, roles: [], apps: []) client.update_member_roles!(member, roles: roles, apps: apps) 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/tunes/build.rb
spaceship/lib/spaceship/tunes/build.rb
require_relative 'build_details' module Spaceship module Tunes # Represents a build which is inside the build train class Build < TunesBase ##################################################### # @!group General metadata ##################################################### # @return (String) The App identifier of this app, provided by App Store Connect # @example # "1013943394" attr_accessor :apple_id # @return (Spaceship::Tunes::BuildTrain) A reference to the build train this build is contained in attr_accessor :build_train # @return (Integer) The ID generated by App Store Connect attr_accessor :id # @return (Boolean) attr_accessor :valid # @return (String) The build version (not the version number), but also is named `build number` attr_accessor :build_version # @return (String) The version number (e.g. 1.3) attr_accessor :train_version # @return (Boolean) Is this build currently processing? attr_accessor :processing # @return (String) The build processing state, may be nil # @example "invalidBinary" # @example "processingFailed" attr_accessor :processing_state # @return (Integer) The number of ticks since 1970 (e.g. 1413966436000) attr_accessor :upload_date # @return (String) URL to the app icon of this build (150x150px) attr_accessor :icon_url # @return (String) The name of the app this build is for attr_accessor :app_name # @return (String) The platform of this build (e.g. 'ios') attr_accessor :platform # @return (Integer) When is this build going to be invalid attr_accessor :internal_expiry_date # @return (Integer): When is the external build going to expire? attr_accessor :external_expiry_date # @return (Bool) Is external beta testing enabled for this train? Only one train can have enabled testing. attr_reader :external_testing_enabled # @return (Bool) Is internal beta testing enabled for this train? Only one train can have enabled testing. attr_reader :internal_testing_enabled # @return (String) The status of internal testflight testing for this build. One of active, submitForReview, approvedInactive, waiting attr_reader :external_testing_status # @return (Bool) Does this build support WatchKit? attr_accessor :watch_kit_enabled # @return (Bool): attr_accessor :ready_to_install ##################################################### # @!group Analytics ##################################################### # @return (Integer) Number of installs of this build attr_accessor :install_count # @return (Integer) Number of installs for this build that come from internal users attr_accessor :internal_install_count # @return (Integer) Number of installs for this build that come from external users attr_accessor :external_install_count # @return (Integer) Might be nil. The number of sessions for this build attr_accessor :session_count # @return (Integer) Might be nil. The number of crashes of this build attr_accessor :crash_count attr_mapping( 'uploadDate' => :upload_date, 'iconUrl' => :icon_url, 'buildVersion' => :build_version, 'trainVersion' => :train_version, 'appName' => :app_name, 'platform' => :platform, 'id' => :id, 'valid' => :valid, 'processing' => :processing, 'processingState' => :processing_state, 'installCount' => :install_count, 'internalInstallCount' => :internal_install_count, 'externalInstallCount' => :external_install_count, 'sessionCount' => :session_count, 'crashCount' => :crash_count, 'internalExpiry' => :internal_expiry_date, 'externalExpiry' => :external_expiry_date, 'watchKitEnabled' => :watch_kit_enabled, 'readyToInstall' => :ready_to_install, 'internalTesting.value' => :internal_testing_enabled, 'externalTesting.value' => :external_testing_enabled, 'buildTestInformationTO.externalStatus' => :external_testing_status ) def setup super self.external_expiry_date ||= 0 self.internal_expiry_date ||= 0 end def details response = client.build_details(app_id: self.apple_id, train: self.train_version, build_number: self.build_version, platform: self.platform) response['apple_id'] = self.apple_id BuildDetails.factory(response) end def apple_id return @apple_id if @apple_id return self.build_train.application.apple_id end def update_build_information!(whats_new: nil, description: nil, feedback_email: nil) parameters = { app_id: self.apple_id, train: self.train_version, build_number: self.build_version, platform: self.platform }.merge({ whats_new: whats_new, description: description, feedback_email: feedback_email }) client.update_build_information!(parameters) end # This will submit this build for TestFlight beta review # @param metadata [Hash] A hash containing the following information (keys must be symbols): # { # # Required Metadata: # changelog: "Changelog", # description: "Your Description", # feedback_email: "Email Address for Feedback", # marketing_url: "https://marketing.com", # first_name: "Felix", # last_name: "Krause", # review_email: "Contact email address for Apple", # phone_number: "0128383383", # review_notes: "Review notes" # # # Optional Metadata: # privacy_policy_url: nil, # review_notes: nil, # review_user_name: nil, # review_password: nil, # encryption: false # } # Note that iTC will pull a lot of this information from previous builds or the app store information, # all of the required values must be set either in this hash or automatically for this to work def submit_for_beta_review!(metadata) parameters = { app_id: self.apple_id, train: self.train_version, build_number: self.build_version, platform: self.platform }.merge(metadata) client.submit_testflight_build_for_review!(parameters) return parameters end # @return [String] A nicely formatted string about the state of this build # @examples: # External, Internal, Inactive, Expired def testing_status testing ||= "External" if self.external_testing_enabled testing ||= "Internal" if self.internal_testing_enabled if Time.at(self.internal_expiry_date / 1000) > Time.now testing ||= "Inactive" else testing = "Expired" end return testing end # This will cancel the review process for this TestFlight build def cancel_beta_review! client.remove_testflight_build_from_review!(app_id: self.apple_id, train: self.train_version, build_number: self.build_version, platform: self.platform) end end end end # Example Response # {"sectionErrorKeys"=>[], # "sectionInfoKeys"=>[], # "sectionWarningKeys"=>[], # "buildVersion"=>"1", # "trainVersion"=>"1.0", # "uploadDate"=>1441975590000, # "iconUrl"=> # "https://is2-ssl.mzstatic.com/image/thumb/Newsstand3/v4/a9/f9/8b/a9f98b23-592d-af2e-6e10-a04873bed5df/Icon-76@2x.png.png/150x150bb-80.png", # "iconAssetToken"=> # "Newsstand3/v4/a9/f9/8b/a9f98b23-592d-af2e-6e10-a04873bed5df/Icon-76@2x.png.png", # "appName"=>"Updated by fastlane", # "platform"=>"ios", # "betaEntitled"=>true, # "exceededFileSizeLimit"=>false, # "wentLiveWithVersion"=>false, # "processing"=>false, # "processingState": nil, # "id"=>5298023, # "valid"=>true, # "missingExportCompliance"=>false, # "waitingForExportComplianceApproval"=>false, # "addedInternalUsersCount"=>0, # "addedExternalUsersCount"=>0, # "invitedExternalUsersCount"=>0, # "invitedInternalUsersCount"=>0, # "acceptedInternalUsersCount"=>1, # "acceptedExternalUsersCount"=>0, # "installCount"=>0, # "internalInstallCount"=>0, # "externalInstallCount"=>0, # "sessionCount"=>0, # "internalSessionCount"=>0, # "externalSessionCount"=>0, # "crashCount"=>0, # "internalCrashCount"=>0, # "externalCrashCount"=>0, # "promotedVersion"=>nil, # "internalState"=>"inactive", # "betaState"=>"submitForReview", # "internalExpiry"=>1444567590000, # "externalExpiry"=>0, # "watchKitEnabled"=>false, # "readyToInstall"=>true, # "sdkBuildWhitelisted"=>true, # "internalTesting"=>{"value"=>false, "isEditable"=>true, "isRequired"=>false, "errorKeys"=>nil}, # "externalTesting"=>{"value"=>false, "isEditable"=>true, "isRequired"=>false, "errorKeys"=>nil}
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/transit_app_file.rb
spaceship/lib/spaceship/tunes/transit_app_file.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents a geo json class TransitAppFile < TunesBase attr_accessor :asset_token attr_accessor :name attr_accessor :time_stamp attr_accessor :url attr_mapping( 'assetToken' => :asset_token, 'timeStemp' => :time_stamp, 'url' => :url, 'name' => :name ) 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/tunes/app_version_promocodes.rb
spaceship/lib/spaceship/tunes/app_version_promocodes.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents the information about remaining number of promo codes for an app version class AppVersionPromocodes < TunesBase # @return attr_reader :app_id attr_reader :app_name attr_reader :version attr_reader :platform attr_reader :number_of_codes attr_reader :maximum_number_of_codes attr_reader :contract_file_name attr_mapping({ 'id' => :app_id, 'appName' => :app_name, 'version' => :version, 'platform' => :platform, 'numberOfCodes' => :number_of_codes, 'maximumNumberOfCodes' => :maximum_number_of_codes, 'contractFileName' => :contract_file_name }) 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/tunes/tunes_base.rb
spaceship/lib/spaceship/tunes/tunes_base.rb
require_relative '../base' module Spaceship module Tunes class TunesBase < Spaceship::Base class << self def client ( @client or Spaceship::Tunes.client or raise "Please login using `Spaceship::Tunes.login('user', 'password')`" ) 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/tunes/iap_status.rb
spaceship/lib/spaceship/tunes/iap_status.rb
module Spaceship module Tunes # Defines the different states of an in-app purchase # # As specified by Apple: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/WorkingWithYourProductsStatus.html module IAPStatus # IAP created, but missing screenshot/metadata MISSING_METADATA = "Missing Metadata" # You can edit the metadata, change screenshot and more. Need to submit. READY_TO_SUBMIT = "Ready to Submit" # Waiting for Apple's Review WAITING_FOR_REVIEW = "Waiting For Review" # Currently in Review IN_REVIEW = "In Review" # Approved (and currently available) APPROVED = "Approved" # Developer deleted DELETED = "Deleted" # In-app purchase rejected for whatever reason REJECTED = "Rejected" # The developer took the app from the App Store DEVELOPER_REMOVED_FROM_SALE = "Developer Removed From Sale" # In-app purchase need developer's action DEVELOPER_ACTION_NEEDED = "Developer Action Needed" # Get the iap status matching based on a string (given by App Store Connect) def self.get_from_string(text) mapping = { 'missingMetadata' => MISSING_METADATA, 'readyToSubmit' => READY_TO_SUBMIT, 'waitingForReview' => WAITING_FOR_REVIEW, 'inReview' => IN_REVIEW, 'readyForSale' => APPROVED, 'deleted' => DELETED, 'rejected' => REJECTED, 'developerRemovedFromSale' => DEVELOPER_REMOVED_FROM_SALE, 'developerActionNeeded' => DEVELOPER_ACTION_NEEDED } mapping.each do |itc_status, readable_status| return readable_status if itc_status == text end return nil 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/tunes/iap_subscription_pricing_tier.rb
spaceship/lib/spaceship/tunes/iap_subscription_pricing_tier.rb
require_relative 'iap_subscription_pricing_info' module Spaceship module Tunes class IAPSubscriptionPricingTier < TunesBase # @return (String) Number of the subscription price tier (e.g. "1" for Tier 1 ) attr_accessor :tier_stem # @return (String) Name of the tier (e.g. "ITC.addons.pricing.tier.1" for Tier 1) attr_accessor :tier_name # @return ([Spaceship::Tunes::IAPSubscriptionPricingInfo]) A list of all prices for the respective countries attr_accessor :pricing_info attr_mapping( "tierStem" => :tier_stem, "tierName" => :tier_name ) def pricing_info @pricing_info ||= raw_data['pricingInfo'].map { |info| IAPSubscriptionPricingInfo.new(info) } 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/tunes/iap_list.rb
spaceship/lib/spaceship/tunes/iap_list.rb
require_relative 'iap_detail' require_relative 'iap_status' require_relative 'iap_type' module Spaceship module Tunes class IAPList < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # @return (String) the IAP Referencename attr_accessor :reference_name # @return (String) the IAP Product-Id attr_accessor :product_id # @return (String) Family Reference Name attr_accessor :family_reference_name attr_accessor :duration_days attr_accessor :versions attr_accessor :purple_apple_id attr_accessor :last_modified_date attr_accessor :is_news_subscription attr_accessor :number_of_codes attr_accessor :maximum_number_of_codes attr_accessor :app_maximum_number_of_codes attr_accessor :is_editable attr_accessor :is_required attr_accessor :can_delete_addon attr_mapping({ 'adamId' => :purchase_id, 'referenceName' => :reference_name, 'familyReferenceName' => :family_reference_name, 'vendorId' => :product_id, 'durationDays' => :duration_days, 'versions' => :versions, 'purpleSoftwareAdamIds' => :purple_apple_id, 'lastModifiedDate' => :last_modified_date, 'isNewsSubscription' => :is_news_subscription, 'numberOfCodes' => :number_of_codes, 'maximumNumberOfCodes' => :maximum_number_of_codes, 'appMaximumNumberOfCodes' => :app_maximum_number_of_codes, 'isEditable' => :is_editable, 'isRequired' => :is_required, 'canDeleteAddOn' => :can_delete_addon }) def type Tunes::IAPType.get_from_string(raw_data["addOnType"]) end def status Tunes::IAPStatus.get_from_string(raw_data["iTunesConnectStatus"]) end def edit attrs = client.load_iap(app_id: application.apple_id, purchase_id: self.purchase_id) attrs[:application] = application if attrs["addOnType"] == Spaceship::Tunes::IAPType::RECURRING raw_pricing_data = client.load_recurring_iap_pricing(app_id: application.apple_id, purchase_id: self.purchase_id) attrs["pricingData"] = raw_pricing_data end Tunes::IAPDetail.new(attrs) end def delete! client.delete_iap!(app_id: application.apple_id, purchase_id: self.purchase_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/tunes/language_converter.rb
spaceship/lib/spaceship/tunes/language_converter.rb
require_relative '../module' module Spaceship module Tunes class LanguageConverter class << self # Converts the iTC format (English_CA, Brazilian Portuguese) to language short codes: (en-US, de-DE) def from_itc_to_standard(from) result = mapping.find { |a| a['name'] == from } (result || {}).fetch('locale', nil) end # Converts the Language "UK English" to itc locale en-GB def from_standard_to_itc_locale(from) result = mapping.find { |a| a['name'] == from } || {} return result['itc_locale'] || result['locale'] end # Converts the language short codes: (en-US, de-DE) to the iTC format (English_CA, Brazilian Portuguese) def from_standard_to_itc(from) result = mapping.find { |a| a['locale'] == from || (a['alternatives'] || []).include?(from) } (result || {}).fetch('name', nil) end # Converts the language "UK English" (user facing) to "English_UK" (value) def from_itc_readable_to_itc(from) readable_mapping.each do |key, value| return key if value == from end nil end # Converts the language "English_UK" (value) to "UK English" (user facing) def from_itc_to_itc_readable(from) readable_mapping[from] end private # Get the mapping JSON parsed def mapping @languages ||= JSON.parse(File.read(File.join(Spaceship::ROOT, "lib", "assets", "languageMapping.json"))) end def readable_mapping @readable ||= JSON.parse(File.read(File.join(Spaceship::ROOT, "lib", "assets", "languageMappingReadable.json"))) end end end end end class String def to_language_code Spaceship::Tunes::LanguageConverter.from_itc_to_standard(self) end def to_itc_locale Spaceship::Tunes::LanguageConverter.from_standard_to_itc_locale(self) end def to_full_language Spaceship::Tunes::LanguageConverter.from_standard_to_itc(self) end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/availability.rb
spaceship/lib/spaceship/tunes/availability.rb
require_relative 'territory' require_relative 'b2b_user' require_relative 'b2b_organization' module Spaceship module Tunes class Availability < TunesBase # @return (Bool) Are future territories included? attr_accessor :include_future_territories # @return (Array of Spaceship::Tunes::Territory objects) A list of the territories attr_accessor :territories # @return (Bool) Cleared for preorder attr_accessor :cleared_for_preorder # @return (String) App available date in format of "YYYY-MM-DD" attr_accessor :app_available_date # @return (Bool) app enabled for b2b users attr_accessor :b2b_app_enabled # @return (Bool) app enabled for educational discount attr_accessor :educational_discount # @return (Bool) b2b available for distribution attr_accessor :b2b_unavailable # @return (Array of Spaceship::Tunes::B2bUser objects) A list of users attr_accessor :b2b_users # @return (Array of Spaceship::Tunes::B2bOrganization objects) A list of b2b orgs attr_accessor :b2b_organizations attr_mapping( 'theWorld' => :include_future_territories, 'preOrder.clearedForPreOrder.value' => :cleared_for_preorder, 'preOrder.appAvailableDate.value' => :app_available_date, 'b2BAppFlagDisabled' => :b2b_unavailable ) # Create a new object based on a set of territories. # This will override any values already set for cleared_for_preorder, app_available_date, b2b_unavailable, # b2b_app_enabled, and educational_discount # @param territories (Array of String or Spaceship::Tunes::Territory objects): A list of the territories # @param params (Hash): Optional parameters (include_future_territories (Bool, default: true) Are future territories included?) def self.from_territories(territories = [], params = {}) # Initializes the DataHash with our preOrder structure so values # that are being modified will be saved # # Note: A better solution for this in the future might be to improve how # Base::DataHash sets values for paths that don't exist obj = self.new( 'preOrder' => { 'clearedForPreOrder' => { 'value' => false }, 'appAvailableDate' => { 'value' => nil } } ) # Detect if the territories attribute is an array of Strings and convert to Territories obj.territories = if territories[0].kind_of?(String) territories.map { |territory| Spaceship::Tunes::Territory.from_code(territory) } else territories end obj.include_future_territories = params.fetch(:include_future_territories, true) obj.cleared_for_preorder = params.fetch(:cleared_for_preorder, false) obj.app_available_date = params.fetch(:app_available_date, nil) obj.b2b_unavailable = params.fetch(:b2b_unavailable, false) obj.b2b_app_enabled = params.fetch(:b2b_app_enabled, false) obj.educational_discount = params.fetch(:educational_discount, true) return obj end def territories @territories ||= raw_data['countries'].map { |info| Territory.new(info) } end def b2b_users @b2b_users || raw_data['b2bUsers'].map { |user| B2bUser.new(user) } end def b2b_organizations @b2b_organizations || raw_data['b2bOrganizations'].map { |user| B2bOrganization.new(user) } end def b2b_app_enabled @b2b_app_enabled.nil? ? raw_data['b2bAppEnabled'] : @b2b_app_enabled end def educational_discount @educational_discount.nil? ? raw_data['educationalDiscount'] : @educational_discount end def cleared_for_preorder super || false end # Sets `b2b_app_enabled` to true and `educational_discount` to false # Requires users to be added with `add_b2b_users` otherwise `update_availability` will error def enable_b2b_app! raise "Not possible to enable b2b on this app" if b2b_unavailable @b2b_app_enabled = true # need to set the educational discount to false @educational_discount = false return self end # Adds users for b2b enabled apps def add_b2b_users(user_list = []) raise "Cannot add b2b users if b2b is not enabled" unless b2b_app_enabled @b2b_users = user_list.map { |user| B2bUser.from_username(user) } return self end # Updates users for b2b enabled apps def update_b2b_users(user_list = []) raise "Cannot add b2b users if b2b is not enabled" unless b2b_app_enabled added_users = b2b_users.map(&:ds_username) # Returns if list is unchanged return self if (added_users - user_list) == (user_list - added_users) users_to_add = user_list.reject { |user| added_users.include?(user) } users_to_remove = added_users.reject { |user| user_list.include?(user) } @b2b_users = b2b_users.reject { |user| users_to_remove.include?(user.ds_username) } @b2b_users.concat(users_to_add.map { |user| B2bUser.from_username(user) }) @b2b_users.concat(users_to_remove.map { |user| B2bUser.from_username(user, is_add_type: false) }) return self end # Updates users for b2b enabled apps def update_dep_organizations(organization_list = []) raise "Cannot add dep organizations if b2b is not enabled" unless b2b_app_enabled added_orgs = b2b_organizations # Returns if list is unchanged return self if (added_orgs - organization_list) == (organization_list - added_orgs) orgs_to_add = organization_list.reject { |organization| added_orgs.include?(organization) } orgs_to_remove = added_orgs.nil? ? organization_list : added_orgs.reject { |organization| organization_list.include?(organization) } @b2b_organizations = b2b_organizations.reject { |organization| orgs_to_remove.include?(organization) } @b2b_organizations.concat(orgs_to_add) @b2b_organizations.concat(orgs_to_remove.map do |organization| B2bOrganization.from_id_info(dep_id: organization.dep_customer_id, dep_name: organization.name, dep_org_id: organization.dep_organization_id, type: false) end) return self 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/tunes/legacy_wrapper.rb
spaceship/lib/spaceship/tunes/legacy_wrapper.rb
require_relative 'app_version' require_relative 'app_submission' require_relative 'application' require_relative 'members' require_relative '../portal/persons' module Spaceship AppVersion = Spaceship::Tunes::AppVersion AppSubmission = Spaceship::Tunes::AppSubmission Application = Spaceship::Tunes::Application Members = Spaceship::Tunes::Members Persons = Spaceship::Portal::Persons end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/iap_subscription_pricing_info.rb
spaceship/lib/spaceship/tunes/iap_subscription_pricing_info.rb
require_relative 'tunes_base' module Spaceship module Tunes class IAPSubscriptionPricingInfo < TunesBase # @return (String) country code, e.g. "US" attr_accessor :country_code # @return (String) currency symbol, e.g. "$" attr_accessor :currency_symbol # @return (String) currency code, e.g. "USD" attr_accessor :currency_code # @return (Number) net proceedings for the developer in the first year attr_accessor :wholesale_price # @return (Number) net proceedings for the developer after the first year attr_accessor :wholesale_price2 # @return (Number) customer price attr_accessor :retail_price # @return (String) formatted customer price, e.g. "$0.00" attr_accessor :f_retail_price # @return (String) formatted net proceedings in the first year, e.g. "$0.00" attr_accessor :f_wholesale_price # @return (String) formatted net proceedings after the first year, e.g. "$0.00" attr_accessor :f_wholesale_price2 attr_mapping( "countryCode" => :country_code, "currencySymbol" => :currency_symbol, "currencyCode" => :currency_code, "wholesalePrice" => :wholesale_price, "wholesalePrice2" => :wholesale_price2, "retailPrice" => :retail_price, "fRetailPrice" => :f_retail_price, "fWholesalePrice" => :f_wholesale_price, "fWholesalePrice2" => :f_wholesale_price2 ) 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/tunes/b2b_user.rb
spaceship/lib/spaceship/tunes/b2b_user.rb
require_relative 'tunes_base' module Spaceship module Tunes class B2bUser < TunesBase # @return (Bool) add the user to b2b list attr_accessor :add # @return (Bool) delete the user to b2b list attr_accessor :delete # @return (String) b2b username attr_accessor :ds_username attr_mapping( 'value.add' => :add, 'value.delete' => :delete, 'value.dsUsername' => :ds_username ) def self.from_username(username, is_add_type: true) self.new({ 'value' => { 'add' => is_add_type, 'delete' => !is_add_type, 'dsUsername' => username } }) end # equality check for the two objects def ==(other) add == other.add && delete == other.delete && ds_username == other.ds_username 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/tunes/iap_type.rb
spaceship/lib/spaceship/tunes/iap_type.rb
module Spaceship module Tunes # Defines the different in-app purchase product types # # As specified by Apple: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/CreatingInAppPurchaseProducts.html module IAPType CONSUMABLE = "consumable" NON_CONSUMABLE = "nonConsumable" RECURRING = "recurring" NON_RENEW_SUBSCRIPTION = "subscription" # A product that is used once READABLE_CONSUMABLE = "Consumable" # A product that is purchased once and does not expire or decrease with use. READABLE_NON_CONSUMABLE = "Non-Consumable" # A product that allows users to purchase dynamic content for a set period (auto-rene). READABLE_AUTO_RENEWABLE_SUBSCRIPTION = "Auto-Renewable Subscription" # A product that allows users to purchase a service with a limited duration. READABLE_NON_RENEWING_SUBSCRIPTION = "Non-Renewing Subscription" # Get the iap type matching based on a string (given by App Store Connect) def self.get_from_string(text) mapping = { 'ITC.addons.type.consumable' => READABLE_CONSUMABLE, 'ITC.addons.type.nonConsumable' => READABLE_NON_CONSUMABLE, 'ITC.addons.type.recurring' => READABLE_AUTO_RENEWABLE_SUBSCRIPTION, 'ITC.addons.type.subscription' => READABLE_NON_RENEWING_SUBSCRIPTION, 'consumable' => READABLE_CONSUMABLE, 'nonConsumable' => READABLE_NON_CONSUMABLE, 'recurring' => READABLE_AUTO_RENEWABLE_SUBSCRIPTION, 'subscription' => READABLE_NON_RENEWING_SUBSCRIPTION } mapping.each do |itc_type, readable_type| return readable_type if itc_type == text end return nil 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/tunes/app_version_common.rb
spaceship/lib/spaceship/tunes/app_version_common.rb
module Spaceship module Tunes # internal to spaceship # Represents the common structure between application['versionSets'] and app_version['platform'] class AppVersionCommon class << self def find_version_id(platform, is_live) version = platform[(is_live ? 'deliverableVersion' : 'inFlightVersion')] return nil unless version version['id'] end def find_platform(versions, search_platform: nil) # We only support platforms that exist ATM search_platform = search_platform.to_sym if search_platform platform = versions.detect do |p| ['ios', 'osx', 'appletvos'].include?(p['platformString']) end raise "Could not find platform 'ios', 'osx' or 'appletvos'" unless platform # If your app has versions for both iOS and tvOS we will default to returning the iOS version for now. # This is intentional as we need to do more work to support apps that have hybrid versions. if versions.length > 1 && search_platform.nil? platform = versions.detect { |p| p['platformString'].to_sym == :ios } elsif !search_platform.nil? platform = versions.detect { |p| p['platformString'].to_sym == search_platform } end platform 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/tunes/iap.rb
spaceship/lib/spaceship/tunes/iap.rb
require 'spaceship/tunes/errors' require 'spaceship/tunes/iap_list' require 'spaceship/tunes/iap_detail' require 'spaceship/tunes/iap_status' require 'spaceship/tunes/iap_type' require 'spaceship/tunes/iap_family_list' require 'spaceship/tunes/iap_families' require 'spaceship/tunes/iap_family_details' require 'spaceship/tunes/iap_families' require 'spaceship/tunes/iap_subscription_pricing_tier' module Spaceship module Tunes class IAP < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # @return (Spaceship::Tunes::IAPFamilies) A reference to the family list def families attrs = {} attrs[:application] = self.application Tunes::IAPFamilies.new(attrs) end # Creates a new In-App-Purchase on App Store Connect # if the In-App-Purchase already exists an exception is raised. Spaceship::TunesClient::ITunesConnectError # @param type (String): The Type of the in-app-purchase (Spaceship::Tunes::IAPType::CONSUMABLE,Spaceship::Tunes::IAPType::NON_CONSUMABLE,Spaceship::Tunes::IAPType::RECURRING,Spaceship::Tunes::IAPType::NON_RENEW_SUBSCRIPTION) # @param versions (Hash): a Hash of the languages # @example: { # 'de-DE': { # name: "Name shown in AppStore", # description: "Description of the In app Purchase" # # } # } # @param reference_name (String): iTC Reference Name # @param product_id (String): A unique ID for your in-app-purchase # @param bundle_id (String): The bundle ID must match the one you used in Xcode. It # @param cleared_for_sale (Boolean): Is this In-App-Purchase Cleared for Sale # @param review_notes (String): Review Notes # @param review_screenshot (String): Path to the screenshot (should be 640x940 PNG) # @param pricing_intervals (Hash): a Hash of the languages # @example: # [ # { # country: "WW", # begin_date: nil, # end_date: nil, # tier: 1 # } # ] # @param family_id (String) Only used on RECURRING purchases, assigns the In-App-Purchase to a specific family # @param subscription_free_trial (String) Free Trial duration (1w,1m,3m....) # @param subscription_duration (String) 1w,1m..... # @param subscription_price_target (Hash) Only used on RECURRING purchases, used to set the # price of all the countries to be roughly the same as the price calculated from the price # tier and currency given as input. # @example: # { # currency: "EUR", # tier: 2 # } def create!(type: "consumable", versions: nil, reference_name: nil, product_id: nil, cleared_for_sale: true, merch_screenshot: nil, review_notes: nil, review_screenshot: nil, pricing_intervals: nil, family_id: nil, subscription_free_trial: nil, subscription_duration: nil, subscription_price_target: nil) client.create_iap!(app_id: self.application.apple_id, type: type, versions: versions, reference_name: reference_name, product_id: product_id, cleared_for_sale: cleared_for_sale, merch_screenshot: merch_screenshot, review_notes: review_notes, review_screenshot: review_screenshot, pricing_intervals: pricing_intervals, family_id: family_id, subscription_duration: subscription_duration, subscription_free_trial: subscription_free_trial) # Update pricing for a recurring subscription. if type == Spaceship::Tunes::IAPType::RECURRING && (pricing_intervals || subscription_price_target) # There are cases where the product that was just created is not immediately found, # and in order to update its pricing the purchase_id is needed. Therefore polling is done # for 4 times until it is found. If it's not found after 6 tries, a PotentialServerError # exception is raised. product = find_product_with_retries(product_id, 6) raw_pricing_intervals = client.transform_to_raw_pricing_intervals(application.apple_id, product.purchase_id, pricing_intervals, subscription_price_target) client.update_recurring_iap_pricing!(app_id: self.application.apple_id, purchase_id: product.purchase_id, pricing_intervals: raw_pricing_intervals) end end # return all available In-App-Purchase's of current app # this is not paged inside iTC-API so if you have a lot if IAP's (2k+) # it might take some time to load, same as it takes when you load the list via App Store Connect def all(include_deleted: false) r = client.iaps(app_id: self.application.apple_id) return_iaps = [] r.each do |product| attrs = product attrs[:application] = self.application loaded_iap = Tunes::IAPList.factory(attrs) next if loaded_iap.status == "deleted" && !include_deleted return_iaps << loaded_iap end return_iaps end # find a specific product # @param product_id (String) Product Id def find(product_id) all.each do |product| if product.product_id == product_id return product end end return nil end # generate app-specific shared secret (or regenerate if exists) def generate_shared_secret client.generate_shared_secret(app_id: self.application.apple_id) end # retrieve app-specific shared secret # @param create (Boolean) Create new shared secret if does not exist def get_shared_secret(create: false) secret = client.get_shared_secret(app_id: self.application.apple_id) if create && secret.nil? secret = generate_shared_secret end secret end private def find_product_with_retries(product_id, max_tries) try_number = 0 product = nil until product if try_number > max_tries raise PotentialServerError.new, "Failed to find the product with id=#{product_id}. "\ "This can be caused either by a server error or due to the removal of the product." end product = find(product_id) try_number += 1 end product 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/tunes/app_version_generated_promocodes.rb
spaceship/lib/spaceship/tunes/app_version_generated_promocodes.rb
require_relative 'app_version_promocodes' module Spaceship module Tunes # Represents the information about the generation of promocodes class AppVersionGeneratedPromocodes < TunesBase # @return attr_reader :effective_date attr_reader :expiration_date attr_reader :username # the AppVersionPromocodes this relates to attr_reader :version # Array of String attr_reader :codes attr_mapping({ 'effectiveDate' => :effective_date, 'expirationDate' => :expiration_date, 'username' => :username }) def setup @version = Tunes::AppVersionPromocodes.factory(raw_data['version']) @codes = raw_data['codes'] 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/tunes/app_version_history.rb
spaceship/lib/spaceship/tunes/app_version_history.rb
require_relative 'app_version_states_history' module Spaceship module Tunes # Represents a read only version of an App Store Connect Versions State History class AppVersionHistory < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this version is for attr_accessor :application # @return (String) The version in string format (e.g. "1.0") attr_reader :version_string # @return (String) The platform value of this version. attr_reader :version_id # @return ([Spaceship::Tunes::AppVersionStatesHistory]) the array of version states attr_reader :items attr_mapping({ 'versionString' => :version_string, 'versionId' => :version_id, 'items' => :items }) # Returns an array of all builds that can be sent to review def items @items ||= fetch_items end # Private methods def setup # Properly parse the AppStatus items = raw_data['items'] @items = map_items(items) if items end private def map_items(items) items.map do |attrs| Tunes::AppVersionStatesHistory.factory(attrs) end end def fetch_items items = client.version_states_history(application.apple_id, application.platform, version_id)['items'] map_items(items) 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/tunes/spaceship.rb
spaceship/lib/spaceship/tunes/spaceship.rb
require_relative 'tunes_client' module Spaceship module Tunes class << self # This client stores the default client when using the lazy syntax # Spaceship.app instead of using the spaceship launcher attr_accessor :client # 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) @client = TunesClient.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 # # @param team_id (String) (optional): The ID of an App Store Connect team # @param team_name (String) (optional): The name of an App Store Connect team def select_team(team_id: nil, team_name: nil) @client.select_team(team_id: 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/tunes/app_screenshot.rb
spaceship/lib/spaceship/tunes/app_screenshot.rb
require_relative 'app_image' module Spaceship module Tunes # Represents a screenshot hosted on App Store Connect class AppScreenshot < Spaceship::Tunes::AppImage attr_accessor :device_type attr_accessor :language 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/tunes/tunes_client.rb
spaceship/lib/spaceship/tunes/tunes_client.rb
require "securerandom" require_relative '../client' require_relative '../du/du_client' require_relative '../du/upload_file' require_relative 'app_version_common' require_relative 'app_version_ref' require_relative 'availability' require_relative 'errors' require_relative 'iap_subscription_pricing_tier' require_relative 'pricing_tier' require_relative 'territory' require_relative '../connect_api/response' module Spaceship # rubocop:disable Metrics/ClassLength class TunesClient < Spaceship::Client # Legacy support ITunesConnectError = Tunes::Error ITunesConnectTemporaryError = Tunes::TemporaryError ITunesConnectPotentialServerError = Tunes::PotentialServerError attr_reader :du_client def initialize super @du_client = DUClient.new # Used by most WebObjects requests starting in July 2021 @additional_headers = { 'x-csrf-itc': 'itc' } end class << self # trailer preview screenshots are required to have a specific size def video_preview_resolution_for(device, is_portrait) resolutions = { 'iphone4' => [1136, 640], 'iphone6' => [1334, 750], 'iphone6Plus' => [2208, 1242], 'iphone58' => [2436, 1125], 'iphone65' => [2688, 1242], 'ipad' => [1024, 768], 'ipad105' => [2224, 1668], 'ipadPro' => [2732, 2048], 'ipadPro11' => [2388, 1668], 'ipadPro129' => [2732, 2048] } r = resolutions[device] r = [r[1], r[0]] if is_portrait r end end ##################################################### # @!group Init and Login ##################################################### def self.hostname "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/" end # Shows a team selection for the user in the terminal. This should not be # called on CI systems # # @param team_id (String) (optional): The ID of an App Store Connect team # @param team_name (String) (optional): The name of an App Store Connect team def select_team(team_id: nil, team_name: nil) t_id = (team_id || ENV['FASTLANE_ITC_TEAM_ID'] || '').strip t_name = (team_name || ENV['FASTLANE_ITC_TEAM_NAME'] || '').strip if t_name.length > 0 && t_id.length.zero? # we prefer IDs over names, they are unique puts("Looking for App Store Connect Team with name #{t_name}") if Spaceship::Globals.verbose? teams.each do |t| t_id = t['providerId'].to_s if t['name'].casecmp(t_name).zero? end puts("Could not find team with name '#{t_name}', trying to fallback to default team") if t_id.length.zero? end t_id = teams.first['providerId'].to_s if teams.count == 1 if t_id.length > 0 puts("Looking for App Store Connect Team with ID #{t_id}") if Spaceship::Globals.verbose? # actually set the team id here self.team_id = t_id return self.team_id end # user didn't specify a team... #thisiswhywecanthavenicethings loop do puts("Multiple #{'App Store Connect teams'.yellow} found, please enter the number of the team you want to use: ") if ENV["FASTLANE_HIDE_TEAM_INFORMATION"].to_s.length == 0 first_team = teams.first puts("Note: to automatically choose the team, provide either the App Store Connect Team ID, or the Team Name in your fastlane/Appfile:") puts("Alternatively you can pass the team name or team ID using the `FASTLANE_ITC_TEAM_ID` or `FASTLANE_ITC_TEAM_NAME` environment variable") puts("") puts(" itc_team_id \"#{first_team['providerId']}\"") puts("") puts("or") puts("") puts(" itc_team_name \"#{first_team['name']}\"") puts("") end # We're not using highline here, as spaceship doesn't have a dependency to fastlane_core or highline teams.each_with_index do |team, i| puts("#{i + 1}) \"#{team['name']}\" (#{team['providerId']})") end unless Spaceship::Client::UserInterface.interactive? puts("Multiple teams found on App Store Connect, Your Terminal is running in non-interactive mode! Cannot continue from here.") puts("Please check that you set FASTLANE_ITC_TEAM_ID or FASTLANE_ITC_TEAM_NAME to the right value.") raise "Multiple App Store Connect Teams found; unable to choose, terminal not interactive!" end selected = ($stdin.gets || '').strip.to_i - 1 team_to_use = teams[selected] if selected >= 0 if team_to_use self.team_id = team_to_use['providerId'].to_s # actually set the team id here return self.team_id end end end def send_login_request(user, password) clear_user_cached_data result = send_shared_login_request(user, password) store_cookie return result end # Sometimes we get errors or info nested in our data # This method allows you to pass in a set of keys to check for # along with the name of the sub_section of your original data # where we should check # Returns a mapping of keys to data array if we find anything, otherwise, empty map def fetch_errors_in_data(data_section: nil, sub_section_name: nil, keys: nil) if data_section && sub_section_name sub_section = data_section[sub_section_name] else sub_section = data_section end unless sub_section return {} end error_map = {} keys.each do |key| errors = sub_section.fetch(key, []) error_map[key] = errors if errors.count > 0 end return error_map end # rubocop:disable Metrics/PerceivedComplexity # If the response is coming from a flaky api, set flaky_api_call to true so we retry a little. # Patience is a virtue. def handle_itc_response(raw, flaky_api_call: false) return unless raw return unless raw.kind_of?(Hash) data = raw['data'] || raw # sometimes it's with data, sometimes it isn't error_keys = ["sectionErrorKeys", "validationErrors", "serviceErrors"] info_keys = ["sectionInfoKeys", "sectionWarningKeys"] error_and_info_keys_to_check = error_keys + info_keys errors_in_data = fetch_errors_in_data(data_section: data, keys: error_and_info_keys_to_check) errors_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: error_and_info_keys_to_check) # If we have any errors or "info" we need to treat them as warnings or errors if errors_in_data.count == 0 && errors_in_version_info.count == 0 logger.debug("Request was successful") end # We pass on the `current_language` so that the error message tells the user # what language the error was caused in handle_response_hash = lambda do |hash, current_language = nil| errors = [] if hash.kind_of?(Hash) current_language ||= hash["language"] hash.each do |key, value| errors += handle_response_hash.call(value, current_language) next unless key == 'errorKeys' && value.kind_of?(Array) && value.count > 0 # Prepend the error with the language so it's easier to understand for the user errors += value.collect do |current_error_message| current_language ? "[#{current_language}]: #{current_error_message}" : current_error_message end end elsif hash.kind_of?(Array) hash.each do |value| errors += handle_response_hash.call(value) end # else: We don't care about simple values end return errors end errors = handle_response_hash.call(data) # Search at data level, as well as "versionInfo" level for errors errors_in_data = fetch_errors_in_data(data_section: data, keys: error_keys) errors_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: error_keys) errors += errors_in_data.values if errors_in_data.values errors += errors_in_version_info.values if errors_in_version_info.values errors = errors.flat_map { |value| value } # Sometimes there is a different kind of error in the JSON response # e.g. {"warn"=>nil, "error"=>["operation_failed"], "info"=>nil} different_error = raw.fetch('messages', {}).fetch('error', nil) errors << different_error if different_error if errors.count > 0 # they are separated by `.` by default # Sample `error` content: [["Forbidden"]] if errors.count == 1 && errors.first == "You haven't made any changes." # This is a special error which we really don't care about elsif errors.count == 1 && errors.first.include?("try again later") raise ITunesConnectTemporaryError.new, errors.first elsif errors.count == 1 && errors.first.include?("Forbidden") raise_insufficient_permission_error! elsif flaky_api_call raise ITunesConnectPotentialServerError.new, errors.join(' ') else raise ITunesConnectError.new, errors.join(' ') end end # Search at data level, as well as "versionInfo" level for info and warnings info_in_data = fetch_errors_in_data(data_section: data, keys: info_keys) info_in_version_info = fetch_errors_in_data(data_section: data, sub_section_name: "versionInfo", keys: info_keys) info_in_data.each do |info_key, info_value| puts(info_value) end info_in_version_info.each do |info_key, info_value| puts(info_value) end return data end # rubocop:enable Metrics/PerceivedComplexity ##################################################### # @!group Applications ##################################################### def applications # Doing this real bad puts for now until a more formal deprecation logic can get made puts("Spaceship::Tunes::Application.all is deprecated") puts(" It's using a temporary patch to keep it from raising an error but things may not work correctly") puts(" Please consider switching to Spaceship::ConnectAPI if you can") puts(" For more details - https://github.com/fastlane/fastlane/pull/20480") # This legacy endpoint went offline around July 7th, 2022. This is a rough attempt # at retrofitting using the newer App Store Connect API endpoints # # This could all be done easily with Spaceship::ConnectAPI::App.find but there were a lot of # circular dependency issues that were very difficult to solve because. Spaceship::Tunes would be # using Spaceship::ConnectAPI which uses Spaceship::Tunes # # However, using Spaceship::ConnectAPI::Response works. This will fetch multiple pages of app # if it needs to # # https://github.com/fastlane/fastlane/pull/20480 r = request(:get, "https://appstoreconnect.apple.com/iris/v1/apps?include=appStoreVersions") response = Spaceship::ConnectAPI::Response.new( body: r.body, status: r.status, headers: r.headers, client: nil ) apps = response.all_pages do |url| r = request(:get, url) Spaceship::ConnectAPI::Response.new( body: r.body, status: r.status, headers: r.headers, client: nil ) end.flat_map(&:to_models) apps.map do |asc_app| platforms = (asc_app.app_store_versions || []).map(&:platform).uniq.map do |asc_platform| case asc_platform when "TV_OS" "appletvos" when "MAC_OS" "osx" when "VISION_OS" "xros" when "IOS" "ios" else raise "Cannot find a matching platform for '#{asc_platform}'}" end end { 'adamId' => asc_app.id, 'name' => asc_app.name, 'vendorId' => "", 'bundleId' => asc_app.bundle_id, 'lastModifiedDate' => nil, 'issuesCount' => nil, 'iconUrl' => nil, 'versionSets' => platforms.map do |platform| { 'type' => 'app', 'platformString' => platform } end } end end def app_details(app_id) r = request(:get, "ra/apps/#{app_id}/details") parse_response(r, 'data') end def bundle_details(app_id) r = request(:get, "ra/appbundles/metadetail/#{app_id}") parse_response(r, 'data') end def update_app_details!(app_id, data) r = request(:post) do |req| req.url("ra/apps/#{app_id}/details") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end # Creates a new application on App Store Connect # @param name (String): The name of your app as it will appear on the App Store. # This can't be longer than 255 characters. # @param primary_language (String): If localized app information isn't available in an # App Store territory, the information from your primary language will be used instead. # @param version *DEPRECATED: Use `Spaceship::Tunes::Application.ensure_version!` method instead* # (String): The version number is shown on the App Store and should match the one you used in Xcode. # @param sku (String): A unique ID for your app that is not visible on the App Store. # @param bundle_id (String): The bundle ID must match the one you used in Xcode. It # can't be changed after you submit your first build. def create_application!(name: nil, primary_language: nil, version: nil, sku: nil, bundle_id: nil, bundle_id_suffix: nil, company_name: nil, platform: nil, platforms: nil, itunes_connect_users: nil) puts("The `version` parameter is deprecated. Use `Spaceship::Tunes::Application.ensure_version!` method instead") if version # First, we need to fetch the data from Apple, which we then modify with the user's values primary_language ||= "English" platform ||= "ios" r = request(:get, "ra/apps/create/v2/?platformString=#{platform}") data = parse_response(r, 'data') # Now fill in the values we have # some values are nil, that's why there is a hash data['name'] = { value: name } data['bundleId'] = { value: bundle_id } data['primaryLanguage'] = { value: primary_language } data['primaryLocaleCode'] = { value: primary_language.to_itc_locale } data['vendorId'] = { value: sku } data['bundleIdSuffix'] = { value: bundle_id_suffix } data['companyName'] = { value: company_name } if company_name data['enabledPlatformsForCreation'] = { value: [platform] } data['initialPlatform'] = platform data['enabledPlatformsForCreation'] = { value: platforms || [platform] } unless itunes_connect_users.nil? data['iTunesConnectUsers']['grantedAllUsers'] = false data['iTunesConnectUsers']['grantedUsers'] = data['iTunesConnectUsers']['availableUsers'].select { |user| itunes_connect_users.include?(user['username']) } end # Now send back the modified hash r = request(:post) do |req| req.url('ra/apps/create/v2') req.body = data.to_json req.headers['Content-Type'] = 'application/json' end data = parse_response(r, 'data') handle_itc_response(data) end def create_version!(app_id, version_number, platform = 'ios') r = request(:post) do |req| req.url("ra/apps/#{app_id}/platforms/#{platform}/versions/create/") req.body = { version: { value: version_number.to_s } }.to_json req.headers['Content-Type'] = 'application/json' end data = parse_response(r, 'data') handle_itc_response(data) end def get_available_bundle_ids(platform: nil) platform ||= "ios" r = request(:get, "ra/apps/create/v2/?platformString=#{platform}") data = parse_response(r, 'data') return data['bundleIds'].keys end def get_resolution_center(app_id, platform) r = request(:get, "ra/apps/#{app_id}/platforms/#{platform}/resolutionCenter?v=latest") parse_response(r, 'data') end def post_resolution_center(app_id, platform, thread_id, version_id, version_number, from, message_body) r = request(:post) do |req| req.url("ra/apps/#{app_id}/platforms/#{platform}/resolutionCenter") req.body = { appNotes: { threads: [{ id: thread_id, versionId: version_id, version: version_number, messages: [{ from: from, date: DateTime.now.strftime('%Q'), body: message_body, tokens: [] }] }] } }.to_json req.headers['Content-Type'] = 'application/json' end data = parse_response(r, 'data') handle_itc_response(data) end def get_ratings(app_id, platform, version_id = '', storefront = '') # if storefront or version_id is empty api fails rating_url = "ra/apps/#{app_id}/platforms/#{platform}/reviews/summary" params = {} params['storefront'] = storefront unless storefront.empty? params['version_id'] = version_id unless version_id.empty? r = request(:get, rating_url, params) parse_response(r, 'data') end def get_reviews(app_id, platform, storefront, version_id, upto_date = nil) index = 0 per_page = 100 # apple default all_reviews = [] upto_date = Time.parse(upto_date) unless upto_date.nil? loop do rating_url = "ra/apps/#{app_id}/platforms/#{platform}/reviews?" rating_url << "sort=REVIEW_SORT_ORDER_MOST_RECENT" rating_url << "&index=#{index}" rating_url << "&storefront=#{storefront}" unless storefront.empty? rating_url << "&versionId=#{version_id}" unless version_id.empty? r = request(:get, rating_url) all_reviews.concat(parse_response(r, 'data')['reviews']) # The following lines throw errors when there are no reviews so exit out of the loop before them if the app has no reviews break if all_reviews.count == 0 last_review_date = Time.at(all_reviews[-1]['value']['lastModified'] / 1000) if upto_date && last_review_date < upto_date all_reviews = all_reviews.select { |review| Time.at(review['value']['lastModified'] / 1000) > upto_date } break end if all_reviews.count < parse_response(r, 'data')['reviewCount'] index += per_page else break end end all_reviews end ##################################################### # @!group AppVersions ##################################################### def app_version(app_id, is_live, platform: nil) raise "app_id is required" unless app_id # First we need to fetch the IDs for the edit / live version r = request(:get, "ra/apps/#{app_id}/overview") platforms = parse_response(r, 'data')['platforms'] platform = Spaceship::Tunes::AppVersionCommon.find_platform(platforms, search_platform: platform) return nil unless platform version_id = Spaceship::Tunes::AppVersionCommon.find_version_id(platform, is_live) return nil unless version_id version_platform = platform['platformString'] app_version_data(app_id, version_platform: version_platform, version_id: version_id) end def app_version_data(app_id, version_platform: nil, version_id: nil) raise "app_id is required" unless app_id raise "version_platform is required" unless version_platform raise "version_id is required" unless version_id r = request(:get, "ra/apps/#{app_id}/platforms/#{version_platform}/versions/#{version_id}") parse_response(r, 'data') end def update_app_version!(app_id, version_id, data) raise "app_id is required" unless app_id raise "version_id is required" unless version_id.to_i > 0 with_tunes_retry do r = request(:post) do |req| req.url("ra/apps/#{app_id}/platforms/ios/versions/#{version_id}") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body, flaky_api_call: true) end end ##################################################### # @!group Members ##################################################### def members r = request(:get, "ra/users/itc") parse_response(r, 'data')["users"] end def reinvite_member(email) request(:post, "ra/users/itc/#{email}/resendInvitation") end def delete_member!(user_id, email) payload = [] payload << { dsId: user_id, email: email } request(:post) do |req| req.url("ra/users/itc/delete") req.body = payload.to_json req.headers['Content-Type'] = 'application/json' end end def create_member!(firstname: nil, lastname: nil, email_address: nil, roles: [], apps: []) r = request(:get, "ra/users/itc/create") data = parse_response(r, 'data') data["user"]["firstName"] = { value: firstname } data["user"]["lastName"] = { value: lastname } data["user"]["emailAddress"] = { value: email_address } roles << "admin" if roles.length == 0 data["user"]["roles"] = [] roles.each do |role| # find role from template data["roles"].each do |template_role| if template_role["value"]["name"] == role data["user"]["roles"] << template_role end end end if apps.length == 0 data["user"]["userSoftwares"] = { value: { grantAllSoftware: true, grantedSoftwareAdamIds: [] } } else data["user"]["userSoftwares"] = { value: { grantAllSoftware: false, grantedSoftwareAdamIds: apps } } end # send the changes back to Apple r = request(:post) do |req| req.url("ra/users/itc/create") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end def update_member_roles!(member, roles: [], apps: []) r = request(:get, "ra/users/itc/#{member.user_id}/roles") data = parse_response(r, 'data') roles << "admin" if roles.length == 0 data["user"]["roles"] = [] roles.each do |role| # find role from template data["roles"].each do |template_role| if template_role["value"]["name"] == role data["user"]["roles"] << template_role end end end if apps.length == 0 data["user"]["userSoftwares"] = { value: { grantAllSoftware: true, grantedSoftwareAdamIds: [] } } else data["user"]["userSoftwares"] = { value: { grantAllSoftware: false, grantedSoftwareAdamIds: apps } } end # send the changes back to Apple r = request(:post) do |req| req.url("ra/users/itc/#{member.user_id}/roles") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end ##################################################### # @!group AppAnalytics ##################################################### def time_series_analytics(app_ids, measures, start_time, end_time, frequency, view_by) data = { adamId: app_ids, dimensionFilters: [], endTime: end_time, frequency: frequency, group: group_for_view_by(view_by, measures), measures: measures, startTime: start_time } r = request(:post) do |req| req.url("https://appstoreconnect.apple.com/analytics/api/v1/data/time-series") req.body = data.to_json req.headers['Content-Type'] = 'application/json' req.headers['X-Requested-By'] = 'appstoreconnect.apple.com' end data = parse_response(r) end ##################################################### # @!group Pricing ##################################################### def update_price_tier!(app_id, price_tier) r = request(:get, "ra/apps/#{app_id}/pricing/intervals") data = parse_response(r, 'data') # preOrder isn't needed for the request and has some # values that can cause a failure (invalid dates) so we are removing it data.delete('preOrder') first_price = (data["pricingIntervalsFieldTO"]["value"] || []).count == 0 # first price data["pricingIntervalsFieldTO"]["value"] ||= [] data["pricingIntervalsFieldTO"]["value"] << {} if data["pricingIntervalsFieldTO"]["value"].count == 0 data["pricingIntervalsFieldTO"]["value"].first["tierStem"] = price_tier.to_s effective_date = (first_price ? nil : Time.now.to_i * 1000) data["pricingIntervalsFieldTO"]["value"].first["priceTierEffectiveDate"] = effective_date data["pricingIntervalsFieldTO"]["value"].first["priceTierEndDate"] = nil data["countriesChanged"] = first_price data["theWorld"] = true if first_price # first price, need to set all countries data["countries"] = supported_countries.collect do |c| c.delete('region') # we don't care about le region c end end # send the changes back to Apple r = request(:post) do |req| req.url("ra/apps/#{app_id}/pricing/intervals") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end def transform_to_raw_pricing_intervals(app_id = nil, purchase_id = nil, pricing_intervals = 5, subscription_price_target = nil) intervals_array = [] if pricing_intervals intervals_array = 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 end if subscription_price_target pricing_calculator = iap_subscription_pricing_target(app_id: app_id, purchase_id: purchase_id, currency: subscription_price_target[:currency], tier: subscription_price_target[:tier]) intervals_array = pricing_calculator.map do |language_code, value| existing_interval = if pricing_intervals pricing_intervals.find { |interval| interval[:country] == language_code } end grandfathered = if existing_interval existing_interval[:grandfathered].clone else { "value" => "FUTURE_NONE" } end { "value" => { "tierStem" => value["tierStem"], "priceTierEffectiveDate" => value["priceTierEffectiveDate"], "priceTierEndDate" => value["priceTierEndDate"], "country" => language_code, "grandfathered" => grandfathered } } end end intervals_array end def price_tier(app_id) r = request(:get, "ra/apps/#{app_id}/pricing/intervals") data = parse_response(r, 'data') begin data["pricingIntervalsFieldTO"]["value"].first["tierStem"] rescue nil end end # Returns an array of all available pricing tiers # # @note Although this information is publicly available, the current spaceship implementation requires you to have a logged in client to access it # # @return [Array] the PricingTier objects (Spaceship::Tunes::PricingTier) # [{ # "tierStem": "0", # "tierName": "Free", # "pricingInfo": [{ # "country": "United States", # "countryCode": "US", # "currencySymbol": "$", # "currencyCode": "USD", # "wholesalePrice": 0.0, # "retailPrice": 0.0, # "fRetailPrice": "$0.00", # "fWholesalePrice": "$0.00" # }, { # ... # }, { # ... def pricing_tiers(app_id) @pricing_tiers ||= begin r = request(:get, "ra/apps/#{app_id}/iaps/pricing/matrix") data = parse_response(r, 'data')['pricingTiers'] data.map { |tier| Spaceship::Tunes::PricingTier.factory(tier) } end end ##################################################### # @!group Availability ##################################################### # Updates the availability # # @note Although this information is publicly available, the current spaceship implementation requires you to have a logged in client to access it # @param app_id (String): The id of your app # @param availability (Availability): The availability update # # @return [Spaceship::Tunes::Availability] the new Availability def update_availability!(app_id, availability) r = request(:get, "ra/apps/#{app_id}/pricing/intervals") data = parse_response(r, 'data') data["countriesChanged"] = true data["countries"] = availability.territories.map { |territory| { 'code' => territory.code } } data["theWorld"] = availability.include_future_territories.nil? ? true : availability.include_future_territories # InitializespreOrder (if needed) data["preOrder"] ||= {} # Sets app_available_date to nil if cleared_for_preorder if false # This is need for apps that have never set either of these before # API will error out if cleared_for_preorder is false and app_available_date has a date cleared_for_preorder = availability.cleared_for_preorder app_available_date = cleared_for_preorder ? availability.app_available_date : nil data["b2bAppEnabled"] = availability.b2b_app_enabled data["educationalDiscount"] = availability.educational_discount data["preOrder"]["clearedForPreOrder"] = { "value" => cleared_for_preorder, "isEditable" => true, "isRequired" => true, "errorKeys" => nil } data["preOrder"]["appAvailableDate"] = { "value" => app_available_date, "isEditable" => true, "isRequired" => true, "errorKeys" => nil } data["b2bUsers"] = availability.b2b_app_enabled ? availability.b2b_users.map { |user| { "value" => { "add" => user.add, "delete" => user.delete, "dsUsername" => user.ds_username } } } : [] data["b2bOrganizations"] = availability.b2b_app_enabled ? availability.b2b_organizations.map { |org| { "value" => { "type" => org.type, "depCustomerId" => org.dep_customer_id, "organizationId" => org.dep_organization_id, "name" => org.name } } } : [] # send the changes back to Apple r = request(:post) do |req| req.url("ra/apps/#{app_id}/pricing/intervals") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) data = parse_response(r, 'data') Spaceship::Tunes::Availability.factory(data) end def availability(app_id) r = request(:get, "ra/apps/#{app_id}/pricing/intervals") data = parse_response(r, 'data') Spaceship::Tunes::Availability.factory(data) end # Returns an array of all supported territories # # @note Although this information is publicly available, the current spaceship implementation requires you to have a logged in client to access it # # @return [Array] the Territory objects (Spaceship::Tunes::Territory) def supported_territories data = supported_countries data.map { |country| Spaceship::Tunes::Territory.factory(country) } end # An array of supported countries # [{ # "code": "AL", # "name": "Albania", # "region": "Europe" # }, { # ... def supported_countries r = request(:get, "ra/apps/pricing/supportedCountries") parse_response(r, 'data') end def available_languages r = request(:get, "ra/ref") parse_response(r, 'data')['detailLocales'] end ##################################################### # @!group App Icons ##################################################### # Uploads a large icon # @param app_version (AppVersion): The version of your app
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
true
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/app_image.rb
spaceship/lib/spaceship/tunes/app_image.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents an image hosted on App Store Connect. Used for icons, screenshots, etc class AppImage < TunesBase HOST_URL = "https://is1-ssl.mzstatic.com/image/thumb" attr_accessor :asset_token attr_accessor :sort_order attr_accessor :original_file_name attr_accessor :url attr_accessor :is_imessage attr_mapping( 'assetToken' => :asset_token, 'sortOrder' => :sort_order, 'url' => :url, 'originalFileName' => :original_file_name ) def reset!(attrs = {}) update_raw_data!( { asset_token: nil, original_file_name: nil, sort_order: nil, url: nil }.merge(attrs) ) end def setup # Since September 2015 we don't get the url anymore, so we have to manually build it self.url = "#{HOST_URL}/#{self.asset_token}/0x0ss.jpg" end private def update_raw_data!(hash) hash.each do |k, v| self.send("#{k}=", v) 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/tunes/b2b_organization.rb
spaceship/lib/spaceship/tunes/b2b_organization.rb
require_relative 'tunes_base' module Spaceship module Tunes class B2bOrganization < TunesBase # @return (String) add or remove attr_accessor :type # @return (String) customer id attr_accessor :dep_customer_id # @return (String) organization id attr_accessor :dep_organization_id # @return (String) organization name attr_accessor :name # enum for types class TYPE ADD = "ADD" REMOVE = "REMOVE" NO_CHANGE = "NO_CHANGE" end attr_mapping( 'value.type' => :type, 'value.depCustomerId' => :dep_customer_id, 'value.organizationId' => :dep_organization_id, 'value.name' => :name ) def self.from_id_info(dep_id: nil, dep_org_id: nil, dep_name: nil, type: TYPE::NO_CHANGE) self.new({ "value" => { "type" => type, "depCustomerId" => dep_id, "organizationId" => dep_org_id, "name" => dep_name } }) end def ==(other) other.class == self.class && other.state == self.state end def state return [type, dep_customer_id, name] end alias eql? == def hash state.hash 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/tunes/app_version_states_history.rb
spaceship/lib/spaceship/tunes/app_version_states_history.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents a read only version of an App Store Connect Versions State History class AppVersionStatesHistory < TunesBase # @return (String) the state attr_reader :state_key # @return (String) The name of the user who made the change attr_reader :user_name # @return (String) the email of the user or nil attr_reader :user_email # @return (Integer) the date of the state attr_reader :date attr_mapping({ 'stateKey' => :state_key, 'userName' => :user_name, 'userEmail' => :user_email, 'date' => :date }) 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/tunes/display_family.rb
spaceship/lib/spaceship/tunes/display_family.rb
require_relative "../module" module Spaceship module Tunes # A definition of different styled displays used by devices # that App Store Connect supports storing screenshots. # Display styles often only vary based on screen resolution # however other aspects of a displays physical appearance are # also factored (i.e if the home indicator is provided via # a hardware button or a software interface). class DisplayFamily # The display family name from the App Store Connect API that # is used when uploading or listing screenshots. This value is # then assigned to the # Spaceship::Tunes::AppScreenshot#device_type attribute. attr_accessor :name # The user friendly name of this definition. # # Source: Media Manager in App Store Connect. attr_accessor :friendly_name # The user friendly category for this definition (i.e iPhone, # Apple TV or Desktop). attr_accessor :friendly_category_name # An array of supported screen resolutions (in pixels) that are # supported for the associated device. # # Source: https://help.apple.com/app-store-connect/#/devd274dd925 attr_accessor :screenshot_resolutions # An internal identifier for the same device definition used # in the DUClient. # # Source: You can find this by uploading an image in App Store # Connect using your browser and then look for the # X-Apple-Upload-Validation-RuleSets value in the uploads # request headers. attr_accessor :picture_type # Similar to `picture_type`, but for iMessage screenshots. attr_accessor :messages_picture_type # Identifies if the device definition supports iMessage screenshots. def messages_supported? true unless messages_picture_type.nil? end # Finds a DisplayFamily definition. # # @param name (Symbol|String) The name of the display family being searched for. # @return DisplayFamily object matching the given name. def self.find(name) name = name.to_sym if name.kind_of?(String) lookup[name] end # All DisplayFamily types currently supported by App Store Connect. def self.all lookup.values end private_class_method def self.lookup return @lookup if defined?(@lookup) display_families = JSON.parse(File.read(File.join(Spaceship::ROOT, "lib", "assets", "displayFamilies.json"))) @lookup ||= display_families.map { |data| [data["name"].to_sym, DisplayFamily.new(data)] }.to_h end private def initialize(data) @name = data["name"] @friendly_name = data["friendly_name"] @friendly_category_name = data["friendly_category_name"] @screenshot_resolutions = data["screenshot_resolutions"] @picture_type = data["picture_type"] @messages_picture_type = data["messages_picture_type"] 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/tunes/app_review_attachment.rb
spaceship/lib/spaceship/tunes/app_review_attachment.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents an image hosted on App Store Connect. Used for app store review attachment file. class AppReviewAttachment < TunesBase HOST_URL = "https://iosapps-ssl.itunes.apple.com/itunes-assets" attr_accessor :asset_token attr_accessor :original_file_name attr_accessor :url attr_accessor :type_of_file attr_mapping( 'assetToken' => :asset_token, 'fileType' => :type_of_file, 'url' => :url, 'name' => :original_file_name ) def reset!(attrs = {}) update_raw_data!( { asset_token: nil, type_of_file: nil, url: nil, original_file_name: nil }.merge(attrs) ) end def setup # Since September 2015 we don't get the url anymore, so we have to manually build it self.url = "#{HOST_URL}/#{self.asset_token}" end private def update_raw_data!(hash) hash.each do |k, v| self.send("#{k}=", v) 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/tunes/language_item.rb
spaceship/lib/spaceship/tunes/language_item.rb
module Spaceship module Tunes # Represents one attribute (e.g. name) of an app in multiple languages class LanguageItem attr_accessor :identifier # title or description attr_accessor :original_array # reference to original array def initialize(identifier, ref) raise "ref is nil" if ref.nil? self.identifier = identifier.to_s self.original_array = ref end def [](key) get_value(key: key) end def []=(key, value) get_lang(key)[identifier]['value'] = value end def get_value(key: nil) get_lang(key)[identifier]['value'] end def get_lang(lang) result = self.original_array.find do |current| lang = lang.to_s current['language'] == lang or current['localeCode'] == lang # Apple being consistent end return result if result raise "Language '#{lang}' is not activated / available for this app version." end # @return (Array) An array containing all languages that are already available def keys return self.original_array.map { |current| current['language'] ||= current['localeCode'] } # Apple being consistent end # @return (Array) An array containing all languages that are already available # alias for keys def languages keys end def inspect result = "" self.original_array.collect do |current| result += "#{current['language'] ||= current['localeCode']}: #{current.fetch(identifier, {}).fetch('value')}\n" end result end def to_s inspect 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/tunes/version_set.rb
spaceship/lib/spaceship/tunes/version_set.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents a version set inside of an application class VersionSet < TunesBase ##################################################### # @!group General metadata ##################################################### # @return (String) The type of the version set. So far only APP attr_accessor :type # @return (Spaceship::Tunes::Application) A reference to the application the version_set is contained in attr_accessor :application # @return (String) attr_accessor :platform attr_mapping( 'type' => :type, 'platformString' => :platform ) 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/tunes/tunes.rb
spaceship/lib/spaceship/tunes/tunes.rb
require_relative 'tunes_base' require_relative 'application' require_relative 'iap' require_relative 'version_set' require_relative 'app_version' require_relative 'app_version_common' require_relative 'app_submission' require_relative 'tunes_client' require_relative 'language_item' require_relative 'app_status' require_relative 'app_image' require_relative 'app_ratings' require_relative 'app_version_ref' require_relative 'app_version_history' require_relative 'app_version_states_history' require_relative 'transit_app_file' require_relative 'app_screenshot' require_relative 'language_converter' require_relative 'build' require_relative 'build_details' require_relative 'build_train' require_relative 'device_type' require_relative 'app_trailer' require_relative 'sandbox_tester' require_relative 'app_details' require_relative 'pricing_tier' require_relative 'territory' require_relative 'availability' require_relative 'members' require_relative 'member' require_relative 'app_version_promocodes' require_relative 'app_version_generated_promocodes' require_relative 'app_analytics'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/app_review.rb
spaceship/lib/spaceship/tunes/app_review.rb
require_relative 'developer_response' module Spaceship module Tunes class AppReview < TunesBase attr_accessor :application attr_reader :rating attr_reader :id attr_reader :title attr_reader :review attr_reader :nickname attr_reader :store_front attr_reader :app_version attr_reader :last_modified attr_reader :helpful_views attr_reader :total_views attr_reader :edited attr_reader :raw_developer_response attr_accessor :developer_response attr_mapping({ 'id' => :id, 'rating' => :rating, 'title' => :title, 'review' => :review, 'nickname' => :nickname, 'storeFront' => :store_front, 'appVersionString' => :app_version, 'lastModified' => :last_modified, 'helpfulViews' => :helpful_views, 'totalViews' => :total_views, 'edited' => :edited, 'developerResponse' => :raw_developer_response }) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) obj = self.new(attrs) response_attrs = {} response_attrs = obj.raw_developer_response if obj.raw_developer_response response_attrs[:application] = obj.application response_attrs[:review_id] = obj.id obj.developer_response = DeveloperResponse.factory(response_attrs) return obj end end def responded? return true if raw_developer_response false 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/tunes/app_ratings.rb
spaceship/lib/spaceship/tunes/app_ratings.rb
require_relative 'app_review' module Spaceship module Tunes # Represents app ratings from App Store Connect class AppRatings < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this version is for attr_accessor :application # @return (Integer) total number of ratings received attr_accessor :rating_count # @return (Integer) total number of one star ratings received attr_accessor :one_star_rating_count # @return (Integer) total number of two star ratings received attr_accessor :two_star_rating_count # @return (Integer) total number of three star ratings received attr_accessor :three_star_rating_count # @return (Integer) total number of four star ratings received attr_accessor :four_star_rating_count # @return (Integer) total number of five star ratings received attr_accessor :five_star_rating_count attr_mapping({ 'reviewCount' => :review_count, 'ratingCount' => :rating_count, 'ratingOneCount' => :one_star_rating_count, 'ratingTwoCount' => :two_star_rating_count, 'ratingThreeCount' => :three_star_rating_count, 'ratingFourCount' => :four_star_rating_count, 'ratingFiveCount' => :five_star_rating_count }) # @return (Float) the average rating for this summary (rounded to 2 decimal places) def average_rating ((one_star_rating_count + (two_star_rating_count * 2) + (three_star_rating_count * 3) + (four_star_rating_count * 4) + (five_star_rating_count * 5)) / rating_count.to_f).round(2) end # @return (Array) of Review Objects def reviews(store_front = '', version_id = '', upto_date = nil) raw_reviews = client.get_reviews(application.apple_id, application.platform, store_front, version_id, upto_date) raw_reviews.map do |review| review["value"]["application"] = self.application AppReview.factory(review["value"]) 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/tunes/app_status.rb
spaceship/lib/spaceship/tunes/app_status.rb
module Spaceship module Tunes # Defines the different states of the app # # As specified by Apple: https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/ChangingAppStatus.html module AppStatus # You can edit this version, upload new binaries and more PREPARE_FOR_SUBMISSION = "Prepare for Submission" # App is currently live in the App Store READY_FOR_SALE = "Ready for Sale" # Waiting for Apple's Review WAITING_FOR_REVIEW = "Waiting For Review" # Currently in Review IN_REVIEW = "In Review" # App rejected for whatever reason REJECTED = "Rejected" # The developer took the app from the App Store DEVELOPER_REMOVED_FROM_SALE = "Developer Removed From Sale" # Developer rejected this version/binary DEVELOPER_REJECTED = "Developer Rejected" # You have to renew your Apple account to keep using App Store Connect PENDING_CONTRACT = "Pending Contract" UPLOAD_RECEIVED = "Upload Received" PENDING_DEVELOPER_RELEASE = "Pending Developer Release" PROCESSING_FOR_APP_STORE = "Processing for App Store" # WAITING_FOR_EXPORT_COMPLIANCE = "Waiting For Export Compliance" METADATA_REJECTED = "Metadata Rejected" REMOVED_FROM_SALE = "Removed From Sale" # INVALID_BINARY = "Invalid Binary" # Get the app status matching based on a string (given by App Store Connect) def self.get_from_string(text) mapping = { 'readyForSale' => READY_FOR_SALE, 'prepareForUpload' => PREPARE_FOR_SUBMISSION, 'devRejected' => DEVELOPER_REJECTED, 'pendingContract' => PENDING_CONTRACT, 'developerRemovedFromSale' => DEVELOPER_REMOVED_FROM_SALE, 'waitingForReview' => WAITING_FOR_REVIEW, 'inReview' => IN_REVIEW, 'rejected' => REJECTED, 'pendingDeveloperRelease' => PENDING_DEVELOPER_RELEASE, 'metadataRejected' => METADATA_REJECTED, 'removedFromSale' => REMOVED_FROM_SALE } mapping.each do |k, v| return v if k == text end return nil 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/tunes/app_trailer.rb
spaceship/lib/spaceship/tunes/app_trailer.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents a preview video hosted on App Store Connect. Used for icons, screenshots, etc class AppTrailer < TunesBase attr_accessor :video_asset_token attr_accessor :picture_asset_token attr_accessor :descriptionXML attr_accessor :preview_frame_time_code attr_accessor :video_url attr_accessor :preview_image_url attr_accessor :full_sized_preview_image_url attr_accessor :device_type attr_accessor :language attr_mapping( 'videoAssetToken' => :video_asset_token, 'pictureAssetToken' => :picture_asset_token, 'descriptionXML' => :descriptionXML, 'previewFrameTimeCode' => :preview_frame_time_code, 'isPortrait' => :is_portrait, 'videoUrl' => :video_url, 'previewImageUrl' => :preview_image_url, 'fullSizedPreviewImageUrl' => :full_sized_preview_image_url, 'contentType' => :content_type, 'videoStatus' => :video_status ) def reset!(attrs = {}) update_raw_data!({ video_asset_token: nil, picture_asset_token: nil, descriptionXML: nil, preview_frame_time_code: nil, is_portrait: nil, video_url: nil, preview_image_url: nil, full_sized_preview_image_url: nil, content_type: nil, video_status: nil, device_type: nil, language: nil }.merge(attrs)) end private def update_raw_data!(hash) hash.each do |k, v| self.send("#{k}=", v) 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/tunes/pricing_tier.rb
spaceship/lib/spaceship/tunes/pricing_tier.rb
require_relative 'pricing_info' module Spaceship module Tunes class PricingTier < TunesBase # @return (String) Number of the price Tier (e.g. "0" for Tier 0 aka Free) attr_accessor :tier_stem # @return (String) Name of the tier (e.g. "Free" for Tier 0) attr_accessor :tier_name # @return (Array of Spaceship::Tunes::PricingInfo objects) A list of all prices for the respective countries attr_accessor :pricing_info attr_mapping( 'tierStem' => :tier_stem, 'tierName' => :tier_name ) def pricing_info @pricing_info ||= raw_data['pricingInfo'].map { |info| PricingInfo.new(info) } 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/tunes/app_submission.rb
spaceship/lib/spaceship/tunes/app_submission.rb
require_relative 'tunes_base' module Spaceship module Tunes # Represents a submission for review of an App Store Connect Application # This class handles the submission of all review information and documents class AppSubmission < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this submission is for attr_accessor :application # @return (AppVersion) The version to use for this submission attr_accessor :version # @return (String) The platform of the device. This is usually "ios" # @example # "appletvos" attr_accessor :platform # @return (Boolean) Submitted for Review attr_accessor :submitted_for_review # To pass from the user # @return (Boolean) Ad ID Info - Serves ads attr_accessor :add_id_info_serves_ads # @return (Boolean) Ad ID Info - Tracks actions attr_accessor :add_id_info_tracks_action # @return (Boolean) Ad ID Info - Tracks installs attr_accessor :add_id_info_tracks_install # @return (Boolean) Content Rights - Contains third party content attr_accessor :content_rights_contains_third_party_content # @return (Boolean) Content Rights - Has rights of content attr_accessor :content_rights_has_rights # @return (Boolean) Export Compliance - Available on French Store attr_accessor :export_compliance_available_on_french_store # @return (Not Yet Implemented) Export Compliance - CCAT File attr_accessor :export_compliance_ccat_file # @return (Boolean) Export Compliance - Contains proprietary cryptography attr_accessor :export_compliance_contains_proprietary_cryptography # @return (Boolean) Export Compliance - Contains third-party cryptography attr_accessor :export_compliance_contains_third_party_cryptography # @return (Boolean) Export Compliance - Is exempt attr_accessor :export_compliance_is_exempt # @return (Boolean) Export Compliance - Uses encryption attr_accessor :export_compliance_uses_encryption # @return (String) Export Compliance - App type attr_accessor :export_compliance_app_type # @return (Boolean) Export Compliance - Encryption Updated attr_accessor :export_compliance_encryption_updated # @return (Boolean) Export Compliance - Compliance Required attr_accessor :export_compliance_compliance_required # @return (String) Export Compliance - Platform attr_accessor :export_compliance_platform attr_mapping({ # Ad ID Info Section 'adIdInfo.servesAds.value' => :add_id_info_serves_ads, 'adIdInfo.tracksAction.value' => :add_id_info_tracks_action, 'adIdInfo.tracksInstall.value' => :add_id_info_tracks_install, # Content Rights Section 'contentRights.containsThirdPartyContent.value' => :content_rights_contains_third_party_content, 'contentRights.hasRights.value' => :content_rights_has_rights, # Export Compliance Section 'exportCompliance.availableOnFrenchStore.value' => :export_compliance_available_on_french_store, 'exportCompliance.ccatFile.value' => :export_compliance_ccat_file, 'exportCompliance.containsProprietaryCryptography.value' => :export_compliance_contains_proprietary_cryptography, 'exportCompliance.containsThirdPartyCryptography.value' => :export_compliance_contains_third_party_cryptography, 'exportCompliance.isExempt.value' => :export_compliance_is_exempt, 'exportCompliance.usesEncryption.value' => :export_compliance_uses_encryption, 'exportCompliance.appType' => :export_compliance_app_type, 'exportCompliance.encryptionUpdated.value' => :export_compliance_encryption_updated, 'exportCompliance.exportComplianceRequired' => :export_compliance_compliance_required, 'exportCompliance.platform' => :export_compliance_platform }) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) # fill content rights section if iTC returns nil if attrs["contentRights"].nil? attrs["contentRights"] = { "containsThirdPartyContent" => { "value" => nil }, "hasRights" => { "value" => nil } } end obj = self.new(attrs) return obj end # @param application (Spaceship::Tunes::Application) The app this submission is for def create(application, version, platform: nil) attrs = client.prepare_app_submissions(application.apple_id, application.edit_version(platform: platform).version_id) attrs[:application] = application attrs[:version] = version attrs[:platform] = platform return self.factory(attrs) end end # Save and complete the app submission def complete! raw_data_clone = raw_data.dup if self.content_rights_has_rights.nil? || self.content_rights_contains_third_party_content.nil? raw_data_clone.set(["contentRights"], nil) end raw_data_clone.delete(:version) raw_data_clone.delete(:application) client.send_app_submission(application.apple_id, application.edit_version(platform: platform).version_id, raw_data_clone) @submitted_for_review = true end def setup @submitted_for_review = false 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/tunes/pricing_info.rb
spaceship/lib/spaceship/tunes/pricing_info.rb
require_relative 'tunes_base' module Spaceship module Tunes class PricingInfo < TunesBase # @return (String) name of the country, e.g. "United States" attr_accessor :country # @return (String) country code, e.g. "US" attr_accessor :country_code # @return (String) currency symbol, e.g. "$" attr_accessor :currency_symbol # @return (String) currency code, e.g. "USD" attr_accessor :currency_code # @return (Number) net proceedings for the developer attr_accessor :wholesale_price # @return (Number) customer price attr_accessor :retail_price # @return (String) formatted customer price, e.g. "$0.00" attr_accessor :f_retail_price # @return (String) formatted net proceedings, e.g. "$0.00" attr_accessor :f_wholesale_price attr_mapping( 'country' => :country, 'countryCode' => :country_code, 'currencySymbol' => :currency_symbol, 'currencyCode' => :currency_code, 'wholesalePrice' => :wholesale_price, 'retailPrice' => :retail_price, 'fRetailPrice' => :f_retail_price, 'fWholesalePrice' => :f_wholesale_price ) 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/tunes/territory.rb
spaceship/lib/spaceship/tunes/territory.rb
require_relative 'tunes_base' module Spaceship module Tunes class Territory < TunesBase # @return (String) The two-character country code (e.g. "US" for the United States) attr_accessor :code # @return (String) The ISO 3166-1 alpha-3 currency code (e.g. "USD" for the United States) attr_accessor :currency_code # @return (String) The country name (e.g. "United States" for the United States) attr_accessor :name # @return (String) The region (e.g. "The United States and Canada" for the United States) attr_accessor :region # @return (String) The region locale key (e.g. "ITC.region.NAM" for the United States) attr_accessor :region_locale_key attr_mapping( 'code' => :code, 'currencyCodeISO3A' => :currency_code, 'name' => :name, 'region' => :region, 'regionLocaleKey' => :region_locale_key ) class << self # Create a new object based on a two-character country code (e.g. "US" for the United States) def from_code(code) obj = self.new obj.code = code return obj 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/tunes/app_version.rb
spaceship/lib/spaceship/tunes/app_version.rb
require_relative 'tunes_client' require_relative 'app_trailer' require_relative 'app_screenshot' require_relative 'app_image' require_relative 'display_family' require_relative 'app_version_generated_promocodes' require_relative 'language_item' require_relative 'transit_app_file' require_relative 'build' require_relative 'app_status' require_relative 'app_review_attachment' module Spaceship module Tunes # Represents an editable version of an App Store Connect Application # This can either be the live or the edit version retrieved via the app # rubocop:disable Metrics/ClassLength class AppVersion < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this version is for attr_accessor :application # @return (String) The platform value of this version. attr_accessor :platform # @return (String) The version number of this version attr_accessor :version # @return (String) The copyright information of this app attr_accessor :copyright # @return (String) The appType number of this version attr_accessor :app_type # @return (Spaceship::Tunes::AppStatus) What's the current status of this app # e.g. Waiting for Review, Ready for Sale, ... attr_reader :app_status # @return (Bool) Is that the version that's currently available in the App Store? attr_accessor :is_live # @return (String) App Status (e.g. 'readyForSale'). You should use `app_status` instead attr_accessor :raw_status # @return (String) Build Version attr_accessor :build_version # @return (Bool) attr_accessor :can_reject_version # @return (Bool) attr_accessor :can_prepare_for_upload # @return (Bool) attr_accessor :can_send_version_live # @return (Bool) Should the app automatically be released once it's approved? attr_accessor :release_on_approval # @return (Fixnum) Milliseconds for releasing in GMT (e.g. 1480435200000 = Tue, 29 Nov 2016 16:00:00 GMT). # Use nil to unset. Setting this will supercede the release_on_approval field, so this field must be nil # for release_on_approval to be used. attr_accessor :auto_release_date # @return (Bool) Should the rating of the app be reset? attr_accessor :ratings_reset # @return (Bool) attr_accessor :can_beta_test # @return (Bool) Does the binary contain a watch binary? attr_accessor :supports_apple_watch # @return (Spaceship::Tunes::AppImage) the structure containing information about the large app icon (1024x1024) attr_accessor :large_app_icon # @return (Spaceship::Tunes::AppImage) the structure containing information about the large watch icon (1024x1024) attr_accessor :watch_app_icon # @return (Integer) a unique ID for this version generated by App Store Connect attr_accessor :version_id # @return (Spaceship::Tunes::AppReviewAttachment) the structure containing information about the review attachment file attr_accessor :review_attachment_file #### # GeoJson #### # @return (Spaceship::Tunes::TransitAppFile) the structure containing information about the geo json. Can be nil attr_accessor :transit_app_file #### # Trade Representative Contact Information #### # @return (String) Trade Representative Contact Information Trade Name. This attribute isn't editable attr_accessor :trade_representative_trade_name # @return (String) Trade Representative Contact Information First Name attr_accessor :trade_representative_first_name # @return (String) Trade Representative Contact Information Last Name attr_accessor :trade_representative_last_name # @return (String) Trade Representative Contact Information Address Line 1 attr_accessor :trade_representative_address_line_1 # @return (String) Trade Representative Contact Information Address Line 2 attr_accessor :trade_representative_address_line_2 # @return (String) Trade Representative Contact Information Address Line 3 attr_accessor :trade_representative_address_line_3 # @return (String) Trade Representative Contact Information City Name attr_accessor :trade_representative_city_name # @return (String) Trade Representative Contact Information State attr_accessor :trade_representative_state # @return (String) Trade Representative Contact Information Country attr_accessor :trade_representative_country # @return (String) Trade Representative Contact Information Postal Code attr_accessor :trade_representative_postal_code # @return (String) Trade Representative Contact Information Phone Number attr_accessor :trade_representative_phone_number # @return (String) Trade Representative Contact Information Email Address attr_accessor :trade_representative_email # @return (Boolean) Display Trade Representative Contact Information on the Korean App Store or not attr_accessor :trade_representative_is_displayed_on_app_store #### # App Review Information #### # @return (String) App Review Information First Name attr_accessor :review_first_name # @return (String) App Review Information Last Name attr_accessor :review_last_name # @return (String) App Review Information Phone Number attr_accessor :review_phone_number # @return (String) App Review Information Email Address attr_accessor :review_email # @return (Boolean) The checkbox that indicates if a demo account # is needed. Is set automatically depending on if a user and pass # are set attr_reader :review_user_needed # @return (String) App Review Information Demo Account User Name attr_accessor :review_demo_user # @return (String) App Review Information Demo Account Password attr_accessor :review_demo_password # @return (String) App Review Information Notes attr_accessor :review_notes #### # Localized values #### # @return (Array) Raw access the all available languages. You shouldn't use it probably attr_accessor :languages # @return (Hash) A hash representing the keywords in all languages attr_reader :keywords # @return (Hash) A hash representing the promotionalText in all languages attr_reader :promotional_text # @return (Hash) A hash representing the description in all languages attr_reader :description # @return (Hash) The changelog attr_reader :release_notes # @return (Hash) A hash representing the support url in all languages attr_reader :support_url # @return (Hash) A hash representing the marketing url in all languages attr_reader :marketing_url # @return (Hash) Represents the screenshots of this app version (read-only) attr_reader :screenshots # @return (Hash) Represents the trailers of this app version (read-only) attr_reader :trailers # @return (Hash) A hash representing all in-app purchases that can get submitted with this version attr_reader :in_app_purchases # @return (Hash) Represents the phased_release hash (read-only) # For now, please use the `toggle_phased_release` method and call `.save!` # as the API will probably change in the future attr_reader :phased_release # Currently phased_release doesn't seem to have all the features enabled # # => {"state"=>{"value"=>"NOT_STARTED", "isEditable"=>true, "isRequired"=>false, "errorKeys"=>nil}, # "startDate"=>nil, # "lastPaused"=>nil, # "pausedDuration"=>nil, # "totalPauseDays"=>30, # "currentDayNumber"=>nil, # "dayPercentageMap"=>{"1"=>1, "2"=>2, "3"=>5, "4"=>10, "5"=>20, "6"=>50, "7"=>100}, # "isEnabled"=>true} # def toggle_phased_release(enabled: false) state = (enabled ? "INACTIVE" : "NOT_STARTED") self.phased_release["state"]["value"] = state end attr_mapping({ 'appType' => :app_type, 'platform' => :platform, 'canBetaTest' => :can_beta_test, 'canPrepareForUpload' => :can_prepare_for_upload, 'canRejectVersion' => :can_reject_version, 'canSendVersionLive' => :can_send_version_live, 'copyright.value' => :copyright, 'details.value' => :languages, 'largeAppIcon.value.originalFileName' => :app_icon_original_name, 'largeAppIcon.value.url' => :app_icon_url, 'releaseOnApproval.value' => :release_on_approval, 'autoReleaseDate.value' => :auto_release_date, 'ratingsReset.value' => :ratings_reset, 'status' => :raw_status, 'preReleaseBuild.buildVersion' => :build_version, 'supportsAppleWatch' => :supports_apple_watch, 'versionId' => :version_id, 'version.value' => :version, 'submittableAddOns.value' => :in_app_purchases, 'phasedRelease' => :phased_release, # GeoJson # 'transitAppFile.value' => :transit_app_file # Trade Representative Contact Information 'appStoreInfo.tradeName.value' => :trade_representative_trade_name, 'appStoreInfo.firstName.value' => :trade_representative_first_name, 'appStoreInfo.lastName.value' => :trade_representative_last_name, 'appStoreInfo.addressLine1.value' => :trade_representative_address_line_1, 'appStoreInfo.addressLine2.value' => :trade_representative_address_line_2, 'appStoreInfo.addressLine3.value' => :trade_representative_address_line_3, 'appStoreInfo.cityName.value' => :trade_representative_city_name, 'appStoreInfo.state.value' => :trade_representative_state, 'appStoreInfo.country.value' => :trade_representative_country, 'appStoreInfo.postalCode.value' => :trade_representative_postal_code, 'appStoreInfo.phoneNumber.value' => :trade_representative_phone_number, 'appStoreInfo.emailAddress.value' => :trade_representative_email, 'appStoreInfo.shouldDisplayInStore.value' => :trade_representative_is_displayed_on_app_store, # App Review Information 'appReviewInfo.firstName.value' => :review_first_name, 'appReviewInfo.lastName.value' => :review_last_name, 'appReviewInfo.phoneNumber.value' => :review_phone_number, 'appReviewInfo.emailAddress.value' => :review_email, 'appReviewInfo.reviewNotes.value' => :review_notes, 'appReviewInfo.accountRequired.value' => :review_user_needed, 'appReviewInfo.userName.value' => :review_demo_user, 'appReviewInfo.password.value' => :review_demo_password }) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) obj = self.new(attrs) obj.unfold_languages return obj end # @param application (Spaceship::Tunes::Application) The app this version is for # @param app_id (String) The unique Apple ID of this app # @param is_live (Boolean) def find(application, app_id, is_live, platform: nil) # we only support applications raise "We do not support BUNDLE types right now" if application.type == 'BUNDLE' # too bad the "id" field is empty, it forces us to make more requests to the server # these could also be cached attrs = client.app_version(app_id, is_live, platform: platform) return nil unless attrs attrs[:application] = application attrs[:is_live] = is_live return self.factory(attrs) end end # @return (Bool) Is that version currently available in the App Store? def is_live? is_live end def review_user_needed (self.review_demo_user.to_s + self.review_demo_password.to_s).length > 0 end # Call this method to make sure the given languages are available for this app # You should call this method before accessing the name, description and other localized values # This will create the new language if it's not available yet and do nothing if everything's there # Important: Due to a bug you have to fetch the `edit_version` again, as it doesn't get refreshed immediately def create_languages(languages) languages = [languages] if languages.kind_of?(String) raise "Please pass an array" unless languages.kind_of?(Array) copy_from = self.languages.find { |a| a['language'] == 'en-US' } || self.languages.first languages.each do |language| # First, see if it's already available found = self.languages.find do |local| local['language'] == language end next if found new_language = copy_from.clone new_language['language'] = language self.languages << new_language end nil end def current_build_number if self.is_live? build_version else if candidate_builds.length > 0 candidate_builds.sort_by(&:upload_date).last.build_version end end end # Returns an array of all builds that can be sent to review def candidate_builds res = client.candidate_builds(self.application.apple_id, self.version_id) builds = [] res.each do |attrs| next unless attrs["type"] == "BUILD" # I don't know if it can be something else. attrs[:apple_id] = self.application.apple_id builds << Tunes::Build.factory(attrs) end return builds end # Select a build to be submitted for Review. # You have to pass a build you got from - candidate_builds # Don't forget to call save! after calling this method def select_build(build) raw_data.set(['preReleaseBuildVersionString', 'value'], build.build_version) raw_data.set(['preReleaseBuildTrainVersionString'], build.train_version) raw_data.set(['preReleaseBuildUploadDate'], build.upload_date) true end # Set the age restriction rating # Call it like this: # v.update_rating({ # 'CARTOON_FANTASY_VIOLENCE' => 0, # 'MATURE_SUGGESTIVE' => 2, # 'UNRESTRICTED_WEB_ACCESS' => 0, # 'GAMBLING_CONTESTS' => 0 # }) # # Available Values # https://docs.fastlane.tools/actions/deliver/#reference def update_rating(hash) raise "Must be a hash" unless hash.kind_of?(Hash) hash.each do |key, value| to_edit = self.raw_data['ratings']['nonBooleanDescriptors'].find do |current| current['name'].include?(key) end if to_edit to_set = "NONE" if value == 0 to_set = "INFREQUENT_MILD" if value == 1 to_set = "FREQUENT_INTENSE" if value == 2 raise "Invalid value '#{value}' for '#{key}', must be 0-2" unless to_set to_edit['level'] = "ITC.apps.ratings.level.#{to_set}" else # Maybe it's a boolean descriptor? to_edit = self.raw_data['ratings']['booleanDescriptors'].find do |current| current['name'].include?(key) end if to_edit to_set = "NO" to_set = "YES" if value.to_i > 0 to_edit['level'] = "ITC.apps.ratings.level.#{to_set}" else raise "Could not find option '#{key}' in the list of available options" end end end true end # Push all changes that were made back to App Store Connect def save! client.update_app_version!(application.apple_id, self.version_id, raw_data) end # @return (String) An URL to this specific resource. You can enter this URL into your browser def url url = "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/#{application.apple_id}/#{self.platform}/versioninfo/" url += "deliverable" if self.is_live? return url end # Private methods def setup status = raw_data['status'] @app_status = Tunes::AppStatus.get_from_string(status) setup_large_app_icon setup_watch_app_icon setup_review_attachment_file if supports_review_attachment_file? setup_transit_app_file if supports_app_transit? setup_screenshots setup_trailers end # This method will generate the required keys/values # for App Store Connect to validate the uploaded image def generate_image_metadata(image_data, original_file_name) { assetToken: image_data["token"], originalFileName: original_file_name, size: image_data["length"], height: image_data["height"], width: image_data["width"], checksum: image_data["md5"] } end # This method will generate the required keys/values # for App Store Connect to validate the review attachment file def generate_review_attachment_file(review_attachment_data, review_attachment_file) { assetToken: review_attachment_data["token"], name: File.basename(review_attachment_file), fileType: Utilities.content_type(review_attachment_file), url: nil } end # Uploads or removes the large icon # @param icon_path (String): The path to the icon. Use nil to remove it def upload_large_icon!(icon_path) unless icon_path @large_app_icon.reset! return end upload_image = UploadFile.from_path(icon_path) image_data = client.upload_large_icon(self, upload_image) raw_data["largeAppIcon"]["value"] = generate_image_metadata(image_data, upload_image.file_name) end # Uploads or removes the watch icon # @param icon_path (String): The path to the icon. Use nil to remove it def upload_watch_icon!(icon_path) unless icon_path @watch_app_icon.reset! return end upload_image = UploadFile.from_path(icon_path) image_data = client.upload_watch_icon(self, upload_image) raw_data["watchAppIcon"]["value"] = generate_image_metadata(image_data, upload_image.file_name) end # Uploads or removes the transit app file # @param icon_path (String): The path to the geojson file. Use nil to remove it def upload_geojson!(geojson_path) unless geojson_path raw_data["transitAppFile"]["value"] = nil @transit_app_file = nil return end upload_file = UploadFile.from_path(geojson_path) geojson_data = client.upload_geojson(self, upload_file) @transit_app_file = Tunes::TransitAppFile.factory({}) if @transit_app_file.nil? @transit_app_file .url = nil # response.headers['Location'] @transit_app_file.asset_token = geojson_data["token"] @transit_app_file.name = upload_file.file_name @transit_app_file.time_stamp = Time.now.to_i * 1000 # works without but... end # Uploads or removes a screenshot # @param icon_path (String): The path to the screenshot. Use nil to remove it # @param sort_order (Fixnum): The sort_order, from 1 to 5 # @param language (String): The language for this screenshot # @param device (string): The device for this screenshot # @param is_messages (Bool): True if the screenshot is for iMessage def upload_screenshot!(screenshot_path, sort_order, language, device, is_messages) raise "sort_order must be higher than 0" unless sort_order > 0 raise "sort_order must not be > 10" if sort_order > 10 # this will also check both language and device parameters device_lang_screenshots = screenshots_data_for_language_and_device(language, device, is_messages)["value"] existing_sort_orders = device_lang_screenshots.map { |s| s["value"]["sortOrder"] } if screenshot_path # adding / replacing upload_file = UploadFile.from_path(screenshot_path) screenshot_data = client.upload_screenshot(self, upload_file, device, is_messages) # Since October 2016 we also need to pass the size, height, width and checksum # otherwise App Store Connect validation will fail at a later point new_screenshot = { "value" => { "assetToken" => screenshot_data["token"], "sortOrder" => sort_order, "originalFileName" => upload_file.file_name, "size" => screenshot_data["length"], "height" => screenshot_data["height"], "width" => screenshot_data["width"], "checksum" => screenshot_data["md5"] } } # We disable "scaling" for this device type / language combination # We only set this, if we actually successfully uploaded a new screenshot # for this device / language combination # if this value is not set, iTC will fallback to another device type for screenshots language_details = raw_data_details.find { |d| d["language"] == language }["displayFamilies"]["value"] device_language_details = language_details.find { |display_family| display_family['name'] == device } scaled_key = is_messages ? "messagesScaled" : "scaled" device_language_details[scaled_key]["value"] = false if existing_sort_orders.include?(sort_order) # replace device_lang_screenshots[existing_sort_orders.index(sort_order)] = new_screenshot else # add device_lang_screenshots << new_screenshot end else # removing raise "cannot remove screenshot with nonexistent sort_order" unless existing_sort_orders.include?(sort_order) device_lang_screenshots.delete_at(existing_sort_orders.index(sort_order)) end setup_screenshots end # Uploads, removes a trailer video # # A preview image for the video is required by ITC and is usually automatically extracted by your browser. # This method will either automatically extract it from the video (using `ffmpeg`) or allow you # to specify it using +preview_image_path+. # If the preview image is specified, `ffmpeg` will not be used. The image resolution will be checked against # expectations (which might be different from the trailer resolution. # # It is recommended to extract the preview image using the spaceship related tools in order to ensure # the appropriate format and resolution are used. # # Note: to extract its resolution and a screenshot preview, the `ffmpeg` tool will be used # # @param trailer_path (String): The path to the trailer. Use nil to remove it # @param sort_order (Fixnum): The sort_order, from 1 to 5 # @param language (String): The language for this screenshot # @param device (String): The device for this screenshot # @param timestamp (String): The optional timestamp of the screenshot to grab # @param preview_image_path (String): The optional image path for the video preview def upload_trailer!(trailer_path, sort_order, language, device, timestamp = "05.00", preview_image_path = nil) raise "No app trailer supported for iphone35" if device == 'iphone35' raise "sort_order must be higher than 0" unless sort_order > 0 raise "sort_order must not be > 3" if sort_order > 3 device_lang_trailers = trailer_data_for_language_and_device(language, device)["value"] existing_sort_orders = device_lang_trailers.map { |s| s["value"]["sortPosition"] } if trailer_path # adding / replacing trailer raise "Invalid timestamp #{timestamp}" if (timestamp =~ /^[0-9][0-9].[0-9][0-9]$/).nil? if preview_image_path check_preview_screenshot_resolution(preview_image_path, device) video_preview_path = preview_image_path else # IDEA: optimization, we could avoid fetching the screenshot if the timestamp hasn't changed video_preview_resolution = video_preview_resolution_for(device, trailer_path) # Keep a reference of the video_preview here to avoid Ruby getting rid of the Tempfile in the meanwhile video_preview = Utilities.grab_video_preview(trailer_path, timestamp, video_preview_resolution) video_preview_path = video_preview.path end video_preview_file = UploadFile.from_path(video_preview_path) video_preview_data = client.upload_trailer_preview(self, video_preview_file, device) upload_file = UploadFile.from_path(trailer_path) trailer_data = client.upload_trailer(self, upload_file) ts = "00:00:#{timestamp}" ts[8] = ':' new_trailer = { "value" => { "videoAssetToken" => trailer_data["responses"][0]["token"], "descriptionXML" => trailer_data["responses"][0]["descriptionDoc"], "contentType" => upload_file.content_type, "sortPosition" => sort_order, "size" => video_preview_data["length"], "width" => video_preview_data["width"], "height" => video_preview_data["height"], "checksum" => video_preview_data["md5"], "pictureAssetToken" => video_preview_data["token"], "previewFrameTimeCode" => ts.to_s, "isPortrait" => Utilities.portrait?(video_preview_path) } } if existing_sort_orders.include?(sort_order) # replace device_lang_trailers[existing_sort_orders.index(sort_order)] = new_trailer else # add device_lang_trailers << new_trailer end else # removing trailer raise "cannot remove trailer with nonexistent sort_order" unless existing_sort_orders.include?(sort_order) device_lang_trailers.delete_at(existing_sort_orders.index(sort_order)) end setup_trailers end # Uploads, app review attachments # # while submitting for review, ITC allow developers to attach file. # # Following list can be found at https://appstoreconnect.apple.com # on iOS app edit version, above the attachment label/button there is # a question mark if it is press the a dialog is shown which has the list. # # File types allowed by Apple are: pdf, doc, docx, rtf, pages, xls, xlsx, numbers # zip, rar, plist, crash, jpg, png, mp4 or avi. # # # @param review_attachment_path (String): The path to the attachment file. def upload_review_attachment!(review_attachment_path) raise 'cannot upload review attachment for live edition.' if self.is_live? if !review_attachment_path || review_attachment_path.size < 1 @review_attachment_file.reset! return end raise "cannot find file: #{review_attachment_path}." unless File.exist?(review_attachment_path) review_attachment_file = UploadFile.from_path(review_attachment_path) review_attachment_data = client.upload_app_review_attachment(self, review_attachment_file) raw_data["appReviewInfo"]["attachmentFiles"]["value"] = generate_review_attachment_file(review_attachment_data, review_attachment_path) end # Prefill name, keywords, etc... def unfold_languages { keywords: :keywords, description: :description, supportUrl: :support_url, marketingUrl: :marketing_url, releaseNotes: :release_notes, promotionalText: :promotional_text }.each do |json, attribute| instance_variable_set("@#{attribute}".to_sym, LanguageItem.new(json, languages)) end end def release! client.release!(self.application.apple_id, self.version_id) end def release_to_all_users! client.release_to_all_users!(self.application.apple_id, self.version_id) end ##################################################### # @!group Promo codes ##################################################### def generate_promocodes!(quantity) data = client.generate_app_version_promocodes!( app_id: self.application.apple_id, version_id: self.version_id, quantity: quantity ) Tunes::AppVersionGeneratedPromocodes.factory(data) end # These methods takes care of properly parsing values that # are not returned in the right format, e.g. boolean as string def release_on_approval super == 'true' end def supports_apple_watch !super.nil? end def reject! raise 'Version not rejectable' unless can_reject_version client.reject!(self.application.apple_id, self.version_id) end private def setup_large_app_icon large_app_icon = raw_data["largeAppIcon"]["value"] @large_app_icon = nil @large_app_icon = Tunes::AppImage.factory(large_app_icon) if large_app_icon end def setup_watch_app_icon watch_app_icon = raw_data["watchAppIcon"]["value"] @watch_app_icon = nil @watch_app_icon = Tunes::AppImage.factory(watch_app_icon) if watch_app_icon end def setup_review_attachment_file review_attachment_file = raw_data["appReviewInfo"]["attachmentFiles"]["value"] @review_attachment_file = nil @review_attachment_file = Tunes::AppReviewAttachment.factory(review_attachment_file) end def supports_review_attachment_file? raw_data["appReviewInfo"]["attachmentFiles"] && raw_data["appReviewInfo"]["attachmentFiles"]["value"] end def supports_app_transit? raw_data["transitAppFile"] != nil end def setup_transit_app_file transit_app_file = raw_data["transitAppFile"]["value"] @transit_app_file = nil @transit_app_file = Tunes::TransitAppFile.factory(transit_app_file) if transit_app_file end def screenshots_data_for_language_and_device(language, device, is_messages) data_field = is_messages ? "messagesScreenshots" : "screenshots" container_data_for_language_and_device(data_field, language, device) end def trailer_data_for_language_and_device(language, device) container_data_for_language_and_device("trailers", language, device) end def container_data_for_language_and_device(data_field, language, device) raise "#{device} isn't a valid device name" unless DisplayFamily.find(device) languages = raw_data_details.select { |d| d["language"] == language } # IDEA: better error for nonexistent language raise "#{language} isn't an activated language" unless languages.count > 0 lang_details = languages[0] display_families = lang_details["displayFamilies"]["value"] device_details = display_families.find { |display_family| display_family['name'] == device } raise "Couldn't find device family for #{device}" if device_details.nil? raise "Unexpected state: missing device details for #{device}" unless device_details.key?(data_field) return device_details[data_field] rescue => ex raise "App Store Connect error: #{ex}" end def setup_screenshots # Enable Scaling for all screen sizes that don't have at least one screenshot or at least one trailer (app_preview) # We automatically disable scaling once we upload at least one screenshot language_details = raw_data_details.each do |current_language| language_details = (current_language["displayFamilies"] || {})["value"] (language_details || []).each do |device_language_details| # Do not enable scaling if a screenshot already exists next if device_language_details["screenshots"].nil? next if device_language_details["screenshots"]["value"].count > 0 # Do not enable scaling if a trailer already exists next if device_language_details["trailers"].nil?
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
true
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/tunes/iap_detail.rb
spaceship/lib/spaceship/tunes/iap_detail.rb
require_relative '../du/upload_file' require_relative 'iap_status' require_relative 'iap_type' require_relative 'tunes_base' module Spaceship module Tunes class IAPDetail < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application attr_accessor :application # @return (Integer) the IAP id attr_accessor :purchase_id # @return (Bool) if it is a news subscription attr_accessor :is_news_subscription # @return (String) the IAP Referencename attr_accessor :reference_name # @return (String) the IAP Product-Id attr_accessor :product_id # @return (String) free trial period attr_accessor :subscription_free_trial # @return (String) subscription duration attr_accessor :subscription_duration # @return (Bool) Cleared for sale flag attr_accessor :cleared_for_sale # @return (Hash) app store promotion image (optional) attr_accessor :merch_screenshot # @return (Hash) app review screenshot (required) attr_accessor :review_screenshot # @return (String) the notes for the review team attr_accessor :review_notes # @return (Hash) subscription pricing target attr_accessor :subscription_price_target # @return (Hash) Relevant only for recurring subscriptions. Holds pricing related data, such # as subscription pricing, intro offers, etc. attr_accessor :raw_pricing_data attr_mapping({ 'adamId' => :purchase_id, 'referenceName.value' => :reference_name, 'productId.value' => :product_id, 'isNewsSubscription' => :is_news_subscription, 'pricingDurationType.value' => :subscription_duration, 'freeTrialDurationType.value' => :subscription_free_trial, 'clearedForSale.value' => :cleared_for_sale }) def setup @raw_pricing_data = @raw_data["pricingData"] @raw_data.delete("pricingData") if @raw_pricing_data @raw_data.set(["pricingIntervals"], @raw_pricing_data["subscriptions"]) end end # @return (Hash) Hash of languages # @example: { # 'de-DE': { # name: "Name shown in AppStore", # description: "Description of the In app Purchase" # # } # } def versions parsed_versions = {} raw_versions = raw_data["versions"].first["details"]["value"] raw_versions.each do |localized_version| language = localized_version["value"]["localeCode"] parsed_versions[language.to_sym] = { name: localized_version["value"]["name"]["value"], description: localized_version["value"]["description"]["value"], id: localized_version["value"]["id"], status: localized_version["value"]["status"] } end return parsed_versions end # transforms user-set versions to iTC ones def versions=(value = {}) if value.kind_of?(Array) # input that comes from iTC api return end new_versions = [] value.each do |language, current_version| new_versions << { "value" => { "name" => { "value" => current_version[:name] }, "description" => { "value" => current_version[:description] }, "localeCode" => language.to_s, "id" => current_version[:id] } } end raw_data.set(["versions"], [{ reviewNotes: { value: @review_notes }, "contentHosting" => raw_data['versions'].first['contentHosting'], "details" => { "value" => new_versions }, "id" => raw_data["versions"].first["id"], "reviewScreenshot" => { "value" => review_screenshot } }]) end # transforms user-set intervals to iTC ones def pricing_intervals=(value = []) raw_pricing_intervals = client.transform_to_raw_pricing_intervals(application.apple_id, self.purchase_id, value) raw_data.set(["pricingIntervals"], raw_pricing_intervals) @raw_pricing_data["subscriptions"] = raw_pricing_intervals if @raw_pricing_data end # @return (Array) pricing intervals # @example: # [ # { # country: "WW", # begin_date: nil, # end_date: nil, # tier: 1 # } # ] def pricing_intervals @pricing_intervals ||= (raw_data["pricingIntervals"] || @raw_pricing_data["subscriptions"] || []).map do |interval| { tier: interval["value"]["tierStem"].to_i, begin_date: interval["value"]["priceTierEffectiveDate"], end_date: interval["value"]["priceTierEndDate"], grandfathered: interval["value"]["grandfathered"], country: interval["value"]["country"] } end end # @return (String) Human Readable type of the purchase def type Tunes::IAPType.get_from_string(raw_data["addOnType"]) end # @return (String) Human Readable status of the purchase def status Tunes::IAPStatus.get_from_string(raw_data["versions"].first["status"]) end # @return (Hash) Hash containing existing promotional image data def merch_screenshot return nil unless raw_data && raw_data["versions"] && raw_data["versions"].first && raw_data["versions"].first["merch"] && raw_data["versions"].first["merch"]["images"].first["image"]["value"] raw_data["versions"].first["merch"]["images"].first["image"]["value"] end # @return (Hash) Hash containing existing review screenshot data def review_screenshot return nil unless raw_data && raw_data["versions"] && raw_data["versions"].first && raw_data["versions"].first["reviewScreenshot"] && raw_data['versions'].first["reviewScreenshot"]["value"] raw_data['versions'].first['reviewScreenshot']['value'] end # Saves the current In-App-Purchase def save! # Transform localization versions back to original format. versions_array = [] versions.each do |language, value| versions_array << { "value" => { "description" => { "value" => value[:description] }, "name" => { "value" => value[:name] }, "localeCode" => language.to_s, "id" => value[:id] } } end raw_data.set(["versions"], [{ reviewNotes: { value: @review_notes }, contentHosting: raw_data['versions'].first['contentHosting'], "details" => { "value" => versions_array }, id: raw_data["versions"].first["id"], reviewScreenshot: { "value" => review_screenshot } }]) # transform pricingDetails raw_pricing_intervals = client.transform_to_raw_pricing_intervals(application.apple_id, self.purchase_id, pricing_intervals, subscription_price_target) raw_data.set(["pricingIntervals"], raw_pricing_intervals) @raw_pricing_data["subscriptions"] = raw_pricing_intervals if @raw_pricing_data if @merch_screenshot # Upload App Store Promotional image (Optional) upload_file = UploadFile.from_path(@merch_screenshot) merch_data = client.upload_purchase_merch_screenshot(application.apple_id, upload_file) raw_data["versions"][0]["merch"] = merch_data end if @review_screenshot # Upload Screenshot upload_file = UploadFile.from_path(@review_screenshot) screenshot_data = client.upload_purchase_review_screenshot(application.apple_id, upload_file) raw_data["versions"][0]["reviewScreenshot"] = screenshot_data end # Update the Purchase client.update_iap!(app_id: application.apple_id, purchase_id: self.purchase_id, data: raw_data) # Update pricing for a recurring subscription. if raw_data["addOnType"] == Spaceship::Tunes::IAPType::RECURRING client.update_recurring_iap_pricing!(app_id: application.apple_id, purchase_id: self.purchase_id, pricing_intervals: raw_data["pricingIntervals"]) end end # Deletes In-App-Purchase def delete! client.delete_iap!(app_id: application.apple_id, purchase_id: self.purchase_id) end # Retrieves the actual prices for an iap. # # @return ([]) An empty array # if the iap is not yet cleared for sale # @return ([Spaceship::Tunes::PricingInfo]) An array of pricing infos from the same pricing tier # if the iap uses world wide pricing # @return ([Spaceship::Tunes::IAPSubscriptionPricingInfo]) An array of pricing infos from multiple subscription pricing tiers # if the iap uses territorial pricing def pricing_info return [] unless cleared_for_sale return world_wide_pricing_info if world_wide_pricing? territorial_pricing_info end private # Checks whether an iap uses world wide or territorial pricing. # # @return (true, false) def world_wide_pricing? pricing_intervals.fetch(0, {})[:country] == "WW" end # Maps a single pricing interval to pricing infos. # # @return ([Spaceship::Tunes::PricingInfo]) An array of pricing infos from the same tier def world_wide_pricing_info client .pricing_tiers(application.apple_id) .find { |p| p.tier_stem == pricing_intervals.first[:tier].to_s } .pricing_info end # Maps pricing intervals to their respective subscription pricing infos. # # @return ([Spaceship::Tunes::IAPSubscriptionPricingInfo]) An array of subscription pricing infos def territorial_pricing_info pricing_matrix = client.subscription_pricing_tiers(application.apple_id) pricing_intervals.map do |interval| pricing_matrix .find { |p| p.tier_stem == interval[:tier].to_s } .pricing_info .find { |i| i.country_code == interval[:country] } 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/du/utilities.rb
spaceship/lib/spaceship/du/utilities.rb
require 'fastimage' require "English" module Spaceship # Set of utility methods useful to work with media files module Utilities #:nodoc: # Identifies the content_type of a file based on its file name extension. # Supports all formats required by DU-UTC right now (video, images and json) # @param path (String) the path to the file def content_type(path) supported_file_types = { '.jpg' => 'image/jpeg', '.jpeg' => 'image/jpeg', '.png' => 'image/png', '.geojson' => 'application/json', '.mov' => 'video/quicktime', '.m4v' => 'video/mp4', '.mp4' => 'video/mp4', '.txt' => 'text/plain', '.pdf' => 'application/pdf', '.doc' => 'application/msword', '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.rtf' => 'application/rtf', '.pages' => 'application/x-iwork-pages-sffpages', '.xls' => 'application/vnd.ms-excel', '.xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.numbers' => 'application/x-iwork-numbers-sffnumbers', '.rar' => 'application/x-rar-compressed', '.plist' => 'application/xml', '.crash' => 'text/x-apport', '.avi' => 'video/x-msvideo', '.zip' => 'application/zip' } extension = File.extname(path.downcase) return supported_file_types[extension] if supported_file_types[extension] raise "Unknown content-type for file #{path}" end # Identifies the resolution of a video or an image. # Supports all video and images required by DU-UTC right now # @param path (String) the path to the file def resolution(path) return FastImage.size(path) if content_type(path).start_with?("image") return video_resolution(path) if content_type(path).start_with?("video") raise "Cannot find resolution of file #{path}" end # Is the video or image in portrait mode ? # Supports all video and images required by DU-UTC right now # @param path (String) the path to the file def portrait?(path) resolution = resolution(path) resolution[0] < resolution[1] end # Grabs a screenshot from the specified video at the specified timestamp using `ffmpeg` # @param video_path (String) the path to the video file # @param timestamp (String) the `ffmpeg` timestamp format (e.g. 00.00) # @param dimensions (Array) the dimension of the screenshot to generate # @return the TempFile containing the generated screenshot def grab_video_preview(video_path, timestamp, dimensions) width, height = dimensions require 'tempfile' tmp = Tempfile.new(['video_preview', ".jpg"]) file = tmp.path command = "ffmpeg -y -i \"#{video_path}\" -s #{width}x#{height} -ss \"#{timestamp}\" -vframes 1 \"#{file}\" 2>&1 >/dev/null" # puts "COMMAND: #{command}" `#{command}` raise "Failed to grab screenshot at #{timestamp} from #{video_path} (using #{command})" unless $CHILD_STATUS.to_i == 0 tmp end # identifies the resolution of a video using `ffmpeg` # @param video_path (String) the path to the video file # @return [Array] the resolution of the video def video_resolution(video_path) command = "ffmpeg -i \"#{video_path}\" 2>&1" # puts "COMMAND: #{command}" output = `#{command}` # Note: ffmpeg exits with 1 if no output specified # raise "Failed to find video information from #{video_path} (using #{command})" unless $CHILD_STATUS.to_i == 0 output = output.force_encoding("BINARY") video_infos = output.split("\n").select { |l| l =~ /Stream.*Video/ } raise "Unable to find Stream Video information from ffmpeg output of #{command}" if video_infos.count == 0 video_info = video_infos[0] res = video_info.match(/.* ([0-9]+)x([0-9]+).*/) raise "Unable to parse resolution information from #{video_info}" if res.size < 3 [res[1].to_i, res[2].to_i] end # @return (String) md5 checksum of given file def md5digest(file_path) Digest::MD5.hexdigest(File.read(file_path)) end module_function :content_type, :grab_video_preview, :portrait?, :resolution, :video_resolution, :md5digest end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/du/du_client.rb
spaceship/lib/spaceship/du/du_client.rb
require_relative '../client' require_relative '../tunes/display_family' require_relative 'utilities' module Spaceship # This class is used to upload Digital files (Images, Videos, JSON files) onto the du-itc service. # Its implementation is tied to the tunes module (in particular using +AppVersion+ instances) class DUClient < Spaceship::Client #:nodoc: ##################################################### # @!group Init and Login ##################################################### def self.hostname "https://du-itc.itunes.apple.com" end ##################################################### # @!group Images ##################################################### def upload_screenshot(app_version, upload_file, content_provider_id, sso_token_for_image, device, is_messages) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: screenshot_picture_type(device, is_messages)) end def upload_purchase_merch_screenshot(app_id, upload_file, content_provider_id, sso_token_for_image) upload_file(app_id: app_id, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: 'MZPFT.MerchandisingIAPIcon') end def upload_purchase_review_screenshot(app_id, upload_file, content_provider_id, sso_token_for_image) upload_file(app_id: app_id, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: get_picture_type(upload_file)) end def upload_large_icon(app_version, upload_file, content_provider_id, sso_token_for_image) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: 'MZPFT.LargeApplicationIcon') end def upload_watch_icon(app_version, upload_file, content_provider_id, sso_token_for_image) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: 'MZPFT.GizmoAppIcon') end def upload_geojson(app_version, upload_file, content_provider_id, sso_token_for_image) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/geo-json', content_provider_id: content_provider_id, sso_token: sso_token_for_image) end def upload_trailer(app_version, upload_file, content_provider_id, sso_token_for_video) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/purple-video', content_provider_id: content_provider_id, sso_token: sso_token_for_video) end def upload_trailer_preview(app_version, upload_file, content_provider_id, sso_token_for_image, device) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/image', content_provider_id: content_provider_id, sso_token: sso_token_for_image, du_validation_rule_set: screenshot_picture_type(device, nil)) end def upload_app_review_attachment(app_version, upload_file, content_provider_id, sso_token_for_attachment) upload_file(app_version: app_version, upload_file: upload_file, path: '/upload/app-resolution-file', content_provider_id: content_provider_id, sso_token: sso_token_for_attachment) end def get_picture_type(upload_file) resolution = Utilities.resolution(upload_file.file_path) result = device_resolution_map.find do |key, resolutions| resolutions.include?(resolution) end raise "Unknown device for screen resolution #{resolution}" if result.nil? picture_type_map[result[0]] end private def upload_file(app_version: nil, upload_file: nil, path: nil, content_provider_id: nil, sso_token: nil, du_validation_rule_set: nil, app_id: nil) raise "File #{upload_file.file_path} is empty" if upload_file.file_size == 0 if app_id app_id = app_id app_type = nil version = nil referrer = nil else version = app_version.version app_id = app_version.application.apple_id app_type = app_version.app_type referrer = app_version.application.url end r = request(:post) do |req| req.url("#{self.class.hostname}#{path}") req.body = upload_file.bytes req.headers['Accept'] = 'application/json, text/plain, */*' req.headers['Content-Type'] = upload_file.content_type req.headers['X-Apple-Upload-Referrer'] = referrer if referrer req.headers['Referrer'] = referrer if referrer req.headers['X-Apple-Upload-AppleId'] = app_id req.headers['X-Apple-Jingle-Correlation-Key'] = "#{app_type}:AdamId=#{app_id}:Version=#{version}" if app_type req.headers['X-Apple-Upload-itctoken'] = sso_token req.headers['X-Apple-Upload-ContentProviderId'] = content_provider_id req.headers['X-Original-Filename'] = upload_file.file_name req.headers['X-Apple-Upload-Validation-RuleSets'] = du_validation_rule_set if du_validation_rule_set req.headers['Content-Length'] = upload_file.file_size.to_s req.headers['Connection'] = "keep-alive" end if r.status == 500 && r.body.include?("Server Error") return upload_file(app_version: app_version, upload_file: upload_file, path: path, content_provider_id: content_provider_id, sso_token: sso_token, du_validation_rule_set: du_validation_rule_set, app_id: app_id) end parse_upload_response(r) end def picture_type_map Spaceship::Tunes::DisplayFamily.all.map { |v| [v.name.to_sym, v.picture_type] }.to_h end def messages_picture_type_map Spaceship::Tunes::DisplayFamily.all.select(&:messages_supported?).map { |v| [v.name.to_sym, v.messages_picture_type] }.to_h end def device_resolution_map Spaceship::Tunes::DisplayFamily.all.map { |v| [v.name.to_sym, v.screenshot_resolutions] }.to_h end def screenshot_picture_type(device, is_messages) map = is_messages ? messages_picture_type_map : picture_type_map device = device.to_sym raise "Unknown picture type for device: #{device}" unless map.key?(device) map[device] end def parse_upload_response(response) content = response.body if !content['statusCode'].nil? && content['statusCode'] != 200 error_codes = "" error_codes = content['errorCodes'].join(',') unless content['errorCodes'].nil? error_message = "[#{error_codes}] #{content['localizedMessage']}" raise UnexpectedResponse.new, error_message end content 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/du/upload_file.rb
spaceship/lib/spaceship/du/upload_file.rb
require 'fileutils' require_relative 'utilities' module Spaceship # a wrapper around the concept of file required to make uploads to DU class UploadFile attr_reader :file_path attr_reader :file_name attr_reader :file_size attr_reader :content_type attr_reader :bytes class << self def from_path(path) raise "Image must exists at path: #{path}" unless File.exist?(path) # md5 from original. keeping track of md5s allows to skip previously uploaded in deliver content_md5 = Spaceship::Utilities.md5digest(path) path = remove_alpha_channel(path) if File.extname(path).casecmp('.png').zero? content_type = Utilities.content_type(path) self.new( file_path: path, file_name: 'ftl_' + content_md5 + '_' + File.basename(path), file_size: File.size(path), content_type: content_type, bytes: File.read(path) ) end # As things like screenshots and app icon shouldn't contain the alpha channel # This will copy the image into /tmp to remove the alpha channel there # That's done to not edit the original image def remove_alpha_channel(original) path = "/tmp/#{Digest::MD5.hexdigest(original)}.png" FileUtils.copy(original, path) if mac? # sips is only available on macOS `sips -s format bmp '#{path}' &> /dev/null` # &> /dev/null since there is warning because of the extension `sips -s format png '#{path}'` end return path end def mac? (/darwin/ =~ RUBY_PLATFORM) != nil end end private def initialize(args) args.each do |k, v| instance_variable_set("@#{k}", v) unless v.nil? 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/helper/plist_middleware.rb
spaceship/lib/spaceship/helper/plist_middleware.rb
require 'faraday_middleware/response_middleware' module FaradayMiddleware class PlistMiddleware < ResponseMiddleware dependency do require 'plist' unless Object.const_defined?("Plist") end define_parser do |body| body = body.force_encoding("UTF-8") Plist.parse_xml(body) end end end Faraday::Response.register_middleware(plist: FaradayMiddleware::PlistMiddleware)
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/helper/rels_middleware.rb
spaceship/lib/spaceship/helper/rels_middleware.rb
module Faraday class Env attr_accessor :rels end end require 'faraday' module FaradayMiddleware class RelsMiddleware < Faraday::Middleware def initialize(app, options = {}) @app = app @options = options end def call(environment) @app.call(environment).on_complete do |env| links = (env.response_headers["Link"] || "").split(', ').map do |link| href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures [name.to_sym, href] end env.rels = Hash[*links.flatten] 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/helper/net_http_generic_request.rb
spaceship/lib/spaceship/helper/net_http_generic_request.rb
require 'net/http' ## monkey-patch Net::HTTP # # Certain apple endpoints return 415 responses if a Content-Type is supplied. # Net::HTTP will default a content-type if none is provided by faraday # This monkey-patch allows us to leave out the content-type if we do not specify one. module NetHTTPGenericRequestMonkeypatch def supply_default_content_type # Return no content type if we communicating with an apple.com domain return if !self['host'].nil? && self['host'].end_with?('.apple.com') # Otherwise use the default implementation super end end # We prepend the monkeypatch so the patch has access to the original implementation # using `super`. Net::HTTPGenericRequest.prepend(NetHTTPGenericRequestMonkeypatch)
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spaceship/lib/spaceship/test_flight/build_trains.rb
spaceship/lib/spaceship/test_flight/build_trains.rb
require_relative 'base' require_relative 'build' module Spaceship::TestFlight class BuildTrains < Base ## # BuildTrains represent the collection of builds for a `train_version` # # Note: builds returned by BuildTrains are _partially_ complete. Properties # such as `exportCompliance`, `testInfo` and many others are not provided. # It is the responsibility of Build to lazy-load the necessary properties. # # See `Spaceship::TestFlight::Build#reload` def self.all(app_id: nil, platform: nil, retry_count: 3) filter_platform = Spaceship::ConnectAPI::Platform.map(platform) if platform connect_builds = Spaceship::ConnectAPI::Build.all( app_id: app_id, sort: "uploadedDate", platform: filter_platform ) trains = {} connect_builds.each do |connect_build| train_version = connect_build.app_version trains[train_version] ||= [] trains[train_version] << connect_build.to_testflight_build end self.new(trains) end def initialize(trains = {}) @trains = trains end def get(key) @trains[key] end alias [] get def values @trains.values end def versions @trains.keys end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false