457 lines
13 KiB
Go
457 lines
13 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"zkillsusser/models"
|
|
|
|
logger "git.site.quack-lab.dev/dave/cylogger"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type APIStatisticsRequest struct {
|
|
Ship *int64 `json:"ship,omitempty"`
|
|
Systems []int64 `json:"systems,omitempty"`
|
|
Modules []int64 `json:"modules,omitempty"`
|
|
Groups []int64 `json:"groups,omitempty"`
|
|
}
|
|
|
|
type APIItemCount struct {
|
|
ItemId int64 `json:"itemId"`
|
|
Count int64 `json:"count"`
|
|
}
|
|
|
|
type APIFitStatistics struct {
|
|
TotalKillmails int64 `json:"totalKillmails"`
|
|
Ships []APIItemCount `json:"ships"`
|
|
SystemBreakdown []APIItemCount `json:"systemBreakdown"`
|
|
HighSlotModules []APIItemCount `json:"highSlotModules"`
|
|
MidSlotModules []APIItemCount `json:"midSlotModules"`
|
|
LowSlotModules []APIItemCount `json:"lowSlotModules"`
|
|
Rigs []APIItemCount `json:"rigs"`
|
|
Drones []APIItemCount `json:"drones"`
|
|
}
|
|
|
|
type APISearchResult struct {
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
}
|
|
|
|
type APIItemNames map[string]string
|
|
|
|
type APIGroupInfo struct {
|
|
GroupID int64 `json:"groupId"`
|
|
}
|
|
|
|
func convertFitStatistics(stats *FitStatistics) *APIFitStatistics {
|
|
api := &APIFitStatistics{
|
|
TotalKillmails: stats.TotalKillmails,
|
|
Ships: convertMapToItemCounts(stats.ShipBreakdown),
|
|
SystemBreakdown: convertMapToItemCounts(stats.SystemBreakdown),
|
|
HighSlotModules: convertModuleMapToItemCounts(stats.HighSlotModules),
|
|
MidSlotModules: convertModuleMapToItemCounts(stats.MidSlotModules),
|
|
LowSlotModules: convertModuleMapToItemCounts(stats.LowSlotModules),
|
|
Rigs: convertModuleMapToItemCounts(stats.Rigs),
|
|
Drones: convertModuleMapToItemCounts(stats.Drones),
|
|
}
|
|
return api
|
|
}
|
|
|
|
func convertMapToItemCounts(m map[int64]SystemStats) []APIItemCount {
|
|
result := make([]APIItemCount, 0, len(m))
|
|
for id, stats := range m {
|
|
result = append(result, APIItemCount{
|
|
ItemId: id,
|
|
Count: stats.Count,
|
|
})
|
|
}
|
|
return result
|
|
}
|
|
|
|
func convertModuleMapToItemCounts(m map[int32]ModuleStats) []APIItemCount {
|
|
result := make([]APIItemCount, 0, len(m))
|
|
for id, stats := range m {
|
|
result = append(result, APIItemCount{
|
|
ItemId: int64(id),
|
|
Count: stats.Count,
|
|
})
|
|
}
|
|
return result
|
|
}
|
|
|
|
func handleStatistics(w http.ResponseWriter, r *http.Request) {
|
|
flog := logger.Default.WithPrefix("handleStatistics")
|
|
flog.Trace("Request received: %s %s", r.Method, r.URL.Path)
|
|
|
|
if r.Method != http.MethodPost {
|
|
flog.Debug("Method not allowed: %s", r.Method)
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
flog.Debug("Decoding request body")
|
|
var req APIStatisticsRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
flog.Error("Failed to decode request body: %v", err)
|
|
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
flog.Dump("Request", req)
|
|
|
|
params := QueryParams{}
|
|
if req.Ship != nil {
|
|
params.Ship = *req.Ship
|
|
flog.Debug("Ship filter: %d", params.Ship)
|
|
}
|
|
params.Systems = req.Systems
|
|
if len(params.Systems) > 0 {
|
|
flog.Debug("Systems filter: %d systems", len(params.Systems))
|
|
}
|
|
params.Modules = req.Modules
|
|
if len(params.Modules) > 0 {
|
|
flog.Debug("Modules filter: %d modules", len(params.Modules))
|
|
}
|
|
params.Groups = req.Groups
|
|
if len(params.Groups) > 0 {
|
|
flog.Debug("Groups filter: %d groups", len(params.Groups))
|
|
}
|
|
|
|
flog.Info("Querying database")
|
|
db, err := GetDB()
|
|
if err != nil {
|
|
flog.Error("Failed to get database: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Trace("Database connection obtained")
|
|
|
|
flog.Debug("Executing QueryFits with params: %+v", params)
|
|
stats, err := db.QueryFits(params)
|
|
if err != nil {
|
|
flog.Error("Failed to query fits: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Info("Query completed: %d total killmails", stats.TotalKillmails)
|
|
flog.Dump("Statistics", stats)
|
|
|
|
flog.Debug("Converting statistics to API format")
|
|
apiStats := convertFitStatistics(stats)
|
|
flog.Dump("API Statistics", apiStats)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
flog.Trace("Encoding response")
|
|
if err := json.NewEncoder(w).Encode(apiStats); err != nil {
|
|
flog.Error("Failed to encode response: %v", err)
|
|
return
|
|
}
|
|
flog.Info("Response sent successfully")
|
|
}
|
|
|
|
func handleSearch(w http.ResponseWriter, r *http.Request) {
|
|
flog := logger.Default.WithPrefix("handleSearch")
|
|
flog.Trace("Request received: %s %s", r.Method, r.URL.Path)
|
|
|
|
if r.Method != http.MethodGet {
|
|
flog.Debug("Method not allowed: %s", r.Method)
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
query := r.URL.Query().Get("q")
|
|
flog.Debug("Search query: %q", query)
|
|
if query == "" {
|
|
flog.Info("Empty query, returning empty results")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode([]APISearchResult{})
|
|
return
|
|
}
|
|
|
|
db, err := GetDB()
|
|
if err != nil {
|
|
flog.Error("Failed to get database: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Trace("Database connection obtained")
|
|
|
|
results := []APISearchResult{}
|
|
|
|
searchPattern := "%" + strings.ToLower(query) + "%"
|
|
flog.Debug("Search pattern: %q", searchPattern)
|
|
|
|
flog.Debug("Searching ships")
|
|
var ships []models.InvType
|
|
db.DB().Table("invTypes").
|
|
Joins("INNER JOIN invGroups ON invTypes.groupID = invGroups.groupID").
|
|
Where("LOWER(invTypes.\"typeName\") LIKE ? AND invGroups.categoryID IN (6)", searchPattern).
|
|
Limit(10).
|
|
Find(&ships)
|
|
flog.Info("Found %d ships", len(ships))
|
|
flog.Trace("Ships: %+v", ships)
|
|
for _, ship := range ships {
|
|
results = append(results, APISearchResult{
|
|
ID: int64(ship.TypeID),
|
|
Name: ship.TypeName,
|
|
Type: "ship",
|
|
})
|
|
}
|
|
|
|
flog.Debug("Searching systems")
|
|
var systems []models.MapSolarSystem
|
|
db.DB().Table("mapSolarSystems").
|
|
Where("LOWER(\"solarSystemName\") LIKE ?", searchPattern).
|
|
Limit(10).
|
|
Find(&systems)
|
|
flog.Info("Found %d systems", len(systems))
|
|
flog.Trace("Systems: %+v", systems)
|
|
for _, system := range systems {
|
|
results = append(results, APISearchResult{
|
|
ID: int64(system.SolarSystemID),
|
|
Name: system.SolarSystemName,
|
|
Type: "system",
|
|
})
|
|
}
|
|
|
|
flog.Debug("Searching modules")
|
|
var modules []models.InvType
|
|
db.DB().Table("invTypes").
|
|
Joins("INNER JOIN invGroups ON invTypes.groupID = invGroups.groupID").
|
|
Where("LOWER(invTypes.\"typeName\") LIKE ? AND invGroups.categoryID IN (7, 66)", searchPattern).
|
|
Limit(10).
|
|
Find(&modules)
|
|
flog.Info("Found %d modules", len(modules))
|
|
flog.Trace("Modules: %+v", modules)
|
|
for _, module := range modules {
|
|
results = append(results, APISearchResult{
|
|
ID: int64(module.TypeID),
|
|
Name: module.TypeName,
|
|
Type: "module",
|
|
})
|
|
}
|
|
|
|
flog.Debug("Searching groups")
|
|
var groups []models.InvGroup
|
|
db.DB().Table("invGroups").
|
|
Where("LOWER(\"groupName\") LIKE ?", searchPattern).
|
|
Limit(10).
|
|
Find(&groups)
|
|
flog.Info("Found %d groups", len(groups))
|
|
flog.Trace("Groups: %+v", groups)
|
|
for _, group := range groups {
|
|
results = append(results, APISearchResult{
|
|
ID: int64(group.GroupID),
|
|
Name: group.GroupName,
|
|
Type: "group",
|
|
})
|
|
}
|
|
|
|
flog.Info("Total search results: %d", len(results))
|
|
flog.Dump("Results", results)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
flog.Trace("Encoding response")
|
|
if err := json.NewEncoder(w).Encode(results); err != nil {
|
|
flog.Error("Failed to encode response: %v", err)
|
|
return
|
|
}
|
|
flog.Info("Response sent successfully")
|
|
}
|
|
|
|
func handleItemNames(w http.ResponseWriter, r *http.Request) {
|
|
flog := logger.Default.WithPrefix("handleItemNames")
|
|
flog.Trace("Request received: %s %s", r.Method, r.URL.Path)
|
|
|
|
if r.Method != http.MethodGet {
|
|
flog.Debug("Method not allowed: %s", r.Method)
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
idsParam := r.URL.Query().Get("ids")
|
|
flog.Debug("IDs parameter: %q", idsParam)
|
|
if idsParam == "" {
|
|
flog.Info("Empty IDs parameter, returning empty map")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(APIItemNames{})
|
|
return
|
|
}
|
|
|
|
flog.Debug("Parsing IDs")
|
|
idStrs := strings.Split(idsParam, ",")
|
|
flog.Trace("ID strings: %v", idStrs)
|
|
ids := make([]int32, 0, len(idStrs))
|
|
for _, idStr := range idStrs {
|
|
id, err := strconv.ParseInt(idStr, 10, 32)
|
|
if err != nil {
|
|
flog.Debug("Failed to parse ID %q: %v", idStr, err)
|
|
continue
|
|
}
|
|
ids = append(ids, int32(id))
|
|
}
|
|
flog.Info("Parsed %d valid IDs from %d strings", len(ids), len(idStrs))
|
|
flog.Dump("IDs", ids)
|
|
|
|
if len(ids) == 0 {
|
|
flog.Info("No valid IDs, returning empty map")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(APIItemNames{})
|
|
return
|
|
}
|
|
|
|
db, err := GetDB()
|
|
if err != nil {
|
|
flog.Error("Failed to get database: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Trace("Database connection obtained")
|
|
|
|
flog.Debug("Querying invTypes for %d IDs", len(ids))
|
|
var items []models.InvType
|
|
db.DB().Table("invTypes").
|
|
Where("typeID IN ?", ids).
|
|
Find(&items)
|
|
flog.Info("Found %d items in invTypes", len(items))
|
|
flog.Trace("Items: %+v", items)
|
|
|
|
names := make(APIItemNames)
|
|
for _, item := range items {
|
|
names[strconv.FormatInt(int64(item.TypeID), 10)] = item.TypeName
|
|
}
|
|
flog.Debug("Added %d item names", len(names))
|
|
|
|
flog.Debug("Querying mapSolarSystems for %d IDs", len(ids))
|
|
systemIDs := ids
|
|
var systems []models.MapSolarSystem
|
|
db.DB().Table("mapSolarSystems").
|
|
Where("\"solarSystemID\" IN ?", systemIDs).
|
|
Find(&systems)
|
|
flog.Info("Found %d systems in mapSolarSystems", len(systems))
|
|
flog.Trace("Systems: %+v", systems)
|
|
for _, system := range systems {
|
|
names[strconv.FormatInt(int64(system.SolarSystemID), 10)] = system.SolarSystemName
|
|
}
|
|
flog.Info("Total names: %d", len(names))
|
|
flog.Dump("Names", names)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
flog.Trace("Encoding response")
|
|
if err := json.NewEncoder(w).Encode(names); err != nil {
|
|
flog.Error("Failed to encode response: %v", err)
|
|
return
|
|
}
|
|
flog.Info("Response sent successfully")
|
|
}
|
|
|
|
func handleItemGroup(w http.ResponseWriter, r *http.Request) {
|
|
flog := logger.Default.WithPrefix("handleItemGroup")
|
|
flog.Trace("Request received: %s %s", r.Method, r.URL.Path)
|
|
|
|
if r.Method != http.MethodGet {
|
|
flog.Debug("Method not allowed: %s", r.Method)
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
flog.Debug("Parsing item ID from path: %s", r.URL.Path)
|
|
path := strings.TrimPrefix(r.URL.Path, "/api/items/")
|
|
path = strings.TrimSuffix(path, "/group")
|
|
flog.Trace("Trimmed path: %q", path)
|
|
parts := strings.Split(path, "/")
|
|
flog.Trace("Path parts: %v", parts)
|
|
if len(parts) == 0 {
|
|
flog.Error("Invalid path: no parts after splitting")
|
|
http.Error(w, "Invalid item ID", http.StatusBadRequest)
|
|
return
|
|
}
|
|
itemID, err := strconv.ParseInt(parts[0], 10, 64)
|
|
if err != nil {
|
|
flog.Error("Failed to parse item ID %q: %v", parts[0], err)
|
|
http.Error(w, "Invalid item ID", http.StatusBadRequest)
|
|
return
|
|
}
|
|
flog.Info("Item ID: %d", itemID)
|
|
|
|
db, err := GetDB()
|
|
if err != nil {
|
|
flog.Error("Failed to get database: %v", err)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Trace("Database connection obtained")
|
|
|
|
flog.Debug("Querying invTypes for typeID: %d", itemID)
|
|
var item models.InvType
|
|
result := db.DB().Table("invTypes").
|
|
Where("typeID = ?", int32(itemID)).
|
|
First(&item)
|
|
if result.Error == gorm.ErrRecordNotFound {
|
|
flog.Info("Item not found: typeID %d", itemID)
|
|
http.Error(w, "Item not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if result.Error != nil {
|
|
flog.Error("Failed to query item: %v", result.Error)
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
flog.Info("Found item: typeID %d, groupID %d", item.TypeID, item.GroupID)
|
|
flog.Dump("Item", item)
|
|
|
|
groupInfo := APIGroupInfo{
|
|
GroupID: int64(item.GroupID),
|
|
}
|
|
flog.Dump("Group Info", groupInfo)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
flog.Trace("Encoding response")
|
|
if err := json.NewEncoder(w).Encode(groupInfo); err != nil {
|
|
flog.Error("Failed to encode response: %v", err)
|
|
return
|
|
}
|
|
flog.Info("Response sent successfully")
|
|
}
|
|
|
|
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func StartAPIServer(port string) {
|
|
flog := logger.Default.WithPrefix("StartAPIServer")
|
|
flog.Info("Initializing API server")
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/api/statistics", corsMiddleware(handleStatistics))
|
|
mux.HandleFunc("/api/search", corsMiddleware(handleSearch))
|
|
mux.HandleFunc("/api/items/names", corsMiddleware(handleItemNames))
|
|
mux.HandleFunc("/api/items/", corsMiddleware(handleItemGroup))
|
|
|
|
flog.Debug("Registered routes:")
|
|
flog.Debug(" POST /api/statistics")
|
|
flog.Debug(" GET /api/search")
|
|
flog.Debug(" GET /api/items/names")
|
|
flog.Debug(" GET /api/items/{id}/group")
|
|
|
|
flog.Info("Starting API server on port %s", port)
|
|
flog.Trace("Listening on :%s", port)
|
|
if err := http.ListenAndServe(":"+port, mux); err != nil {
|
|
flog.Error("Failed to start API server: %v", err)
|
|
}
|
|
}
|