forked from oplancelot/shelllab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
403 lines (353 loc) · 14.7 KB
/
Copy pathapp.go
File metadata and controls
403 lines (353 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
package main
import (
"context"
_ "embed" // Use blank import to ensure it sticks, though explicit usage should be enough
"fmt"
"os"
"path/filepath"
"sync"
"inklab/backend/database"
"inklab/backend/datatools"
"inklab/backend/services"
"github.com/joho/godotenv"
)
// App struct
type App struct {
ctx context.Context
db *database.SQLiteDB
DataDir string // Path to data directory
// Repositories
itemRepo *database.ItemRepository
creatureRepo *database.CreatureRepository
questRepo *database.QuestRepository
spellRepo *database.SpellRepository
lootRepo *database.LootRepository
factionRepo *database.FactionRepository
objectRepo *database.GameObjectRepository
zoneRepo *database.ZoneRepository
categoryRepo *database.CategoryRepository
atlasLootRepo *database.AtlasLootRepository
favoriteRepo *database.FavoriteRepository
raceRepo *database.RaceRepository
// Cache for category lookups
categoryCache map[int]*database.Category
rootCategoryByName map[string]int
// Services
npcService *services.NpcService
syncService *services.SyncService
scraper *services.ScraperService
mysqlDB *database.MySQLConnection
// Cached client MPQ source for on-demand model rendering. The mpq set is not
// concurrency-safe, so clientSrcMu guards both the (re)open and every use.
clientSrc datatools.ClientFiles
clientSrcDir string
clientSrcMu sync.Mutex
// Mode
isDevMode bool
}
// NewApp creates a new App application struct
func NewApp(dataDir string, isDevMode bool) *App {
return &App{
DataDir: dataDir,
isDevMode: isDevMode,
categoryCache: make(map[int]*database.Category),
rootCategoryByName: make(map[string]int),
}
}
// startup is called when the app starts
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Collect leftovers from a previous self-update (Windows can't delete the
// running binary during the swap, so it gets parked as .old).
cleanupOldUpdate()
fmt.Println("Initializing InkLab (SQLite Version)...")
// Load .env. godotenv.Load() only reads the current working directory, which
// is the project root under `wails dev` but is unpredictable for a packaged
// build — so also look next to the executable and in the data dir. Without
// this, MySQL-backed sync (e.g. creature spawns) silently does nothing in a
// release build even when MySQL is reachable.
envCandidates := []string{".env"}
if exe, err := os.Executable(); err == nil {
envCandidates = append(envCandidates, filepath.Join(filepath.Dir(exe), ".env"))
}
envCandidates = append(envCandidates, filepath.Join(a.DataDir, ".env"))
envLoaded := false
for _, p := range envCandidates {
if err := godotenv.Load(p); err == nil {
fmt.Printf("✓ Loaded environment from %s\n", p)
envLoaded = true
break
}
}
if !envLoaded {
fmt.Printf("Warning: no .env found (looked in %v), MySQL features disabled\n", envCandidates)
}
// Initialize SQLite database
dbPath := filepath.Join(a.DataDir, "inklab.db")
db, err := database.NewSQLiteDB(dbPath)
if err != nil {
fmt.Printf("ERROR: Failed to open database: %v\n", err)
return
}
// Ensure schema exists
if err := db.InitSchema(); err != nil {
fmt.Printf("ERROR: Failed to initialize schema: %v\n", err)
return
}
a.db = db
// Initialize all repositories
a.itemRepo = database.NewItemRepository(db)
a.creatureRepo = database.NewCreatureRepository(db)
a.questRepo = database.NewQuestRepository(db)
a.spellRepo = database.NewSpellRepository(db)
a.lootRepo = database.NewLootRepository(db)
a.factionRepo = database.NewFactionRepository(db)
a.objectRepo = database.NewGameObjectRepository(db)
a.zoneRepo = database.NewZoneRepository(db)
a.categoryRepo = database.NewCategoryRepository(db)
a.atlasLootRepo = database.NewAtlasLootRepository(db)
a.favoriteRepo = database.NewFavoriteRepository(db)
a.raceRepo = database.NewRaceRepository(db)
// Initialize favorites schema
if err := a.favoriteRepo.InitSchema(); err != nil {
fmt.Printf("ERROR: Failed to initialize favorites schema: %v\n", err)
}
// Initialize MySQL (Optional)
mysqlUser := os.Getenv("MYSQL_USER")
if mysqlUser != "" {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
os.Getenv("MYSQL_USER"),
os.Getenv("MYSQL_PASSWORD"),
os.Getenv("MYSQL_HOST"),
os.Getenv("MYSQL_PORT"),
os.Getenv("MYSQL_DATABASE"),
)
mysqlConn, err := database.NewMySQLConnection(dsn)
if err != nil {
fmt.Printf("MySQL Connection Failed: %v\n", err)
} else {
a.mysqlDB = mysqlConn
fmt.Println("✓ MySQL Connected")
// Inject into CreatureRepository
a.creatureRepo.SetMySQL(mysqlConn.DB())
}
}
// Print stats
itemCount, _ := a.itemRepo.GetItemCount()
catCount, _ := a.categoryRepo.GetCategoryCount()
fmt.Printf("✓ Database Connected: %s\n", dbPath)
fmt.Printf(" - Items: %d\n", itemCount)
fmt.Printf(" - Categories: %d\n", catCount)
// Build category cache
a.buildCategoryCache()
// Construct the services the frontend can call immediately (NPC/object/sync)
// BEFORE the possibly-slow data imports below. On a `wails dev` rebuild the
// app restarts while the frontend reconnects and may re-fire e.g.
// GetNpcDetails during startup — if these aren't set yet that call hits a nil
// service. Their deps (db, MySQL, repos) are all ready by here.
a.scraper = services.NewScraperService()
a.npcService = services.NewNpcService(a.db.DB(), a.mysqlDB, a.scraper, a.itemRepo, a.creatureRepo, a.DataDir)
a.syncService = services.NewSyncService(a.db.DB())
// Full syncs run a worker pool of octowow.st scrapes. Shipped clients keep the
// low default so they don't hammer the server; the dev build (running big
// backfills) gets a higher cap.
if a.isDevMode {
services.SetScrapeConcurrency(10)
}
// Data import using importers
// dataDir is already set in a.DataDir
// If database is already populated (itemCount > 0), skip costly imports
if itemCount > 0 {
fmt.Println("Database already populated. Skipping initialization imports.")
} else {
// Import Item Sets
fmt.Println("Checking item sets...")
itemSetImporter := database.NewItemSetImporter(db)
if err := itemSetImporter.CheckAndImport(a.DataDir); err != nil {
fmt.Printf("ERROR: Failed to import item sets: %v\n", err)
}
// Import Factions
fmt.Println("Checking faction data...")
factionImporter := database.NewFactionImporter(db)
factionImporter.CheckAndImport(a.DataDir)
}
// Import Metadata (Zones, Skills) - Always run this as it checks internally and initializes static data
fmt.Println("Checking metadata...")
metadataImporter := database.NewMetadataImporter(db)
metadataImporter.ImportAll(a.DataDir)
// Faction templates (NPC -> faction membership). Always check: the JSON is
// generated by the client DBC export, which may happen after first run.
database.NewFactionImporter(db).CheckAndImportTemplates(a.DataDir)
// MySQL is initialized once above from the MYSQL_* env vars (loaded from
// .env), in both dev and production. The previous dev-only block here passed
// the ".env" path itself as the DSN, which always failed with "invalid DSN:
// missing the slash separating the database name".
// 4. Import Data (Developer Mode Only - users use pre-built DB)
if a.isDevMode {
// Import AtlasLoot
fmt.Println("Checking AtlasLoot data...")
alImporter := database.NewAtlasLootImporter(a.db)
if err := alImporter.CheckAndImport(a.DataDir); err != nil {
fmt.Printf("ERROR: Failed to import AtlasLoot: %v\n", err)
}
// Import MySQL Tables
a.importFullTables(a.DataDir)
}
// Install client-localized item type/slot names as resolver overrides. Runs
// every startup (not just dev/import) so the shipped DB's localized tables
// take effect; a no-op falls back to built-in English when absent.
database.NewGeneratedImporter(a.db.DB()).LoadItemNameOverrides()
// Icon downloading is now on-demand via fix button
// No need to auto-download on startup
// (NPC/sync services are constructed earlier, before the data imports above.)
// Async sync creature spawns for dev convenience
if a.isDevMode && a.mysqlDB != nil {
var spawnCount int
a.db.DB().QueryRow("SELECT COUNT(*) FROM creature_spawn").Scan(&spawnCount)
if spawnCount == 0 {
fmt.Println("⚡ Starting async creature spawn sync (First Run)...")
go func() {
// No progress callback necessary for background startup task
err := a.npcService.SyncAllCreatureSpawns(nil)
if err != nil {
fmt.Printf("Startup spawn sync warning: %v\n", err)
} else {
fmt.Println("✓ Creature spawn sync complete")
}
}()
} else {
fmt.Printf("⏭️ creature_spawn already has %d rows, skipping startup sync\n", spawnCount)
}
// Same one-time sync for game-object spawns.
var goSpawnCount int
a.db.DB().QueryRow("SELECT COUNT(*) FROM gameobject_spawn").Scan(&goSpawnCount)
if goSpawnCount == 0 {
fmt.Println("⚡ Starting async gameobject spawn sync (First Run)...")
go func() {
if err := a.npcService.SyncAllGameObjectSpawns(nil); err != nil {
fmt.Printf("Startup gameobject spawn sync warning: %v\n", err)
} else {
fmt.Println("✓ GameObject spawn sync complete")
}
}()
} else {
fmt.Printf("⏭️ gameobject_spawn already has %d rows, skipping startup sync\n", goSpawnCount)
}
}
// Keep the npc_images render cache bounded (TTL sweep; renders re-create on view).
a.startNpcImageCleanup()
fmt.Println("✓ InkLab ready!")
}
// importFullTables imports data from MySQL if available
// The MySQL importer checks each table individually - only empty tables are imported
func (a *App) importFullTables(dataDir string) {
if a.mysqlDB == nil {
fmt.Println("⚠️ No MySQL connection available. Database import skipped.")
return
}
fmt.Println("⚡ Checking database tables and importing from MySQL if needed...")
importer := database.NewMySQLImporter(a.db.DB(), a.mysqlDB.DB())
if err := importer.ImportAllFromMySQL(); err != nil {
fmt.Printf("❌ MySQL Import Failed: %v\n", err)
} else {
fmt.Println("✓ MySQL Import Check Complete")
}
// Apply the DBC-derived icon mappings onto the freshly imported templates.
// These are generated by cmd/dbc2json (item_icons.json / spells_enhanced.json).
gen := database.NewGeneratedImporter(a.db.DB())
if err := gen.ImportSpellsFromDBC(filepath.Join(dataDir, "spells_enhanced.json")); err != nil {
fmt.Printf("⚠️ Spell DBC import failed: %v\n", err)
}
if err := gen.ImportItemIcons(filepath.Join(dataDir, "item_icons.json")); err != nil {
fmt.Printf("⚠️ Item icon import failed: %v\n", err)
}
if err := gen.ImportSpellIcons(filepath.Join(dataDir, "spells_enhanced.json")); err != nil {
fmt.Printf("⚠️ Spell icon import failed: %v\n", err)
}
if err := gen.ImportTalents(filepath.Join(dataDir, "talents.json")); err != nil {
fmt.Printf("⚠️ Talent import failed: %v\n", err)
}
if err := gen.ImportTaxi(filepath.Join(dataDir, "taxi.json")); err != nil {
fmt.Printf("⚠️ Taxi import failed: %v\n", err)
}
// Link flight nodes to their flightmaster NPCs (needs the just-imported taxi
// node world coords + MySQL spawn coords). Octo-free.
a.MatchFlightmasters()
if err := gen.ImportCreatureFamilies(filepath.Join(dataDir, "creature_families.json")); err != nil {
fmt.Printf("⚠️ Creature family import failed: %v\n", err)
}
if err := gen.ImportLocks(filepath.Join(dataDir, "locks.json")); err != nil {
fmt.Printf("⚠️ Lock import failed: %v\n", err)
}
if err := gen.ImportRandomSuffixes(filepath.Join(dataDir, "random_suffixes.json")); err != nil {
fmt.Printf("⚠️ Random suffix import failed: %v\n", err)
}
if err := gen.ImportClasses(filepath.Join(dataDir, "classes.json")); err != nil {
fmt.Printf("⚠️ Class import failed: %v\n", err)
}
if err := gen.ImportSpellSchools(filepath.Join(dataDir, "spell_schools.json")); err != nil {
fmt.Printf("⚠️ Spell school import failed: %v\n", err)
}
if err := gen.ImportStatNames(filepath.Join(dataDir, "stat_names.json")); err != nil {
fmt.Printf("⚠️ Stat name import failed: %v\n", err)
}
if err := gen.ImportRaces(filepath.Join(dataDir, "races.json")); err != nil {
fmt.Printf("⚠️ Race import failed: %v\n", err)
}
if err := gen.ImportSpellMechanics(filepath.Join(dataDir, "spell_mechanics.json")); err != nil {
fmt.Printf("⚠️ Spell mechanic import failed: %v\n", err)
}
if err := gen.ImportDispelTypes(filepath.Join(dataDir, "spell_dispel_types.json")); err != nil {
fmt.Printf("⚠️ Dispel type import failed: %v\n", err)
}
if err := gen.ImportEnchantProcSpells(filepath.Join(dataDir, "enchant_proc_spells.json")); err != nil {
fmt.Printf("⚠️ Enchant proc import failed: %v\n", err)
}
if err := gen.ImportLockTypes(filepath.Join(dataDir, "lock_types.json")); err != nil {
fmt.Printf("⚠️ Lock type import failed: %v\n", err)
}
if err := gen.ImportItemClassNames(filepath.Join(dataDir, "item_class_names.json")); err != nil {
fmt.Printf("⚠️ Item class name import failed: %v\n", err)
}
if err := gen.ImportItemSubclassNames(filepath.Join(dataDir, "item_subclass_names.json")); err != nil {
fmt.Printf("⚠️ Item subclass name import failed: %v\n", err)
}
if err := gen.ImportInventoryTypes(filepath.Join(dataDir, "inventory_types.json")); err != nil {
fmt.Printf("⚠️ Inventory type import failed: %v\n", err)
}
if err := gen.ImportCreatureTypeNames(filepath.Join(dataDir, "creature_types.json")); err != nil {
fmt.Printf("⚠️ Creature type name import failed: %v\n", err)
}
if err := gen.ImportClientStrings(filepath.Join(dataDir, "client_strings.json")); err != nil {
fmt.Printf("⚠️ Client string import failed: %v\n", err)
}
// Resolve $-placeholders against the just-imported (DBC-authoritative) values.
services.NewSyncService(a.db.DB()).FullSyncSpells(0, false, "", 0, nil)
}
// buildCategoryCache builds a cache of categories for faster lookups
func (a *App) buildCategoryCache() {
roots, err := a.categoryRepo.GetRootCategories()
if err != nil {
return
}
for _, cat := range roots {
a.categoryCache[cat.ID] = cat
a.rootCategoryByName[cat.Name] = cat.ID
}
}
// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) {
a.clientSrcMu.Lock()
if a.clientSrc != nil {
a.clientSrc.Close()
a.clientSrc = nil
}
a.clientSrcMu.Unlock()
if a.db != nil {
a.db.Close()
}
}
// WaitForReady waits for the app to be ready (max 5 seconds)
func (a *App) WaitForReady() bool {
return a.db != nil
}