You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
11 KiB

  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "git.aiterp.net/lucifer/new-server/models"
  7. sq "github.com/Masterminds/squirrel"
  8. "github.com/jmoiron/sqlx"
  9. "log"
  10. "strings"
  11. )
  12. type deviceRecord struct {
  13. ID int `db:"id"`
  14. BridgeID int `db:"bridge_id"`
  15. InternalID string `db:"internal_id"`
  16. Icon string `db:"icon"`
  17. Name string `db:"name"`
  18. Capabilities string `db:"capabilities"`
  19. ButtonNames string `db:"button_names"`
  20. SceneAssignmentJSON json.RawMessage `db:"scene_assignments"`
  21. }
  22. type deviceStateRecord struct {
  23. DeviceID int `db:"device_id"`
  24. Hue float64 `db:"hue"`
  25. Saturation float64 `db:"saturation"`
  26. Kelvin int `db:"kelvin"`
  27. Power bool `db:"power"`
  28. Intensity float64 `db:"intensity"`
  29. }
  30. type devicePropertyRecord struct {
  31. DeviceID int `db:"device_id"`
  32. Key string `db:"prop_key"`
  33. Value string `db:"prop_value"`
  34. IsUser bool `db:"is_user"`
  35. }
  36. type deviceTagRecord struct {
  37. DeviceID int `db:"device_id"`
  38. TagName string `db:"tag_name"`
  39. }
  40. type DeviceRepo struct {
  41. DBX *sqlx.DB
  42. }
  43. func (r *DeviceRepo) Find(ctx context.Context, id int) (*models.Device, error) {
  44. var device deviceRecord
  45. err := r.DBX.GetContext(ctx, &device, "SELECT * FROM device WHERE id = ?", id)
  46. if err != nil {
  47. return nil, dbErr(err)
  48. }
  49. return r.populateOne(ctx, device)
  50. }
  51. func (r *DeviceRepo) FetchByReference(ctx context.Context, kind models.ReferenceKind, value string) ([]models.Device, error) {
  52. q := sq.Select("device.*").From("device")
  53. var requiredTags []string
  54. var unwantedTags []string
  55. switch kind {
  56. case models.RKDeviceID:
  57. q = q.Where(sq.Eq{"id": strings.Split(value, ",")})
  58. case models.RKBridgeID:
  59. q = q.Where(sq.Eq{"bridge_id": strings.Split(value, ",")})
  60. case models.RKName:
  61. value = strings.ReplaceAll(value, "*", "%")
  62. q = q.Where(sq.Like{"name": value})
  63. case models.RKTag:
  64. allTags := strings.Split(strings.ReplaceAll(strings.ReplaceAll(value, "-", ",-"), "+", ",+"), ",")
  65. optionalTags := make([]string, 0, len(allTags))
  66. for _, tag := range allTags {
  67. if tag == "" || tag == "+" || tag == "-" {
  68. continue
  69. }
  70. if strings.HasPrefix(tag, "+") {
  71. requiredTags = append(requiredTags, tag[1:])
  72. } else if strings.HasPrefix(tag, "-") {
  73. unwantedTags = append(unwantedTags, tag[1:])
  74. } else {
  75. optionalTags = append(optionalTags, tag)
  76. }
  77. }
  78. q = q.Join("device_tag dt ON device.id=dt.device_id").Where(sq.Eq{"dt.tag_name": optionalTags})
  79. case models.RKAll:
  80. default:
  81. log.Println("Unknown reference kind used for device fetch:", kind)
  82. return []models.Device{}, nil
  83. }
  84. query, args, err := q.OrderBy("name", "id").ToSql()
  85. if err != nil {
  86. if err == sql.ErrNoRows {
  87. return []models.Device{}, nil
  88. }
  89. return nil, dbErr(err)
  90. }
  91. records := make([]deviceRecord, 0, 8)
  92. err = r.DBX.SelectContext(ctx, &records, query, args...)
  93. if err != nil {
  94. return nil, dbErr(err)
  95. }
  96. if len(requiredTags) > 0 || len(unwantedTags) > 0 {
  97. return r.populateFiltered(ctx, records, requiredTags, unwantedTags)
  98. }
  99. return r.populate(ctx, records)
  100. }
  101. func (r *DeviceRepo) SaveMany(ctx context.Context, mode models.SaveMode, devices []models.Device) error {
  102. tx, err := r.DBX.Beginx()
  103. if err != nil {
  104. return dbErr(err)
  105. }
  106. defer tx.Rollback()
  107. for i, device := range devices {
  108. scenesJSON, err := json.Marshal(device.SceneAssignments)
  109. if err != nil {
  110. return err
  111. }
  112. record := deviceRecord{
  113. ID: device.ID,
  114. BridgeID: device.BridgeID,
  115. InternalID: device.InternalID,
  116. SceneAssignmentJSON: scenesJSON,
  117. Icon: device.Icon,
  118. Name: device.Name,
  119. Capabilities: strings.Join(models.DeviceCapabilitiesToStrings(device.Capabilities), ","),
  120. ButtonNames: strings.Join(device.ButtonNames, ","),
  121. }
  122. if device.ID > 0 {
  123. _, err := tx.NamedExecContext(ctx, `
  124. UPDATE device SET
  125. internal_id = :internal_id,
  126. icon = :icon,
  127. name = :name,
  128. capabilities = :capabilities,
  129. button_names = :button_names
  130. WHERE id=:id
  131. `, record)
  132. if err != nil {
  133. return dbErr(err)
  134. }
  135. // Let's just be lazy for now, optimize later if need be.
  136. if mode == 0 || mode&models.SMTags != 0 {
  137. _, err = tx.ExecContext(ctx, "DELETE FROM device_tag WHERE device_id=?", record.ID)
  138. if err != nil {
  139. return dbErr(err)
  140. }
  141. }
  142. if mode == 0 || mode&models.SMProperties != 0 {
  143. _, err = tx.ExecContext(ctx, "DELETE FROM device_property WHERE device_id=?", record.ID)
  144. if err != nil {
  145. return dbErr(err)
  146. }
  147. }
  148. } else {
  149. res, err := tx.NamedExecContext(ctx, `
  150. INSERT INTO device (bridge_id, internal_id, icon, name, capabilities, button_names)
  151. VALUES (:bridge_id, :internal_id, :icon, :name, :capabilities, :button_names)
  152. `, record)
  153. if err != nil {
  154. return dbErr(err)
  155. }
  156. lastID, err := res.LastInsertId()
  157. if err != nil {
  158. return dbErr(err)
  159. }
  160. record.ID = int(lastID)
  161. devices[i].ID = int(lastID)
  162. }
  163. if mode == 0 || mode&models.SMTags != 0 {
  164. for _, tag := range device.Tags {
  165. _, err := tx.ExecContext(ctx, "INSERT INTO device_tag (device_id, tag_name) VALUES (?, ?)", record.ID, tag)
  166. if err != nil {
  167. return dbErr(err)
  168. }
  169. }
  170. }
  171. if mode == 0 || mode&models.SMProperties != 0 {
  172. for key, value := range device.UserProperties {
  173. _, err := tx.ExecContext(ctx, "INSERT INTO device_property (device_id, prop_key, prop_value, is_user) VALUES (?, ?, ?, 1)",
  174. record.ID, key, value,
  175. )
  176. if err != nil {
  177. return dbErr(err)
  178. }
  179. }
  180. for key, value := range device.DriverProperties {
  181. j, err := json.Marshal(value)
  182. if err != nil {
  183. // Eh, it'll get filled by the driver anyway
  184. continue
  185. }
  186. _, err = tx.ExecContext(ctx, "INSERT INTO device_property (device_id, prop_key, prop_value, is_user) VALUES (?, ?, ?, 0)",
  187. record.ID, key, string(j),
  188. )
  189. if err != nil {
  190. // Return err here anyway, it might put the tx in a bad state to ignore it.
  191. return dbErr(err)
  192. }
  193. }
  194. }
  195. if mode == 0 || mode&models.SMState != 0 {
  196. _, err = tx.NamedExecContext(ctx, `
  197. REPLACE INTO device_state(device_id, hue, saturation, kelvin, power, intensity)
  198. VALUES (:device_id, :hue, :saturation, :kelvin, :power, :intensity)
  199. `, deviceStateRecord{
  200. DeviceID: record.ID,
  201. Hue: device.State.Color.Hue,
  202. Saturation: device.State.Color.Saturation,
  203. Kelvin: device.State.Color.Kelvin,
  204. Power: device.State.Power,
  205. Intensity: device.State.Intensity,
  206. })
  207. if err != nil {
  208. return dbErr(err)
  209. }
  210. }
  211. }
  212. return tx.Commit()
  213. }
  214. func (r *DeviceRepo) Save(ctx context.Context, device *models.Device, mode models.SaveMode) error {
  215. devices := []models.Device{*device}
  216. err := r.SaveMany(ctx, mode, devices)
  217. if err != nil {
  218. return err
  219. }
  220. *device = devices[0]
  221. return nil
  222. }
  223. func (r *DeviceRepo) Delete(ctx context.Context, device *models.Device) error {
  224. _, err := r.DBX.ExecContext(ctx, "DELETE FROM device WHERE Id=?", device.ID)
  225. if err != nil {
  226. return dbErr(err)
  227. }
  228. return nil
  229. }
  230. func (r *DeviceRepo) populateOne(ctx context.Context, record deviceRecord) (*models.Device, error) {
  231. records, err := r.populate(ctx, []deviceRecord{record})
  232. if err != nil {
  233. return nil, err
  234. }
  235. return &records[0], nil
  236. }
  237. func (r *DeviceRepo) populateFiltered(ctx context.Context, records []deviceRecord, requiredTags []string, unwantedTags []string) ([]models.Device, error) {
  238. devices, err := r.populate(ctx, records)
  239. if err != nil {
  240. return nil, err
  241. }
  242. filteredDevices := make([]models.Device, 0, len(devices))
  243. for _, device := range devices {
  244. if device.HasTag(unwantedTags...) {
  245. continue
  246. }
  247. if len(requiredTags) == 0 || device.HasTag(requiredTags...) {
  248. filteredDevices = append(filteredDevices, device)
  249. }
  250. }
  251. return filteredDevices, nil
  252. }
  253. func (r *DeviceRepo) populate(ctx context.Context, records []deviceRecord) ([]models.Device, error) {
  254. if len(records) == 0 {
  255. return []models.Device{}, nil
  256. }
  257. ids := make([]int, 0, len(records))
  258. for _, record := range records {
  259. ids = append(ids, record.ID)
  260. }
  261. tagsQuery, tagsArgs, err := sq.Select("*").From("device_tag").Where(sq.Eq{"device_id": ids}).ToSql()
  262. if err != nil {
  263. return nil, dbErr(err)
  264. }
  265. propsQuery, propsArgs, err := sq.Select("*").From("device_property").Where(sq.Eq{"device_id": ids}).ToSql()
  266. if err != nil {
  267. return nil, dbErr(err)
  268. }
  269. stateQuery, stateArgs, err := sq.Select("*").From("device_state").Where(sq.Eq{"device_id": ids}).ToSql()
  270. if err != nil {
  271. return nil, dbErr(err)
  272. }
  273. states := make([]deviceStateRecord, 0, len(records))
  274. props := make([]devicePropertyRecord, 0, len(records)*8)
  275. tags := make([]deviceTagRecord, 0, len(records)*4)
  276. err = r.DBX.SelectContext(ctx, &states, stateQuery, stateArgs...)
  277. if err != nil {
  278. return nil, dbErr(err)
  279. }
  280. err = r.DBX.SelectContext(ctx, &props, propsQuery, propsArgs...)
  281. if err != nil {
  282. return nil, dbErr(err)
  283. }
  284. err = r.DBX.SelectContext(ctx, &tags, tagsQuery, tagsArgs...)
  285. if err != nil {
  286. return nil, dbErr(err)
  287. }
  288. hasAdded := make(map[int]bool, len(records))
  289. devices := make([]models.Device, 0, len(records))
  290. for _, record := range records {
  291. if hasAdded[record.ID] {
  292. continue
  293. }
  294. device := models.Device{
  295. ID: record.ID,
  296. BridgeID: record.BridgeID,
  297. InternalID: record.InternalID,
  298. Icon: record.Icon,
  299. Name: record.Name,
  300. SceneAssignments: make([]models.DeviceSceneAssignment, 0, 4),
  301. ButtonNames: strings.Split(record.ButtonNames, ","),
  302. DriverProperties: make(map[string]interface{}, 8),
  303. UserProperties: make(map[string]string, 8),
  304. Tags: make([]string, 0, 8),
  305. }
  306. _ = json.Unmarshal(record.SceneAssignmentJSON, &device.SceneAssignments)
  307. if device.ButtonNames[0] == "" {
  308. device.ButtonNames = device.ButtonNames[:0]
  309. }
  310. caps := make([]models.DeviceCapability, 0, 16)
  311. for _, capStr := range strings.Split(record.Capabilities, ",") {
  312. caps = append(caps, models.DeviceCapability(capStr))
  313. }
  314. device.Capabilities = caps
  315. for _, state := range states {
  316. if state.DeviceID == record.ID {
  317. device.State = models.DeviceState{
  318. Power: state.Power,
  319. Color: models.ColorValue{
  320. Hue: state.Hue,
  321. Saturation: state.Saturation,
  322. Kelvin: state.Kelvin,
  323. },
  324. Intensity: state.Intensity,
  325. }
  326. }
  327. }
  328. driverProps := make(map[string]json.RawMessage, 8)
  329. for _, prop := range props {
  330. if prop.DeviceID == record.ID {
  331. if prop.IsUser {
  332. device.UserProperties[prop.Key] = prop.Value
  333. } else {
  334. driverProps[prop.Key] = json.RawMessage(prop.Value)
  335. }
  336. }
  337. }
  338. if len(driverProps) > 0 {
  339. j, err := json.Marshal(driverProps)
  340. if err != nil {
  341. return nil, dbErr(err)
  342. }
  343. err = json.Unmarshal(j, &device.DriverProperties)
  344. if err != nil {
  345. return nil, dbErr(err)
  346. }
  347. }
  348. for _, tag := range tags {
  349. if tag.DeviceID == record.ID {
  350. device.Tags = append(device.Tags, tag.TagName)
  351. }
  352. }
  353. hasAdded[record.ID] = true
  354. devices = append(devices, device)
  355. }
  356. return devices, nil
  357. }