Skip to content

Commit 604a480

Browse files
author
Dennis Schwartz
committed
Clean up updatecomponents.py
1 parent cdd6477 commit 604a480

File tree

4 files changed

+79
-115
lines changed

4 files changed

+79
-115
lines changed

biojs/settings.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
# SECURITY WARNING: keep the secret key used in production secret!
2323
SECRET_KEY = '$&&+$xz)50khd6q+aq&95r1$2urmmdv37=-*lu3v-wwh46829t'
2424

25+
GITHUB_CLIENT_ID = os.environ.get('GITHUB_CLIENT_ID') or ''
26+
GITHUB_CLIENT_SECRET = os.environ.get('GITHUB_CLIENT_SECRET') or ''
27+
2528
# SECURITY WARNING: don't run with debug turned on in production!
2629
try:
2730
from config import *

docker-compose.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ services:
44
command: /bin/sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000 --verbosity 3"
55
image: biojs-backend-base
66
working_dir: /opt
7+
environment:
8+
GITHUB_CLIENT_SECRET: 289807644cc6b4afe50b4bb2c5afcd7056047de0
9+
GITHUB_CLIENT_ID: DennisSchwartz
710
volumes:
811
- .:/opt
912
ports:
1013
- 8000:8000
1114
networks:
1215
- service
13-
1416
networks:
1517
service:

main/management/commands/updatecomponents.py

Lines changed: 65 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,65 @@
11
from django.core.management import BaseCommand
2-
import urllib2, json, urllib
2+
import urllib2, json, urllib, base64
33
from main.models import *
44
try:
5-
from biojs.config import *
5+
from biojs.settings import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET
66
except:
7+
print('ERROR: Could not load config!')
78
GITHUB_CLIENT_ID = ''
89
GITHUB_CLIENT_SECRET = ''
910
from datetime import datetime
1011
import pytz
1112
import ast
13+
import re
1214

1315
# Get sniper data
1416
'''
1517
https://rawgit.com/cytoscape/cytoscape.js/master/package.json
1618
"sniper" key, has "js" and "css". Search for "first"
1719
'''
1820

19-
def get_commit_hash(commits_url):
20-
commits_url = commits_url.split('{')[0] + '?client_id=' + GITHUB_CLIENT_ID + '&client_secret=' + GITHUB_CLIENT_SECRET
21-
print (commits_url)
22-
response = urllib.urlopen(commits_url)
23-
data = json.loads(response.read())[0]
24-
return data['sha']
21+
def get_npm_data():
22+
# response = urllib2.urlopen()
23+
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
24+
req = urllib2.Request("http://registry.npmjs.com/-/v1/search?text=keywords:biojs,bionode&size=500", headers=hdr)
25+
# req = urllib2.Request("http://registry.npmjs.com/-/v1/search?text=biojs-vis-msa&size=1", headers=hdr)
26+
response = urllib2.urlopen(req)
27+
data = json.load(response)
28+
return data
29+
30+
def send_GET_request(user, password, url):
31+
request = urllib2.Request(url)
32+
if (user is not None and password is not None):
33+
base64string = base64.encodestring('%s:%s' % (user, password)).replace('\n', '')
34+
request.add_header('Authorization', 'Basic %s' % base64string)
35+
return urllib2.urlopen(request)
36+
37+
def create_jsdelivr_link(owner, repo, file_path, commit=None):
38+
return str('https://cdn.jsdelivr.net/gh/' + owner + '/' + repo + ('@' + commit if commit else '') + file_path)
39+
40+
def build_dependency_link(owner, repo, dependency, commit=None):
41+
if (re.match('^(?:[a-z]+:)?//', dependency)):
42+
print('Absolute dependency!', dependency)
43+
return dependency
44+
else:
45+
print('relative dependency!', dependency)
46+
return create_jsdelivr_link(owner, repo, dependency, commit)
2547

