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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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import os
import base64
import math
import random
import re
import json
import yaml
import uvicorn
import httpx
import secrets
from fastapi import FastAPI, Request, Response, HTTPException, Security, Depends, Path, Query, status
from fastapi.security.api_key import APIKeyHeader
from fastapi.openapi.utils import get_openapi
from fastapi.encoders import jsonable_encoder
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import HTMLResponse, JSONResponse, RedirectResponse
from typing import Annotated
from cachetools import TTLCache


# ---------- Start Cache ---------- #
cache = TTLCache(maxsize=1000, ttl=21600)
# ---------- End Cache ---------- #


# ---------- Start App ---------- #
app = FastAPI(
    debug = True,
    title = "🗺️ Map Tiles Proxy Service",
    # summary = "Proxy for Map Tiles Service | Control Your Little Globe 🌍",
    description = (
        "<br><hr><br>"
        "<blockquote>🗺️ **Map Tiles Proxy Service** is an app that acts as a proxy for tile maps from multiple sources, allowing you to easily aggregate map services from various providers in one place ✨</blockquote>"
        "<br><hr><br>"
    ),
    version = "template",
    license_info = {
        "name": "Web Sparkle © 2025 by MeowSkyKung is licensed under CC BY-SA 4.0",
        "url": "https://creativecommons.org/licenses/by-sa/4.0/",
    },
    # contact = {
    #     "name": "MeowIsWorking",
    #     "url": "https://meowverse.azurewebsites.net",
    #     "email": "[email protected]"
    # },
    openapi_tags = [
        {
            "name": "🎉 Features 🎉",
            "description": (
                "* 🔐 Basic Authentication to prevent unauthorized access\n"
                "* 🧭 Restricts geographic bounds and zoom levels to control map access precisely\n"
                "* 🚀 Caching system to improve performance and reduce redundant requests\n"
                "* 🔄 Supports subdomain switching for load balancing\n"
            )
        },
        {
            "name": "📥 Installation 📥",
            "description": (
                "1. Clone this repository\n"
                "2. Configure the `config.yaml` file as shown in the repo\n"
                "3. Set the Environment Secret `PASSWORD` for Basic Auth\n"
            )
        },
        {
            "name": "🚀 Usage 🚀",
            "description": (
                "* Use the API via the endpoint `/serviceId/{z}/{x}/{y}` with Basic Auth\n"
                "* View each service’s details via the root endpoint `/`\n"
            )
        },
        {
            "name": "💖 Supporting by 💖",
            "description": (
                "* Like Me on Hugging Face 🌟\n"
                "* Donate on Ko-Fi ☕\n"
            )
        }
    ],
    openapi_url = None,
    docs_url = None,
    redoc_url = None
)
# ---------- End App ---------- #


# ---------- Start Config ---------- #
CONFIG_FILE = "config.yaml"
configs = {}

def load():
    global configs
    with open(CONFIG_FILE, "r") as f:
        data = yaml.safe_load(f)
        configs.update({
            service["serviceId"]: service for service in data.get("tileServices", [])
        })
        app.state.urls = list(configs.keys())

load()
# ---------- End Config ---------- #


# ---------- Start Limit ---------- #
def xyz_to_bbox(z, x, y):
    """Returns (minLat, minLon, maxLat, maxLon) for a given tile."""
    n = 2.0 ** z
    lonDegMin = x / n * 360.0 - 180.0
    lonDegMax = (x + 1) / n * 360.0 - 180.0

    latRadMin = math.atan(math.sinh(math.pi * (1 - 2 * y / n)))
    latRadMax = math.atan(math.sinh(math.pi * (1 - 2 * (y + 1) / n)))
    latDegMin = math.degrees(latRadMax)
    latDegMax = math.degrees(latRadMin)

    return lonDegMin, latDegMin, lonDegMax, latDegMax  # west, north, east, south
# ---------- End Limit ---------- #


# ---------- Start Switch ---------- #
def switch(template: str) -> str:
    """Replace {switch:a,b,c,d} with a random subdomain."""
    match = re.search(r"{switch:([^}]+)}", template)
    if match:
        options = match.group(1).split(",")
        chosen = random.choice(options)
        return template.replace(match.group(0), chosen)
    return template
# ---------- End Switch ---------- #


# ---------- Start Auth ---------- #
PASSWORD = os.getenv("PASSWORD")
if not PASSWORD:
    raise RuntimeError("Missing PASSWORD environment secret")
    
stats = {}

header = APIKeyHeader(name="X-Authorization", scheme_name="X-Authorization", description="base64 encoded username:password", auto_error=False)
 
