-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropboxInstall.py
executable file
·296 lines (251 loc) · 11.5 KB
/
DropboxInstall.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python
import sys
import os
import re
import string
import glob
import argparse
import subprocess
import tempfile
import shutil
import urllib
PLIST_BUDDY = "/usr/libexec/PlistBuddy"
MOBILE_PROVISIONS = "~/Library/MobileDevice/Provisioning Profiles/*.mobileprovision"
OUTPUT_IPA = "Output.ipa"
ICON_PNG = "Icon.png"
MANIFEST_PLIST = "manifest.plist"
INDEX_HTML = "index.html"
DEFAULT_DROPBOX_ROOT = "/AdHocBuilds"
tmpDir = None
log = None
class Logger:
def __init__(self, quiet):
self.quiet = quiet
def e(self, *args):
self._write(sys.stderr, args)
def v(self, *args):
if not self.quiet:
self._write(sys.stdout, args)
def o(self, *args):
self._write(sys.stdout, args)
def _write(self, stream, args):
for a in args:
stream.write(str(a))
stream.write("\n")
stream.flush()
def requireFile(path, errordesc, extraError = None):
if not os.path.isfile(path):
log.e("Error: ", errordesc, " not a file.")
log.e(" path = ", path)
if extraError is not None:
log.e(" ", extraError)
sys.exit(1)
def requireDir(path, errordesc, extraError = None):
if not os.path.isdir(path):
log.e("Error: ", errordesc, " not a directory.")
log.e(" path = ", path)
if extraError is not None:
log.e(" ", extraError)
sys.exit(1)
def requireMatch(pattern, string, errordesc):
m = re.match(pattern, string)
if m is None:
log.e("Error: ", errordesc, " does not match expected pattern.")
log.e(" value = ", string)
log.e(" pattern = ", pattern)
sys.exit(1)
def getPlistValue(path, key):
try:
with open(os.devnull, 'w') as devnull:
return subprocess.check_output([PLIST_BUDDY, "-c", "Print " + key, path], stderr = devnull).strip()
except:
return ""
def writeMobileProvisionPList(mobileprovision, plistFile):
with open(plistFile, "w") as f:
r = subprocess.call(["security", "cms", "-D", "-u0", "-i", mobileprovision], stdout = f)
if r != 0:
return False
return True
def getMobileProvisionPlistValue(mobileprovision, key):
tmpFile = os.path.join(tmpDir, "tmp.plist")
if not writeMobileProvisionPList(mobileprovision, tmpFile):
return None
return getPlistValue(tmpFile, key)
def findBestIcon(bundlePath, bundleInfoPlist):
bestIcon = None
bestSize = 0.0
for key in [":CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles", ":CFBundleIcons~ipad:CFBundlePrimaryIcon:CFBundleIconFiles"]:
for m in re.finditer(r"\w+(\d+(?:\.\d+)?)x\1", getPlistValue(bundleInfoPlist, key)):
size = float(m.group(1))
for scale, scaleSuffix in [(1, ""), (2, "@2x"), (3, "@3x")]:
iconSize = size * scale
if bestIcon is None or iconSize > bestSize:
for deviceSuffix in ["", "~iphone", "~ipad"]:
icon = os.path.join(bundlePath, m.group() + scaleSuffix + deviceSuffix + ".png")
if os.path.isfile(icon):
bestIcon = icon
bestSize = iconSize
return bestIcon
def findSigningIdentity(teamIdentifier):
output = subprocess.check_output(["security", "find-identity", "-v", "-p", "codesigning"])
match = re.search(r"iPhone Distribution: .* \(" + teamIdentifier + "\)", output)
if match is None:
log.e("Error: Failed to automatically find signing identity.")
sys.exit(1)
return match.group(0)
def findMobileProvisionAndSigningIdentity(bundleIdentifier):
for mobileprovision in glob.iglob(os.path.expanduser(MOBILE_PROVISIONS)):
tmpFile = os.path.join(tmpDir, "tmp.plist")
if not writeMobileProvisionPList(mobileprovision, tmpFile):
continue
mpBundleId = getPlistValue(tmpFile, ":Entitlements:application-identifier")
mpTeamId = getPlistValue(tmpFile, ":TeamIdentifier:0")
if mpTeamId + "." + bundleIdentifier != mpBundleId:
continue
if getPlistValue(tmpFile, ":Platform:0") != "iOS":
continue
if getPlistValue(tmpFile, ":Entitlements:get-task-allow") == "true":
continue
if getPlistValue(tmpFile, ":ProvisionedDevices") == "":
continue
signingIdentity = findSigningIdentity(mpTeamId)
return (mobileprovision, signingIdentity)
return (None, None)
class DropboxUploader:
def __init__(self, uploaderDir):
self.script = os.path.join(uploaderDir, "dropbox_uploader.sh")
requireFile(self.script, "Dropbox uploader script")
requireFile(os.path.expanduser("~/.dropbox_uploader"), "Dropbox uploader config file", "Please run " + self.script + "to set up dropbox_uploader. The 'App permission' mode is recommended.")
def upload(self, source, dest):
subprocess.check_call([self.script, "-q", "upload", source, dest])
def share(self, path):
return subprocess.check_output([self.script, "-q", "share", path]).strip().replace("?dl=0", "").replace("www.dropbox.com", "dl.dropboxusercontent.com")
def run(args):
scriptDir = os.path.dirname(sys.argv[0])
templateDir = os.path.join(scriptDir, "templates")
binDir = os.path.join(scriptDir, "bin")
manifestTemplate = os.path.join(templateDir, MANIFEST_PLIST)
manifestTarget = os.path.join(tmpDir, MANIFEST_PLIST)
indexTemplate = os.path.join(templateDir, INDEX_HTML)
indexTarget = os.path.join(tmpDir, INDEX_HTML)
dropboxUploader = DropboxUploader(os.path.join(scriptDir, "externals", "Dropbox-Uploader"))
bundlePath = args.bundle
bundleInfoPlist = os.path.join(bundlePath, "Info.plist")
bundleEmbeddedMobileProvision = os.path.join(bundlePath, "embedded.mobileprovision")
packageApplication = os.path.join(tmpDir, "PackageApplication")
packageApplicationOrig = os.path.join(scriptDir, "externals", "PackageApplication", "PackageApplication")
packageApplicationPatch = os.path.join(scriptDir, "PackageApplication.patch")
# package application needs absolute path:
ipaTarget = os.path.realpath(os.path.join(tmpDir, OUTPUT_IPA))
requireFile(manifestTemplate, "Manifest template")
requireFile(indexTemplate, "Index template")
requireDir(bundlePath, "Bundle")
requireFile(bundleInfoPlist, "Bundle Info.plist")
requireFile(bundleEmbeddedMobileProvision, "Bundle embedded.mobileprovision")
log.v("Gathering Info...")
bundleIdentifier = getPlistValue(bundleInfoPlist, ":CFBundleIdentifier")
requireMatch(r"^\w+(\.\w+)*$", bundleIdentifier, "Bundle Identifier")
bundleVersion = getPlistValue(bundleInfoPlist, ":CFBundleVersion")
requireMatch(r"^\d+(\.\d+)*$", bundleVersion, "Bundle Version")
bundleDisplayName = getPlistValue(bundleInfoPlist, ":CFBundleDisplayName")
requireMatch(r"^.+$", bundleDisplayName, "Bundle Name")
iconTarget = findBestIcon(bundlePath, bundleInfoPlist)
dropboxRoot = os.path.join(args.dropbox_root, bundleIdentifier)
ipaDropboxTarget = os.path.join(dropboxRoot, OUTPUT_IPA)
iconDropboxTarget = os.path.join(dropboxRoot, ICON_PNG)
manifestDropboxTarget = os.path.join(dropboxRoot, MANIFEST_PLIST)
indexDropboxTarget = os.path.join(dropboxRoot, INDEX_HTML)
log.v(" Bundle Identifier = ", bundleIdentifier)
log.v(" Bundle Version = ", bundleVersion)
log.v(" Bundle Name = ", bundleDisplayName)
log.v(" Best Icon = ", os.path.basename(iconTarget))
log.v(" Dropbox Target = ", dropboxRoot)
log.v(" done")
log.v("Determining (re)signing info...")
(mobileprovision, signingIdentity) = findMobileProvisionAndSigningIdentity(bundleIdentifier)
if args.signing_identity is not None:
signingIdentity = args.signing_identity
log.v(" Signing Identity = ", signingIdentity)
if args.mobile_provision is not None:
mobileprovision = args.mobile_provision
log.v(" Mobile Provision = ", mobileprovision)
if args.check_only:
return
log.v("Packaging application...")
shutil.copy(packageApplicationOrig, packageApplication)
subprocess.check_output(["patch", packageApplication, packageApplicationPatch])
subprocess.check_output(["chmod", "+x", packageApplication])
subprocess.check_call([packageApplication, bundlePath, "-s", signingIdentity, "-o", ipaTarget, "--embed", mobileprovision])
log.v(" done")
log.v("Uploading IPA to Dropbox...")
dropboxUploader.upload(ipaTarget, ipaDropboxTarget)
ipaDropboxUrl = dropboxUploader.share(ipaDropboxTarget)
dropboxUploader.upload(iconTarget, iconDropboxTarget)
iconDropboxUrl = dropboxUploader.share(iconDropboxTarget)
log.v(" done")
log.v("Creating manifest...")
with open(manifestTemplate, "r") as fIn:
with open(manifestTarget, "w") as fOut:
fOut.write(string.Template(fIn.read()).safe_substitute(
IpaUrl = ipaDropboxUrl,
BundleIdentifier = bundleIdentifier,
BundleVersion = bundleVersion,
Title = bundleDisplayName,
IconUrl = iconDropboxUrl
))
dropboxUploader.upload(manifestTarget, manifestDropboxTarget)
manifestDropboxUrl = dropboxUploader.share(manifestDropboxTarget)
log.v(" done")
log.v("Creating index...")
with open(indexTemplate, "r") as fIn:
with open(indexTarget, "w") as fOut:
fOut.write(string.Template(fIn.read()).safe_substitute(
Title = bundleDisplayName,
About = "",
IconUrl = iconDropboxUrl,
BundleVersion = bundleVersion,
IpaSize = "%.1f MiB" % (os.path.getsize(ipaTarget) / 1048576.0),
EscapedManifestUrl = urllib.quote(manifestDropboxUrl, safe = '')
))
dropboxUploader.upload(indexTarget, indexDropboxTarget)
indexDropboxUrl = dropboxUploader.share(indexDropboxTarget)
log.v(" done")
log.v("")
log.v("Link to OTA install page:")
log.o(indexDropboxUrl)
if __name__ == "__main__":
try:
tmpDir = tempfile.mkdtemp()
parser = argparse.ArgumentParser(
description = "Upload AdHoc iPhone builds to Dropbox, for OTA installation on devices."
)
parser.add_argument(
"--check-only",
action = "store_const",
const = True,
default = False,
help = "Only perform checks, don't upload anything.")
parser.add_argument(
"--dropbox-root",
default = DEFAULT_DROPBOX_ROOT,
help = "Path in DropBox to put builds. This path is either relative to your Dropbox root or the uploader's folder in Apps depending on how you have set up dropbox_uploader. (Default: %(default)s)")
parser.add_argument(
"-s", "--signing-identity",
help = "Signing identify to use when signing the IPA file. If not supplied the program will try to automatically find one.")
parser.add_argument(
"--mobile-provision",
help = "Path to mobile provision to embed within the IPA file. If not supplied the problem will try to automatically find one.")
parser.add_argument(
"-q", "--quiet",
action = "store_const",
const = True,
default = False,
help = "Supress all output except the final HTML URL.")
parser.add_argument(
"bundle",
help = "Path to built .app bundle.")
args = parser.parse_args()
log = Logger(args.quiet)
run(args)
finally:
shutil.rmtree(tmpDir)