forked from seabus0316/GeoFS-flightradar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserscript.js
More file actions
332 lines (302 loc) · 11.2 KB
/
userscript.js
File metadata and controls
332 lines (302 loc) · 11.2 KB
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
(function () {
'use strict';
/*** CONFIG ***/
const WS_URL = 'wss://geofs-flightradar.duckdns.org/ws';
const SEND_INTERVAL_MS = 1500;
/*************/
// ===== 新增 Modal 函數 =====
function showModal(msg, duration = null, updateBtnUrl = null) {
if (document.getElementById("geofs-atc-modal")) return;
let overlay = document.createElement("div");
overlay.id = "geofs-atc-modal";
overlay.style.cssText = `
position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:99999;
background:rgba(24,32,48,0.45);display:flex;align-items:center;justify-content:center;
`;
let box = document.createElement("div");
box.style.cssText = `
background:linear-gradient(135deg,#232942 80%,#151a25 100%);
color:#dbeaff;padding:30px 34px;border-radius:18px;box-shadow:0 6px 32px #000b;
min-width:280px;max-width:90vw;display:flex;flex-direction:column;align-items:center;gap:14px;
border:2.5px solid #3d6aff;font-size:1.15rem;letter-spacing:0.3px;
text-align:center;animation:popIn .21s;
`;
let content = document.createElement("div");
content.innerHTML = msg;
box.appendChild(content);
if (updateBtnUrl) {
let updateBtn = document.createElement("a");
updateBtn.textContent = "Update";
updateBtn.href = updateBtnUrl;
updateBtn.target = "_blank";
updateBtn.style.cssText = `
margin-top:6px;padding:8px 38px;font-size:1.05rem;background:#1e3f6e;
color:#fff;border:1.5px solid #4eaaff;border-radius:7px;font-weight:bold;cursor:pointer;
box-shadow:0 1px 8px #4eaaff30;transition:background .18s;display:inline-block;text-decoration:none;
`;
updateBtn.onmouseover = function(){this.style.background="#1552a1";}
updateBtn.onmouseout = function(){this.style.background="#1e3f6e";}
box.appendChild(updateBtn);
}
let okBtn = document.createElement("button");
okBtn.textContent = "OK";
okBtn.style.cssText = `
margin-top:16px;padding:8px 38px;font-size:1.05rem;background:#222b3c;
color:#b2cfff;border:1.5px solid #4eaaff;border-radius:7px;font-weight:bold;cursor:pointer;
box-shadow:0 1px 8px #3d6aff30;transition:background .18s;
`;
okBtn.onclick = () => { document.body.removeChild(overlay); };
box.appendChild(okBtn);
overlay.appendChild(box);
document.body.appendChild(overlay);
if (duration) setTimeout(() => {
if (document.body.contains(overlay)) document.body.removeChild(overlay);
}, duration);
overlay.tabIndex = -1; overlay.focus();
overlay.onkeydown = (e) => {
if (e.key === "Enter" || e.key === "Escape") {
if (document.body.contains(overlay)) document.body.removeChild(overlay);
}
};
if (!document.getElementById("geofs-atc-modal-anim")) {
const style = document.createElement('style');
style.id = "geofs-atc-modal-anim";
style.textContent = `
@keyframes popIn { from { transform:scale(0.85);opacity:0; } to { transform:scale(1);opacity:1; } }
`;
document.head.appendChild(style);
}
}
function log(...args) {
console.log('[ATC-Reporter]', ...args);
}
// --- 全域變數 ---
let flightInfo = { departure: '', arrival: '', flightNo: '', squawk: '' };
let flightUI;
let wasOnGround = true;
let takeoffTimeUTC = '';
// ======= Update check (English) =======
const CURRENT_VERSION = '1.9.4';
const VERSION_JSON_URL = 'https://raw.githubusercontent.com/seabus0316/GeoFS-flightradar/main/version.json';
const UPDATE_URL = 'https://raw.githubusercontent.com/seabus0316/GeoFS-flightradar/main/userscript.js';
(function checkUpdate() {
fetch(VERSION_JSON_URL)
.then(r => r.json())
.then(data => {
if (data.version && data.version !== CURRENT_VERSION) {
showModal(
`🚩 GeoFS flightradar receiver new version available (${data.version})!<br>Please reinstall the latest user.js from GitHub.`,
null,
UPDATE_URL
);
}
})
.catch(() => {});
})();
// --- WebSocket 管理 ---
let ws;
function connect() {
try {
ws = new WebSocket(WS_URL);
ws.addEventListener('open', () => {
log('WS connected');
safeSend({ type: 'hello', role: 'player' });
});
ws.addEventListener('close', () => {
log('WS closed, retrying...');
setTimeout(connect, 2000);
});
ws.addEventListener('error', (e) => {
console.warn('[ATC-Reporter] WS error', e);
try { ws.close(); } catch {}
});
} catch (e) {
console.warn('[ATC-Reporter] WS connect error', e);
setTimeout(connect, 2000);
}
}
connect();
function safeSend(obj) {
try {
if (ws && ws.readyState === 1) ws.send(JSON.stringify(obj));
} catch (e) {
console.warn('[ATC-Reporter] send error', e);
}
}
// --- 工具函式 ---
function getAircraftName() {
return geofs?.aircraft?.instance?.aircraftRecord?.name || 'Unknown';
}
function getPlayerCallsign() {
return geofs?.userRecord?.callsign || 'Unknown';
}
// --- AGL 計算 ---
function calculateAGL() {
try {
const altitudeMSL = geofs?.animation?.values?.altitude;
const groundElevationFeet = geofs?.animation?.values?.groundElevationFeet;
const aircraft = geofs?.aircraft?.instance;
if (
typeof altitudeMSL === 'number' &&
typeof groundElevationFeet === 'number' &&
aircraft?.collisionPoints?.length >= 2 &&
typeof aircraft.collisionPoints[aircraft.collisionPoints.length - 2]?.worldPosition?.[2] === 'number'
) {
const collisionZFeet = aircraft.collisionPoints[aircraft.collisionPoints.length - 2].worldPosition[2] * 3.2808399;
return Math.round((altitudeMSL - groundElevationFeet) + collisionZFeet);
}
} catch (err) {
console.warn('[ATC-Reporter] AGL calculation error:', err);
}
return null;
}
// --- 起飛偵測 ---
function checkTakeoff() {
const onGround = geofs?.aircraft?.instance?.groundContact ?? true;
if (wasOnGround && !onGround) {
takeoffTimeUTC = new Date().toISOString();
console.log('[ATC-Reporter] Takeoff at', takeoffTimeUTC);
}
wasOnGround = onGround;
}
// --- 擷取飛行狀態 ---
function readSnapshot() {
try {
const inst = geofs?.aircraft?.instance;
if (!inst) return null;
const lla = inst.llaLocation || [];
const lat = lla[0];
const lon = lla[1];
const altMeters = lla[2];
if (typeof lat !== 'number' || typeof lon !== 'number') return null;
const altMSL = (typeof altMeters === 'number') ? altMeters * 3.28084 : geofs?.animation?.values?.altitude ?? 0;
const altAGL = calculateAGL();
const heading = geofs?.animation?.values?.heading360 ?? 0;
const speed = geofs.animation.values.kias ? geofs.animation.values.kias.toFixed(1) : 'N/A';
return { lat, lon, altMSL, altAGL, heading, speed };
} catch (e) {
console.warn('[ATC-Reporter] readSnapshot error:', e);
return null;
}
}
// --- 組裝 payload ---
function buildPayload(snap) {
checkTakeoff();
let flightPlan = [];
try {
if (geofs.flightPlan && typeof geofs.flightPlan.export === "function") {
flightPlan = geofs.flightPlan.export();
}
} catch (e) {}
const userId = geofs?.userRecord?.id || null;
return {
id: getPlayerCallsign(),
callsign: getPlayerCallsign(),
type: getAircraftName(),
lat: snap.lat,
lon: snap.lon,
alt: (typeof snap.altAGL === 'number') ? snap.altAGL : Math.round(snap.altMSL || 0),
altMSL: Math.round(snap.altMSL || 0),
heading: Math.round(snap.heading || 0),
speed: Math.round(snap.speed || 0),
flightNo: flightInfo.flightNo,
departure: flightInfo.departure,
arrival: flightInfo.arrival,
takeoffTime: takeoffTimeUTC,
squawk: flightInfo.squawk,
flightPlan: flightPlan,
nextWaypoint: geofs.flightPlan?.trackedWaypoint?.ident || null, // ← 加這行
userId: userId // ← 添加這行
};
}
// --- 定期傳送 ---
setInterval(() => {
if (!ws || ws.readyState !== 1) return;
const snap = readSnapshot();
if (!snap) return;
const payload = buildPayload(snap);
safeSend({ type: 'position_update', payload });
}, SEND_INTERVAL_MS);
// --- Toast 提示 ---
function showToast(msg) {
const toast = document.createElement('div');
toast.textContent = msg;
toast.style.position = 'fixed';
toast.style.bottom = '20px';
toast.style.right = '20px';
toast.style.background = 'rgba(0,0,0,0.8)';
toast.style.color = '#fff';
toast.style.padding = '8px 12px';
toast.style.borderRadius = '6px';
toast.style.fontSize = '13px';
toast.style.zIndex = 1000000;
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.3s ease';
document.body.appendChild(toast);
requestAnimationFrame(() => { toast.style.opacity = '1'; });
setTimeout(() => {
toast.style.opacity = '0';
setTimeout(() => toast.remove(), 300);
}, 2000);
}
// --- UI 注入 ---
function injectFlightUI() {
flightUI = document.createElement('div');
flightUI.id = 'flightInfoUI';
flightUI.style.position = 'fixed';
flightUI.style.bottom = '280px';
flightUI.style.right = '6px';
flightUI.style.background = 'rgba(0,0,0,0.6)';
flightUI.style.padding = '8px';
flightUI.style.borderRadius = '6px';
flightUI.style.color = 'white';
flightUI.style.fontSize = '12px';
flightUI.style.zIndex = 999999;
flightUI.innerHTML = `
<div>Dep: <input id="depInput" style="width:60px"></div>
<div>Arr: <input id="arrInput" style="width:60px"></div>
<div>Flt#: <input id="fltInput" style="width:60px"></div>
<div>SQK: <input id="sqkInput" style="width:60px" maxlength="4"></div>
<button id="saveBtn">Save</button>
`;
document.body.appendChild(flightUI);
// 讓輸入框自動轉大寫
['depInput','arrInput','fltInput','sqkInput'].forEach(id => {
const el = document.getElementById(id);
el.addEventListener('input', () => {
el.value = el.value.toUpperCase();
});
});
document.getElementById('saveBtn').onclick = () => {
flightInfo.departure = document.getElementById('depInput').value.trim();
flightInfo.arrival = document.getElementById('arrInput').value.trim();
flightInfo.flightNo = document.getElementById('fltInput').value.trim();
flightInfo.squawk = document.getElementById('sqkInput').value.trim();
showToast('Flight info saved!');
};
}
injectFlightUI();
// --- 快捷鍵 W 收合 UI ---
document.addEventListener('keydown', (e) => {
if (e.key.toLowerCase() === 'w') {
if (flightUI.style.display === 'none') {
flightUI.style.display = 'block';
showToast('Flight Info UI Shown');
} else {
flightUI.style.display = 'none';
showToast('Flight Info UI Hidden');
}
}
});
// --- 關閉所有 input 的 autocomplete ---
document.querySelectorAll("input").forEach(el => {
el.setAttribute("autocomplete", "off");
});
// --- 防止 input 觸發 GeoFS hotkey ---
document.addEventListener("keydown", (e) => {
const target = e.target;
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA") {
e.stopPropagation();
}
}, true);
})();