def authenticate(credentials: Annotated[str, Security(header)]):
    try:
        decoded = base64.b64decode(credentials).decode("utf-8")
        username, password = decoded.split(":", 1)
    except Exception:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid auth header")
    
    if not secrets.compare_digest(password.encode("utf-8"), PASSWORD.encode("utf-8")):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect password")

    stats[username] = stats.get(username, 0) + 1
    print(f"User '{username}' used the service {stats[username]} times.")

    return username
# ---------- End Auth ---------- #


# ---------- Start Middleware ---------- #
class DebugHeadersMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, next):
        print("Request headers:", request.headers)
        response = await next(request)
        return response

class TileValidationMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, next):
        parts = request.url.path.strip("/").split("/")
        if len(parts) >= 4:
            id = parts[0]
            config = configs.get(id)
            if not config:
                return JSONResponse(content={"detail": f"Service '{id}' not found"}, status_code=status.HTTP_404_NOT_FOUND)

            minZoom = config.get("minZoom", 0)
            maxZoom = config.get("maxZoom", 20)
            minLat = config.get("minLat", -90.0)
            maxLat = config.get("maxLat", 90.0)
            minLon = config.get("minLon", -180.0)
            maxLon = config.get("maxLon", 180.0)

            if config:
                try:
                    z = int(parts[1])
                    x = int(parts[2])
                    y = int(parts[3])

                    if not (minZoom <= z <= maxZoom):
                        return JSONResponse(content={"detail": "Zoom level out of bounds"}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)

                    west, north, east, south = xyz_to_bbox(z, x, y)

                    if (
                        south < minLat or north > maxLat or
                        west < minLon or east > maxLon
                    ):
                        return JSONResponse(content={"detail": "Tile out of bounding box"}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)

                except Exception as e:
                    return JSONResponse(content={"detail": f"Invalid tile parameters: {str(e)}"}, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY)

        return await next(request)

app.add_middleware(DebugHeadersMiddleware)
app.add_middleware(TileValidationMiddleware)
# ---------- End Middleware ---------- #


# ---------- Start Proxy ---------- #
@app.get("/{id}/{z}/{x}/{y}", 
    responses={
        status.HTTP_200_OK: {
            "description": "Tile Data",
            "content": {"application/octet-stream": {}}
        },
        status.HTTP_400_BAD_REQUEST: {
            "description": "Bad Request"
        },
        status.HTTP_401_UNAUTHORIZED: {
            "description": "Authentication Required"
        },
        status.HTTP_404_NOT_FOUND: {
            "description": "Service Not Found"
        },
        status.HTTP_422_UNPROCESSABLE_ENTITY: {
            "description": "Unprocessable Entity"
        },
    },
    response_class=Response,
    summary="Fetch tile from service endpoint",
    description=(
        "Retrieve a map tile using the given service name, zoom level (`z`), and tile coordinates (`x`, `y`).\n\n"
        "- If the service URL contains `{key}`, the `key` query parameter must be included.\n"
        "- Returns a binary tile image (`application/octet-stream`).\n"
        "- Caches responses for performance.\n\n"
        "**Authentication**:\n"
        "- X-Password Header required\n"
        "- Username for statistics collection\n"
        "- Password matched with environment secret"
    ),
    response_description="Binary tile data"
)
async def proxy(
    request: Request,
    username: Annotated[str, Security(authenticate)],
    id: str = Path(..., description="Service name"),
    z: int = Path(..., description="Zoom level"),
    x: int = Path(..., description="Tile X coordinate"),
    y: int = Path(..., description="Tile Y coordinate"),
    key: str = Query(None, description="API key (required if serviceURL contains {key})")
):
    config = configs.get(id)
    if not config:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND , detail=f"Service '{id}' not found")

    try:
        queries = dict(request.query_params)
        key = queries.get("key", None)

        format = {"z": z, "x": x, "y": y}
        if "{key}" in config["serviceURL"]:
            if not key:
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing required 'key' parameter")
            format["key"] = key

        template = switch(config["serviceURL"])
        url = template.format(**format)

        find = f"{id}/{z}/{x}/{y}"
        if find in cache:
            content, type = cache[find]
        else:
            async with httpx.AsyncClient(http2=True) as client:
                resp = await client.get(url)
                if resp.status_code != 200:
                    raise HTTPException(resp.status_code, detail="Upstream service error")
                content = resp.content
                type = resp.headers.get("content-type", "application/octet-stream")
                cache[find] = (content, type)

        return Response(content=content, media_type=type, headers={
            "Cache-Control": "public, max-age=21600, immutable"
        })
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Error formatting tile URL: {str(e)}")
# ---------- End Proxy ---------- #


