-
Notifications
You must be signed in to change notification settings - Fork 124
/
total-conversion-build.user.js
2202 lines (1788 loc) · 72.4 KB
/
total-conversion-build.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @id ingress-intel-total-conversion@breunigs
// @name intel map total conversion
// @version 0.2-2013-02-07-163236
// @namespace https://github.com/breunigs/ingress-intel-total-conversion
// @updateURL https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/total-conversion-build.user.js
// @downloadURL https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/total-conversion-build.user.js
// @description total conversion for the ingress intel map.
// @include http://www.ingress.com/intel*
// ==/UserScript==
// REPLACE ORIG SITE ///////////////////////////////////////////////////
if(document.getElementsByTagName('html')[0].getAttribute('itemscope') != null)
throw('Ingress Intel Website is down, not a userscript issue.');
// disable vanilla JS
window.onload = function() {};
// rescue user data from original page
var scr = document.getElementsByTagName('script');
for(var x in scr) {
var s = scr[x];
if(s.src) continue;
if(s.type !== 'text/javascript') continue;
var d = s.innerHTML.split('\n');
break;
}
for(var i = 0; i < d.length; i++) {
if(!d[i].match('var PLAYER = ')) continue;
eval(d[i].match(/^var /, 'window.'));
break;
}
// player information is now available in a hash like this:
// window.PLAYER = {"ap": "123", "energy": 123, "available_invites": 123, "nickname": "somenick", "team": "ALIENS||RESISTANCE"};
// remove complete page. We only wanted the user-data and the page’s
// security context so we can access the API easily. Setup as much as
// possible without requiring scripts.
document.getElementsByTagName('head')[0].innerHTML = ''
+ '<link rel="stylesheet" type="text/css" href="http://breunigs.github.com/ingress-intel-total-conversion/style.css"/>'
+ '<link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css"/>'
+ '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Coda"/>';
document.getElementsByTagName('body')[0].innerHTML = ''
+ '<div id="map">Loading, please wait</div>'
+ '<div id="chatcontrols" style="display:none">'
+ ' <a>expand</a><a>automated</a><a>public</a><a class="active">faction</a>'
+ '</div>'
+ '<div id="chat" style="display:none">'
+ ' <div id="chatfaction"></div>'
+ ' <div id="chatpublic"></div>'
+ ' <div id="chatautomated"></div>'
+ '</div>'
+ '<form id="chatinput" style="display:none"><time></time><span>tell faction:</span><input type="text"/></form>'
+ '<div id="sidebar" style="display: none">'
+ ' <div id="playerstat">t</div>'
+ ' <div id="gamestat"> loading global control stats</div>'
+ ' <input id="geosearch" placeholder="Search location…" type="text"/>'
+ ' <div id="portaldetails"></div>'
+ ' <input id="redeem" placeholder="Redeem code…" type="text"/>'
+ ' <div id="updatestatus"></div>'
+ '</div>';
// putting everything in a wrapper function that in turn is placed in a
// script tag on the website allows us to execute in the site’s context
// instead of in the Greasemonkey/Extension/etc. context.
function wrapper() {
// LEAFLET PREFER CANVAS ///////////////////////////////////////////////
// Set to true if Leaflet should draw things using Canvas instead of SVG
// Disabled for now because it has several bugs: flickering, constant
// CPU usage and it continuously fires the moveend event.
L_PREFER_CANVAS = false;
// CONFIG OPTIONS ////////////////////////////////////////////////////
var REFRESH = 30; // refresh view every 30s (base time)
var ZOOM_LEVEL_ADJ = 5; // add 5 seconds per zoom level
var REFRESH_GAME_SCORE = 5*60; // refresh game score every 5 minutes
var MAX_IDLE_TIME = 4; // stop updating map after 4min idling
var PRECACHE_PLAYER_NAMES_ZOOM = 17; // zoom level to start pre-resolving player names
var SIDEBAR_WIDTH = 300;
// chat messages are requested for the visible viewport. On high zoom
// levels this gets pretty pointless, so request messages in at least a
// X km radius.
var CHAT_MIN_RANGE = 6;
// this controls how far data is being drawn outside the viewport. Set
// it 0 to only draw entities that intersect the current view. A value
// of one will render an area twice the size of the viewport (or some-
// thing like that, Leaflet doc isn’t too specific). Setting it too low
// makes the missing data on move/zoom out more obvious. Setting it too
// high causes too many items to be drawn, making drag&drop sluggish.
var VIEWPORT_PAD_RATIO = 0.3;
// how many items to request each query
var CHAT_PUBLIC_ITEMS = 200
var CHAT_FACTION_ITEMS = 50
// Leaflet will get very slow for MANY items. It’s better to display
// only some instead of crashing the browser.
var MAX_DRAWN_PORTALS = 1000;
var MAX_DRAWN_LINKS = 400;
var MAX_DRAWN_FIELDS = 200;
var COLOR_SELECTED_PORTAL = '#f00';
var COLORS = ['#FFCE00', '#0088FF', '#03FE03']; // none, res, enl
var COLORS_LVL = ['#000', '#FECE5A', '#FFA630', '#FF7315', '#E40000', '#FD2992', '#EB26CD', '#C124E0', '#9627F4'];
// circles around a selected portal that show from where you can hack
// it and how far the portal reaches (i.e. how far links may be made
// from this portal)
var ACCESS_INDICATOR_COLOR = 'orange';
var RANGE_INDICATOR_COLOR = 'red';
// INGRESS CONSTANTS /////////////////////////////////////////////////
// http://decodeingress.me/2012/11/18/ingress-portal-levels-and-link-range/
var RESO_NRG = [0, 1000, 1500, 2000, 2500, 3000, 4000, 5000, 6000];
var MAX_XM_PER_LEVEL = [0, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000];
var MIN_AP_FOR_LEVEL = [0, 10000, 30000, 70000, 150000, 300000, 600000, 1200000];
var HACK_RANGE = 35; // in meters, max. distance from portal to be able to access it
var SLOT_TO_CARDINAL = ['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE'];
var DEFAULT_PORTAL_IMG = 'http://commondatastorage.googleapis.com/ingress/img/default-portal-image.png';
// OTHER MORE-OR-LESS CONSTANTS //////////////////////////////////////
var NOMINATIM = 'http://nominatim.openstreetmap.org/search?format=json&limit=1&q=';
var DEG2RAD = Math.PI / 180;
var TEAM_NONE = 0, TEAM_RES = 1, TEAM_ENL = 2;
var TEAM_TO_CSS = ['none', 'res', 'enl'];
// make PLAYER variable available in site context
var PLAYER = window.PLAYER;
var CHAT_SHRINKED = 60;
// STORAGE ///////////////////////////////////////////////////////////
// global variables used for storage. Most likely READ ONLY. Proper
// way would be to encapsulate them in an anonymous function and write
// getters/setters, but if you are careful enough, this works.
var refreshTimeout;
var urlPortal = null;
window.playersToResolve = [];
window.playersInResolving = [];
window.selectedPortal = null;
window.portalRangeIndicator = null;
window.portalAccessIndicator = null;
window.mapRunsUserAction = false;
var portalsLayer, linksLayer, fieldsLayer;
// contain references to all entities shown on the map. These are
// automatically kept in sync with the items on *sLayer, so never ever
// write to them.
window.portals = {};
window.links = {};
window.fields = {};
// MAP DATA //////////////////////////////////////////////////////////
// these functions handle how and which entities are displayed on the
// map. They also keep them up to date, unless interrupted by user
// action.
// requests map data for current viewport. For details on how this
// works, refer to the description in “MAP DATA REQUEST CALCULATORS”
window.requestData = function() {
console.log('refreshing data');
requests.abort();
cleanUp();
var magic = convertCenterLat(map.getCenter().lat);
var R = calculateR(magic);
var bounds = map.getBounds();
// convert to point values
topRight = convertLatLngToPoint(bounds.getNorthEast(), magic, R);
bottomLeft = convertLatLngToPoint(bounds.getSouthWest() , magic, R);
// how many quadrants intersect the current view?
quadsX = Math.abs(bottomLeft.x - topRight.x);
quadsY = Math.abs(bottomLeft.y - topRight.y);
// will group requests by second-last quad-key quadrant
tiles = {};
// walk in x-direction, starts right goes left
for(var i = 0; i <= quadsX; i++) {
var x = Math.abs(topRight.x - i);
var qk = pointToQuadKey(x, topRight.y);
var bnds = convertPointToLatLng(x, topRight.y, magic, R);
if(!tiles[qk.slice(0, -1)]) tiles[qk.slice(0, -1)] = [];
tiles[qk.slice(0, -1)].push(generateBoundsParams(qk, bnds));
// walk in y-direction, starts top, goes down
for(var j = 1; j <= quadsY; j++) {
var qk = pointToQuadKey(x, topRight.y + j);
var bnds = convertPointToLatLng(x, topRight.y + j, magic, R);
if(!tiles[qk.slice(0, -1)]) tiles[qk.slice(0, -1)] = [];
tiles[qk.slice(0, -1)].push(generateBoundsParams(qk, bnds));
}
}
// finally send ajax requests
$.each(tiles, function(ind, tls) {
data = { minLevelOfDetail: -1 };
data.boundsParamsList = tls;
window.requests.add(window.postAjax('getThinnedEntitiesV2', data, window.handleDataResponse));
});
}
// works on map data response and ensures entities are drawn/updated.
window.handleDataResponse = function(data, textStatus, jqXHR) {
// remove from active ajax queries list
if(!data || !data.result) {
window.failedRequestCount++;
console.warn(data);
return;
}
var portalUpdateAvailable = false;
var portalInUrlAvailable = false;
var m = data.result.map;
// defer rendering of portals because there is no z-index in SVG.
// this means that what’s rendered last ends up on top. While the
// portals can be brought to front, this costs extra time. They need
// to be in the foreground, or they cannot be clicked. See
// https://github.com/Leaflet/Leaflet/issues/185
var ppp = [];
$.each(m, function(qk, val) {
$.each(val.deletedGameEntityGuids, function(ind, guid) {
window.removeByGuid(guid);
});
$.each(val.gameEntities, function(ind, ent) {
// ent = [GUID, id(?), details]
// format for links: { controllingTeam, creator, edge }
// format for portals: { controllingTeam, turret }
if(ent[2].turret !== undefined) {
if(selectedPortal == ent[0]) portalUpdateAvailable = true;
if(urlPortal && ent[0] == urlPortal) portalInUrlAvailable = true;
var latlng = [ent[2].locationE6.latE6/1E6, ent[2].locationE6.lngE6/1E6];
if(!window.getPaddedBounds().contains(latlng)
&& selectedPortal != ent[0]
&& urlPortal != ent[0]
) return;
ppp.push(ent); // delay portal render
} else if(ent[2].edge !== undefined)
renderLink(ent);
else if(ent[2].capturedRegion !== undefined)
renderField(ent);
else
throw('Unknown entity: ' + JSON.stringify(ent));
});
});
$.each(ppp, function(ind, portal) { renderPortal(portal); });
if(portals[selectedPortal]) portals[selectedPortal].bringToFront();
if(portalInUrlAvailable) {
renderPortalDetails(urlPortal);
urlPortal = null; // select it only once
}
if(portalUpdateAvailable) renderPortalDetails(selectedPortal);
resolvePlayerNames();
}
// removes entities that are still handled by Leaflet, although they
// do not intersect the current viewport.
window.cleanUp = function() {
var cnt = [0,0,0];
var b = getPaddedBounds();
var minlvl = getMinPortalLevel();
portalsLayer.eachLayer(function(portal) {
// portal must be in bounds and have a high enough level. Also don’t
// remove if it is selected.
if(portal.options.guid == window.selectedPortal ||
(b.contains(portal.getLatLng()) && portal.options.level >= minlvl)) return;
cnt[0]++;
portalsLayer.removeLayer(portal);
});
linksLayer.eachLayer(function(link) {
if(b.intersects(link.getBounds())) return;
cnt[1]++;
linksLayer.removeLayer(link);
});
fieldsLayer.eachLayer(function(field) {
if(b.intersects(field.getBounds())) return;
cnt[2]++;
fieldsLayer.removeLayer(field);
});
console.log('removed out-of-bounds: '+cnt[0]+' portals, '+cnt[1]+' links, '+cnt[2]+' fields');
}
// removes given entity from map
window.removeByGuid = function(guid) {
// portals end in “.11” or “.12“, links in “.9", fields in “.b”
// .11 == portals
// .12 == portals
// .9 == links
// .b == fields
// .c == player/creator
// .d == chat messages
switch(guid.slice(33)) {
case '11':
case '12':
if(!window.portals[guid]) return;
portalsLayer.removeLayer(window.portals[guid]);
break;
case '9':
if(!window.links[guid]) return;
linksLayer.removeLayer(window.links[guid]);
break;
case 'b':
if(!window.fields[guid]) return;
fieldsLayer.removeLayer(window.fields[guid]);
break;
default:
console.warn('unknown GUID type: ' + guid);
//window.debug.printStackTrace();
}
}
// renders a portal on the map from the given entity
window.renderPortal = function(ent) {
removeByGuid(ent[0]);
if(Object.keys(portals).length >= MAX_DRAWN_PORTALS && ent[0] != selectedPortal)
return;
var latlng = [ent[2].locationE6.latE6/1E6, ent[2].locationE6.lngE6/1E6];
// needs to be checked before, so the portal isn’t added to the
// details list and other places
//if(!getPaddedBounds().contains(latlng)) return;
// hide low level portals on low zooms
var portalLevel = getPortalLevel(ent[2]);
if(portalLevel < getMinPortalLevel() && ent[0] != selectedPortal) return;
// pre-load player names for high zoom levels
if(map.getZoom() >= PRECACHE_PLAYER_NAMES_ZOOM) {
if(ent[2].captured && ent[2].captured.capturingPlayerId)
getPlayerName(ent[2].captured.capturingPlayerId);
if(ent[2].resonatorArray && ent[2].resonatorArray.resonators)
$.each(ent[2].resonatorArray.resonators, function(ind, reso) {
if(reso) getPlayerName(reso.ownerGuid);
});
}
var team = getTeam(ent[2]);
var p = L.circleMarker(latlng, {
radius: 7,
color: ent[0] == selectedPortal ? COLOR_SELECTED_PORTAL : COLORS[team],
opacity: 1,
weight: 3,
fillColor: COLORS[team],
fillOpacity: 0.5,
clickable: true,
level: portalLevel,
details: ent[2],
guid: ent[0]});
p.on('remove', function() { delete window.portals[this.options.guid]; });
p.on('add', function() { window.portals[this.options.guid] = this; });
p.on('click', function() { window.renderPortalDetails(ent[0]); });
p.on('dblclick', function() {
window.renderPortalDetails(ent[0]);
window.map.setView(latlng, 17);
});
p.addTo(portalsLayer);
}
// renders a link on the map from the given entity
window.renderLink = function(ent) {
removeByGuid(ent[0]);
if(Object.keys(links).length >= MAX_DRAWN_LINKS) return;
var team = getTeam(ent[2]);
var edge = ent[2].edge;
var latlngs = [
[edge.originPortalLocation.latE6/1E6, edge.originPortalLocation.lngE6/1E6],
[edge.destinationPortalLocation.latE6/1E6, edge.destinationPortalLocation.lngE6/1E6]
];
var poly = L.polyline(latlngs, {
color: COLORS[team],
opacity: 1,
weight:2,
clickable: false,
guid: ent[0],
smoothFactor: 10
});
if(!getPaddedBounds().intersects(poly.getBounds())) return;
poly.on('remove', function() { delete window.links[this.options.guid]; });
poly.on('add', function() { window.links[this.options.guid] = this; });
poly.addTo(linksLayer).bringToBack();
}
// renders a field on the map from a given entity
window.renderField = function(ent) {
window.removeByGuid(ent[0]);
if(Object.keys(fields).length >= MAX_DRAWN_FIELDS) return;
var team = getTeam(ent[2]);
var reg = ent[2].capturedRegion;
var latlngs = [
[reg.vertexA.location.latE6/1E6, reg.vertexA.location.lngE6/1E6],
[reg.vertexB.location.latE6/1E6, reg.vertexB.location.lngE6/1E6],
[reg.vertexC.location.latE6/1E6, reg.vertexC.location.lngE6/1E6]
];
var poly = L.polygon(latlngs, {
fillColor: COLORS[team],
fillOpacity: 0.25,
stroke: false,
clickable: false,
smoothFactor: 10,
guid: ent[0]});
if(!getPaddedBounds().intersects(poly.getBounds())) return;
poly.on('remove', function() { delete window.fields[this.options.guid]; });
poly.on('add', function() { window.fields[this.options.guid] = this; });
poly.addTo(fieldsLayer).bringToBack();
}
// REQUEST HANDLING //////////////////////////////////////////////////
// note: only meant for portal/links/fields request, everything else
// does not count towards “loading”
window.activeRequests = [];
window.failedRequestCount = 0;
window.requests = function() {}
window.requests.add = function(ajax) {
window.activeRequests.push(ajax);
renderUpdateStatus();
}
window.requests.remove = function(ajax) {
window.activeRequests.splice(window.activeRequests.indexOf(ajax), 1);
renderUpdateStatus();
}
window.requests.abort = function() {
$.each(window.activeRequests, function(ind, actReq) {
if(actReq) actReq.abort();
});
window.activeRequests = [];
window.failedRequestCount = 0;
window.chat._requestOldPublicRunning = false;
window.chat._requestNewPublicRunning = false;
window.chat._requestOldFactionRunning = false;
window.chat._requestNewFactionRunning = false;
renderUpdateStatus();
}
// gives user feedback about pending operations. Draws current status
// to website.
window.renderUpdateStatus = function() {
var t = '<b>map status:</b> ';
if(mapRunsUserAction)
t += 'paused during interaction';
else if(isIdle())
t += '<span style="color:red">Idle, not updating.</span>';
else if(window.activeRequests.length > 0)
t += window.activeRequests.length + ' requests running.';
else
t += 'Up to date.';
if(renderLimitReached())
t += ' <span style="color:red" class="help" title="Can only render so much before it gets unbearably slow. Not all entities are shown. Zoom in or increase the limit (search for MAX_DRAWN_*).">RENDER LIMIT</span> '
if(window.failedRequestCount > 0)
t += ' ' + window.failedRequestCount + ' requests failed.'
t += '<br/>(';
var minlvl = getMinPortalLevel();
if(minlvl === 0)
t += 'showing all portals';
else
t+= 'only showing portals with level '+minlvl+' and up';
t += ')</span>';
$('#updatestatus').html(t);
}
// sets the timer for the next auto refresh. Ensures only one timeout
// is queued. May be given 'override' in milliseconds if time should
// not be guessed automatically. Especially useful if a little delay
// is required, for example when zooming.
window.startRefreshTimeout = function(override) {
// may be required to remove 'paused during interaction' message in
// status bar
window.renderUpdateStatus();
if(refreshTimeout) clearTimeout(refreshTimeout);
var t = 0;
if(override) {
t = override;
} else {
t = REFRESH*1000;
var adj = ZOOM_LEVEL_ADJ * (18 - window.map.getZoom());
if(adj > 0) t += adj*1000;
}
var next = new Date(new Date().getTime() + t).toLocaleTimeString();
console.log('planned refresh: ' + next);
refreshTimeout = setTimeout(window.requests._callOnRefreshFunctions, t);
}
window.requests._onRefreshFunctions = [];
window.requests._callOnRefreshFunctions = function() {
startRefreshTimeout();
if(isIdle()) {
console.log('user has been idle for ' + idleTime + ' minutes. Skipping refresh.');
renderUpdateStatus();
return;
}
console.log('refreshing');
$.each(window.requests._onRefreshFunctions, function(ind, f) {
f();
});
}
// add method here to be notified of auto-refreshes
window.requests.addRefreshFunction = function(f) {
window.requests._onRefreshFunctions.push(f);
}
// UTILS + MISC ///////////////////////////////////////////////////////
// retrieves parameter from the URL?query=string.
window.getURLParam = function(param) {
var v = document.URL;
var i = v.indexOf(param);
if(i <= -1) return '';
v = v.substr(i);
i = v.indexOf("&");
if(i >= 0) v = v.substr(0, i);
return v.replace(param+"=","");
}
// read cookie by name.
// http://stackoverflow.com/a/5639455/1684530 by cwolves
var cookies;
window.readCookie = function(name,c,C,i){
if(cookies) return cookies[name];
c = document.cookie.split('; ');
cookies = {};
for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
cookies[C[0]] = unescape(C[1]);
}
return cookies[name];
}
window.writeCookie = function(name, val) {
document.cookie = name + "=" + val + '; expires=Thu, 31 Dec 2020 23:59:59 GMT; path=/';
}
// add thousand separators to given number.
// http://stackoverflow.com/a/1990590/1684530 by Doug Neiner.
window.digits = function(d) {
return (d+"").replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1 ");
}
// posts AJAX request to Ingress API.
// action: last part of the actual URL, the rpc/dashboard. is
// added automatically
// data: JSON data to post. method will be derived automatically from
// action, but may be overridden. Expects to be given Hash.
// Strings are not supported.
// success: method to call on success. See jQuery API docs for avail-
// able arguments: http://api.jquery.com/jQuery.ajax/
// error: see above. Additionally it is logged if the request failed.
window.postAjax = function(action, data, success, error) {
data = JSON.stringify($.extend({method: 'dashboard.'+action}, data));
var remove = function(data, textStatus, jqXHR) { window.requests.remove(jqXHR); };
var errCnt = function(jqXHR) { window.failedRequestCount++; window.requests.remove(jqXHR); };
return $.ajax({
url: 'rpc/dashboard.'+action,
type: 'POST',
data: data,
dataType: 'json',
success: [remove, success],
error: error ? [errCnt, error] : errCnt,
contentType: 'application/json; charset=utf-8',
beforeSend: function(req) {
req.setRequestHeader('X-CSRFToken', readCookie('csrftoken'));
}
});
}
// converts unix timestamps to HH:mm:ss format if it was today;
// otherwise it returns YYYY-MM-DD
window.unixTimeToString = function(time, full) {
if(!time) return null;
var d = new Date(typeof time === 'string' ? parseInt(time) : time);
var time = d.toLocaleTimeString();
var date = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
if(typeof full !== 'undefined' && full) return date + ' ' + time;
if(d.toDateString() == new Date().toDateString())
return time;
else
return date;
}
window.unixTimeToHHmm = function(time) {
if(!time) return null;
var d = new Date(typeof time === 'string' ? parseInt(time) : time);
var h = '' + d.getHours(); h = h.length === 1 ? '0' + h : h;
var s = '' + d.getMinutes(); s = s.length === 1 ? '0' + s : s;
return h + ':' + s;
}
window.rangeLinkClick = function() {
if(window.portalRangeIndicator)
window.map.fitBounds(window.portalRangeIndicator.getBounds());
}
window.reportPortalIssue = function(info) {
var t = 'Redirecting you to a Google Help Page. Once there, click on “Contact Us” in the upper right corner.\n\nThe text box contains all necessary information. Press CTRL+C to copy it.';
//codename, approx addr, portalname
if(prompt(t, info) !== null)
location.href = 'https://support.google.com/ingress?hl=en';
}
window._storedPaddedBounds = undefined;
window.getPaddedBounds = function() {
if(_storedPaddedBounds === undefined) {
map.on('zoomstart zoomend movestart moveend', function() {
window._storedPaddedBounds = null;
});
}
if(window._storedPaddedBounds) return window._storedPaddedBounds;
var p = window.map.getBounds().pad(VIEWPORT_PAD_RATIO);
window._storedPaddedBounds = p;
return p;
}
window.renderLimitReached = function() {
if(Object.keys(portals).length >= MAX_DRAWN_PORTALS) return true;
if(Object.keys(links).length >= MAX_DRAWN_LINKS) return true;
if(Object.keys(fields).length >= MAX_DRAWN_FIELDS) return true;
return false;
}
window.getMinPortalLevel = function() {
var z = map.getZoom();
if(z >= 16) return 0;
var conv = ['impossible', 8,7,7,6,6,5,5,4,4,3,3,2,2,1,1];
return conv[z];
}
// returns number of pixels left to scroll down before reaching the
// bottom. Works similar to the native scrollTop function.
window.scrollBottom = function(elm) {
if(typeof elm === 'string') elm = $(elm);
return elm.get(0).scrollHeight - elm.innerHeight() - elm.scrollTop();
}
window.zoomToAndShowPortal = function(guid, latlng) {
renderPortalDetails(guid);
map.setView(latlng, 17);
}
// SETUP /////////////////////////////////////////////////////////////
// these functions set up specific areas after the boot function
// created a basic framework. All of these functions should only ever
// be run once.
window.setupLargeImagePreview = function() {
$('#portaldetails').on('click', '.imgpreview img', function() {
var ex = $('#largepreview');
if(ex.length > 0) {
ex.remove();
return;
}
var img = $(this).parent().html();
var w = $(this)[0].naturalWidth/2;
var h = $(this)[0].naturalHeight/2;
var c = $('#portaldetails').attr('class');
$('body').append(
'<div id="largepreview" class="'+c+'" style="margin-left: '+(-SIDEBAR_WIDTH/2-w-2)+'px; margin-top: '+(-h-2)+'px">' + img + '</div>'
);
$('#largepreview').click(function() { $(this).remove() });
$('#largepreview img').attr('title', '');
});
}
window.setupStyles = function() {
$('head').append('<style>' +
[ '#map { margin-right: '+(SIDEBAR_WIDTH+2)+'px } ',
'#largepreview.enl img { border:2px solid '+COLORS[TEAM_ENL]+'; } ',
'#largepreview.none img { border:2px solid '+COLORS[TEAM_NONE]+'; } ',
'#chatcontrols { bottom: '+(CHAT_SHRINKED+24)+'px; }',
'#chat { height: '+CHAT_SHRINKED+'px; } ',
'#updatestatus { width:'+(SIDEBAR_WIDTH-2*4)+'px; } ',
'#sidebar, #gamestat, #gamestat span, input, ',
'.imgpreview img { width:'+SIDEBAR_WIDTH+'px; }'].join("\n")
+ '</style>');
}
window.setupMap = function() {
$('#map').text('');
var osmOpt = {attribution: 'Map data © OpenStreetMap contributors', maxZoom: 18};
var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmOpt);
var cmOpt = {attribution: 'Map data © OpenStreetMap contributors, Imagery © CloudMade', maxZoom: 18};
var cmMin = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/22677/256/{z}/{x}/{y}.png', cmOpt);
var cmMid = new L.TileLayer('http://{s}.tile.cloudmade.com/654cef5fd49a432ab81267e200ecc502/999/256/{z}/{x}/{y}.png', cmOpt);
var views = [cmMid, cmMin, osm, new L.Google('INGRESS'), new L.Google('ROADMAP'),
new L.Google('SATELLITE'), new L.Google('HYBRID')];
portalsLayer = L.layerGroup([]);
linksLayer = L.layerGroup([]);
fieldsLayer = L.layerGroup([]);
window.map = new L.Map('map', $.extend(getPosition(), {zoomControl: false}));
try {
map.addLayer(views[readCookie('ingress.intelmap.type')]);
} catch(e) { map.addLayer(views[0]); }
map.addLayer(portalsLayer);
map.addLayer(fieldsLayer, true);
map.addLayer(linksLayer, true);
map.addControl(new L.Control.Layers({
'OSM Cloudmade Midnight': views[0],
'OSM Cloudmade Minimal': views[1],
'OSM Mapnik': views[2],
'Google Roads Ingress Style': views[3],
'Google Roads': views[4],
'Google Satellite': views[5],
'Google Hybrid': views[6]
}, {
'Portals': portalsLayer,
'Links': linksLayer,
'Fields': fieldsLayer
}));
map.attributionControl.setPrefix('');
// listen for changes and store them in cookies
map.on('moveend', window.storeMapPosition);
map.on('zoomend', window.storeMapPosition);
$("[name='leaflet-base-layers']").change(function () {
writeCookie('ingress.intelmap.type', $(this).parent().index());
});
// map update status handling
map.on('movestart zoomstart', function() { window.mapRunsUserAction = true });
map.on('moveend zoomend', function() { window.mapRunsUserAction = false });
// update map hooks
map.on('movestart zoomstart', window.requests.abort);
map.on('moveend zoomend', function() { window.startRefreshTimeout(500) });
// run once on init
window.requestData();
window.startRefreshTimeout();
window.addResumeFunction(window.requestData);
window.requests.addRefreshFunction(window.requestData);
};
// renders player details into the website. Since the player info is
// included as inline script in the original site, the data is static
// and cannot be updated.
window.setupPlayerStat = function() {
var level;
var ap = parseInt(PLAYER.ap);
for(level = 0; level < MIN_AP_FOR_LEVEL.length; level++) {
if(ap < MIN_AP_FOR_LEVEL[level]) break;
}
var thisLvlAp = MIN_AP_FOR_LEVEL[level-1];
var nextLvlAp = MIN_AP_FOR_LEVEL[level] || ap;
var lvlUpAp = digits(nextLvlAp-ap);
var lvlApProg = Math.round((ap-thisLvlAp)/(nextLvlAp-thisLvlAp)*100);
var xmMax = MAX_XM_PER_LEVEL[level];
var xmRatio = Math.round(PLAYER.energy/xmMax*100);
var cls = PLAYER.team === 'ALIENS' ? 'enl' : 'res';
var t = 'Level:\t\t' + level + '\n'
+ 'XM:\t\t\t' + PLAYER.energy + ' / ' + xmMax + '\n'
+ 'AP:\t\t\t' + digits(ap) + '\n'
+ (level < 8 ? 'level up in:\t' + lvlUpAp + ' AP' : 'Congrats! (neeeeerd)')
+ '\n\Invites:\t\t'+PLAYER.available_invites;
+ '\n\nNote: your player stats can only be updated by a full reload (F5)';
$('#playerstat').html(''
+ '<h2 title="'+t+'">'+level+' '
+ '<span class="'+cls+'">'+PLAYER.nickname+'</span>'
+ '<div>'
+ '<sup>XM: '+xmRatio+'%</sup>'
+ '<sub>' + (level < 8 ? 'level: '+lvlApProg+'%' : 'max level') + '</sub>'
+ '</div>'
+ '</h2>'
);
}
// BOOTING ///////////////////////////////////////////////////////////
function boot() {
console.log('loading done, booting');
window.setupStyles();
window.setupMap();
window.setupGeosearch();
window.setupRedeem();
window.setupLargeImagePreview();
window.updateGameScore();
window.setupPlayerStat();
window.chat.setup();
// read here ONCE, so the URL is only evaluated one time after the
// necessary data has been loaded.
urlPortal = getURLParam('pguid');
// load only once
var n = window.PLAYER['nickname'];
window.PLAYER['nickMatcher'] = new RegExp('\\b('+n+')\\b');
$('#sidebar').show();
}
// this is the minified load.js script that allows us to easily load
// further javascript files async as well as in order.
// https://github.com/chriso/load.js
// Copyright (c) 2010 Chris O'Hara <[email protected]>. MIT Licensed
function asyncLoadScript(a){return function(b,c){var d=document.createElement("script");d.type="text/javascript",d.src=a,d.onload=b,d.onerror=c,d.onreadystatechange=function(){var a=this.readyState;if(a==="loaded"||a==="complete")d.onreadystatechange=null,b()},head.insertBefore(d,head.firstChild)}}(function(a){a=a||{};var b={},c,d;c=function(a,d,e){var f=a.halt=!1;a.error=function(a){throw a},a.next=function(c){c&&(f=!1);if(!a.halt&&d&&d.length){var e=d.shift(),g=e.shift();f=!0;try{b[g].apply(a,[e,e.length,g])}catch(h){a.error(h)}}return a};for(var g in b){if(typeof a[g]=="function")continue;(function(e){a[e]=function(){var g=Array.prototype.slice.call(arguments);if(e==="onError"){if(d)return b.onError.apply(a,[g,g.length]),a;var h={};return b.onError.apply(h,[g,g.length]),c(h,null,"onError")}return g.unshift(e),d?(a.then=a[e],d.push(g),f?a:a.next()):c({},[g],e)}})(g)}return e&&(a.then=a[e]),a.call=function(b,c){c.unshift(b),d.unshift(c),a.next(!0)},a.next()},d=a.addMethod=function(d){var e=Array.prototype.slice.call(arguments),f=e.pop();for(var g=0,h=e.length;g<h;g++)typeof e[g]=="string"&&(b[e[g]]=f);--h||(b["then"+d.substr(0,1).toUpperCase()+d.substr(1)]=f),c(a)},d("chain",function(a){var b=this,c=function(){if(!b.halt){if(!a.length)return b.next(!0);try{null!=a.shift().call(b,c,b.error)&&c()}catch(d){b.error(d)}}};c()}),d("run",function(a,b){var c=this,d=function(){c.halt||--b||c.next(!0)},e=function(a){c.error(a)};for(var f=0,g=b;!c.halt&&f<g;f++)null!=a[f].call(c,d,e)&&d()}),d("defer",function(a){var b=this;setTimeout(function(){b.next(!0)},a.shift())}),d("onError",function(a,b){var c=this;this.error=function(d){c.halt=!0;for(var e=0;e<b;e++)a[e].call(c,d)}})})(this);var head=document.getElementsByTagName("head")[0]||document.documentElement;addMethod("load",function(a,b){for(var c=[],d=0;d<b;d++)(function(b){c.push(asyncLoadScript(a[b]))})(d);this.call("run",c)})
// modified version of https://github.com/shramov/leaflet-plugins. Also
// contains the default Ingress map style.
var LLGMAPS = 'http://breunigs.github.com/ingress-intel-total-conversion/leaflet_google.js';
var JQUERY = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
var LEAFLET = 'http://cdn.leafletjs.com/leaflet-0.5/leaflet.js';
var AUTOLINK = 'https://raw.github.com/bryanwoods/autolink-js/master/autolink.js';
// after all scripts have loaded, boot the actual app
load(JQUERY, LEAFLET, AUTOLINK).then(LLGMAPS).thenRun(boot);
window.chat = function() {};
window.chat._lastNicksForAutocomplete = [[], []];
window.chat.addNickForAutocomplete = function(nick, isFaction) {
var r = chat._lastNicksForAutocomplete[isFaction ? 0 : 1];
if(r.indexOf(nick) !== -1) return;
r.push(nick);
if(r.length >= 15)
r.shift();
}
window.chat.handleTabCompletion = function() {
var el = $('#chatinput input');
var curPos = el.get(0).selectionStart;
var text = el.val();
var word = text.slice(0, curPos).replace(/.*\b([a-z0-9-_])/, '$1').toLowerCase();
var list = window.chat._lastNicksForAutocomplete;
list = list[1].concat(list[0]);
var nick = null;
for(var i = 0; i < list.length; i++) {
if(!list[i].toLowerCase().startsWith(word)) continue;
if(nick && nick !== list[i]) {
console.log('More than one nick matches, aborting. ('+list[i]+' vs '+nick+')');
return;
}
nick = list[i];
}
if(!nick) {
console.log('No matches for ' + word);
return;
}
var posStart = curPos - word.length;
var newText = text.substring(0, posStart);
newText += nick + (posStart === 0 ? ': ' : ' ');
newText += text.substring(curPos);
el.val(newText);
}
//
// timestamp and clear management
//
window.chat._oldFactionTimestamp = -1;
window.chat._newFactionTimestamp = -1;
window.chat._oldPublicTimestamp = -1;
window.chat._newPublicTimestamp = -1;
window.chat.getOldestTimestamp = function(public) {
return chat['_old'+(public ? 'Public' : 'Faction')+'Timestamp'];
}
window.chat.getNewestTimestamp = function(public) {
return chat['_new'+(public ? 'Public' : 'Faction')+'Timestamp'];
}
window.chat.clearIfRequired = function(elm) {
if(!elm.data('needsClearing')) return;
elm.data('ignoreNextScroll', true).data('needsClearing', false).html('');
}
window.chat._oldBBox = null;
window.chat.genPostData = function(public, getOlderMsgs) {
if(typeof public !== 'boolean') throw('Need to know if public or faction chat.');
chat._localRangeCircle.setLatLng(map.getCenter());
var b = map.getBounds().extend(chat._localRangeCircle.getBounds());
var ne = b.getNorthEast();
var sw = b.getSouthWest();
// round bounds in order to ignore rounding errors
var bbs = $.map([ne.lat, ne.lng, sw.lat, sw.lng], function(x) { return Math.round(x*1E4) }).join();
if(chat._oldBBox && chat._oldBBox !== bbs) {
$('#chat > div').data('needsClearing', true);
console.log('Bounding Box changed, chat will be cleared (old: '+chat._oldBBox+' ; new: '+bbs+' )');
// need to reset these flags now because clearing will only occur
// after the request is finished – i.e. there would be one almost
// useless request.
chat._displayedFactionGuids = [];
chat._displayedPublicGuids = [];
chat._displayedPlayerActionTime = {};
chat._oldFactionTimestamp = -1;
chat._newFactionTimestamp = -1;
chat._oldPublicTimestamp = -1;
chat._newPublicTimestamp = -1;
}
chat._oldBBox = bbs;
var ne = b.getNorthEast();
var sw = b.getSouthWest();
var data = {
desiredNumItems: public ? CHAT_PUBLIC_ITEMS : CHAT_FACTION_ITEMS,
minLatE6: Math.round(sw.lat*1E6),
minLngE6: Math.round(sw.lng*1E6),
maxLatE6: Math.round(ne.lat*1E6),
maxLngE6: Math.round(ne.lng*1E6),
minTimestampMs: -1,
maxTimestampMs: -1,
factionOnly: !public
}
if(getOlderMsgs) {
// ask for older chat when scrolling up
data = $.extend(data, {maxTimestampMs: chat.getOldestTimestamp(public)});
} else {
// ask for newer chat
var min = chat.getNewestTimestamp(public);
// the inital request will have both timestamp values set to -1,
// thus we receive the newest desiredNumItems. After that, we will
// only receive messages with a timestamp greater or equal to min
// above.
// After resuming from idle, there might be more new messages than
// desiredNumItems. So on the first request, we are not really up to
// date. We will eventually catch up, as long as there are less new
// messages than desiredNumItems per each refresh cycle.
// A proper solution would be to query until no more new results are
// returned. Another way would be to set desiredNumItems to a very
// large number so we really get all new messages since the last
// request. Setting desiredNumItems to -1 does unfortunately not
// work.
// Currently this edge case is not handled. Let’s see if this is a