unify formatting

This commit is contained in:
Sebastian Hugentobler 2023-02-01 20:37:40 +01:00
parent 6419d5defd
commit 553f764e69
Signed by: shu
GPG Key ID: BB32CF3CA052C2F0

View File

@ -16,29 +16,29 @@ let gpxTrack = null;
* @returns Calculated lat and lon. * @returns Calculated lat and lon.
*/ */
function toWGS84(point) { function toWGS84(point) {
// convert LV95 into the civilian system // convert LV95 into the civilian system
let y_aux = (point[0] - 2600000)/1000000; let y_aux = (point[0] - 2600000) / 1000000;
let x_aux = (point[1] - 1200000)/1000000; let x_aux = (point[1] - 1200000) / 1000000;
// calculate longitude and latitude in the unit 10000" // calculate longitude and latitude in the unit 10000"
let lat = 16.9023892 + let lat = 16.9023892 +
3.238272 * x_aux - 3.238272 * x_aux -
0.270978 * Math.pow(y_aux, 2) - 0.270978 * Math.pow(y_aux, 2) -
0.002528 * Math.pow(x_aux, 2) - 0.002528 * Math.pow(x_aux, 2) -
0.0447 * Math.pow(y_aux, 2) * x_aux - 0.0447 * Math.pow(y_aux, 2) * x_aux -
0.0140 * Math.pow(x_aux, 3); 0.0140 * Math.pow(x_aux, 3);
let lon = 2.6779094 + let lon = 2.6779094 +
4.728982 * y_aux + 4.728982 * y_aux +
0.791484 * y_aux * x_aux + 0.791484 * y_aux * x_aux +
0.1306 * y_aux * Math.pow(x_aux, 2) - 0.1306 * y_aux * Math.pow(x_aux, 2) -
0.0436 * Math.pow(y_aux, 3); 0.0436 * Math.pow(y_aux, 3);
// unit 10000" to 1" and seconds to degrees (dec) // unit 10000" to 1" and seconds to degrees (dec)
lat = lat * 100 / 36; lat = lat * 100 / 36;
lon = lon * 100 / 36; lon = lon * 100 / 36;
return {lat: lat, lon: lon}; return { lat: lat, lon: lon };
} }
/** /**
@ -47,9 +47,9 @@ function toWGS84(point) {
* @param {*} point Array of Swiss projection coordinates, position 0 is E and 1 is N. * @param {*} point Array of Swiss projection coordinates, position 0 is E and 1 is N.
* @returns Track point xml node for gpx. * @returns Track point xml node for gpx.
*/ */
function toTrackPoint(point) { function toTrackPoint(point) {
let wgs84Point = toWGS84(point); let wgs84Point = toWGS84(point);
return `<trkpt lat="${wgs84Point.lat}" lon="${wgs84Point.lon}"/>`; return `<trkpt lat="${wgs84Point.lat}" lon="${wgs84Point.lon}"/>`;
} }
/** /**
@ -57,9 +57,9 @@ function toWGS84(point) {
* *
* @returns Way point xml node for gpx. * @returns Way point xml node for gpx.
*/ */
function toWayPoint(point) { function toWayPoint(point) {
let wgs84Point = toWGS84(point.geom.coordinates); let wgs84Point = toWGS84(point.geom.coordinates);
return ` return `
<wpt lat="${wgs84Point.lat}" lon="${wgs84Point.lon}"> <wpt lat="${wgs84Point.lat}" lon="${wgs84Point.lon}">
<ele>${point.altitude}</ele> <ele>${point.altitude}</ele>
<name>${point.display_name}</name> <name>${point.display_name}</name>
@ -73,10 +73,12 @@ function toWGS84(point) {
* @returns Combined route number, id and route title. * @returns Combined route number, id and route title.
*/ */
function trackTitle(geoJson) { function trackTitle(geoJson) {
const route = geoJson.segments[0]; const route = geoJson.segments[0];
const book = geoJson.book_route_number ? `${geoJson.book_route_number} - ` : ""; const book = geoJson.book_route_number
? `${geoJson.book_route_number} - `
: "";
return `${book}${geoJson.title}`; return `${book}${geoJson.title}`;
} }
/** /**
@ -86,20 +88,22 @@ function trackTitle(geoJson) {
* @returns Simple gpx string. * @returns Simple gpx string.
*/ */
function toGpx(geoJson) { function toGpx(geoJson) {
let trackSegments = geoJson.segments.map(segment => { let trackSegments = geoJson.segments.map((segment) => {
return `<trkseg> return `<trkseg>
${segment.geom.coordinates.map(toTrackPoint).join("")} ${segment.geom.coordinates.map(toTrackPoint).join("")}
</trkseg>`; </trkseg>`;
}).join(""); }).join("");
let endPoint = geoJson.end_point ? toWayPoint(geoJson.end_point) : ""; let endPoint = geoJson.end_point ? toWayPoint(geoJson.end_point) : "";
let waypoints = geoJson.waypoints ? geoJson.waypoints.map(wp => { let waypoints = geoJson.waypoints
return toWayPoint(wp.reference_poi); ? geoJson.waypoints.map((wp) => {
}).join("") : ""; return toWayPoint(wp.reference_poi);
}).join("")
: "";
const routeTitle = trackTitle(geoJson); const routeTitle = trackTitle(geoJson);
const xmlString = `<?xml version="1.0" encoding="UTF-8" standalone="no" ?> const xmlString = `<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0" xmlns="http://www.topografix.com/GPX/1/0"
@ -117,41 +121,41 @@ function toGpx(geoJson) {
</gpx> </gpx>
`; `;
const parser = new DOMParser(); const parser = new DOMParser();
let xmlDoc = parser.parseFromString(xmlString, "text/xml"); let xmlDoc = parser.parseFromString(xmlString, "text/xml");
return new XMLSerializer().serializeToString(xmlDoc.documentElement); return new XMLSerializer().serializeToString(xmlDoc.documentElement);
} }
/** /**
* Intercept the download of GeoJSON data and save it for the background script. * Intercept the download of GeoJSON data and save it for the background script.
*/ */
function listener(details) { function listener(details) {
let filter = browser.webRequest.filterResponseData(details.requestId); let filter = browser.webRequest.filterResponseData(details.requestId);
let decoder = new TextDecoder("utf-8"); let decoder = new TextDecoder("utf-8");
let encoder = new TextEncoder(); let encoder = new TextEncoder();
let data = []; let data = [];
filter.ondata = event => { filter.ondata = (event) => {
data.push(event.data); data.push(event.data);
}; };
filter.onstop = async event => { filter.onstop = async (event) => {
let blob = new Blob(data, {type: 'text/html'}); let blob = new Blob(data, { type: "text/html" });
let buffer = await blob.arrayBuffer(); let buffer = await blob.arrayBuffer();
let str = decoder.decode(buffer); let str = decoder.decode(buffer);
updateActiveTab(browser.tabs); updateActiveTab(browser.tabs);
filter.write(encoder.encode(str)); filter.write(encoder.encode(str));
filter.close(); filter.close();
let geoJson = JSON.parse(str); let geoJson = JSON.parse(str);
const routeTitle = trackTitle(geoJson); const routeTitle = trackTitle(geoJson);
gpxTrack = {title: routeTitle, data: toGpx(geoJson)}; gpxTrack = { title: routeTitle, data: toGpx(geoJson) };
}; };
return {}; return {};
} }
/** /**
@ -161,76 +165,84 @@ function listener(details) {
* @returns True if the active tab is an sac website, false otherwise. * @returns True if the active tab is an sac website, false otherwise.
*/ */
function checkTrack(tab) { function checkTrack(tab) {
if (!tab.url) { if (!tab.url) {
return false; return false;
} }
return tab.url.match("https://www.sac-cas.ch/.*") && gpxTrack; return tab.url.match("https://www.sac-cas.ch/.*") && gpxTrack;
} }
/** /**
* If a valid tack was selected, download it as a gpx file. * If a valid tack was selected, download it as a gpx file.
*/ */
function handleClick(tab) { function handleClick(tab) {
const hasTrack = checkTrack(tab); const hasTrack = checkTrack(tab);
if (!hasTrack) { if (!hasTrack) {
return; return;
} }
let blob = new Blob([gpxTrack.data], {type: "application/gpx+xml"}); let blob = new Blob([gpxTrack.data], { type: "application/gpx+xml" });
let objectURL = URL.createObjectURL(blob); let objectURL = URL.createObjectURL(blob);
let downloading = browser.downloads.download({ let downloading = browser.downloads.download({
url : objectURL, url: objectURL,
filename : `${gpxTrack.title}.gpx`, filename: `${gpxTrack.title}.gpx`,
saveAs: true, saveAs: true,
conflictAction : 'uniquify' conflictAction: "uniquify",
}); });
downloading.then( downloading.then(
(id) => console.log(`Started downloading: ${id}`), (id) => console.log(`Started downloading: ${id}`),
(error) => console.log(`Download failed: ${error}`)); (error) => console.log(`Download failed: ${error}`),
gpxTrack = null; );
gpxTrack = null;
} }
/** /**
* Update the download icon and text. * Update the download icon and text.
*/ */
function updateActiveTab(tabs) { function updateActiveTab(tabs) {
function updateTab(tabs) { function updateTab(tabs) {
if (tabs[0]) { if (tabs[0]) {
updateIcon(tabs[0]); updateIcon(tabs[0]);
}
} }
}
let gettingActiveTab = browser.tabs.query({active: true, currentWindow: true}); let gettingActiveTab = browser.tabs.query({
gettingActiveTab.then(updateTab); active: true,
currentWindow: true,
});
gettingActiveTab.then(updateTab);
} }
/** /**
* Update the download icon. * Update the download icon.
*/ */
function updateIcon(tab) { function updateIcon(tab) {
const hasTrack = checkTrack(tab); const hasTrack = checkTrack(tab);
browser.browserAction.setIcon({ browser.browserAction.setIcon({
path: hasTrack ? { path: hasTrack
? {
48: "icons/map.png", 48: "icons/map.png",
} : { }
: {
48: "icons/map-disabled.png", 48: "icons/map-disabled.png",
}, },
tabId: tab.id tabId: tab.id,
}); });
browser.browserAction.setTitle({ browser.browserAction.setTitle({
title: hasTrack ? `Download track "${gpxTrack.title}"` : 'No track selected', title: hasTrack
tabId: tab.id ? `Download track "${gpxTrack.title}"`
}); : "No track selected",
tabId: tab.id,
});
} }
browser.webRequest.onBeforeRequest.addListener( browser.webRequest.onBeforeRequest.addListener(
listener, listener,
{urls: ["https://www.sac-cas.ch/*[routeId]*"]}, { urls: ["https://www.sac-cas.ch/*[routeId]*"] },
["blocking"] ["blocking"],
); );
browser.browserAction.onClicked.addListener(handleClick); browser.browserAction.onClicked.addListener(handleClick);