# ---------- Start Root ---------- #
@app.get("/", 
    responses={
        status.HTTP_200_OK: {
            "description": "Service Meta",
            "content": {"application/json": {}},
        }
    },
    response_class=Response,
    summary="List all available tile services",
    description=(
        "Returns a dictionary of available tile services loaded from the `config.yaml`.\n"
        "Each entry describes the service's URL pattern, zoom level limits, bounding box, and whether an API key is required."
    ),
    response_description="A dictionary of available services with metadata"
)
async def root(request: Request):
    base = str(request.base_url).rstrip("/")
    available = {}
    for name in app.state.urls:
        conf = configs[name]
        available[name] = {
            "url": f"{base}/{name}/{{z}}/{{x}}/{{y}}?key=",
            "minZoom": conf.get("minZoom"),
            "maxZoom": conf.get("maxZoom"),
            "minLat": conf.get("minLat"),
            "maxLat": conf.get("maxLat"),
            "minLon": conf.get("minLon"),
            "maxLon": conf.get("maxLon"),
            "keyRequired": "{key}" in conf.get("serviceURL", ""),
        }
    return JSONResponse(content={"available": available}, status_code=status.HTTP_200_OK)
# ---------- End Root ---------- #


@app.get("/play", include_in_schema=False)
async def play():
    # ดึง schema ต้นฉบับ
    display = get_openapi(
        title=app.title,
        version=app.version,
        openapi_version=app.openapi_version,
        summary="",
        description="",
        terms_of_service="",
        contact="",
        license_info="",
        tags="",
        routes=app.routes,
        webhooks=app.webhooks.routes,
        servers=app.servers,
        separate_input_output_schemas=app.separate_input_output_schemas,
    )

    # แก้ security ของแต่ละ path + method
    for path, methods in display.get("paths", {}).items():
        for method, details in methods.items():
            if "security" in details:
                # แปลงจาก [{"Authorization": []}] เป็น [{"HTTPBasic": []}]
                details["security"] = [{"HTTPBasic": []}]

    # แก้ components.securitySchemes
    display["components"]["securitySchemes"] = {
        "HTTPBasic": {
            "type": "http",
            "scheme": "basic"
        }
    }
    
    html = f"""    
        <!DOCTYPE html>
        <html>
            <head>
                <link type="text/css" rel="stylesheet" href="{get_swagger_ui_html.__kwdefaults__["swagger_css_url"]}">
                <link rel="shortcut icon" href="{get_swagger_ui_html.__kwdefaults__["swagger_favicon_url"]}">
                <title>{app.title} - Swagger UI</title>
            </head>
            <body>
                <div id="swagger-ui"></div>
                <script src="{get_swagger_ui_html.__kwdefaults__["swagger_js_url"]}"></script>
                <script>
                    const spec = {json.dumps(display, ensure_ascii=False).replace("</", "<\\/")}
                    const ui = SwaggerUIBundle({{
                        dom_id: '#swagger-ui',
                        spec: {json.dumps(display)},
                        layout: 'BaseLayout',
                        presets: [
                            SwaggerUIBundle.presets.apis,
                            SwaggerUIBundle.SwaggerUIStandalonePreset
                        ]
                    }})
                </script>
                <script>
                    (function() {{
                        const originalFetch = window.fetch;
                        window.fetch = function(input, init = {{}}) {{
                            if(init.headers) {{
                                if(init.headers instanceof Headers) {{
                                    if(init.headers.has('Authorization')) {{
                                        let authValue = init.headers.get('Authorization');
                                        if (typeof authValue === 'string' && authValue.startsWith('Basic ')) {{
                                            authValue = authValue.slice(6);
                                        }}
                                        init.headers.delete('Authorization');
                                        init.headers.set('X-Authorization', authValue);
                                    }}
                                }} else if (typeof init.headers === 'object') {{
                                    if('Authorization' in init.headers) {{
                                        let authValue = init.headers['Authorization'];
                                        if (typeof authValue === 'string' && authValue.startsWith('Basic ')) {{
                                            authValue = authValue.slice(6);
                                        }}
                                        init.headers['X-Authorization'] = authValue;
                                        delete init.headers['Authorization'];
                                    }}
                                }}
                            }}
                            return originalFetch(input, init);
                        }};
                    }})();
                </script>
            </body>
        </html>
    """
    
    return HTMLResponse(html)


if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False, log_level="debug")