-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJEHealthCheck.user.js
437 lines (316 loc) · 14.2 KB
/
JEHealthCheck.user.js
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// ==UserScript==
// @name Just Eat hygiene Check
// @namespace https://github.com/lisa-lionheart/JustEatHealthCheck
// @version 1.6
// @description Check the ratings.food.gov for restaurants on just eat and hungry house
// @author Lisa Croxford
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// @require https://cdnjs.cloudflare.com/ajax/libs/async/1.4.2/async.min.js
// @match http://www.just-eat.co.uk/*
// @match https://www.just-eat.co.uk/*
// @match http://hungryouse.co.uk/*
// @match https://hungryhouse.co.uk/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
var DATA_STORE_VERSION = 2;
function normalizeBuisnessName(name) {
name = name.toLowerCase();
name = name.replace('&', 'and');
name = name.replace(' restaurant', '');
return name;
}
function normalizeAddress(address) {
address = address.trim().replace('\n','').replace('\n',', ').split(', ').map(function(line){ return line.trim(); });
var street = address[0].replace('\'','');
var postCode = address[address.length-1].trim().replace(/ \(.+\)/g, '');
if(address.length == 3) {
return [street,address[1], postCode];
}
if(address.length == 4) {
return [street,address[2], postCode];
}
console.log('failed to normalize address', address);
}
function checkName(establismentData, jeName) {
govName = normalizeBuisnessName(establismentData.BusinessName);
jeName = normalizeBuisnessName(jeName);
if(govName === jeName)
return true;
if(govName.indexOf(jeName) !== -1)
return true;
if(jeName.indexOf(govName) !== -1)
return true;
//console.log('Rejected match:', govName, 'not match', jeName);
return false;
}
function callApi(method,args, done) {
var qs = [];
for(var k in args) {
qs.push( k + '='+args[k]);
}
GM_xmlhttpRequest({
method: "GET",
url: 'http://api.ratings.food.gov.uk/'+method+'?'+qs.join('&'),
headers: {
'x-api-version':2,
accept: 'application/json'
},
onload: function(response) {
done(null,JSON.parse(response.responseText));
}
});
}
function apiToResult(e) {
return {
rating: e.RatingValue,
image: e.RatingKey+'.JPG',
name: e.BuisnessName,
address: [
e.AddressLine2,
e.AddressLine3,
e.PostCode
],
link: 'http://ratings.food.gov.uk/business/en-GB/'+e.FHRSID+'/'+e.BusinessName
};
}
function parseResult(name,address, data, done) {
var establisments = data.establishments;
if(data.establishments.length == 1)
return done(null, apiToResult(data.establishments[0]));
for(var i=0; i < data.establishments.length; i++) {
var e = data.establishments[i];
if(checkName(e, name)) {
console.log('Matched', name, 'as', e.BusinessName);
return done(null, apiToResult(e));
}
}
console.log('Could not match', name, 'at', address);
console.log('Possibles', data.establishments);
//Fallthrough
done(null, null);
}
function getValidCacheItem(id) {
var result = localStorage.getItem(id);
if(result && result !== 'undefined') {
result = JSON.parse(result);
if(result.version === DATA_STORE_VERSION)
return result;
}
return null
}
function lookup(id, name, address, done) {
var result = getValidCacheItem(id);
if(result) return done(null, result);
lookupNoCache(name,address, function(err,result) {
if(result) {
result.version = DATA_STORE_VERSION;
localStorage.setItem(id, JSON.stringify(result));
}
done(err,result);
});
}
function lookupNoCache(name, address, done) {
//console.log('Finding rating for ', name);
var addressQuery = address[0] +', '+ address[2];
callApi('Establishments', {address:addressQuery}, function(err, data) {
if(err)
return done(err);
if(data.establishments.length !== 0) {
return parseResult(name,address,data,done);
}
console.log('No matches for for ', name, 'at', address, 'expanding search...');
var streetQuery = address[0].replace(/^([0-9-abcd]+)/,'').substring(1) + ', ' + address[2];
return callApi('Establishments',{address:streetQuery}, function(err, data) {
if(err)
return done(err);
if(data.establishments.length !== 0) {
return parseResult(name,address, data,done);
}
console.log('Failed to find match for', name, 'querying',streetQuery);
done(null,null);
});
});
}
var SitesCommon = {
updateBadgeCallback: function(imageSize, ratingEl, done) {
return function(err,result) {
ratingEl.removeClass('hygieneRatingLoading');
if(err) {
ratingEl.text('Ooops. something went wrong');
return done(err);
}
if(result === null) {
ratingEl.addClass('unrated');
ratingEl.attr('data-value', -1);
ratingEl.text('Manual search');
ratingEl.attr('href', 'http://ratings.food.gov.uk/');
} else {
ratingEl.attr('data-value', result.rating);
ratingEl.css('backgroundImage', 'url(http://ratings.food.gov.uk/images/scores/'+imageSize+'/'+result.image+')');
ratingEl.attr('href',result.link);
}
done();
};
}
};
var ajaxLoader = 'data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQACgABACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkEAAoAAgAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkEAAoAAwAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkEAAoABAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQACgAFACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQACgAGACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAAKAAcALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==';
var JustEat = {
processSearchResult: function(el, done) {
console.log('processSearchResult');
var address = normalizeAddress($(el).find('p.address').text());
var name = $(el).find('h2.name').text().trim();
var id = $(el).parent().attr('data-restaurant-id');
console.log(name,address);
var ratingEl = $('<a class="hygieneRating hygieneRatingLoading"></a>');
$(el).find('p.viewMenu, p.preOrderButton').append(ratingEl);
lookup(id, name,address, SitesCommon.updateBadgeCallback('small',ratingEl, done));
},
processMenuPage: function(i, el) {
var address = normalizeAddress($('.restInfoAddress').text());
var name = $('.restaurant-name').text().trim();
var id = $('#RestaurantId').val();
var ratingEl = $('<a class="hygieneRatingBig hygieneRatingLoading"></a>');
$('#divBasketUpdate').prepend(ratingEl);
lookup(id, name,address, SitesCommon.updateBadgeCallback('large',ratingEl));
},
sort: function(){
if(window.location.href.indexOf('?so=hygiene') === -1)
return;
elementList = [];
$(".restaurant").each(function(i, e){
var hygineScore = $(e).find(".hygieneRating").attr('data-value');
var userScore = $(e).find('meta[itemprop=ratingValue]').attr('content');
var combinedScore = hygineScore * 1000 + userScore;
elementList.push({rating:combinedScore, element:e, parent:$(e).parent()});
$(e).remove();
});
elementList.sort(function(a,b){
return b.rating - a.rating;
});
for (i = 0; i < elementList.length; i++){
e = elementList[i];
e.parent.append(e.element);
}
},
addSortOption: function(i, el) {
if(window.location.href.indexOf('?so=hygiene') !== -1) {
$('#sort .options ul li.selected').removeClass('selected');
$('#sort .options ul').append('<li class="selected"><span class="item">Hygiene Rating</a></li>');
}else{
$('#sort .options ul').append('<li><a class="item" href="'+window.location.pathname+'?so=hygiene">hygiene Rating</a></li>')
}
},
initialize: function() {
var css = '';
css += '.hygieneRatingLoading { background-image: url('+ajaxLoader+'); backgound-repeat: no-repeat !important }'
css += '.hygieneRating { position: absolute; width: 80px !important; background-color: white !important; min-height: 38px; right: 9px; top: 52px; background-position: center; }';
css += '.hygieneRatingBig { display: block; width: 100% !important; min-height: 150px; background-position: center; background-repeat: no-repeat }';
$('head').append('<style>' + css + '</style>');
this.addSortOption();
async.eachLimit($('.restaurantInner').get(), 5, this.processSearchResult, this.sort);
$('.restaurant-info-detail').each(this.processMenuPage);
}
};
var HungryHouse = {
processMenuPage: function() {
var ratingEl = $('<a class="hygieneRatingBig hygieneRatingLoading"></a>');
$('#shopping-cart-form').prepend(ratingEl);
var name = $('h1 span').attr('content');
var address = normalizeAddress($('span.address').text());
var id = window.location.pathname.substr(1);
console.log('Name:',name,'address:',address);
lookup(id, name,address, SitesCommon.updateBadgeCallback('medium',ratingEl));
},
lookupFromId: function(id, done) {
var result = getValidCacheItem(id);
if(result) return done(null, result);
GM_xmlhttpRequest({
method: "GET",
url: 'https://hungryhouse.co.uk/'+id,
onload: function(response) {
var doc = $(response.responseText);
var name = doc.find('h1 span').attr('content');
var address = normalizeAddress(doc.find('span.address span').get().map(function(el){return $(el).text().trim(); }).join(', '));
console.log('Name:',name,'address:',address);
done(null,name,address);
}
});
},
addRatingToSearchResult: function(el, done) {
var id = el.find('.restPageLink').attr('href').substr(1);
var ratingEl = $('<a class="hygieneRating hygieneRatingLoading"></a>');
el.find('.restsRestInfo').append(ratingEl);
HungryHouse.lookupFromId(id, function(err, name, address) {
lookup(id, name,address, SitesCommon.updateBadgeCallback('small',ratingEl,done));
});
},
//Hungry house loads stuff with ajax so we have to continuously check
pollForNewSearchItems: function() {
var newResults = [];
$('#searchContainer .restaurantBlock').each(function(i,el) {
if($(el).find('.hygieneRating').length === 0)
newResults.push($(el));
});
if(newResults.length===0)
return;
console.log('Found ', newResults.length, 'restraunts withour rating');
async.eachLimit(newResults, 5, HungryHouse.addRatingToSearchResult, window.location.hash === '#hygiene' ? HungryHouse.sortResults : null);
},
sortResults: function(){
$('.restsResNotification').remove();
elementList = [];
$(".restaurantBlock").each(function(i, e){
var hygineScore = parseInt($(e).find(".hygieneRating").attr('data-value'),0);
var userScore = parseInt(($(e).find('.restsRating div').css('width') || '0px').replace(/[px\%]+/,''),10);
var combinedScore = hygineScore * 1000 + userScore;
console.log('Score:', $(e).find('h2').text(), hygineScore, userScore, combinedScore);
elementList.push({rating:combinedScore, element:e, parent:$(e).parent()});
$(e).remove();
});
elementList.sort(function(a,b){
return b.rating - a.rating;
});
for (i = 0; i < elementList.length; i++){
e = elementList[i];
e.parent.append(e.element);
}
},
addSortOption: function() {
var a = $('<a href="'+window.location.href+'#hygiene">Hygiene Rating</a>');
$('#sort-form').append(' | ');
$('#sort-form').append(a);
if(window.location.hash==='#hygeine') {
$('#sort-form a').removeClass('active');
a.addClass('active');
}
a.click(function(){
$('#sort-form a').removeClass('active');
a.addClass('active');
HungryHouse.sortResults();
});
},
initialize: function() {
var css = '';
css += '.hygieneRatingLoading { background-image: url('+ajaxLoader+'); }'
css += '.restsRestStatus { top: -5px !important }';
css += '.hygieneRating { display: block; position: relative; float: right; width: 120px !important; min-height: 66px !important; background-position: center; background-repeat: no-repeat; right: 0px; top: -10px;}';
css += '.hygieneRatingBig { display: block; width: 100% !important; min-height: 150px; background-position: center; background-repeat: no-repeat }';
$('head').append('<style>' + css + '</style>');
$(this.addSortOption);
$('#website-restaurant-container').each(this.processMenuPage);
setInterval(this.pollForNewSearchItems,500);
}
};
try {
switch (window.location.host){
case 'www.just-eat.co.uk':
JustEat.initialize();
JustEat.sort();
break;
case 'hungryhouse.co.uk':
HungryHouse.initialize();
break;
}
}catch(e) {
console.error(e.message, e.stack);
}