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.

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