Skip to content

Commit 54e1764

Browse files
committed
cleanups
1 parent a5df480 commit 54e1764

File tree

9 files changed

+25
-59
lines changed

9 files changed

+25
-59
lines changed

backend/app/api/__init__.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
from fastapi import APIRouter
22

3-
# When using HASSIO_RUN_MODE (Home Assistant ingress with automatic login), we make this distinction:
4-
# - api_public: exported to the local network via port 8989, no authentication required
5-
# - api_no_auth: accessible via Home Assistant ingress (on port 8990) without authentication
6-
# - api_with_auth: accessible via Home Assistant ingress (on port 8990) without authentication
7-
8-
# When not using HASSIO_RUN_MODE (running directly from Docker), we make this distinction:
3+
# When not using HASSIO_RUN_MODE (running directly from Docker):
94
# - api_public: routes that do not require authentication
105
# - api_no_auth: routes that do not require authentication
116
# - api_with_auth: routes that can only be accessed by authenticated users
127

8+
# When using HASSIO_RUN_MODE (Home Assistant ingress with automatic login):
9+
# - api_public: exported to the local network via port 8989, no authentication required
10+
# - api_no_auth: accessible via Home Assistant ingress (on port 8990) without authentication
11+
# - api_with_auth: accessible via Home Assistant ingress (on port 8990) without authentication
12+
1313
api_public = APIRouter()
1414
api_no_auth = APIRouter()
1515
api_with_auth = APIRouter()

backend/app/api/frames.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
from app.config import config
3030
from app.utils.network import is_safe_host
3131
from app.redis import get_redis
32-
from app.config import Config, get_config
3332
from . import api_with_auth, api_no_auth
3433

3534

@@ -58,7 +57,7 @@ async def api_frame_get_logs(id: int, db: Session = Depends(get_db)):
5857

5958

6059
@api_with_auth.get("/frames/{id:int}/image_link", response_model=FrameImageLinkResponse)
61-
async def get_image_link(id: int, config: Config = Depends(get_config)):
60+
async def get_image_link(id: int):
6261
expire_minutes = 5
6362
now = datetime.utcnow()
6463
expire = now + timedelta(minutes=expire_minutes)
@@ -68,13 +67,14 @@ async def get_image_link(id: int, config: Config = Depends(get_config)):
6867
expires_in = int((expire - now).total_seconds())
6968

7069
return {
71-
"url": config.base_path + f"/api/frames/{id}/image?token={token}",
70+
"url": config.ingress_path + f"/api/frames/{id}/image?token={token}",
7271
"expires_in": expires_in
7372
}
7473

7574
@api_no_auth.get("/frames/{id:int}/image")
7675
async def api_frame_get_image(id: int, token: str, request: Request, db: Session = Depends(get_db), redis: Redis = Depends(get_redis)):
7776
if config.HASSIO_RUN_MODE != 'ingress':
77+
# All modes except ingress require a token in the url
7878
try:
7979
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
8080
if payload.get("sub") != f"frame={id}":

backend/app/api/templates.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
)
2727
from app.api.auth import SECRET_KEY, ALGORITHM
2828
from app.api import api_with_auth, api_no_auth
29-
from app.config import Config, get_config
3029
from app.redis import get_redis
3130

3231

@@ -241,7 +240,7 @@ async def get_template(template_id: str, db: Session = Depends(get_db)):
241240
return d
242241

243242
@api_with_auth.get("/templates/{template_id}/image_link", response_model=TemplateImageLinkResponse)
244-
async def get_image_link(template_id: str, config: Config = Depends(get_config)):
243+
async def get_image_link(template_id: str):
245244
expire_minutes = 5
246245
now = datetime.utcnow()
247246
expire = now + timedelta(minutes=expire_minutes)
@@ -250,13 +249,14 @@ async def get_image_link(template_id: str, config: Config = Depends(get_config))
250249
expires_in = int((expire - now).total_seconds())
251250

