|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/gorilla/mux" |
| 6 | + "image/png" |
| 7 | + "net/http" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// Init the HTTP (or rest api) server |
| 13 | +func initHttp() { |
| 14 | + r := mux.NewRouter() |
| 15 | + r.HandleFunc("/{type}/{id}", handleAvatar).Methods("GET") |
| 16 | + |
| 17 | + http.ListenAndServe(":8080", r) |
| 18 | +} |
| 19 | + |
| 20 | +// Handle the incoming avatar request. |
| 21 | +func handleAvatar(w http.ResponseWriter, r *http.Request) { |
| 22 | + // Default values passed from URL |
| 23 | + vars := mux.Vars(r) |
| 24 | + identifier := vars["id"] |
| 25 | + mode := vars["type"] |
| 26 | + scaleStr := r.URL.Query().Get("scale") |
| 27 | + |
| 28 | + // Double check that the requested render is supported |
| 29 | + if mode != "isometric" && mode != "body" && mode != "avatar" { |
| 30 | + http.Error(w, "Unsupported render mode. Valid render modes are isometric, body & avatar", http.StatusBadRequest) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + // Initialize default scale |
| 35 | + scale := 512 |
| 36 | + |
| 37 | + // Parse scale from string to int, if possible |
| 38 | + if scaleStr != "" { |
| 39 | + if parsedScale, err := strconv.Atoi(scaleStr); err == nil { |
| 40 | + scale = parsedScale |
| 41 | + } else { |
| 42 | + fmt.Println("Invalid scale value, using default") |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + var uuid string |
| 47 | + var err error |
| 48 | + |
| 49 | + // Check if the supplied ID is a valid UUID |
| 50 | + if isValidUUID(identifier) { |
| 51 | + // We don't need the - in the UUID, so we remove it |
| 52 | + uuid = strings.ReplaceAll(identifier, "-", "") |
| 53 | + |
| 54 | + // Check if the supplied ID is a texture hash |
| 55 | + } else if isValidSHA256Hash(identifier) { |
| 56 | + uuid = identifier |
| 57 | + } else { |
| 58 | + |
| 59 | + // Supplied ID was likely a username. So we try to resolve it |
| 60 | + uuid, err = getUUID(identifier) |
| 61 | + if err != nil || uuid == "" { |
| 62 | + uuid = strings.ReplaceAll(generateOfflineUUID(identifier).String(), "-", "") |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + // Request the skin from the MOJANG servers |
| 67 | + skinPath, err := fetchSkin(uuid) |
| 68 | + if err != nil { |
| 69 | + skinPath = "fallback.png" |
| 70 | + } |
| 71 | + |
| 72 | + // Render the skin for the API |
| 73 | + img, err := renderSkin(skinPath, mode, scale, uuid, true) |
| 74 | + if err != nil { |
| 75 | + http.Error(w, "Failed to render skin", http.StatusInternalServerError) |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + // Encode the image ready for browser rendering |
| 80 | + w.Header().Set("Content-Type", "image/png") |
| 81 | + err = png.Encode(w, img) |
| 82 | + if err != nil { |
| 83 | + http.Error(w, "Failed to encode image", http.StatusInternalServerError) |
| 84 | + return |
| 85 | + } |
| 86 | +} |
0 commit comments