Code:
// ==UserScript==
// @name Corrected Coords
// @namespace http://barnygeeft.com
// @version 0.8.1
// @description Exchange Corrected Coordinates.
// @author Barny
// @resource coordCSS https://barnyruilt.alwaysdata.net/style.css
// @match https://www.geocaching.com/geocache/*
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @connect barnyruilt.alwaysdata.net
// ==/UserScript==
// https://github.com/Tampermonkey/tampermonkey/issues/475
(function() {
'use strict';
const link_id = 'linkToCorrectedCoords';
const state_id = 'elementForStateInformation';
const url = 'https://barnyruilt.alwaysdata.net';
const wait_time_increase = 200;
var button_info = {
error: {
class: 'gc-pink-background',
text: '☠',
},
found: {
class: 'gc-green-background',
text: '✓',
title: 'Corrected Coordinate found, click to update',
},
loading: {
class: 'gc-gray-background',
text: '❄',
//animate: ['◷', '◶', '◵', '◴'],
//animate: ['▝', '▗', '▖', '▘' ],
animate: ['⠈⠉', '⠀⠙', '⠀⠸', '⠀⢰', '⠀⣠', '⢀⣀', '⣀⡀', '⣄⠀', '⡆⠀', '⠇⠀', '⠋⠀', '⠉⠁'],
timeout: 97,
title: 'Loading',
},
min: {
class: 'gc-yellow-background',
text: '?',
title: 'You\'ve requested this coordinate',
},
notfound: {
class: 'gc-red-background',
text: '✗',
title: 'No Corrected Coordinate Available',
},
plus: {
class: 'gc-yellow-background',
text: '✓',
title: 'You\'ve contributed this coordinate',
},
unknown: {
class: 'gc-blue-background',
text: '?',
title: 'Click to check for Corrected Coordinates',
},
wait: {
class: 'gc-yellow-background',
text: '◔',
title: 'Not so fast cowboy',
},
};
var time_period = [
{ name: 'seconds', factor: 1000 },
{ name: 'minutes', factor: 60 },
{ name: 'hours', factor: 60 },
{ name: 'days', factor: 24 },
{ name: 'months', factor: 31 },
{ name: 'years', factor: 12 },
]
var wait_time = 0;
var button_timeout = null;
var multiple_timer = null;
// Geocaching functions
function geocachePage() {
//console.debug('geocachePage');
if ('undefined' === typeof(userInfo)) {
setTimeout(geocachePage, 50);
return;
}
GM_setValue('userid', userInfo.ID);
createButton();
waitForCorrected();
}
function waitForCorrected() {
//console.debug('waitForCorrected');
gccode = document.getElementById('ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode').innerHTML;
coords = document.getElementById('uxLatLon').innerHTML;
const hasCorrectedCoords = document.getElementById('activityBadge');
if (hasCorrectedCoords) {
// note = document.getElementById('viewCacheNote');
// note = note ? note.innerHTML : '';
note = '';
updateButton('loading');
sendCoordinate();
} else {
setTimeout(waitForCorrected, 150);
}
}
function postData(data) {
return Object.keys(data).map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&');
}
function updateButton(state, title = '') {
if (button_timeout) { clearTimeout(button_timeout); button_timeout = null; }
if (button_info[state].animate) {
if (!button_info[state].frame) { button_info[state].frame = 0; }
if (!button_info[state].timeout) { button_info[state].timeout = 314; }
button_info[state].text = button_info[state].animate[button_info[state].frame];
button_info[state].frame = (button_info[state].frame + 1) % button_info[state].animate.length;
button_timeout = setTimeout(() => updateButton(state, title), button_info[state].timeout);
}
if (('' === title) && (button_info[state].title)) { title = button_info[state].title }
var button = document.getElementById(link_id);
var old_state = button.getAttribute('data-state');
if (old_state != state) {
if (old_state) {
button.classList.remove(button_info[old_state].class);
button.classList.remove(button_info[old_state].class + '-hover');
}
button.setAttribute('data-state', state);
button.classList.add(button_info[state].class);
button.classList.add(button_info[state].class + '-hover');
}
button.title = title;
button.innerHTML = button_info[state].text;
}
function createButton() {
var button = document.createElement('div');
button.id = link_id;
button.style = 'margin-right: 0.5em';
button.classList.add('coords-box');
button.setAttribute('data-state', 'wait');
button.addEventListener('click', onClick);
var link = document.getElementById('uxLatLonLink');
link.parentNode.insertBefore(button, link)
updateButton('unknown');
}
function onClick() {
var args = {}
switch (document.getElementById(link_id).getAttribute('data-state')) {
case 'found': getCoordinate(); break;
case 'unknown': checkCoordinate(); break;
}
return false
}
function checkCoordinate() {
updateButton('loading');
console.log('Checking: ' + gccode);
GM_xmlhttpRequest({
url: url,
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
data: postData({ 'gccode': gccode }),
onload: (data) => {
if (JSON.parse(data.responseText).hasCorrected) {
updateButton('found');
} else {
updateButton('notfound');
}
},
onerror: (data) => {
updateButton('error', 'Something went wrong while checking coordinates');
console.error(data)
},
});
}
function getCoordinate() {
updateButton('loading');
if (requestToken(getCoordinate)) { return; }
GM_xmlhttpRequest({
url: url,
method: 'POST',
headers: {
'Content-type': 'application/x-www-forms-urlencoded',
'Accept': 'application/json',
},
data: postData({
'prid': userInfo.ID,
'gccode': gccode,
'token': GM_getValue('token_value'),
}),
onload: (resp) => {
var data = JSON.parse(resp.responseText)
if (data.error) {
updateButton('error', data.error);
} else if (data.wait) {
waitCoordinate(Date.now() + 1000 * data.wait, 'found')
} else if (data.latitude && data.longitude) {
if((Math.abs(data.latitude) > 90) || (Math.abs(data.latitude) > 180)) {
updateButton('error', 'Invalid coordinates');
} else {
// alert('Koordinaten: \n'+ data.latitude + ' ' + data.longitude + "\n" + formatLatLngDisplay(data.latitude, data.longitude));
// alert('Koordinaten: '+ data.latitude + ' ' + data.longitude);
alert('Koordinaten: '+ formatLatLngDisplay(data.latitude, data.longitude));
// updateCoordinate(data)
}
} else {
updateButton('notfound', 'No coordinates returned');
console.error(data);
}
},
onerror: (data) => {
updateButton('error', 'Something went wrong while retreiving coordinates');
console.error(data)
},
});
}
function dmsToDecimal(dmsString) {
const match = dmsString.match(/([NSEW])\s*(\d+)°?\s*(\d+\.\d+)'?/);
if (!match) return null;
const [, direction, degrees, minutes] = match;
let decimal = parseInt(degrees, 10) + parseFloat(minutes) / 60;
if (direction === 'S' || direction === 'W') {
decimal = -decimal;
}
return decimal;
}
function decimalToDMS(decimal, isLatitude) {
const direction = isLatitude
? (decimal >= 0 ? 'N' : 'S')
: (decimal >= 0 ? 'E' : 'W');
const absolute = Math.abs(decimal);
const degrees = Math.floor(absolute);
const minutes = (absolute - degrees) * 60;
// Grad mit führenden Nullen auf 3 Stellen für Longitude (wie "000"), 2 für Latitude
const degreesStr = isLatitude
? String(degrees).padStart(2, '0')
: String(degrees).padStart(3, '0');
const minutesStr = minutes.toFixed(3);
return `${direction} ${degreesStr}° ${minutesStr}'`;
}
function formatLatLngDisplay(lat, lng) {
return `${decimalToDMS(lat, true)} ${decimalToDMS(lng, false)}`;
}
function updateCoordinate(data) {
$.getJSON({
url: 'https://www.geocaching.com/seek/cache_details.aspx/SetUserCoordinate',
type: "POST",
dataType: "json",
contentType : "application/json",
data: JSON.stringify({
dto: {
data: {
lat: data.latitude,
lng: data.longitude,
},
ut: userToken,
}
}),
success: () => location.reload(), // Because groundspeak is also to lazy to use the response to update the page
error: (data) => {
updateButton('error', 'Something went wrong while updating coordinate');
console.error(data);
},
});
console.log(data);
}
function sendCoordinate() {
// console.debug('sendCoordinate');
if (requestToken(sendCoordinate)) { return; }
GM_xmlhttpRequest({
url: url,
method: 'POST',
headers: {
//'Content-type': 'application/x-www-forms-urlencoded',
'Accept': 'application/json',
},
data: postData({
'gccode': gccode,
'note': note,
'prid': userInfo.ID,
'token': GM_getValue('token_value'),
}),
onload: (data) => {
var json = JSON.parse(data.responseText);
console.log(json);
updateButton((1 == json['direction']) ? 'plus' : 'min');
},
error: (data) => {
updateButton('error', 'Something went wrong while sending coordinates');
console.error(data)
},
});
}
function waitCoordinate(timestamp, next) {
var delta = timestamp - Date.now();
if (delta > 0) {
var i = 1;
delta /= time_period[0].factor;
var wait = time_period[0].factor / 4;
while ((delta > 99) && (i < time_period.length)) {
delta /= time_period[i].factor;
wait *= time_period[i].factor;
i++;
}
updateButton('wait', 'Please wait ' + Math.ceil(delta) + ' ' + time_period[i-1].name);
setTimeout(() => waitCoordinate(timestamp, next), wait);
return;
}
updateButton(next);
}
function requestToken(func = null) {
if (
((GM_getValue('token_expires') || 0) < (Date.now() + 5*60*1000)) &&
(
((GM_getValue('token_requested') || 0) < (Date.now() - 10*60*1000)) ||
((GM_getValue('token_expires') || 0) >= (GM_getValue('token_requested') || 0))
)
) {
getToken();
}
if (func) {
if (GM_getValue('token_expires') < Date.now()) {
console.log(GM_getValue('token_expires') + ' expires');
console.log(GM_getValue('token_requested') + ' requested');
wait_time += wait_time_increase;
console.debug('Waiting for token: ' + wait_time)
setTimeout(func, wait_time);
} else {
return false;
}
}
return true;
}
function getToken() {
console.log('getToken()');
GM_setValue('token_requested', Date.now());
GM_xmlhttpRequest({
url: "https://www.geocaching.com/account/oauth/token",
method: 'POST',
headers: {
//'Content-type': 'application/x-www-forms-urlencoded',
'Accept': 'application/json',
},
onload: (resp) => {
var result = JSON.parse(resp.responseText);
GM_setValue('token_value', result.access_token);
GM_setValue('token_expires', Date.now() + 1000 * (result.expires_in - 60)); // - 60 seconds as a safety
}
});
}
// Main functions
var coords = '';
var gccode = '';
var note = '';
var userid = '';
GM_addStyle(GM_getResourceText("coordCSS"));
switch (window.location.hostname) {
case 'www.geocaching.com' :
requestToken();
console.debug(window.location.pathname)
if (window.location.pathname.match(/\/geocache/)) {
geocachePage();
}
break;
}
})();