252251
return {
253-
"url": config.base_path + f"/api/templates/{template_id}/image?token={token}",
252+
"url": config.ingress_path + f"/api/templates/{template_id}/image?token={token}",
254253
"expires_in": expires_in
255254
}
256255

257256
@api_no_auth.get("/templates/{template_id}/image")
258257
async def get_template_image(template_id: str, token: str, request: Request, db: Session = Depends(get_db)):
259258
if config.HASSIO_RUN_MODE != 'ingress':
259+
# All modes except ingress require a token in the url
260260
try:
261261
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
262262
if payload.get("sub") != f"template={template_id}":

backend/app/api/tests/test_ingress.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ def clear_env(monkeypatch):
1313
"""
1414
monkeypatch.delenv("HASSIO_RUN_MODE", raising=False)
1515
monkeypatch.delenv("HASSIO_TOKEN", raising=False)
16-
monkeypatch.delenv("HOSTNAME", raising=False)
1716
monkeypatch.delenv("SUPERVISOR_TOKEN", raising=False)
1817

1918
def _reload_app_and_config():
@@ -47,7 +46,7 @@ async def test_no_hassio_env(clear_env):
4746
app, conf = _reload_app_and_config()
4847
assert conf.HASSIO_TOKEN is None
4948
assert conf.HASSIO_RUN_MODE is None
50-
assert conf.base_path == ""
49+
assert conf.ingress_path == ""
5150

5251
client = TestClient(app)
5352

@@ -77,7 +76,7 @@ async def test_hassio_run_mode_public(clear_env, monkeypatch):
7776
app, conf = _reload_app_and_config()
7877
assert conf.HASSIO_TOKEN == "token"
7978
assert conf.HASSIO_RUN_MODE == "public"
80-
assert conf.base_path == ""
79+
assert conf.ingress_path == ""
8180

8281
client = TestClient(app)
8382

@@ -104,7 +103,6 @@ async def test_hassio_run_mode_ingress(clear_env, monkeypatch):
104103
custom_ingress = "/hostname/ingress"
105104
monkeypatch.setenv("HASSIO_TOKEN", "token")
106105
monkeypatch.setenv("HASSIO_RUN_MODE", "ingress")
107-
monkeypatch.setenv("HOSTNAME", "hostname")
108106
monkeypatch.setenv("SUPERVISOR_TOKEN", "token")
109107

110108
def mock_requests_get(url, headers):
@@ -118,7 +116,7 @@ def mock_requests_get(url, headers):
118116

119117
assert conf.HASSIO_TOKEN == "token"
120118
assert conf.HASSIO_RUN_MODE == "ingress"
121-
assert conf.base_path == custom_ingress, f"Expected conf.base_path={custom_ingress}, got '{conf.base_path}'"
119+
assert conf.ingress_path == custom_ingress, f"Expected conf.ingress_path={custom_ingress}, got '{conf.ingress_path}'"
122120

123121
client = TestClient(app)
124122

backend/app/config.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ class Config:
3030
HASSIO_RUN_MODE = os.environ.get('HASSIO_RUN_MODE', None)
3131
HASSIO_TOKEN = os.environ.get('HASSIO_TOKEN', None)
3232
SUPERVISOR_TOKEN = os.environ.get('SUPERVISOR_TOKEN', None)
33-
HOSTNAME = os.environ.get('HOSTNAME', None)
34-
base_path = ''
33+
ingress_path = ''
3534

3635
def __init__(self):
3736
# Get Home Assistant Supervisor Ingress URL
@@ -46,8 +45,8 @@ def __init__(self):
4645
ingress_url = info.get("data", {}).get("ingress_url")
4746
if ingress_url and ingress_url.endswith("/"):
4847
ingress_url = ingress_url[:-1]
49-
self.base_path = ingress_url
50-
print(f"🟢 Fetched HA ingress URL: {self.base_path}")
48+
self.ingress_path = ingress_url
49+
print(f"🟢 Fetched HA ingress URL: {self.ingress_path}")
5150
except Exception as e:
5251
print(f"🔴 Failed to get HA ingress URL: {e}")
5352

@@ -71,7 +70,7 @@ class ProductionConfig(Config):
7170
def __init__(self):
7271
super().__init__()
7372
if self.SECRET_KEY is None:
74-
if self.HASSIO_TOKEN is not None:
73+
if self.HASSIO_RUN_MODE is not None:
7574
self.SECRET_KEY = secrets.token_urlsafe(32)
7675
else:
7776
raise ValueError('SECRET_KEY must be set in production')

backend/app/fastapi.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ async def lifespan(app: FastAPI):
6464

6565
if config.HASSIO_RUN_MODE:
6666
frameos_app_config["HASSIO_RUN_MODE"] = config.HASSIO_RUN_MODE
67-
if config.base_path:
68-
frameos_app_config["base_path"] = config.base_path
67+
if config.ingress_path:
68+
frameos_app_config["ingress_path"] = config.ingress_path
6969

7070
index_html = index_html.replace('<head>', f'<head><script>window.FRAMEOS_APP_CONFIG={json.dumps(frameos_app_config)}</script>')
7171

frontend/src/main.tsx

Lines changed: 1 addition & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,9 @@ import { App } from './scenes/App'
33
import './index.css'
44
import { resetContext } from 'kea'
55
import { subscriptionsPlugin } from 'kea-subscriptions'
6-
import { routerPlugin } from 'kea-router'
7-
import { getBasePath } from './utils/getBasePath'
8-
9-
function addIngressPathIfMissing(path: string): string {
10-
const ingressPath = getBasePath()
11-
if (ingressPath && path.startsWith(ingressPath)) {
12-
return path
13-
}
14-
return `${ingressPath}${path}`
15-
}
16-
17-
function removeIngressPathIfPressent(path: string): string {
18-
const ingressPath = getBasePath()
19-
if (ingressPath && path.startsWith(ingressPath)) {
20-
return path.slice(ingressPath.length)
21-
}
22-
return path
23-
}
246

257
resetContext({
26-
plugins: [
27-
subscriptionsPlugin,
28-
routerPlugin({
29-
// pathFromRoutesToWindow: (path) => {
30-
// return addIngressPathIfMissing(path)
31-
// },
32-
// transformPathInActions: (path) => {
33-
// return addIngressPathIfMissing(path)
34-
// },
35-
// pathFromWindowToRoutes: (path) => {
36-
// return removeIngressPathIfPressent(path)
37-
// },
38-
}),
39-
],
8+
plugins: [subscriptionsPlugin],
409
})
4110

4211
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<App />)

frontend/src/utils/getBasePath.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
export function getBasePath(): string {
2-
const basePath = typeof window !== 'undefined' ? (window as any).FRAMEOS_APP_CONFIG?.base_path || '' : ''
2+
const basePath = typeof window !== 'undefined' ? (window as any).FRAMEOS_APP_CONFIG?.ingress_path || '' : ''
33
return basePath.endsWith('/') ? basePath.slice(0, -1) : basePath
44
}

frontend/utils.mjs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export function copyIndexHtml(
5353
const scriptCode = `
5454
window.ESBUILD_LOAD_SCRIPT = async function (file) {
5555
try {
56-
await import((window.FRAMEOS_APP_CONFIG?.base_path || '') + '/static/' + file)
56+
await import((window.FRAMEOS_APP_CONFIG?.ingress_path || '') + '/static/' + file)
5757
} catch (error) {
5858
console.error('Error loading chunk: "' + file + '"')
5959
console.error(error)
@@ -80,7 +80,7 @@ export function copyIndexHtml(
8080
const cssLoader = `
8181
const link = document.createElement("link");
8282
link.rel = "stylesheet";
83-
link.href = (window.FRAMEOS_APP_CONFIG?.base_path || '') + "/static/" + ${JSON.stringify(cssFile)};
83+
link.href = (window.FRAMEOS_APP_CONFIG?.ingress_path || '') + "/static/" + ${JSON.stringify(cssFile)};
8484
document.head.appendChild(link)
8585
`
8686

0 commit comments

Comments
 (0)