database.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  2. from sqlalchemy.orm import DeclarativeBase
  3. from backend.app.core.config import settings
  4. engine = create_async_engine(
  5. settings.database_url,
  6. echo=settings.debug,
  7. )
  8. async_session = async_sessionmaker(
  9. engine,
  10. class_=AsyncSession,
  11. expire_on_commit=False,
  12. )
  13. async def close_all_connections():
  14. """Close all database connections for backup/restore operations."""
  15. global engine
  16. await engine.dispose()
  17. async def reinitialize_database():
  18. """Reinitialize database connection after restore."""
  19. global engine, async_session
  20. engine = create_async_engine(
  21. settings.database_url,
  22. echo=settings.debug,
  23. )
  24. async_session = async_sessionmaker(
  25. engine,
  26. class_=AsyncSession,
  27. expire_on_commit=False,
  28. )
  29. class Base(DeclarativeBase):
  30. pass
  31. async def get_db() -> AsyncSession:
  32. async with async_session() as session:
  33. try:
  34. yield session
  35. await session.commit()
  36. except Exception:
  37. await session.rollback()
  38. raise
  39. finally:
  40. await session.close()
  41. async def init_db():
  42. # Import models to register them with SQLAlchemy
  43. from backend.app.models import ( # noqa: F401
  44. ams_history,
  45. api_key,
  46. archive,
  47. external_link,
  48. filament,
  49. github_backup,
  50. group,
  51. kprofile_note,
  52. library,
  53. maintenance,
  54. notification,
  55. notification_template,
  56. pending_upload,
  57. print_queue,
  58. printer,
  59. project,
  60. project_bom,
  61. settings,
  62. slot_preset,
  63. smart_plug,
  64. user,
  65. )
  66. async with engine.begin() as conn:
  67. await conn.run_sync(Base.metadata.create_all)
  68. # Run migrations for new columns (SQLite doesn't auto-add columns)
  69. await run_migrations(conn)
  70. # Seed default notification templates
  71. await seed_notification_templates()
  72. # Seed default groups and migrate existing users
  73. await seed_default_groups()
  74. async def run_migrations(conn):
  75. """Add new columns to existing tables if they don't exist."""
  76. from sqlalchemy import text
  77. # Migration: Add is_favorite column to print_archives
  78. try:
  79. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  80. except Exception:
  81. # Column already exists
  82. pass
  83. # Migration: Add content_hash column to print_archives for duplicate detection
  84. try:
  85. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  86. except Exception:
  87. # Column already exists
  88. pass
  89. # Migration: Add auto_off_executed column to smart_plugs
  90. try:
  91. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  92. except Exception:
  93. # Column already exists
  94. pass
  95. # Migration: Add on_print_stopped column to notification_providers
  96. try:
  97. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  98. except Exception:
  99. # Column already exists
  100. pass
  101. # Migration: Add source_3mf_path column to print_archives
  102. try:
  103. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  104. except Exception:
  105. # Column already exists
  106. pass
  107. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  108. try:
  109. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  110. except Exception:
  111. # Column already exists
  112. pass
  113. # Migration: Add on_maintenance_due column to notification_providers
  114. try:
  115. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  116. except Exception:
  117. # Column already exists
  118. pass
  119. # Migration: Add location column to printers for grouping
  120. try:
  121. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  122. except Exception:
  123. # Column already exists
  124. pass
  125. # Migration: Add interval_type column to maintenance_types
  126. try:
  127. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  128. except Exception:
  129. # Column already exists
  130. pass
  131. # Migration: Add custom_interval_type column to printer_maintenance
  132. try:
  133. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  134. except Exception:
  135. # Column already exists
  136. pass
  137. # Migration: Add power alert columns to smart_plugs
  138. try:
  139. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  140. except Exception:
  141. pass
  142. try:
  143. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  144. except Exception:
  145. pass
  146. try:
  147. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  148. except Exception:
  149. pass
  150. try:
  151. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  152. except Exception:
  153. pass
  154. # Migration: Add schedule columns to smart_plugs
  155. try:
  156. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  157. except Exception:
  158. pass
  159. try:
  160. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  161. except Exception:
  162. pass
  163. try:
  164. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  165. except Exception:
  166. pass
  167. # Migration: Add daily digest columns to notification_providers
  168. try:
  169. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  170. except Exception:
  171. pass
  172. try:
  173. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  174. except Exception:
  175. pass
  176. # Migration: Add project_id column to print_archives
  177. try:
  178. await conn.execute(
  179. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  180. )
  181. except Exception:
  182. pass
  183. # Migration: Add project_id column to print_queue
  184. try:
  185. await conn.execute(
  186. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  187. )
  188. except Exception:
  189. pass
  190. # Migration: Create FTS5 virtual table for archive full-text search
  191. try:
  192. await conn.execute(
  193. text("""
  194. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  195. print_name,
  196. filename,
  197. tags,
  198. notes,
  199. designer,
  200. filament_type,
  201. content='print_archives',
  202. content_rowid='id'
  203. )
  204. """)
  205. )
  206. except Exception:
  207. pass
  208. # Migration: Create triggers to keep FTS index in sync
  209. try:
  210. await conn.execute(
  211. text("""
  212. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  213. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  214. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  215. END
  216. """)
  217. )
  218. except Exception:
  219. pass
  220. try:
  221. await conn.execute(
  222. text("""
  223. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  224. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  225. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  226. END
  227. """)
  228. )
  229. except Exception:
  230. pass
  231. try:
  232. await conn.execute(
  233. text("""
  234. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  235. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  236. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  237. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  238. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  239. END
  240. """)
  241. )
  242. except Exception:
  243. pass
  244. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  245. try:
  246. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  247. except Exception:
  248. pass
  249. try:
  250. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  251. except Exception:
  252. pass
  253. # Migration: Add AMS alarm notification columns to notification_providers
  254. try:
  255. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  256. except Exception:
  257. pass
  258. try:
  259. await conn.execute(
  260. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  261. )
  262. except Exception:
  263. pass
  264. # Migration: Add AMS-HT alarm notification columns to notification_providers
  265. try:
  266. await conn.execute(
  267. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  268. )
  269. except Exception:
  270. pass
  271. try:
  272. await conn.execute(
  273. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  274. )
  275. except Exception:
  276. pass
  277. # Migration: Add plate not empty notification column to notification_providers
  278. try:
  279. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  280. except Exception:
  281. pass
  282. # Migration: Add notes column to projects (Phase 2)
  283. try:
  284. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  285. except Exception:
  286. pass
  287. # Migration: Add attachments column to projects (Phase 3)
  288. try:
  289. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  290. except Exception:
  291. pass
  292. # Migration: Add tags column to projects (Phase 4)
  293. try:
  294. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  295. except Exception:
  296. pass
  297. # Migration: Add due_date column to projects (Phase 5)
  298. try:
  299. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  300. except Exception:
  301. pass
  302. # Migration: Add priority column to projects (Phase 5)
  303. try:
  304. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  305. except Exception:
  306. pass
  307. # Migration: Add budget column to projects (Phase 6)
  308. try:
  309. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  310. except Exception:
  311. pass
  312. # Migration: Add is_template column to projects (Phase 8)
  313. try:
  314. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  315. except Exception:
  316. pass
  317. # Migration: Add template_source_id column to projects (Phase 8)
  318. try:
  319. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  320. except Exception:
  321. pass
  322. # Migration: Add parent_id column to projects (Phase 10)
  323. try:
  324. await conn.execute(
  325. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  326. )
  327. except Exception:
  328. pass
  329. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  330. try:
  331. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  332. except Exception:
  333. pass
  334. # Migration: Add unit_price column to project_bom_items
  335. try:
  336. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  337. except Exception:
  338. pass
  339. # Migration: Add sourcing_url column to project_bom_items
  340. try:
  341. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  342. except Exception:
  343. pass
  344. # Migration: Rename notes to remarks in project_bom_items
  345. try:
  346. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  347. except Exception:
  348. pass
  349. # Migration: Add show_in_switchbar column to smart_plugs
  350. try:
  351. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  352. except Exception:
  353. pass
  354. # Migration: Add runtime tracking columns to printers
  355. try:
  356. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  357. except Exception:
  358. pass
  359. try:
  360. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  361. except Exception:
  362. pass
  363. # Migration: Add quantity column to print_archives for tracking item count
  364. try:
  365. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  366. except Exception:
  367. pass
  368. # Migration: Add manual_start column to print_queue for staged prints
  369. try:
  370. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  371. except Exception:
  372. pass
  373. # Migration: Add wiki_url column to maintenance_types for documentation links
  374. try:
  375. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  376. except Exception:
  377. pass
  378. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  379. try:
  380. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  381. except Exception:
  382. pass
  383. # Migration: Add target_parts_count column to projects for tracking total parts needed
  384. try:
  385. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  386. except Exception:
  387. pass
  388. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  389. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  390. try:
  391. # Check if printer_id is already nullable by trying to insert NULL
  392. # This is a safe check that won't affect existing data
  393. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  394. row = result.fetchone()
  395. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  396. # Need to migrate - printer_id is currently NOT NULL
  397. await conn.execute(
  398. text("""
  399. CREATE TABLE print_queue_new (
  400. id INTEGER PRIMARY KEY,
  401. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  402. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  403. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  404. position INTEGER DEFAULT 0,
  405. scheduled_time DATETIME,
  406. manual_start BOOLEAN DEFAULT 0,
  407. require_previous_success BOOLEAN DEFAULT 0,
  408. auto_off_after BOOLEAN DEFAULT 0,
  409. ams_mapping TEXT,
  410. status VARCHAR(20) DEFAULT 'pending',
  411. started_at DATETIME,
  412. completed_at DATETIME,
  413. error_message TEXT,
  414. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  415. )
  416. """)
  417. )
  418. await conn.execute(
  419. text("""
  420. INSERT INTO print_queue_new
  421. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  422. manual_start, require_previous_success, auto_off_after, ams_mapping,
  423. status, started_at, completed_at, error_message, created_at
  424. FROM print_queue
  425. """)
  426. )
  427. await conn.execute(text("DROP TABLE print_queue"))
  428. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  429. except Exception:
  430. pass
  431. # Migration: Add plug_type column to smart_plugs for HA integration
  432. try:
  433. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  434. except Exception:
  435. pass
  436. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  437. try:
  438. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  439. except Exception:
  440. pass
  441. # Migration: Add project_id column to library_folders for linking folders to projects
  442. try:
  443. await conn.execute(
  444. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  445. )
  446. except Exception:
  447. pass
  448. # Migration: Add archive_id column to library_folders for linking folders to archives
  449. try:
  450. await conn.execute(
  451. text(
  452. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  453. )
  454. )
  455. except Exception:
  456. pass
  457. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  458. try:
  459. # Check if ip_address is currently NOT NULL
  460. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  461. row = result.fetchone()
  462. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  463. # Need to migrate - ip_address is currently NOT NULL
  464. await conn.execute(
  465. text("""
  466. CREATE TABLE smart_plugs_new (
  467. id INTEGER PRIMARY KEY,
  468. name VARCHAR(100) NOT NULL,
  469. ip_address VARCHAR(45),
  470. plug_type VARCHAR(20) DEFAULT 'tasmota',
  471. ha_entity_id VARCHAR(100),
  472. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  473. enabled BOOLEAN NOT NULL DEFAULT 1,
  474. auto_on BOOLEAN NOT NULL DEFAULT 1,
  475. auto_off BOOLEAN NOT NULL DEFAULT 1,
  476. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  477. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  478. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  479. username VARCHAR(50),
  480. password VARCHAR(100),
  481. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  482. power_alert_high FLOAT,
  483. power_alert_low FLOAT,
  484. power_alert_last_triggered DATETIME,
  485. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  486. schedule_on_time VARCHAR(5),
  487. schedule_off_time VARCHAR(5),
  488. show_in_switchbar BOOLEAN DEFAULT 0,
  489. last_state VARCHAR(10),
  490. last_checked DATETIME,
  491. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  492. auto_off_pending BOOLEAN DEFAULT 0,
  493. auto_off_pending_since DATETIME,
  494. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  495. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  496. )
  497. """)
  498. )
  499. await conn.execute(
  500. text("""
  501. INSERT INTO smart_plugs_new
  502. SELECT id, name, ip_address,
  503. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  504. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  505. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  506. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  507. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  508. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  509. FROM smart_plugs
  510. """)
  511. )
  512. await conn.execute(text("DROP TABLE smart_plugs"))
  513. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  514. except Exception:
  515. pass
  516. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  517. try:
  518. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  519. except Exception:
  520. pass
  521. # Migration: Add print options columns to print_queue
  522. try:
  523. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  524. except Exception:
  525. pass
  526. try:
  527. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  528. except Exception:
  529. pass
  530. try:
  531. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  532. except Exception:
  533. pass
  534. try:
  535. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  536. except Exception:
  537. pass
  538. try:
  539. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  540. except Exception:
  541. pass
  542. try:
  543. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  544. except Exception:
  545. pass
  546. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  547. # This allows queue items to reference library files directly (archive created at print start)
  548. try:
  549. await conn.execute(
  550. text(
  551. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  552. )
  553. )
  554. except Exception:
  555. pass
  556. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  557. try:
  558. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  559. row = result.fetchone()
  560. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  561. # Need to migrate - archive_id is currently NOT NULL
  562. await conn.execute(
  563. text("""
  564. CREATE TABLE print_queue_new2 (
  565. id INTEGER PRIMARY KEY,
  566. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  567. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  568. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  569. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  570. position INTEGER DEFAULT 0,
  571. scheduled_time DATETIME,
  572. manual_start BOOLEAN DEFAULT 0,
  573. require_previous_success BOOLEAN DEFAULT 0,
  574. auto_off_after BOOLEAN DEFAULT 0,
  575. ams_mapping TEXT,
  576. plate_id INTEGER,
  577. bed_levelling BOOLEAN DEFAULT 1,
  578. flow_cali BOOLEAN DEFAULT 0,
  579. vibration_cali BOOLEAN DEFAULT 1,
  580. layer_inspect BOOLEAN DEFAULT 0,
  581. timelapse BOOLEAN DEFAULT 0,
  582. use_ams BOOLEAN DEFAULT 1,
  583. status VARCHAR(20) DEFAULT 'pending',
  584. started_at DATETIME,
  585. completed_at DATETIME,
  586. error_message TEXT,
  587. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  588. )
  589. """)
  590. )
  591. await conn.execute(
  592. text("""
  593. INSERT INTO print_queue_new2
  594. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  595. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  596. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  597. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  598. status, started_at, completed_at, error_message, created_at
  599. FROM print_queue
  600. """)
  601. )
  602. await conn.execute(text("DROP TABLE print_queue"))
  603. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  604. except Exception:
  605. pass
  606. # Migration: Add HA energy sensor entity columns to smart_plugs
  607. try:
  608. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  609. except Exception:
  610. pass
  611. try:
  612. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  613. except Exception:
  614. pass
  615. try:
  616. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  617. except Exception:
  618. pass
  619. # Migration: Create users table for authentication
  620. try:
  621. await conn.execute(
  622. text("""
  623. CREATE TABLE IF NOT EXISTS users (
  624. id INTEGER PRIMARY KEY,
  625. username VARCHAR(100) NOT NULL UNIQUE,
  626. password_hash VARCHAR(255) NOT NULL,
  627. role VARCHAR(20) NOT NULL DEFAULT 'user',
  628. is_active BOOLEAN NOT NULL DEFAULT 1,
  629. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  630. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  631. )
  632. """)
  633. )
  634. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  635. except Exception:
  636. pass
  637. # Migration: Add external camera columns to printers
  638. try:
  639. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  640. except Exception:
  641. pass
  642. try:
  643. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  644. except Exception:
  645. pass
  646. try:
  647. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  648. except Exception:
  649. pass
  650. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  651. try:
  652. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  653. except Exception:
  654. pass
  655. # Migration: Add is_external column to library_files for external cloud files
  656. try:
  657. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  658. except Exception:
  659. pass
  660. # Migration: Add project_id column to library_files
  661. try:
  662. await conn.execute(
  663. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  664. )
  665. except Exception:
  666. pass
  667. # Migration: Add is_external column to library_folders for external cloud folders
  668. try:
  669. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  670. except Exception:
  671. pass
  672. # Migration: Add external folder settings columns to library_folders
  673. try:
  674. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  675. except Exception:
  676. pass
  677. try:
  678. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  679. except Exception:
  680. pass
  681. try:
  682. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  683. except Exception:
  684. pass
  685. # Migration: Add plate_detection_enabled column to printers
  686. try:
  687. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  688. except Exception:
  689. pass
  690. # Migration: Add plate detection ROI columns to printers
  691. try:
  692. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  693. except Exception:
  694. pass
  695. try:
  696. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  697. except Exception:
  698. pass
  699. try:
  700. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  701. except Exception:
  702. pass
  703. try:
  704. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  705. except Exception:
  706. pass
  707. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  708. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  709. # SQLite requires table recreation to drop constraints
  710. try:
  711. # Check if we need to migrate (if UNIQUE constraint exists)
  712. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  713. row = result.fetchone()
  714. if row and "printer_id INTEGER UNIQUE" in (row[0] or ""):
  715. # Create new table without UNIQUE constraint on printer_id
  716. await conn.execute(
  717. text("""
  718. CREATE TABLE smart_plugs_temp (
  719. id INTEGER PRIMARY KEY,
  720. name VARCHAR(100) NOT NULL,
  721. ip_address VARCHAR(45),
  722. plug_type VARCHAR(20) DEFAULT 'tasmota',
  723. ha_entity_id VARCHAR(100),
  724. ha_power_entity VARCHAR(100),
  725. ha_energy_today_entity VARCHAR(100),
  726. ha_energy_total_entity VARCHAR(100),
  727. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  728. enabled BOOLEAN NOT NULL DEFAULT 1,
  729. auto_on BOOLEAN NOT NULL DEFAULT 1,
  730. auto_off BOOLEAN NOT NULL DEFAULT 1,
  731. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  732. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  733. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  734. username VARCHAR(50),
  735. password VARCHAR(100),
  736. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  737. power_alert_high FLOAT,
  738. power_alert_low FLOAT,
  739. power_alert_last_triggered DATETIME,
  740. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  741. schedule_on_time VARCHAR(5),
  742. schedule_off_time VARCHAR(5),
  743. show_in_switchbar BOOLEAN DEFAULT 0,
  744. last_state VARCHAR(10),
  745. last_checked DATETIME,
  746. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  747. auto_off_pending BOOLEAN DEFAULT 0,
  748. auto_off_pending_since DATETIME,
  749. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  750. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  751. )
  752. """)
  753. )
  754. # Copy data
  755. await conn.execute(
  756. text("""
  757. INSERT INTO smart_plugs_temp
  758. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  759. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  760. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  761. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  762. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  763. show_in_switchbar, last_state, last_checked, auto_off_executed,
  764. auto_off_pending, auto_off_pending_since, created_at, updated_at
  765. FROM smart_plugs
  766. """)
  767. )
  768. # Drop old table and rename new one
  769. await conn.execute(text("DROP TABLE smart_plugs"))
  770. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  771. except Exception:
  772. pass
  773. # Migration: Add show_on_printer_card column to smart_plugs
  774. try:
  775. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  776. except Exception:
  777. pass
  778. # Migration: Add MQTT smart plug fields (legacy)
  779. try:
  780. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  781. except Exception:
  782. pass
  783. try:
  784. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  785. except Exception:
  786. pass
  787. try:
  788. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  789. except Exception:
  790. pass
  791. try:
  792. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  793. except Exception:
  794. pass
  795. try:
  796. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  797. except Exception:
  798. pass
  799. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  800. try:
  801. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  802. except Exception:
  803. pass
  804. try:
  805. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  806. except Exception:
  807. pass
  808. try:
  809. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  810. except Exception:
  811. pass
  812. try:
  813. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  814. except Exception:
  815. pass
  816. try:
  817. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  818. except Exception:
  819. pass
  820. try:
  821. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  822. except Exception:
  823. pass
  824. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  825. try:
  826. await conn.execute(
  827. text("""
  828. UPDATE smart_plugs
  829. SET mqtt_power_topic = mqtt_topic,
  830. mqtt_power_multiplier = mqtt_multiplier
  831. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  832. """)
  833. )
  834. except Exception:
  835. pass
  836. # Migration: Create groups table for permission-based access control
  837. try:
  838. await conn.execute(
  839. text("""
  840. CREATE TABLE IF NOT EXISTS groups (
  841. id INTEGER PRIMARY KEY,
  842. name VARCHAR(100) NOT NULL UNIQUE,
  843. description VARCHAR(500),
  844. permissions JSON,
  845. is_system BOOLEAN NOT NULL DEFAULT 0,
  846. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  847. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  848. )
  849. """)
  850. )
  851. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  852. except Exception:
  853. pass
  854. # Migration: Create user_groups association table
  855. try:
  856. await conn.execute(
  857. text("""
  858. CREATE TABLE IF NOT EXISTS user_groups (
  859. user_id INTEGER NOT NULL,
  860. group_id INTEGER NOT NULL,
  861. PRIMARY KEY (user_id, group_id),
  862. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  863. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  864. )
  865. """)
  866. )
  867. except Exception:
  868. pass
  869. # Migration: Add model-based queue assignment columns to print_queue
  870. try:
  871. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  872. except Exception:
  873. pass
  874. try:
  875. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  876. except Exception:
  877. pass
  878. try:
  879. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  880. except Exception:
  881. pass
  882. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  883. try:
  884. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  885. except Exception:
  886. pass
  887. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  888. try:
  889. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  890. except Exception:
  891. pass
  892. # Migration: Add queue notification event columns to notification_providers
  893. try:
  894. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  895. except Exception:
  896. pass
  897. try:
  898. await conn.execute(
  899. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  900. )
  901. except Exception:
  902. pass
  903. try:
  904. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  905. except Exception:
  906. pass
  907. try:
  908. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  909. except Exception:
  910. pass
  911. try:
  912. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  913. except Exception:
  914. pass
  915. try:
  916. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  917. except Exception:
  918. pass
  919. try:
  920. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  921. except Exception:
  922. pass
  923. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  924. try:
  925. await conn.execute(
  926. text("ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  927. )
  928. except Exception:
  929. pass
  930. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  931. try:
  932. await conn.execute(
  933. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  934. )
  935. except Exception:
  936. pass
  937. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  938. try:
  939. await conn.execute(
  940. text("ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  941. )
  942. except Exception:
  943. pass
  944. # Migration: Convert absolute paths to relative paths in library_files table
  945. # This ensures backup/restore portability across different installations
  946. try:
  947. base_dir_str = str(settings.base_dir)
  948. # Ensure we have a trailing slash for clean replacement
  949. if not base_dir_str.endswith("/"):
  950. base_dir_str += "/"
  951. # Update file_path - remove base_dir prefix from absolute paths
  952. await conn.execute(
  953. text("""
  954. UPDATE library_files
  955. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  956. WHERE file_path LIKE :pattern
  957. """),
  958. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  959. )
  960. # Update thumbnail_path - remove base_dir prefix from absolute paths
  961. await conn.execute(
  962. text("""
  963. UPDATE library_files
  964. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  965. WHERE thumbnail_path LIKE :pattern
  966. """),
  967. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  968. )
  969. except Exception:
  970. pass
  971. async def seed_notification_templates():
  972. """Seed default notification templates if they don't exist."""
  973. from sqlalchemy import select
  974. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  975. async with async_session() as session:
  976. # Get existing template event types
  977. result = await session.execute(select(NotificationTemplate.event_type))
  978. existing_types = {row[0] for row in result.fetchall()}
  979. if not existing_types:
  980. # No templates exist - insert all defaults
  981. for template_data in DEFAULT_TEMPLATES:
  982. template = NotificationTemplate(
  983. event_type=template_data["event_type"],
  984. name=template_data["name"],
  985. title_template=template_data["title_template"],
  986. body_template=template_data["body_template"],
  987. is_default=True,
  988. )
  989. session.add(template)
  990. else:
  991. # Templates exist - only add missing ones
  992. for template_data in DEFAULT_TEMPLATES:
  993. if template_data["event_type"] not in existing_types:
  994. template = NotificationTemplate(
  995. event_type=template_data["event_type"],
  996. name=template_data["name"],
  997. title_template=template_data["title_template"],
  998. body_template=template_data["body_template"],
  999. is_default=True,
  1000. )
  1001. session.add(template)
  1002. await session.commit()
  1003. async def seed_default_groups():
  1004. """Seed default groups and migrate existing users to appropriate groups.
  1005. Creates the default system groups (Administrators, Operators, Viewers) if they
  1006. don't exist, then migrates existing users:
  1007. - Users with role='admin' -> Administrators group
  1008. - Users with role='user' -> Operators group
  1009. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1010. """
  1011. import logging
  1012. from sqlalchemy import select
  1013. from backend.app.core.permissions import DEFAULT_GROUPS
  1014. from backend.app.models.group import Group
  1015. from backend.app.models.user import User
  1016. logger = logging.getLogger(__name__)
  1017. # Map old permissions to new ones for migration
  1018. # Administrators get *_all permissions, Operators get *_own permissions
  1019. PERMISSION_MIGRATION_ALL = {
  1020. "queue:update": "queue:update_all",
  1021. "queue:delete": "queue:delete_all",
  1022. "archives:update": "archives:update_all",
  1023. "archives:delete": "archives:delete_all",
  1024. "archives:reprint": "archives:reprint_all",
  1025. "library:update": "library:update_all",
  1026. "library:delete": "library:delete_all",
  1027. }
  1028. PERMISSION_MIGRATION_OWN = {
  1029. "queue:update": "queue:update_own",
  1030. "queue:delete": "queue:delete_own",
  1031. "archives:update": "archives:update_own",
  1032. "archives:delete": "archives:delete_own",
  1033. "archives:reprint": "archives:reprint_own",
  1034. "library:update": "library:update_own",
  1035. "library:delete": "library:delete_own",
  1036. }
  1037. async with async_session() as session:
  1038. # Get existing groups
  1039. result = await session.execute(select(Group))
  1040. existing_groups = {group.name: group for group in result.scalars().all()}
  1041. # Create default groups if they don't exist
  1042. groups_created = []
  1043. for group_name, group_config in DEFAULT_GROUPS.items():
  1044. if group_name not in existing_groups:
  1045. group = Group(
  1046. name=group_name,
  1047. description=group_config["description"],
  1048. permissions=group_config["permissions"],
  1049. is_system=group_config["is_system"],
  1050. )
  1051. session.add(group)
  1052. groups_created.append(group_name)
  1053. logger.info(f"Created default group: {group_name}")
  1054. else:
  1055. # Migrate existing group's permissions from old to new format
  1056. group = existing_groups[group_name]
  1057. if group.permissions:
  1058. updated = False
  1059. new_permissions = list(group.permissions)
  1060. # Determine which migration map to use based on group
  1061. migration_map = (
  1062. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1063. )
  1064. for old_perm, new_perm in migration_map.items():
  1065. if old_perm in new_permissions:
  1066. new_permissions.remove(old_perm)
  1067. if new_perm not in new_permissions:
  1068. new_permissions.append(new_perm)
  1069. updated = True
  1070. logger.info(f"Migrated permission '{old_perm}' to '{new_perm}' in group '{group_name}'")
  1071. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1072. if group_name == "Administrators":
  1073. for _own_perm, all_perm in [
  1074. ("queue:update_own", "queue:update_all"),
  1075. ("queue:delete_own", "queue:delete_all"),
  1076. ("archives:update_own", "archives:update_all"),
  1077. ("archives:delete_own", "archives:delete_all"),
  1078. ("archives:reprint_own", "archives:reprint_all"),
  1079. ("library:update_own", "library:update_all"),
  1080. ("library:delete_own", "library:delete_all"),
  1081. ]:
  1082. # Add *_all if not present
  1083. if all_perm not in new_permissions:
  1084. new_permissions.append(all_perm)
  1085. updated = True
  1086. if updated:
  1087. group.permissions = new_permissions
  1088. await session.commit()
  1089. # Migrate existing users to groups if they're not already in any group
  1090. if groups_created:
  1091. # Refresh to get newly created groups
  1092. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1093. admin_group = admin_result.scalar_one_or_none()
  1094. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1095. operators_group = operators_result.scalar_one_or_none()
  1096. # Get all users
  1097. users_result = await session.execute(select(User))
  1098. users = users_result.scalars().all()
  1099. for user in users:
  1100. # Skip if user already has groups
  1101. if user.groups:
  1102. continue
  1103. if user.role == "admin" and admin_group:
  1104. user.groups.append(admin_group)
  1105. logger.info(f"Migrated admin user '{user.username}' to Administrators group")
  1106. elif operators_group:
  1107. user.groups.append(operators_group)
  1108. logger.info(f"Migrated user '{user.username}' to Operators group")
  1109. await session.commit()