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.

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