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.22.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+)"/)[1];
  51.  
  52. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.highlight-title').css('position', 'relative');
  53.  
  54. if(WazeVal !== re.toString()){
  55. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value')[0].innerHTML = re;
  56. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value').css('color','red');
  57. $('#header > div > div.user-info > div > div.user-highlights > div > div:nth-child(3) > div.user-stats-value').prop('title', 'Waze reported value: ' + WazeVal);
  58. }
  59.  
  60. $('#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>');
  61.  
  62. $('#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>');
  63. });
  64.  
  65. var count = 0;
  66. W.EditorProfile.data.editingActivity.forEach(function(x) { if(x !== 0) count++; });
  67. $('#editing-activity > div > h3').append(" (" + count + " of last 91 days)");
  68.  
  69. await getManagedAreas();
  70. BuildManagedAreasWKTInterface();
  71. /************** Add Average & Total to Editing Activity ***********/
  72. AddEditingActivityAvgandTot();
  73. /************** Add Editor Stats Section **************/
  74. AddEditorStatsSection();
  75. }
  76.  
  77. function AddLabelsToAreas(){
  78. $('svg.leaflet-zoom-animated g > text').remove();
  79. var svg = $('svg.leaflet-zoom-animated')[0];
  80. var pt = svg.createSVGPoint(), svgP;
  81.  
  82. let displayedAreas = $('svg.leaflet-zoom-animated g');
  83.  
  84. for(let i=0;i<displayedAreas.length;i++){
  85. let windowPosition = $(displayedAreas[i])[0].getBoundingClientRect();
  86. pt.x = (windowPosition.left + windowPosition.right) / 2;
  87. pt.y = (windowPosition.top + windowPosition.bottom) / 2;
  88. svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
  89.  
  90. if(svgP.x != 0 && svgP.y != 0){
  91. var newText = document.createElementNS("http://www.w3.org/2000/svg","text");
  92. newText.setAttributeNS(null,"x",svgP.x - (`Area ${i+1}`.visualLength() /2));
  93. newText.setAttributeNS(null,"y",svgP.y);
  94. newText.setAttributeNS(null, "fill", "red");
  95. newText.setAttributeNS(null,"font-size","12");
  96.  
  97. var textNode = document.createTextNode(`Area ${i+1}`);
  98. newText.appendChild(textNode);
  99. $(displayedAreas[i])[0].appendChild(newText);
  100. }
  101. }
  102. }
  103.  
  104. function BuildManagedAreasWKTInterface(){
  105. if(naMA.managedAreas.length > 0 || rowMA.managedAreas.length > 0 || ilMA.managedAreas.length > 0){
  106. $('#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>');
  107.  
  108. /****** MO to update labels when panning/zooming the map ************/
  109. var observer = new MutationObserver(function(mutations) {
  110. mutations.forEach(function(mutation) {
  111. if ($(mutation.target).hasClass('leaflet-map-pane') && (mutation.attributeName === "class" || mutation.attributeName === "style")){
  112. if(mutation.attributeName === "class" && mutation.target.classList.length == 1) //zoom has ended, we can redraw our labels
  113. setTimeout(AddLabelsToAreas, 200);
  114. else if(mutation.attributeName === "style") //panning the map
  115. setTimeout(AddLabelsToAreas, 200);
  116. }
  117. });
  118. });
  119. observer.observe(document.getElementsByClassName('component-map-view')[0], { childList: true, subtree: true, attributes:true });
  120.  
  121. AddLabelsToAreas();
  122.  
  123. $('#userMA').click(function(){
  124. if($('#wpeWKT').css('visibility') === 'visible')
  125. $('#wpeWKT').css({'visibility': 'hidden'});
  126. else
  127. $('#wpeWKT').css({'visibility': 'visible'});
  128. });
  129.  
  130. var result = buildWKTArray(naMA);
  131. nawkts = result.wktArr;
  132. combinedNAWKT = result.combinedWKT;
  133.  
  134. result = buildWKTArray(rowMA);
  135. rowwkts = result.wktArr;
  136. combinedROWWKT = result.combinedWKT;
  137.  
  138. result = buildWKTArray(ilMA);
  139. ilwkts = result.wktArr;
  140. combinedILWKT = result.combinedWKT;
  141.  
  142. var $section = $("<div>", {style:"padding:8px 16px"});
  143. $section.html([
  144. '<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
  145. '<div style="float:right; cursor:pointer;" id="wpeClose"><i class="fa fa-window-close" aria-hidden="true"></i></div>',
  146. '<ul class="nav nav-tabs">',
  147. `${naMA.managedAreas.length > 0 ? '<li class="active"><a data-toggle="pill" href="#naAreas">NA</a></li>' : ''}`,
  148. `${rowMA.managedAreas.length > 0 ? '<li><a data-toggle="pill" href="#rowAreas">ROW</a></li>' : ''}`,
  149. `${ilMA.managedAreas.length > 0 ? '<li><a data-toggle="pill" href="#ilAreas">IL</a></li>' : ''}`,
  150. '</ul>',
  151. '<div class="tab-content">',
  152. '<div id="naAreas" class="tab-pane fade in active">',
  153. '<div id="wpenaAreas" style="float:left;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(nawkts,"na") + '</div>',
  154. '<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>',
  155. '</div>',//naAreas
  156. '<div id="rowAreas" class="tab-pane fade">',
  157. '<div id="wperowAreas" style="float:left;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(rowwkts, "row") + '</div>',
  158. '<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>',
  159. '</div>',//rowAreas
  160. '<div id="ilAreas" class="tab-pane fade">',
  161. '<div id="wpeilAreas" style="float:left;"><h3 style="float:left; left:50%;">Editor Areas</h3><br>' + buildAreaList(ilwkts, "il") + '</div>',
  162. '<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>',
  163. '</div>',//ilAreas
  164. '<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>',
  165. '</div>', //tab-content
  166. '</div>' //end main div
  167. ].join(' '));
  168.  
  169. $('body').append($section.html());
  170.  
  171. $('[id^="wpenaAreaButton"]').click(function(){
  172. let index = parseInt($(this)[0].id.replace("wpenaAreaButton", ""));
  173. $('#wpenaAreaWKT').text(nawkts[index]);
  174. $('#wpenaPolygons > h3').text(`Area ${index+1} WKT`);
  175. });
  176.  
  177. $('[id^="wperowAreaButton"]').click(function(){
  178. let index = parseInt($(this)[0].id.replace("wperowAreaButton", ""));
  179. $('#wperowAreaWKT').text(rowwkts[index]);
  180. $('#wperowPolygons > h3').text(`Area ${index+1} WKT`);
  181. });
  182.  
  183. $('[id^="wpeilAreaButton"]').click(function(){
  184. let index = parseInt($(this)[0].id.replace("wpeilAreaButton", ""));
  185. $('#wpeilAreaWKT').text(ilwkts[index]);
  186. $('#wpeilPolygons > h3').text(`Area ${index+1} WKT`);
  187. });
  188.  
  189. $('#wpenaCombinedAreaButton').click(function(){
  190. $('#wpenaAreaWKT').text(combinedNAWKT);
  191. $('#wpenaPolygons > h3').text(`Combined Area WKT`);
  192. });
  193.  
  194. $('#wperowCombinedAreaButton').click(function(){
  195. $('#wperowAreaWKT').text(combinedROWWKT);
  196. $('#wperowPolygons > h3').text(`Combined Area WKT`);
  197. });
  198.  
  199. $('#wpeilCombinedAreaButton').click(function(){
  200. $('#wpeilAreaWKT').text(combinedILWKT);
  201. $('#wpeilPolygons > h3').text(`Combined Area WKT`);
  202. });
  203.  
  204. $('#wpeClose').click(function(){
  205. if($('#wpeWKT').css('visibility') === 'visible')
  206. $('#wpeWKT').css({'visibility': 'hidden'});
  207. else
  208. $('#wpeWKT').css({'visibility': 'visible'});
  209. });
  210. }
  211. }
  212.  
  213. function AddEditorStatsSection(){
  214. let edits = W.EditorProfile.data.edits
  215. let editActivity = [].concat(W.EditorProfile.data.editingActivity);
  216. let rank = W.EditorProfile.data.rank+1;
  217. let count = 0;
  218. editActivity.forEach(function(x) {if(x !== 0) count++; });
  219. let editAverageDailyActive = Math.round(editActivity.reduce(reducer)/count);
  220. let editAverageDaily = Math.round(editActivity.reduce(reducer)/91);
  221.  
  222. var $editorProgress = $("<div>");
  223. $editorProgress.html([
  224. `<div id="collapsible" style="display:${settings.EditingStatsExpanded ? "block" : "none"};">`,
  225. '<div style="display:inline-block;"><div><h4>Average Edits per Day</h4></div><div>' + editAverageDaily + '</div></div>',
  226. '<div style="display:inline-block; margin-left:25px;"><div><h4>Average Edits per Day (active days only)</h4></div><div>' + editAverageDailyActive + '</div></div>',
  227. '<div class="editor-progress-list" style="display:flex; flex-flow:row wrap; justify-content:space-around;">',
  228. buildProgressItemsHTML(),
  229. '</div>'
  230. ].join(' '));
  231.  
  232. $('#editing-activity').append('<div id="editor-progress"><h3 id="collapseHeader" style="cursor:pointer;">Editing Stats</h3></div>');
  233. $('#editor-progress').append($editorProgress.html()+'</div>');
  234.  
  235. $('#collapseHeader').click(function(){
  236. $('#collapsible').toggle();
  237. settings.EditingStatsExpanded = ($('#collapsible').css("display") === "block");
  238. saveSettings();
  239. });
  240. }
  241.  
  242. function buildProgressItemsHTML(){
  243. var itemsArr = [];
  244. var $items = $("<div>");
  245. let editActivity = W.EditorProfile.data.editingActivity;
  246.  
  247. //loop over the 13 tracked weeks on the profile
  248. for(let i=0; i<13; i++){
  249. let header = "";
  250. let weekEditCount = 0;
  251. //let weekEditPct = 0;
  252. if(i==0){
  253. header = "Past 7 days";
  254. weekEditCount = editActivity.slice(-7).reduce(reducer);
  255. }
  256. else{
  257. header = `Past ${i*7+1} - ${(i+1)*7} days`;
  258. weekEditCount = editActivity.slice(-((i+1)*7),-i*7).reduce(reducer);
  259. }
  260. let weekDailyAvg = Math.round(weekEditCount/7*100)/100;
  261. itemsArr.push('<div style="margin-right:20px;">');
  262. itemsArr.push(`<h4>${header}</h4>`);
  263. itemsArr.push('<div class="editor-progress-item">');
  264. itemsArr.push(`<div class="editor-progress__name">Week\'s Edits</div><div class="editor-progress__count">${weekEditCount}</div>`); //, ${weekEditPct}%</div>`);
  265. itemsArr.push(`<div class="editor-progress__name">Average Edits/Day</div><div class="editor-progress__count">${weekDailyAvg}</div>`);
  266. itemsArr.push('</div></div>');
  267. }
  268. $items.html(itemsArr.join(' '));
  269. return $items.html();
  270. }
  271.  
  272. function AddEditingActivityAvgandTot(){
  273. $('.legend').append('<div class="day-initial">Avg</div> <div class="day-initial">Tot</div>');
  274. $('.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
  275.  
  276. let currWeekday = new Date().getDay();
  277. if(currWeekday === 0)
  278. currWeekday = 7;
  279. let localEditActivity = [].concat(W.EditorProfile.data.editingActivity);
  280. let weekEditsArr = localEditActivity.splice(-currWeekday);
  281. let weekEditsCount = weekEditsArr.reduce(reducer);
  282. $('.weeks div:nth-child(13) .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>`);
  283. for(let i=12; i>0; i--){
  284. weekEditsArr = localEditActivity.splice(-7);
  285. weekEditsCount = weekEditsArr.splice(-7).reduce(reducer);
  286. let avg = Math.round(weekEditsCount/7 * 100) / 100;
  287. $(`.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>`);
  288. }
  289. }
  290.  
  291. function buildAreaList(wkts, server){
  292. let html = "";
  293. for(let i=0; i<wkts.length; i++){
  294. html +=`<button id="wpe${server}AreaButton${i}" class="btn btn-outline-primary" style="margin-bottom:5px;">Area ${i+1}</button><br>`;
  295. }
  296. if(wkts.length > 1)
  297. html +=`<button id="wpe${server}CombinedAreaButton" class="btn btn-outline-primary" style="margin-bottom:5px;">Combined</button><br>`;
  298. return html;
  299. }
  300.  
  301. function buildWKTArray(wktObj){
  302. let wkt = "";
  303. let combined = "";
  304. let wktArr = [];
  305. for(let i=0; i<wktObj.managedAreas.length; i++){
  306. if(i>0)
  307. combined += ",";
  308. wkt = "";
  309. combined += "(";
  310. for(let j=0; j<wktObj.managedAreas[i].coordinates.length; j++){
  311. if(j>0){
  312. wkt += ",";
  313. combined += ",";
  314. }
  315. combined += "(";
  316. wkt +="(";
  317. for(let k=0; k<wktObj.managedAreas[i].coordinates[j].length; k++){
  318. if(k > 0){
  319. wkt+=", ";
  320. combined += ",";
  321. }
  322. wkt += round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][0])).toString() + " " + round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][1])).toString();
  323. combined += round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][0])).toString() + " " + round(parseFloat(wktObj.managedAreas[i].coordinates[j][k][1])).toString();
  324. }
  325. combined += ")";
  326. wkt += ")";
  327. }
  328. combined += ")";
  329. wkt = `POLYGON${wkt}`;
  330. wktArr.push(wkt);
  331. }
  332. if(wktObj.managedAreas.length > 1)
  333. combined = `MULTIPOLYGON(${combined})` ;
  334. else
  335. combined = `POLYGON${combined}`;
  336.  
  337. return {wktArr: wktArr, combinedWKT: combined};
  338. }
  339.  
  340. function round(val){
  341. return Math.round(val*1000000)/1000000;
  342. }
  343.  
  344. async function getManagedAreas(){
  345. naMA = await $.get(`https://www.waze.com/Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  346. rowMA = await $.get(`https://www.waze.com/row-Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  347. ilMA = await $.get(`https://www.waze.com/il-Descartes/app/UserProfile/Areas?userID=${W.EditorProfile.data.userID}`);
  348.  
  349. /*return await new W.EditorProfile.Models.ManagedAreas([],{
  350. lastEditEnv: 'na',
  351. userId: W.EditorProfile.data.userID
  352. }).fetch();*/
  353. }
  354.  
  355. function injectCSS() {
  356. /*var css = [
  357. ].join(' ');
  358. $('<style type="text/css">' + css + '</style>').appendTo('head');*/
  359. }
  360.  
  361. function loadSettings() {
  362. var loadedSettings = $.parseJSON(localStorage.getItem("WEPE_Settings"));
  363. var defaultSettings = {
  364. EditingStatsExpanded: true
  365. };
  366. settings = loadedSettings ? loadedSettings : defaultSettings;
  367. for (var prop in defaultSettings) {
  368. if (!settings.hasOwnProperty(prop))
  369. settings[prop] = defaultSettings[prop];
  370. }
  371. }
  372.  
  373. function saveSettings() {
  374. if (localStorage) {
  375. var localsettings = {
  376. EditingStatsExpanded: settings.EditingStatsExpanded,
  377. };
  378.  
  379. localStorage.setItem("WEPE_Settings", JSON.stringify(localsettings));
  380. }
  381. }
  382. })();