import { PushNotifications } from '@capacitor/push-notifications'; import Socket from "/_/code/ws/Socket.js" import "./Home/Home.js" import "./Home/AuthPage/AuthPage.js" import "./Home/ConnectionError.js" import util from "./util.js" let Global = class { Socket = new Socket() profile = null currentNetwork = "" lastApp = "" util = util currentApp() { const pathname = window.location.pathname; const segments = pathname.split('/').filter(Boolean) const secondSegment = segments[1] || "" const capitalized = secondSegment.charAt(0).toUpperCase() + secondSegment.slice(1); return capitalized } openApp = function(appName) { const appUrl = appName.charAt(0).toLowerCase() + appName.slice(1); let parts = window.location.pathname.split('/').filter(Boolean); let newPath = "/" + parts[0] + "/" + appUrl window.navigateTo(newPath) const event = new CustomEvent('appchange', { detail: { name: appName } }); window.dispatchEvent(event) } async fetchAppData() { let personalSpace = this.currentNetwork === this.profile if (personalSpace) { return {} } let appData = await fetch(`${util.HOST}/api/${personalSpace ? "my" : "org"}data/` + this.currentNetwork.id, {method: "GET"}) let json = await appData.json() return json } onNavigate = async () => { if(!global.profile) return let selectedNetwork = this.networkFromPath() if(!selectedNetwork) { if (!this.currentNetwork || this.currentNetwork === this.profile) { let path = `/${this.getDefaultNetworkName()}/${this.getDefaultAppName()}` history.replaceState({}, '', path) } } else if(!this.currentApp()) { if(this.currentNetwork === window.profile) { history.replaceState({}, '', `${window.location.pathname}/${window.profile.apps[0]}`) } else { history.replaceState({}, '', `${window.location.pathname}/${this.getDefaultAppName()}`) } } selectedNetwork = this.networkFromPath() let networkChanged = this.currentNetwork !== selectedNetwork let appChanged = this.currentApp() !== this.lastApp if(appChanged) { this.lastApp = this.currentApp() } if(networkChanged) { this.currentNetwork = selectedNetwork const event = new CustomEvent('networkchange', { detail: { name: this.currentNetwork } }); window.dispatchEvent(event) } if(!this.currentNetwork?.data) { this.currentNetwork.data = await this.fetchAppData() } if(appChanged && !networkChanged) { const event = new CustomEvent('appchange', { detail: { name: this.currentApp() } }); window.dispatchEvent(event) } document.title = (this.currentNetwork === this.profile) ? "Forum" : `${this.currentNetwork.abbreviation} | Forum` } setCurrentNetworkAndApp() { this.currentNetwork = this.networkFromPath() } getDefaultNetworkName() { let defaultNetwork = this.profile.networks[0] if (!defaultNetwork) { return "my"; } return defaultNetwork.abbreviation } getDefaultAppName() { let defaultNetwork = this.profile.networks[0] if (!defaultNetwork) { return this.profile.apps[0].toLowerCase(); } return defaultNetwork.apps[0].toLowerCase() } networkFromPath = function () { const pathname = window.location.pathname; const firstSegment = pathname.split('/').filter(Boolean)[0] || ''; if(firstSegment === "my") { return this.profile } else { let networks = this.profile.networks for(let i = 0; i < networks.length; i++) { let network = networks[i] if(network.abbreviation === firstSegment) { return network } } } } async getProfile() { try { const res = await util.authFetch(`${util.HOST}/auth/profile`, { method: "GET", credentials: "include", headers: { "Accept": "application/json" } }); if(res.status === 401) { return res.status } if (!res.ok) return res.status; const profile = await res.json(); console.log("getProfile: ", profile); this.profile = profile return 200; } catch (err) { // Network error / Error reaching server console.error(err); return 500; } } async renderHome() { location.reload() } async onLogout() { await util.removeAuthToken() await fetch(`${util.HOST}/auth/signout`, { method: "GET", credentials: "include" }); this.profile = null location.reload() } async setupPushNotifications() { PushNotifications.addListener('registration', async (token) => { console.log('Device token:', token.value) const stored = localStorage.getItem('deviceToken') if (stored === token.value) return; console.log("new push token") await server.updatePushToken(token.value) localStorage.setItem('deviceToken', token.value) }); PushNotifications.addListener('registrationError', (error) => { console.error('Registration error:', JSON.stringify(error)) }); PushNotifications.addListener('pushNotificationReceived', (notification) => { console.log('Notification received:', notification) }); PushNotifications.addListener('pushNotificationActionPerformed', (action) => { console.log('Notification tapped:', action.notification) // navigate somewhere based on action.notification.data }); const permission = await PushNotifications.requestPermissions(); if (permission.receive === 'granted') { await PushNotifications.register(); console.log('after registter:') } } async init() { try { const module = await import(`${util.HOST}/@server/server.js`); window.server = module.default; } catch(E) { console.error(E) } this.setupPushNotifications() window.addEventListener("navigate", this.onNavigate) this.getProfile().then(async (status) => { if (status === 401) { navigateTo("/") AuthPage() } else if(status === 500) { ConnectionError() } else { await this.Socket.init() await this.onNavigate() Home() } }) } constructor() { this.init() } } window.global = new Global()