This repository has been archived by the owner on Nov 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghpu.py
290 lines (221 loc) · 10.8 KB
/
ghpu.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
#!/usr/bin/env python2.5
# 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.
# for the latest version and documentation:
# https://github.com/jheddings/indigo-ghpu
import os
import tempfile
import subprocess
import shutil
import json
import httplib
import plistlib
import indigo
from urllib2 import urlopen
from StringIO import StringIO
from zipfile import ZipFile
################################################################################
class GitHubPluginUpdater(object):
#---------------------------------------------------------------------------
def __init__(self, owner, repo, plugin=None):
self.owner = owner
self.repo = repo
self.plugin = plugin
#---------------------------------------------------------------------------
# install the latest version of the plugin represented by this updater
def install(self):
self._log('Installing plugin from %s/%s...' % (self.owner, self.repo))
latestRelease = self.getLatestRelease()
if (latestRelease == None):
self._error('No release available')
return False
try:
self._installRelease(latestRelease)
except Exception as e:
self._error(str(e))
return False
return True
#---------------------------------------------------------------------------
# updates the contained plugin if needed
def update(self, currentVersion=None):
update = self._prepareForUpdate(currentVersion)
if (update == None): return False
try:
self._installRelease(update)
except Exception as e:
self._error(str(e))
return False
return True
#---------------------------------------------------------------------------
# returns the URL for an update if there is one
def checkForUpdate(self, currentVersion=None):
update = self._prepareForUpdate(currentVersion)
return (update != None)
#---------------------------------------------------------------------------
# returns the update package, if there is one
def getUpdate(self, currentVersion):
self._debug('Current version is: %s' % currentVersion)
update = self.getLatestRelease()
if (update == None):
self._debug('No release available')
return None
# assume the tag is the release version
latestVersion = update['tag_name'].lstrip('v')
self._debug('Latest release is: %s' % latestVersion)
if (ver(currentVersion) >= ver(latestVersion)):
return None
return update
#---------------------------------------------------------------------------
# returns the latest release information from a given user / repo
# https://developer.github.com/v3/repos/releases/
def getLatestRelease(self):
self._debug('Getting latest release from %s/%s...' % (self.owner, self.repo))
return self._GET('/repos/' + self.owner + '/' + self.repo + '/releases/latest')
#---------------------------------------------------------------------------
# returns a tuple for the current rate limit: (limit, remaining, resetTime)
# https://developer.github.com/v3/rate_limit/
# NOTE this does not count against the current limit
def getRateLimit(self):
limiter = self._GET('/rate_limit')
remain = int(limiter['rate']['remaining'])
limit = int(limiter['rate']['limit'])
resetAt = int(limiter['rate']['reset'])
return (limit, remain, resetAt)
#---------------------------------------------------------------------------
# form a GET request to api.github.com and return the parsed JSON response
def _GET(self, requestPath):
self._debug('GET %s' % requestPath)
headers = {
'User-Agent': 'Indigo-Plugin-Updater',
'Accept': 'application/vnd.github.v3+json'
}
data = None
try:
conn = httplib.HTTPSConnection('api.github.com')
conn.request('GET', requestPath, None, headers)
resp = conn.getresponse()
self._debug('HTTP %d %s' % (resp.status, resp.reason))
if (resp.status == 200):
data = json.loads(resp.read())
elif (400 <= resp.status < 500):
error = json.loads(resp.read())
self._error('Client Error: %s' % error['message'])
else:
self._error('Unhandled Error: %s' % resp.reason)
except Exception as e:
self._error('Unhandled Exception: %s' % str(e))
return None
return data
#---------------------------------------------------------------------------
# prepare for an update
def _prepareForUpdate(self, currentVersion=None):
self._log('Checking for updates...')
# sort out the currentVersion based on user params
if ((currentVersion == None) and (self.plugin == None)):
self._error('Must provide either currentVersion or plugin reference')
return None
elif (currentVersion == None):
currentVersion = str(self.plugin.pluginVersion)
self._debug('Plugin version detected: %s' % currentVersion)
else:
self._debug('Plugin version provided: %s' % currentVersion)
update = self.getUpdate(currentVersion)
if (update == None):
self._log('No updates are available')
return None
self._error('A new version is available: %s' % update['html_url'])
return update
#---------------------------------------------------------------------------
# verifies the plugin info in the zipfile and returns the confirmed name-version
def _verifyPluginInfo(self, zipfile):
topdir = zipfile.namelist()[0]
# read and confirm the plugin info contained in the zipfile
plistFile = os.path.join(topdir, 'Contents', 'Info.plist')
self._debug('Searching for plugin info: %s' % plistFile)
plistData = zipfile.read(plistFile)
if (plistData == None):
raise Exception('Unable to read new plugin info')
plist = plistlib.readPlistFromString(plistData)
pluginId = plist.get('CFBundleIdentifier', None)
self._debug('Detected pluginId in zipfile: %s' % pluginId)
pluginName = plist.get('CFBundleDisplayName', None)
self._debug('Detected pluginName in zipfile: %s' % pluginName)
pluginVersion = plist.get('PluginVersion', None)
self._debug('Detected pluginNersion in zipfile: %s' % pluginVersion)
if (pluginId == None):
raise Exception('Unable to detect pluginId in download')
elif (pluginName == None):
raise Exception('Unable to detect pluginName in download')
elif (pluginVersion == None):
raise Exception('Unable to detect pluginVersion in download')
elif (self.plugin and (self.plugin.pluginId != pluginId)):
raise Exception('ID mismatch in download')
return pluginName + '-' + pluginVersion
#---------------------------------------------------------------------------
# install a given release
def _installRelease(self, release):
tmpdir = tempfile.gettempdir()
self._debug('Workspace: %s' % tmpdir)
zipfile = self._getZipFileFromRelease(release)
newPluginName = self._verifyPluginInfo(zipfile)
self._debug('Found plugin in download: %s' % newPluginName)
# the top level directory should be the first entry in the zipfile
# it is typically a combination of the owner, repo & release tag
repotag = zipfile.namelist()[0]
# this is where the files will end up after extraction
destDir = os.path.join(tmpdir, repotag)
self._debug('Destination directory: %s' % destDir)
if (os.path.exists(destDir)): shutil.rmtree(destDir)
# this is where the plugin will reside prior to installation
newPluginDir = os.path.join(tmpdir, newPluginName + '.indigoPlugin')
self._debug('Plugin directory: %s' % newPluginDir)
if (os.path.exists(newPluginDir)): shutil.rmtree(newPluginDir)
# at this point, we should have been able to confirm the top-level directory
# based on reading the pluginId, we know the plugin in the zipfile matches our
# internal plugin reference (if we have one), temp directories are available
# and we know the package location for installing the plugin
zipfile.extractall(tmpdir)
# now, make sure we got what we expected
if (not os.path.exists(destDir)):
raise Exception('Failed to extract plugin')
# for 'open' to work properly, we need to use the .indigoPlugin package extension
os.rename(destDir, newPluginDir)
self._debug('Installing %s' % newPluginName)
subprocess.call(['open', newPluginDir])
# all clear... the new plugin has been installed
#---------------------------------------------------------------------------
# return the valid zipfile from the release, or raise an exception
def _getZipFileFromRelease(self, release):
# download and verify zipfile from the release package
zipball = release.get('zipball_url', None)
if (zipball == None):
raise Exception('Invalid release package: no zipball')
self._debug('Downloading zip file: %s' % zipball)
zipdata = urlopen(zipball).read()
zipfile = ZipFile(StringIO(zipdata))
self._debug('Verifying zip file (%d bytes)...' % len(zipdata))
if (zipfile.testzip() != None):
raise Exception('Download corrupted')
return zipfile
#---------------------------------------------------------------------------
# convenience method for log messages
def _log(self, msg):
indigo.server.log(msg)
#---------------------------------------------------------------------------
# convenience method for debug messages
def _debug(self, msg):
if self.plugin:
self.plugin.debugLog(msg)
#---------------------------------------------------------------------------
# convenience method for error messages
def _error(self, msg):
if self.plugin:
self.plugin.errorLog(msg)
################################################################################
# maps the standard version string as a tuple for comparrison
def ver(vstr): return tuple(map(int, (vstr.split('.'))))