forked from jessepeterson/margarita
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmargarita.py
251 lines (194 loc) · 7.83 KB
/
margarita.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
from flask import Flask
from flask import jsonify, render_template, redirect
from flask import request, Response
app = Flask(__name__)
import os, sys
try:
import json
except ImportError:
# couldn't find json, try simplejson library
import simplejson as json
import getopt
from operator import itemgetter
from reposadolib import reposadocommon
def json_response(r):
'''Glue for wrapping raw JSON responses'''
return Response(json.dumps(r), status=200, mimetype='application/json')
@app.route('/')
def index():
return render_template('margarita.html')
@app.route('/branches', methods=['GET'])
def list_branches():
'''Returns catalog branch names and associated updates'''
catalog_branches = reposadocommon.getCatalogBranches()
# reorganize the updates into an array of branches
branches = []
for branch in catalog_branches.keys():
branches.append({'name': branch, 'products': catalog_branches[branch]})
return json_response(branches)
def get_packages_urls(p):
if not p.has_key('Packages'):
return None
packages = p['Packages']
if len(packages) == 0:
return None
out=''
for p in packages:
out+="<a href='%s/%s'>%s</a> (%.2f Mb), " % (reposadocommon.pref('LocalCatalogURLBase'),p['URL'][p['URL'].index('/',9)+1:], p['URL'].split('/')[-1], p['Size']/1024./1024)
return out[:-2]
def get_description_content(html):
if len(html) == 0:
return None
# in the interest of (attempted) speed, try to avoid regexps
lwrhtml = html.lower()
celem = 'p'
startloc = lwrhtml.find('<' + celem + '>')
if startloc == -1:
startloc = lwrhtml.find('<' + celem + ' ')
if startloc == -1:
celem = 'body'
startloc = lwrhtml.find('<' + celem)
if startloc != -1:
startloc += 6 # length of <body>
if startloc == -1:
# no <p> nor <body> tags. bail.
return None
endloc = lwrhtml.rfind('</' + celem + '>')
if endloc == -1:
endloc = len(html)
elif celem != 'body':
# if the element is a body tag, then don't include it.
# DOM parsing will just ignore it anyway
endloc += len(celem) + 3
return html[startloc:endloc]
@app.route('/products', methods=['GET'])
def products():
products = reposadocommon.getProductInfo()
prodlist = []
for prodid in products.keys():
if 'title' in products[prodid] and 'version' in products[prodid] and 'PostDate' in products[prodid]:
prodlist.append({
'title': products[prodid]['title'],
'version': products[prodid]['version'],
'PostDate': products[prodid]['PostDate'].strftime('%Y-%m-%d'),
'description': get_description_content(products[prodid]['description']),
'packages': get_packages_urls(products[prodid]['CatalogEntry']),
'id': prodid,
'depr': len(products[prodid].get('AppleCatalogs', [])) < 1,
'seed': 'seed' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'yosemite': 'index-10.10' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'mavericks': 'index-10.9' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'mountainlion': 'index-mountainlion' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'lion': 'index-lion' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'snowleopard': 'index-leopard-snowleopard.merged-1.sucatalog' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'leopard': 'index-leopard.merged-1.sucatalog' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
'tiger': 'index-1.sucatalog' in ''.join(products[prodid].get('OriginalAppleCatalogs', [])),
})
else:
print 'Invalid update!'
sprodlist = sorted(prodlist, key=itemgetter('PostDate'), reverse=True)
return json_response(sprodlist)
@app.route('/new_branch/<branchname>', methods=['POST'])
def new_branch(branchname):
catalog_branches = reposadocommon.getCatalogBranches()
if branchname in catalog_branches:
reposadocommon.print_stderr('Branch %s already exists!', branchname)
abort(401)
catalog_branches[branchname] = []
reposadocommon.writeCatalogBranches(catalog_branches)
return jsonify(result='success')
@app.route('/delete_branch/<branchname>', methods=['POST'])
def delete_branch(branchname):
catalog_branches = reposadocommon.getCatalogBranches()
if not branchname in catalog_branches:
reposadocommon.print_stderr('Branch %s does not exist!', branchname)
return
del catalog_branches[branchname]
# this is not in the common library, so we have to duplicate code
# from repoutil
for catalog_URL in reposadocommon.pref('AppleCatalogURLs'):
localcatalogpath = reposadocommon.getLocalPathNameFromURL(catalog_URL)
# now strip the '.sucatalog' bit from the name
if localcatalogpath.endswith('.sucatalog'):
localcatalogpath = localcatalogpath[0:-10]
branchcatalogpath = localcatalogpath + '_' + branchname + '.sucatalog'
if os.path.exists(branchcatalogpath):
reposadocommon.print_stdout(
'Removing %s', os.path.basename(branchcatalogpath))
os.remove(branchcatalogpath)
reposadocommon.writeCatalogBranches(catalog_branches)
return jsonify(result=True);
@app.route('/add_all/<branchname>', methods=['POST'])
def add_all(branchname):
products = reposadocommon.getProductInfo()
catalog_branches = reposadocommon.getCatalogBranches()
catalog_branches[branchname] = products.keys()
reposadocommon.writeCatalogBranches(catalog_branches)
reposadocommon.writeAllBranchCatalogs()
return jsonify(result=True)
@app.route('/process_queue', methods=['POST'])
def process_queue():
catalog_branches = reposadocommon.getCatalogBranches()
for change in request.json:
prodId = change['productId']
branch = change['branch']
if branch not in catalog_branches.keys():
print 'No such catalog'
continue
if change['listed']:
# if this change /was/ listed, then unlist it
if prodId in catalog_branches[branch]:
print 'Removing product %s from branch %s' % (prodId, branch, )
catalog_branches[branch].remove(prodId)
else:
# if this change /was not/ listed, then list it
if prodId not in catalog_branches[branch]:
print 'Adding product %s to branch %s' % (prodId, branch, )
catalog_branches[branch].append(prodId)
print 'Writing catalogs'
reposadocommon.writeCatalogBranches(catalog_branches)
reposadocommon.writeAllBranchCatalogs()
return jsonify(result=True)
@app.route('/dup_apple/<branchname>', methods=['POST'])
def dup_apple(branchname):
catalog_branches = reposadocommon.getCatalogBranches()
if branchname not in catalog_branches.keys():
print 'No branch ' + branchname
return jsonify(result=False)
# generate list of (non-drepcated) updates
products = reposadocommon.getProductInfo()
prodlist = []
for prodid in products.keys():
if len(products[prodid].get('AppleCatalogs', [])) >= 1:
prodlist.append(prodid)
catalog_branches[branchname] = prodlist
print 'Writing catalogs'
reposadocommon.writeCatalogBranches(catalog_branches)
reposadocommon.writeAllBranchCatalogs()
return jsonify(result=True)
@app.route('/dup/<frombranch>/<tobranch>', methods=['POST'])
def dup(frombranch, tobranch):
catalog_branches = reposadocommon.getCatalogBranches()
if frombranch not in catalog_branches.keys() or tobranch not in catalog_branches.keys():
print 'No branch ' + branchname
return jsonify(result=False)
catalog_branches[tobranch] = catalog_branches[frombranch]
print 'Writing catalogs'
reposadocommon.writeCatalogBranches(catalog_branches)
reposadocommon.writeAllBranchCatalogs()
return jsonify(result=True)
def main():
optlist, args = getopt.getopt(sys.argv[1:], 'db:p:')
flaskargs = {}
flaskargs['host'] = '0.0.0.0'
flaskargs['port'] = 8089
for o, a in optlist:
if o == '-d':
flaskargs['debug'] = True
elif o == '-b':
flaskargs['host'] = a
elif o == '-p':
flaskargs['port'] = int(a)
app.run(**flaskargs)
if __name__ == '__main__':
main()