2648
### store the dependency urls and snippet urls
2749
def update_visualizations(component, commit_hash, test=False):
2850
github_url_list = component.github_url.split('?')[0].split('/')
2951
owner = github_url_list[4]
3052
repo_name = github_url_list[5]
3153
try:
32-
sniper_data = json.load(urllib.urlopen("https://cdn.rawgit.com/" + str(owner) +
33-
'/' + str(repo_name) + "/" + commit_hash + "/package.json"))["sniper"]
34-
except:
54+
url = create_jsdelivr_link(owner, repo_name, '/package.json', commit_hash)
55+
# url = str('https://cdn.jsdelivr.net/gh/' + str(owner) + '/' + str(repo_name) + '@' + commit_hash + '/package.json')
56+
response = send_GET_request(None, None, url)
57+
package = json.load(response)
58+
sniper_data = package["sniper"]
59+
except KeyError:
60+
print('No sniper info in ', repo_name)
3561
return
62+
# buildJS and js are thrown together and then separated by string matching?
3663
try:
3764
buildJS = sniper_data["buildJS"]
3865
except:
@@ -51,56 +78,8 @@ def update_visualizations(component, commit_hash, test=False):
5178
except:
5279
css = []
5380
css_dependencies = buildCSS + css
54-
for dependency in js_dependencies:
55-
if dependency.startswith('http') :
56-
dependency, created = JSDependency.objects.get_or_create(component=component, js_url=dependency)
57-
elif dependency.startswith('/'):
58-
dependency_string = dependency
59-
if 'build/' in dependency_string:
60-
continue
61-
dependency = "https://cdn.rawgit.com/" + str(owner) + '/' + str(repo_name) + "/" + commit_hash + dependency
62-
try:
63-
req_dependency = JSDependency.objects.get(component=component, sniper_data_value=dependency_string)
64-
req_dependency.js_url = dependency
65-
req_dependency.save()
66-
except:
67-
req_dependency = JSDependency.objects.create(component=component, sniper_data_value=dependency_string, js_url=dependency)
68-
else:
69-
dependency_string = dependency
70-
if 'build/' in dependency_string:
71-
continue
72-
dependency = "https://cdn.rawgit.com/" + str(owner) + '/' + str(repo_name) + "/" + commit_hash + "/" + dependency
73-
try:
74-
req_dependency = JSDependency.objects.get(component=component, sniper_data_value=dependency_string)
75-
req_dependency.js_url = dependency
76-
req_dependency.save()
77-
except:
78-
req_dependency = JSDependency.objects.create(component=component, sniper_data_value=dependency_string, js_url=dependency)
79-
for dependency in css_dependencies:
80-
if dependency.startswith('http'):
81-
dependency, created = CSSDependency.objects.get_or_create(component=component, css_url=dependency)
82-
elif dependency.startswith('/'):
83-
dependency_string = dependency
84-
if 'build/' in dependency_string:
85-
continue
86-
dependency = "https://cdn.rawgit.com/" + str(owner) + '/' + str(repo_name) + "/" + commit_hash + dependency
87-
try:
88-
req_dependency = CSSDependency.objects.get(component=component, sniper_data_value=dependency_string)
89-
req_dependency.css_url = dependency
90-
req_dependency.save()
91-
except:
92-
req_dependency = CSSDependency.objects.create(component=component, sniper_data_value=dependency_string, css_url=dependency)
93-
else:
94-
dependency_string = dependency
95-
if 'build/' in dependency_string:
96-
continue
97-
dependency = "https://cdn.rawgit.com/" + str(owner) + '/' + str(repo_name) + "/" + commit_hash + dependency
98-
try:
99-
req_dependency = CSSDependency.objects.get(component=component, sniper_data_value=dependency_string)
100-
req_dependency.css_url = dependency
101-
req_dependency.save()
102-
except:
103-
req_dependency = CSSDependency.objects.create(component=component, sniper_data_value=dependency_string, css_url=dependency)
81+
js_deps = map(lambda l: build_dependency_link(owner, repo_name, l, commit_hash), js_dependencies)
82+
css_deps = map(lambda l: build_dependency_link(owner, repo_name, l, commit_hash), css_dependencies)
10483
try:
10584
sniperData = SniperData.objects.get(component=component)
10685
except:
@@ -114,7 +93,7 @@ def update_visualizations(component, commit_hash, test=False):
11493
if no_browserify:
11594
sniperData.wzrd_url = '#'
11695
else:
117-
sniperData.wzrd_url = "https://wzrd.in/bundle/" + component.name
96+
sniperData.wzrd_url = "https://wzrd.in/bundle/" + component.name
11897
except:
11998
sniperData.wzrd_url = "https://wzrd.in/bundle/" + component.name
12099
try:
@@ -147,35 +126,6 @@ def update_visualizations(component, commit_hash, test=False):
147126
except:
148127
pass
149128

