-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathitmstransporter-service.ts
224 lines (193 loc) · 9.52 KB
/
itmstransporter-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
///<reference path="../.d.ts"/>
"use strict";
import * as path from "path";
import * as temp from "temp";
import {EOL} from "os";
import {ITMSConstants} from "../constants";
import {ItunesConnectApplicationTypes} from "../constants";
import {quoteString, versionCompare} from "../common/helpers";
export class ITMSTransporterService implements IITMSTransporterService {
private _itmsTransporterPath: string = null;
private _itunesConnectApplications: IiTunesConnectApplication[] = null;
private _bundleIdentifier: string = null;
constructor(private $bplistParser: IBinaryPlistParser,
private $childProcess: IChildProcess,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $errors: IErrors,
private $fs: IFileSystem,
private $hostInfo: IHostInfo,
private $httpClient: Server.IHttpClient,
private $injector: IInjector,
private $logger: ILogger,
private $staticConfig: IStaticConfig,
private $xcodeSelectService: IXcodeSelectService) { }
// This property was introduced due to the fact that the $platformService dependency
// ultimately tries to resolve the current project's dir and fails if not executed from within a project
private get $platformService(): IPlatformService {
return this.$injector.resolve("platformService");
}
private get $projectData(): IProjectData {
return this.$injector.resolve("projectData");
}
public upload(data: IITMSData): IFuture<void> {
return (() => {
if (!this.$hostInfo.isDarwin) {
this.$errors.failWithoutHelp("iOS publishing is only available on Mac OS X.");
}
temp.track();
let itmsTransporterPath = this.getITMSTransporterPath().wait(),
ipaFileName = "app.ipa",
itmsDirectory = temp.mkdirSync("itms-"),
innerDirectory = path.join(itmsDirectory, "mybundle.itmsp"),
ipaFileLocation = path.join(innerDirectory, ipaFileName),
platform = this.$devicePlatformsConstants.iOS,
forDevice = true,
iOSBuildConfig: IiOSBuildConfig = {
buildForDevice: forDevice,
mobileProvisionIdentifier: data.mobileProvisionIdentifier,
codeSignIdentity: data.codeSignIdentity
},
loggingLevel = data.verboseLogging ? ITMSConstants.VerboseLoggingLevels.Verbose : ITMSConstants.VerboseLoggingLevels.Informational,
bundleId = this.getBundleIdentifier(data.ipaFilePath).wait(),
iOSApplication = this.getiOSApplication(data.username, data.password, bundleId).wait();
this.$fs.createDirectory(innerDirectory).wait();
if (data.ipaFilePath) {
this.$fs.copyFile(data.ipaFilePath, ipaFileLocation).wait();
} else {
this.$platformService.buildPlatform(platform, iOSBuildConfig).wait();
this.$platformService.copyLastOutput(platform, ipaFileLocation, { isForDevice: forDevice }).wait();
}
let ipaFileHash = this.$fs.getFileShasum(ipaFileLocation, {algorithm: "md5"}).wait(),
ipaFileSize = this.$fs.getFileSize(ipaFileLocation).wait(),
metadata = this.getITMSMetadataXml(iOSApplication.adamId, ipaFileName, ipaFileHash, ipaFileSize);
this.$fs.writeFile(path.join(innerDirectory, ITMSConstants.ApplicationMetadataFile), metadata).wait();
this.$childProcess.spawnFromEvent(itmsTransporterPath, ["-m", "upload", "-f", itmsDirectory, "-u", quoteString(data.username), "-p", quoteString(data.password), "-v", loggingLevel], "close", { stdio: "inherit" }).wait();
}).future<void>()();
}
public getiOSApplications(credentials: ICredentials): IFuture<IiTunesConnectApplication[]> {
return ((): IiTunesConnectApplication[] => {
if (!this._itunesConnectApplications) {
let requestBody = this.getContentDeliveryRequestBody(credentials),
contentDeliveryResponse = this.$httpClient.httpRequest({
url: "https://contentdelivery.itunes.apple.com/WebObjects/MZLabelService.woa/json/MZITunesProducerService",
method: "POST",
body: requestBody
}).wait(),
contentDeliveryBody: IContentDeliveryBody = JSON.parse(contentDeliveryResponse.body);
if (!contentDeliveryBody.result.Success || !contentDeliveryBody.result.Applications) {
let errorMessage = ["Unable to connect to iTunes Connect"];
if (contentDeliveryBody.result.Errors && contentDeliveryBody.result.Errors.length) {
errorMessage = errorMessage.concat(contentDeliveryBody.result.Errors);
}
this.$errors.failWithoutHelp(errorMessage.join(EOL));
}
this._itunesConnectApplications = contentDeliveryBody.result.Applications.filter(app => app.type === ItunesConnectApplicationTypes.iOS);
}
return this._itunesConnectApplications;
}).future<IiTunesConnectApplication[]>()();
}
/**
* Gets iTunes Connect application corresponding to the given bundle identifier.
* @param {string} username For authentication with iTunes Connect.
* @param {string} password For authentication with iTunes Connect.
* @param {string} bundleId Application's Bundle Identifier
* @return {IFuture<IiTunesConnectApplication>} The iTunes Connect application.
*/
private getiOSApplication(username: string, password: string, bundleId: string) : IFuture<IiTunesConnectApplication> {
return (():IiTunesConnectApplication => {
let iOSApplications = this.getiOSApplications({username, password}).wait();
if (!iOSApplications || !iOSApplications.length) {
this.$errors.failWithoutHelp(`Cannot find any registered applications for Apple ID ${username} in iTunes Connect.`);
}
let iOSApplication = _.find(iOSApplications, app => app.bundleId === bundleId);
if (!iOSApplication) {
this.$errors.failWithoutHelp(`Cannot find registered applications that match the specified identifier ${bundleId} in iTunes Connect.`);
}
return iOSApplication;
}).future<IiTunesConnectApplication>()();
}
/**
* Gets the application's bundle identifier. If ipaFileFullPath is provided will extract the bundle identifier from the .ipa file.
* @param {string} ipaFileFullPath Optional full path to .ipa file
* @return {IFuture<string>} Application's bundle identifier.
*/
private getBundleIdentifier(ipaFileFullPath?: string): IFuture<string> {
return ((): string => {
if (!this._bundleIdentifier) {
if (!ipaFileFullPath) {
this._bundleIdentifier = this.$projectData.projectId;
} else {
if (!this.$fs.exists(ipaFileFullPath).wait() || path.extname(ipaFileFullPath) !== ".ipa") {
this.$errors.failWithoutHelp(`Cannot use specified ipa file ${ipaFileFullPath}. File either does not exist or is not an ipa file.`);
}
this.$logger.trace("--ipa set - extracting .ipa file to get app's bundle identifier");
temp.track();
let destinationDir = temp.mkdirSync("ipa-");
this.$fs.unzip(ipaFileFullPath, destinationDir).wait();
let plistObject = this.$bplistParser.parseFile(path.join(destinationDir, "Payload", "iossampleapp.app", "Info.plist")).wait();
let bundleId = plistObject && plistObject[0] && plistObject[0].CFBundleIdentifier;
if (!bundleId) {
this.$errors.failWithoutHelp(`Unable to determine bundle identifier from ${ipaFileFullPath}.`);
}
this.$logger.trace(`bundle identifier determined to be ${bundleId}`);
this._bundleIdentifier = bundleId;
}
}
return this._bundleIdentifier;
}).future<string>()();
}
private getITMSTransporterPath(): IFuture<string> {
return ((): string => {
if (!this._itmsTransporterPath) {
let xcodePath = this.$xcodeSelectService.getContentsDirectoryPath().wait(),
xcodeVersion = this.$xcodeSelectService.getXcodeVersion().wait(),
result = path.join(xcodePath, "Applications", "Application Loader.app", "Contents");
xcodeVersion.patch = xcodeVersion.patch || "0";
// iTMS Transporter's path has been modified in Xcode 6.3
// https://github.com/nomad/shenzhen/issues/243
if (xcodeVersion.major && xcodeVersion.minor &&
versionCompare(xcodeVersion, "6.3.0") < 0) {
result = path.join(result, "MacOS");
}
this._itmsTransporterPath = path.join(result, ITMSConstants.iTMSDirectoryName, "bin", ITMSConstants.iTMSExecutableName);
}
if(!this.$fs.exists(this._itmsTransporterPath).wait()) {
this.$errors.failWithoutHelp('iTMS Transporter not found on this machine - make sure your Xcode installation is not damaged.');
}
return this._itmsTransporterPath;
}).future<string>()();
}
private getContentDeliveryRequestBody(credentials: ICredentials): string {
// All of those values except credentials are hardcoded
// Apple's content delivery API is very picky with handling requests
// and if only one of these ends up missing the API returns
// a response with 200 status code and an error
return JSON.stringify({
id: "1", // magic number
jsonrpc: "2.0",
method: "lookupSoftwareApplications",
params: {
Username: credentials.username,
Password: credentials.password,
Version: "2.9.1 (441)",
Application: "Application Loader",
OSIdentifier: "Mac OS X 10.8.5 (x86_64)"
}
});
}
private getITMSMetadataXml(appleId: string, ipaFileName: string, ipaFileHash: string, ipaFileSize: number): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<package version="software4.7" xmlns="http://apple.com/itunes/importer">
<software_assets apple_id="${appleId}">
<asset type="bundle">
<data_file>
<file_name>${ipaFileName}</file_name>
<checksum type="md5">${ipaFileHash}</checksum>
<size>${ipaFileSize}</size>
</data_file>
</asset>
</software_assets>
</package>`;
}
}
$injector.register("itmsTransporterService", ITMSTransporterService);