Waze Editor Profile Enhancements

Pulls the correct forum post count - changed to red to signify the value as pulled from the forum by the script

当前为 2018-07-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Waze Editor Profile Enhancements
  3. // @namespace http://tampermonkey.net/
  4. // @version 2018.07.23.01
  5. // @description Pulls the correct forum post count - changed to red to signify the value as pulled from the forum by the script
  6. // @author JustinS83
  7. // @include https://www.waze.com/*user/editor*
  8. // @include https://beta.waze.com/*user/editor*
  9. // @grant GM_xmlhttpRequest
  10. // @require https://code.jquery.com/ui/1.12.1/jquery-ui.js
  11. // @contributionURL https://github.com/WazeDev/Thank-The-Authors
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. var settings = {};
  18. var nawkts, rowwkts, ilwkts = [];
  19. var combinedNAWKT, combinedROWWKT, combinedILWKT= "";
  20. var naMA, rowMA, ilMA;
  21. const reducer = (accumulator, currentValue) => accumulator + currentValue;
  22.  
  23. function bootstrap(tries = 1) {
  24. if (W &&
  25. W.EditorProfile &&
  26. $) {
  27. init();
  28. } else if (tries < 1000) {
  29. setTimeout(function () {bootstrap(tries++);}, 200);
  30. }
  31. }
  32.  
  33. bootstrap();
  34.  
  35. async function init(){
  36. $('body').append('<span id="ruler" style="visibility:hidden; white-space:nowrap;"></span>');
  37. //injectCSS();
  38. loadSettings();
  39. String.prototype.visualLength = function(){ //measures the visual length of a string so we can better center the area labels on the areas
  40. var ruler = $("#ruler");
  41. ruler[0].innerHTML = this;
  42. return ruler[0].offsetWidth;
  43. }
  44. $.get('https://www.waze.com/forum/memberlist.php?username=' + W.EditorProfile.data.username, function(forumResult){
  45. var re = 0;
  46. var matches = forumResult.match(/<a.*?"Search user’s posts">(\d+)<\/a>/);
  47. if(matches && matches.length > 0)
  48. re = matches[1];
  49. var WazeVal = $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value')[0].innerHTML.trim();
  50. var userForumID = forumResult.match(/<a href="\.\/memberlist\.php\?mode=viewprofile&amp;u=(\d+)"/);
  51. if(userForumID != null){
  52. userForumID = userForumID[1];
  53. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.highlight-title').css('position', 'relative');
  54.  
  55. if(WazeVal !== re.toString()){
  56. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value')[0].innerHTML = re;
  57. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value').css('color','red');
  58. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value').prop('title', 'Waze reported value: ' + WazeVal);
  59. }
  60.  
  61. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3)').wrap('<a href="https://www.waze.com/forum/search.php?author_id=' + userForumID + '&sr=posts" targ="_blank"></a>');
  62.  
  63. $('#header > div > div.user-info > div > div.user-highlights > a').prepend('<a href="https://www.waze.com/forum/memberlist.php?mode=viewprofile&u=' + userForumID +'" target="_blank" style="margin-right:5px;"><button class="message s-modern-button s-modern"><i class="fa fa-user"></i><span>Forum Profile</span></button></a>');
  64. }
  65. });
  66.  
  67. var count = 0;
  68. W.EditorProfile.data.editingActivity.forEach(function(x) { if(x !== 0) count++; });
  69. $('#editing-activity > div > h3').append(" (" + count + " of last 91 days)");
  70.  
  71. await getManagedAreas();
  72. BuildManagedAreasWKTInterface();
  73. /************** Add Average & Total to Editing Activity ***********/
  74. AddEditingActivityAvgandTot();
  75. /************** Add Editor Stats Section **************/
  76. AddEditorStatsSection();
  77. }
  78.  
  79. function AddLabelsToAreas(){
  80. $('svg.leaflet-zoom-animated g > text').remove();
  81. var svg = $('svg.leaflet-zoom-animated')[0];
  82. var pt = svg.createSVGPoint(), svgP;
  83.  
  84. let displayedAreas = $('svg.leaflet-zoom-animated g');
  85.  
  86. for(let i=0;i<displayedAreas.length;i++){
  87. let windowPosition = $(displayedAreas[i])[0].getBoundingClientRect();
  88. pt.x = (windowPosition.left + windowPosition.right) / 2;
  89. pt.y = (windowPosition.top + windowPosition.bottom) / 2;
  90. svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
  91.  
  92. if(svgP.x != 0 && svgP.y != 0){
  93. var newText = document.createElementNS("http://www.w3.org/2000/svg","text");
  94. newText.setAttributeNS(null,"x",svgP.x - (`Area ${i+1}`.visualLength() /2));
  95. newText.setAttributeNS(null,"y",svgP.y);
  96. newText.setAttributeNS(null, "fill", "red");
  97. newText.setAttributeNS(null,"font-size","12");
  98.  
  99. var textNode = document.createTextNode(`Area ${i+1}`);
  100. newText.appendChild(textNode);
  101. $(displayedAreas[i])[0].appendChild(newText);
  102. }
  103. }
  104. }
  105.  
  106. function BuildManagedAreasWKTInterface(){
  107. if(naMA.managedAreas.length > 0 || rowMA.managedAreas.length > 0 || ilMA.managedAreas.length > 0){
  108. $('#header > div > div.user-info > div > div.user-highlights > a').append('<a href="#" title="View editor\'s managed areas in WKT format"><button class="message s-modern-button s-modern" id="userMA"><i class="fa fa-map-o" aria-hidden="true"></i></button></a>');
  109.  
  110. /****** MO to update labels when panning/zooming the map ************/
  111. var observer = new MutationObserver(function(mutations) {
  112. mutations.forEach(function(mutation) {
  113. if ($(mutation.target).hasClass('leaflet-map-pane') && (mutation.attributeName === "class" || mutation.attributeName === "style")){
  114. if(mutation.attributeName === "class" && mutation.target.classList.length == 1) //zoom has ended, we can redraw our labels
  115. setTimeout(AddLabelsToAreas, 200);
  116. else if(mutation.attributeName === "style") //panning the map
  117. setTimeout(AddLabelsToAreas, 200);
  118. }
  119. });
  120. });
  121. observer.observe(document.getElementsByClassName('component-map-view')[0], { childList: true, subtree: true, attributes:true });
  122.  
  123. AddLabelsToAreas();
  124.  
  125. $('#userMA').click(function(){
  126. if($('#wpeWKT').css('visibility') === 'visible')
  127. $('#wpeWKT').css({'visibility': 'hidden'});
  128. else
  129. $('#wpeWKT').css({'visibility': 'visible'});
  130. });
  131.  
  132. var result = buildWKTArray(naMA);
  133. nawkts = result.wktArr;
  134. combinedNAWKT = result.combinedWKT;
  135.  
  136. result = buildWKTArray(rowMA);
  137. rowwkts = result.wktArr;
  138. combinedROWWKT = result.combinedWKT;
  139.  
  140. result = buildWKTArray(ilMA);
  141. ilwkts = result.wktArr;
  142. combinedILWKT = result.combinedWKT;
  143.  
  144. var $section = $("<div>", {style:"padding:8px 16px"});
  145. $section.html([
  146. '<div id="wpeWKT" style="padding:8px 16px; position:fixed; border-radius:10px; box-shadow:5px 5px 10px 4px Silver; top:25%; left:40%; background-color:white; visibility:hidden;">', //Main div
  147. '<div style="float:right; cursor:pointer;" id="wpeClose"><i class="fa fa-window-close" aria-hidden="true"></i></div>',
  148. '<ul class="nav nav-tabs">',
  149. `${naMA.managedAreas.length > 0 ? '<li class="active"><a data-toggle="pill" href="#naAreas">NA</a></li>' : ''}`,
  150. `${rowMA.managedAreas.length > 0 ? '<li><a data-toggle="pill" href="#rowAreas">ROW</a></li>' : ''}`,
  151. `${ilMA.managedAreas.length > 0 ? '<li><a data-toggle="pill" href="#ilAreas">IL</a></li>' : ''}`,
  152. '</ul>',
  153. '<div class="tab-content">',
  154. '<div id="naAreas" class="tab-pane fade in active">',
  155. '<div id="wpenaAreas" style="float:left; max-height:350px; overflow:auto;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(nawkts,"na") + '</div>',
  156. '<div id="wpenaPolygons" style="float:left; padding-left:15px;"><h3 style="position:relative; float:left; left:40%;">Area WKT</h3><br><textarea rows="7" cols="55" id="wpenaAreaWKT" style="height:auto;"></textarea></div>',
  157. '</div>',//naAreas
  158. '<div id="rowAreas" class="tab-pane fade">',
  159. '<div id="wperowAreas" style="float:left; max-height:350px; overflow:auto;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(rowwkts, "row") + '</div>',
  160. '<div id="wperowPolygons" style="float:left; padding-left:15px;"><h3 style="position:relative; float:left; left:40%;">Area WKT</h3><br><textarea rows="7" cols="55" id="wperowAreaWKT" style="height:auto;"></textarea></div>',
  161. '</div>',//rowAreas
  162. '<div id="ilAreas" class="tab-pane fade">',
  163. '<div id="wpeilAreas" style="float:left; max-height:350px; overflow:auto;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(ilwkts, "il") + '</div>',
  164. '<div id="wpeilPolygons" style="float:left; padding-left:15px;"><h3 style="position:relative; float:left; left:40%;">Area WKT</h3><br><textarea rows="7" cols="55" id="wpeilAreaWKT" style="height:auto;"></textarea></div>',
  165. '</div>',//ilAreas
  166. '<div id="wpeFooter" style="clear:both; margin-top:10px;">View the areas by entering the WKT at <a href="http://map.wazedev.com" target="_blank">http://map.wazedev.com</a></div>',
  167. '</div>', //tab-content
  168. '</div>' //end main div
  169. ].join(' '));
  170.  
  171. $('body').append($section.html());
  172.  
  173. $('[id^="wpenaAreaButton"]').click(function(){
  174. let index = parseInt($(this)[0].id.replace("wpenaAreaButton", ""));
  175. $('#wpenaAreaWKT').text(nawkts[index]);
  176. $('#wpenaPolygons > h3').text(`Area ${index+1} WKT`);
  177. });
  178.  
  179. $('[id^="wperowAreaButton"]').click(function(){
  180. let index = parseInt($(this)[0].id.replace("wperowAreaButton", ""));
  181. $('#wperowAreaWKT').text(rowwkts[index]);
  182. $('#wperowPolygons > h3').text(`Area ${index+1} WKT`);
  183. });
  184.  
  185. $('[id^="wpeilAreaButton"]').click(function(){
  186. let index = parseInt($(this)[0].id.replace("wpeilAreaButton", ""));
  187. $('#wpeilAreaWKT').text(ilwkts[index]);
  188. $('#wpeilPolygons > h3').text(`Area ${index+1} WKT`);
  189. });
  190.  
  191. $('#wpenaCombinedAreaButton').click(function(){
  192. $('#wpenaAreaWKT').text(combinedNAWKT);
  193. $('#wpenaPolygons > h3').text(`Combined Area WKT`);
  194. });
  195.  
  196. $('#wperowCombinedAreaButton').click(function(){
  197. $('#wperowAreaWKT').text(combinedROWWKT);
  198. $('#wperowPolygons > h3').text(`Combined Area WKT`);
  199. });
  200.  
  201. $('#wpeilCombinedAreaButton').click(function(){
  202. $('#wpeilAreaWKT').text(combinedILWKT);
  203. $('#wpeilPolygons > h3').text(`Combined Area WKT`);
  204. });
  205.  
  206. $('#wpeClose').click(function(){
  207. if($('#wpeWKT').css('visibility') === 'visible')
  208. $('#wpeWKT').css({'visibility': 'hidden'});
  209. else
  210. $('#wpeWKT').css({'visibility': 'visible'});
  211. });
  212. }
  213. }
  214.  
  215. function AddEditorStatsSection(){
  216. let edits = W.EditorProfile.data.edits
  217. let editActivity = [].concat(W.EditorProfile.data.editingActivity);
  218. let rank = W.EditorProfile.data.rank+1;
  219. let count = 0;
  220. editActivity.forEach(function(x) {if(x !== 0) count++; });
  221. let editAverageDailyActive = Math.round(editActivity.reduce(reducer)/count);
  222. let editAverageDaily = Math.round(editActivity.reduce(reducer)/91);
  223.  
  224. var $editorProgress = $("<div>");
  225. $editorProgress.html([
  226. `<div id="collapsible" style="display:${settings.EditingStatsExpanded ? "block" : "none"};">`,
  227. '<div style="display:inline-block;"><div><h4>Average Edits per Day</h4></div><div>' + editAverageDaily + '</div></div>',
  228. '<div style="display:inline-block; margin-left:25px;"><div><h4>Average Edits per Day (active days only)</h4></div><div>' + editAverageDailyActive + '</div></div>',
  229. '<div class="editor-progress-list" style="display:flex; flex-flow:row wrap; justify-content:space-around;">',
  230. buildProgressItemsHTML(),
  231. '</div>'
  232. ].join(' '));
  233.  
  234. $('#editing-activity').append('<div id="editor-progress"><h3 id="collapseHeader" style="cursor:pointer;">Editing Stats</h3></div>');
  235. $('#editor-progress').append($editorProgress.html()+'</div>');
  236.  
  237. $('#collapseHeader').click(function(){
  238. $('#collapsible').toggle();
  239. settings.EditingStatsExpanded = ($('#collapsible').css("display") === "block");
  240. saveSettings();
  241. });
  242. }
  243.  
  244. function buildProgressItemsHTML(){
  245. var itemsArr = [];
  246. var $items = $("<div>");
  247. let editActivity = W.EditorProfile.data.editingActivity;
  248.  
  249. //loop over the 13 tracked weeks on the profile
  250. for(let i=0; i<13; i++){
  251. let header = "";
  252. let weekEditCount = 0;
  253. //let weekEditPct = 0;
  254. if(i==0){
  255. header = "Past 7 days";
  256. weekEditCount = editActivity.slice(-7).reduce(reducer);
  257. }
  258. else{
  259. header = `Past ${i*7+1} - ${(i+1)*7} days`;
  260. weekEditCount = editActivity.slice(-((i+1)*7),-i*7).reduce(reducer);
  261. }
  262. let weekDailyAvg = Math.round(weekEditCount/7*100)/100;
  263. itemsArr.push('<div style="margin-right:20px;">');
  264. itemsArr.push(`<h4>${header}</h4>`);
  265. itemsArr.push('<div class="editor-progress-item">');
  266. itemsArr.push(`<div class="editor-progress__name">Week\'s Edits</div><div class="editor-progress__count">${weekEditCount}</div>`); //, ${weekEditPct}%</div>`);
  267. itemsArr.push(`<div class="editor-progress__name">Average Edits/Day</div><div class="editor-progress__count">${weekDailyAvg}</div>`);
  268. itemsArr.push('</div></div>');
  269. }
  270. $items.html(itemsArr.join(' '));
  271. return $items.html();
  272. }
  273.  
  274. function AddEditingActivityAvgandTot(){
  275. $('.legend').append('<div class="day-initial">Avg</div> <div class="day-initial">Tot</div>');
  276. $('.editing-activity').css({"width":"1010px"}); //With adding the Avg and Tot rows we have to widen the div a little so it doesn't wrap one of the columns
  277.  
  278. let currWeekday = new Date().getDay();
  279. if(currWeekday === 0)
  280. currWeekday = 7;
  281. let localEditActivity = [].concat(W.EditorProfile.data.editingActivity);
  282. let weekEditsArr = localEditActivity.splice(-currWeekday);
  283. let weekEditsCount = weekEditsArr.reduce(reducer);
  284. var iteratorStart = 13;
  285. if(currWeekday === 7)
  286. iteratorStart = 12;
  287. $(`.weeks div:nth-child(${iteratorStart+1}) .week`).append(`<div class="day" style="font-size:10px; height:10px; text-align:center; margin-top:-5px;" title="Average edits per day for this week">${Math.round(weekEditsCount/currWeekday * 100) / 100}</div><div style="font-size:10px; height:10px; text-align:center;" title="Total edits for this week">${weekEditsCount}</div>`);
  288. for(let i=iteratorStart; i>0; i--){
  289. weekEditsArr = localEditActivity.splice(-7);
  290. weekEditsCount = weekEditsArr.splice(-7).reduce(reducer);
  291. let avg = Math.round(weekEditsCount/7 * 100) / 100;
  292. $(`.weeks div:nth-child(${i}) .week`).append(`<div class="day" style="font-size:10px; height:10px; text-align:center; margin-top:-5px;" title="Average edits per day for this week">${avg}</div><div style="font-size:10px; height:10px; text-align:center;" title="Total edits for this week">${weekEditsCount}</div>`);
  293. }
  294. }
  295.  
  296. function buildAreaList(wkts, server){
  297. let html = "";
  298. for(let i=0; i<wkts.length; i++){
  299. html +=`<button id="wpe${server}AreaButton${i}" class="s-button s-button--mercury " style="margin-bottom:5px;">Area ${i+1}</button><br>`;
  300. }
  301. if(wkts.length > 1)
  302. html +=`<button id="wpe${server}CombinedAreaButton" class="s-button s-button--mercury " style="margin-bottom:5px;">Combined</button><br>`;
  303. return html;
  304. }
  305.  
  306. function buildWKTArray(wktObj){
  307. let wkt = "";
  308. let combined = "";
  309. let wktArr = [];
  310. for(let i=0; i<wktObj.managedAreas.length; i++){
  311. if(i>0)
  312. combined += ",";
  313. wkt = "";
  314. combined += "(";
  315. for(let j=0; j<wktObj.managedAreas[i].coordinates.length; j++){
  316. if(j>0){
  317. wkt += ",";
  318. combined += ",";
  319. }
  320. combined += "(";
  321. wkt +="(";
  322. for(let k=0; k<wktObj.managedAreas[i].coordinates[j].length; k++){
  323. if(k > 0){
  324. wkt+=", ";
  325. combined += ",";
  326. }
  327. wkt += round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][0])).toString() + " " + round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][1])).toString();
  328. combined += round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][0])).toString() + " " + round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][1])).toString();
  329. }
  330. combined += ")";
  331. wkt += ")";
  332. }
  333. combined += ")";
  334. wkt = `POLYGON${wkt}`;
  335. wktArr.push(wkt);
  336. }
  337. if(wktObj.managedAreas.length > 1)
  338. combined = `MULTIPOLYGON(${combined})` ;
  339. else
  340. combined = `POLYGON${combined}`;
  341.  
  342. return {wktArr: wktArr, combinedWKT: combined};
  343. }
  344.  
  345. function round(val){
  346. return Math.round(val*1000000)/1000000;
  347. }
  348.  
  349. async function getManagedAreas(){
  350. naMA = await $.get(`https://www.waze.com/Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  351. rowMA = await $.get(`https://www.waze.com/row-Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  352. ilMA = await $.get(`https://www.waze.com/il-Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  353.  
  354. /*return await new W.EditorProfile.Models.ManagedAreas([],{
  355. lastEditEnv: 'na',
  356. userId: W.EditorProfile.data.userID
  357. }).fetch();*/
  358. }
  359.  
  360. function injectCSS() {
  361. /*var css = [
  362. ].join(' ');
  363. $('<style type="text/css">' + css + '</style>').appendTo('head');*/
  364. }
  365.  
  366. function loadSettings() {
  367. var loadedSettings = $.parseJSON(localStorage.getItem("WEPE_Settings"));
  368. var defaultSettings = {
  369. EditingStatsExpanded: true
  370. };
  371. settings = loadedSettings ? loadedSettings : defaultSettings;
  372. for (var prop in defaultSettings) {
  373. if (!settings.hasOwnProperty(prop))
  374. settings[prop] = defaultSettings[prop];
  375. }
  376. }
  377.  
  378. function saveSettings() {
  379. if (localStorage) {
  380. var localsettings = {
  381. EditingStatsExpanded: settings.EditingStatsExpanded,
  382. };
  383.  
  384. localStorage.setItem("WEPE_Settings", JSON.stringify(localsettings));
  385. }
  386. }
  387. })();