-
Notifications
You must be signed in to change notification settings - Fork 19
/
testflight_invite.py
executable file
·257 lines (226 loc) · 9.26 KB
/
testflight_invite.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
#!/usr/bin/python
#
# testflight_invite.py
#
# TestFlight Inviter
# Copyright 2014-2015 Brian Donohue
#
# Version 1.0
#
# Latest version and additional information available at:
# http://appdailysales.googlecode.com/
#
# This script will automate TestFlight invites for Apple's TestFlight integration.
#
# This script is heavily based off of appdailysales.py (https://github.com/kirbyt/appdailysales)
# Original Maintainer
# Kirby Turner
#
# Original Contributors:
# Leon Ho
# Rogue Amoeba Software, LLC
# Keith Simmons
# Andrew de los Reyes
# Maarten Billemont
# Daniel Dickison
# Mike Kasprzak
# Shintaro TAKEMURA
# aaarrrggh (Paul)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import json
import urllib
import urllib2
import cookielib
import re
import sys
import os
from getpass import getpass
class ITCException(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value);
class TFInviteDuplicateException(Exception):
pass
# There is an issue with Python 2.5 where it assumes the 'version'
# cookie value is always interger. However, itunesconnect.apple.com
# returns this value as a string, i.e., "1" instead of 1. Because
# of this we need a workaround that "fixes" the version field.
#
# More information at: http://bugs.python.org/issue3924
class MyCookieJar(cookielib.CookieJar):
def _cookie_from_cookie_tuple(self, tup, request):
name, value, standard, rest = tup
version = standard.get('version', None)
if version is not None:
version = version.replace('"', '')
standard["version"] = version
return cookielib.CookieJar._cookie_from_cookie_tuple(self, tup, request)
class TestFlightInvite:
urlITCBase = 'https://itunesconnect.apple.com%s'
def __init__(self, itcLogin, itcPassword, appId, proxy='', groupId=None, contentProviderId=None):
self.itcLogin = itcLogin
self.itcPassword = itcPassword
self.appId = str(appId)
self._service_key = None
self.proxy = proxy
self.groupId = groupId
self.contentProviderId = contentProviderId
self.opener = self.createOpener()
self.loggedIn = False
def readData(self, url, data=None, headers={}, method=None):
request = urllib2.Request(url, data, headers)
if method is not None:
request.get_method = lambda: method
urlHandle = self.opener.open(request)
return urlHandle.read()
def createOpener(self):
handlers = [] # proxy support
if self.proxy: # proxy support
handlers.append(urllib2.ProxyHandler({"https": self.proxy})) # proxy support
cj = MyCookieJar();
cj.set_policy(cookielib.DefaultCookiePolicy(rfc2965=True))
cjhdr = urllib2.HTTPCookieProcessor(cj)
handlers.append(cjhdr) # proxy support
return urllib2.build_opener(*handlers) # proxy support
@property
def service_key(self):
if self._service_key:
return self._service_key
jsUrl = self.urlITCBase % '/itc/static-resources/controllers/login_cntrl.js'
content = self.readData(jsUrl)
matches = re.search(r"itcServiceKey = '(.*)'", content)
if not matches:
raise ValueError('Unable to find iTunes Connect Service key')
return matches.group(1)
def getGroups(self):
text = self.readData('https://itunesconnect.apple.com/testflight/v2/providers/{teamId}/apps/{appId}/groups'.format(
teamId=self.contentProviderId, appId=self.appId
))
data = json.loads(text)
return data['data']
def getDefaultExternalGroupId(self):
self.groupData = self.getGroups()
for group in self.groupData:
if group['isDefaultExternalGroup']:
return group['id']
return None
def getFirstContentProviderId(self):
# Sample return value
# => {"associatedAccounts"=>
# [{"contentProvider"=>{"contentProviderId"=>11142800, "name"=>"Felix Krause", "contentProviderTypes"=>["Purple Software"]}, "roles"=>["Developer"], "lastLogin"=>1468784113000}],
# "sessionToken"=>{"dsId"=>"8501011116", "contentProviderId"=>18111111, "expirationDate"=>nil, "ipAddress"=>nil},
text = self.readData("https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/detail")
data = json.loads(text)
account = data['data']['associatedAccounts'][0]
return account['contentProvider']['contentProviderId']
def login(self):
if self.loggedIn:
return
data = {
'accountName': self.itcLogin,
'password': self.itcPassword,
'rememberMe': 'false'
}
headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json, text/javascript'
}
loginUrl = 'https://idmsa.apple.com/appleauth/auth/signin?widgetKey=%s' % self.service_key
self.readData(
'https://idmsa.apple.com/appleauth/auth/signin?widgetKey=%s' % self.service_key,
data=json.dumps(data),
headers=headers
)
if not self.contentProviderId:
self.contentProviderId = self.getFirstContentProviderId()
if not self.groupId:
self.groupId = self.getDefaultExternalGroupId()
self.loggedIn = True
def numTesters(self):
self.login()
endpoint = '/WebObjects/iTunesConnect.woa/ra/user/externalTesters/%s/' % self.appId
urlWebsiteExternalTesters = self.urlITCBase % endpoint
externalResponse = self.readData(
"https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/externalTesters/%s/" % self.appId,
headers={'Content-Type': 'application/json'}
)
data = json.loads(externalResponse)
return len(data['data']['users'])
def addTester(self, email, firstname='', lastname=''):
self.login()
params = { 'email': email, 'firstName': firstname, 'lastName': lastname }
text = self.readData(
'https://itunesconnect.apple.com/testflight/v2/providers/{teamId}/apps/{appId}/testers'.format(
teamId=self.contentProviderId, appId=self.appId
),
json.dumps(params),
headers={'Content-Type': 'application/json'}
)
testerResponseBody = json.loads(text)
testerId = testerResponseBody['data']['id']
params = {
'groupId': self.groupId,
'testerId': testerId,
}
return self.readData(
'https://itunesconnect.apple.com/testflight/v2/providers/{teamId}/apps/{appId}/groups/{groupId}/testers/{testerId}'.format(
teamId=self.contentProviderId, appId=self.appId, groupId=self.groupId, testerId=testerId
),
json.dumps(params),
headers={'Content-Type': 'application/json'},
method='PUT'
)
def usage():
print 'Usage: %s <iTC login email> <App ID> <Invitee Email> <Invitee First Name (Optional)> <Invitee Last Name (Optional)' % sys.argv[0]
def main():
if len(sys.argv) < 4:
usage()
return -1
itcLogin = sys.argv[1]
try:
appId = int(sys.argv[2])
except Exception as e:
print 'Invalid App ID'
usage()
sys.exit(-1)
email = sys.argv[3]
firstName = sys.argv[4] if len(sys.argv) > 4 else ''
lastName = sys.argv[5] if len(sys.argv) > 5 else ''
try:
itcPassword = getpass('iTunes Connect Password: ')
assert len(itcPassword)
except:
print '\nFailed to get iTunes Connect password. Aborting...'
usage()
return -1
try:
invite = TestFlightInvite(itcLogin, itcPassword, appId)
invite.addTester(email, firstName, lastName)
print 'Invite Successful'
except TFInviteDuplicateException as e:
print '%s already a tester for AppID %d' % (email, appId)
return -2
except Exception as e:
print 'Invite Failed: %s' % str(e)
return -3
if __name__ == '__main__':
sys.exit(main())