150-
def get_github_data(github_url):
151-
response = urllib.urlopen(github_url)
152-
data = json.load(response)
153-
return data
154-
155-
def get_npm_data():
156-
# response = urllib2.urlopen()
157-
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}
158-
req = urllib2.Request("http://registry.npmjs.com/-/v1/search?text=keywords:biojs,bionode&size=500", headers=hdr)
159-
# req = urllib2.Request("http://registry.npmjs.com/-/v1/search?text=biojs-vis-msa&size=1", headers=hdr)
160-
response = urllib2.urlopen(req)
161-
data = json.load(response)
162-
return data
163-
164-
def get_contributors_data(contributors_url):
165-
response = urllib.urlopen(contributors_url)
166-
data = json.load(response)
167-
return data
168-
169-
def get_downloads(downloads_url):
170-
print (downloads_url)
171-
response = urllib.urlopen(downloads_url)
172-
downloads = 0
173-
data = ast.literal_eval(response.read())
174-
for download in data:
175-
downloads += int(download['download_count'])
176-
return downloads
177-
178-
179129
class Command(BaseCommand):
180130
# during --help
181131
help = "Command to update the details of all the components from Github"
@@ -228,7 +178,7 @@ def handle(self, *args, **options):
228178
try:
229179
github_url = component_data['links']['repository']
230180
url_list = github_url.split('/')
231-
_component.github_url = 'https://api.github.com/repos/' + str(url_list[3]) + '/' + str(url_list[4]) + '?client_id=' + GITHUB_CLIENT_ID + '&client_secret=' + GITHUB_CLIENT_SECRET
181+
_component.github_url = 'https://api.github.com/repos/' + str(url_list[3]) + '/' + str(url_list[4])
232182
except:
233183
pass
234184
try:
@@ -244,8 +194,15 @@ def handle(self, *args, **options):
244194
if _component.github_url:
245195
print (_component.github_url)
246196
try:
247-
github_data = get_github_data(_component.github_url)
248-
except:
197+
response = send_GET_request(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, _component.github_url)
198+
github_data = json.load(response)
199+
except urllib2.HTTPError as e:
200+
print('Error getting github data!')
201+
print(e)
202+
continue
203+
except Exception as e:
204+
print('Unexpected error accessing Github!')
205+
print(e)
249206
continue
250207
_component.stars = github_data['stargazers_count']
251208
_component.forks = github_data['forks']
@@ -277,17 +234,21 @@ def handle(self, *args, **options):
277234
# else:
278235
_component.github_update_time = aware_date
279236
try:
280-
latest_commit_hash = get_commit_hash(github_data['commits_url'])
237+
response = send_GET_request(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, github_data['commits_url'].split('{')[0])
238+
latest_commit = json.load(response)[0]
239+
latest_commit_hash = latest_commit['sha']
240+
_component.latest_commit_hash = latest_commit_hash
241+
update_visualizations(_component, latest_commit_hash)
281242
except:
282-
continue
283-
_component.latest_commit_hash = latest_commit_hash
284-
update_visualizations(_component, latest_commit_hash)
243+
print('Error getting commit hash!')
244+
pass
285245
# except:
286246
# pass
287247
_component.save()
288-
print (str(github_data['contributors_url']) + '?client_id=' + GITHUB_CLIENT_ID + '&client_secret=' + GITHUB_CLIENT_SECRET)
248+
print (str(github_data['contributors_url']))
289249
try:
290-
contributors_data = get_contributors_data(str(github_data['contributors_url']) + '?client_id=' + GITHUB_CLIENT_ID + '&client_secret=' + GITHUB_CLIENT_SECRET)
250+
response = send_GET_request(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, str(github_data['contributors_url']))
251+
contributors_data = json.load(response)
291252
except:
292253
continue
293254
commits = 0
@@ -307,12 +268,11 @@ def handle(self, *args, **options):
307268
commits += _contribution.contributions
308269
count +=1
309270
except:
310-
print 'Error'
271+
print ('Error')
311272
continue
312-
try:
313-
_component.downloads = get_downloads(str(github_data['downloads_url']) + '?client_id=' + GITHUB_CLIENT_ID + '&client_secret=' + GITHUB_CLIENT_SECRET)
314-
except:
315-
pass
273+
response = send_GET_request(GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, github_data['downloads_url'])
274+
downloads_array = json.load(response)
275+
_component.downloads = len(downloads_array)
316276
_component.commits = commits
317277
_component.no_of_contributors = count
318278
_component.save()

main/templates/main/visualizations.html

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@
3232
<div id='snippetDiv'></div>
3333
</body>
3434
<script type="text/javascript">
35-
String.prototype.replaceAll = function(search, replacement) {
36-
var target = this;
37-
return target.replace(new RegExp(search, 'g'), replacement);
35+
const replaceAll = function(str, search, replacement) {
36+
return str.replace(new RegExp(search, 'g'), replacement);
3837
};
3938

4039
// find main element variable
@@ -47,7 +46,7 @@
4746
}
4847
});
4948
return defaultDiv;
50-
};
49+
};
5150

5251
// translate relative paths
5352
translateRelative = function(body, baseLocal, path) {
@@ -58,15 +57,15 @@
5857
}
5958
return body;
6059
};
61-
60+
6261

6362
var script = document.getElementById("placeholderDiv").innerHTML;
64-
script = script.replaceAll("&lt;", "<");
65-
script = script.replaceAll("&gt;", ">");
63+
script = replaceAll(script, "&lt;", "<");
64+
script = replaceAll(script, "&gt;", ">");
6665

6766
var githubURL = "{{component.github_url}}";
6867
var lastCommitHash = "{{component.latest_commit_hash}}";
69-
68+
7069
var div = findMainVar(script);
7170
var mainDiv = "var "+div+" = document.getElementById('snippetDiv');"
7271

@@ -84,6 +83,6 @@
8483
// complete script and evaluate the script
8584
script = mainDiv + script;
8685
eval(script);
87-
86+
8887
</script>
8988
</html>

0 commit comments

Comments
 (0)