package device import ( "fmt" "git.nutfactory.org/hoernschen/Matrix/utils/database" ) func CreateDevice(device *Device, userId string) (err error) { sqlStmt := fmt.Sprintf(`INSERT INTO device (id, name, accessToken, userId) VALUES (?, ?, ?, ?)`) tx, err := database.DB.Begin() if err != nil { return } stmt, err := tx.Prepare(sqlStmt) if err != nil { return } defer stmt.Close() _, err = stmt.Exec(device.Id, device.Name, device.AccessToken, userId) if err != nil { tx.Rollback() return } tx.Commit() return } func ReadDevice(id string) (foundDevice *Device, err error) { queryStmt := fmt.Sprintf(`SELECT id, name, accessToken FROM device WHERE id = '%s'`, id) rows, err := database.DB.Query(queryStmt) if err != nil { return } defer rows.Close() if rows.Next() { foundDevice = &Device{} err = rows.Scan(&foundDevice.Id, &foundDevice.Name, &foundDevice.AccessToken) if err != nil { return } foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id) } return } func ReadDeviceFromAccessToken(accessToken string) (foundDevice *Device, err error) { queryStmt := fmt.Sprintf(`SELECT id, name, accessToken FROM device WHERE accessToken = '%s'`, accessToken) rows, err := database.DB.Query(queryStmt) if err != nil { return } defer rows.Close() if rows.Next() { foundDevice = &Device{} err = rows.Scan(&foundDevice.Id, &foundDevice.Name, &foundDevice.AccessToken) if err != nil { return } foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id) } return } func ReadDevicesForUser(userId string) (devices map[string]*Device, err error) { queryStmt := fmt.Sprintf(`SELECT id, name, accessToken FROM device WHERE userId = '%s'`, userId) rows, err := database.DB.Query(queryStmt) if err != nil { return } defer rows.Close() devices = make(map[string]*Device) for rows.Next() { foundDevice := &Device{} err = rows.Scan(&foundDevice.Id, &foundDevice.Name, &foundDevice.AccessToken) if err != nil { return } foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id) devices[foundDevice.Id] = foundDevice } return } func UpdateDevice(device *Device) (err error) { sqlStmt := fmt.Sprintf(`UPDATE device SET name = ?, accessToken = ? WHERE id = ?`) tx, err := database.DB.Begin() if err != nil { return } stmt, err := tx.Prepare(sqlStmt) if err != nil { return } defer stmt.Close() _, err = stmt.Exec(device.Name, device.AccessToken, device.Id) if err != nil { tx.Rollback() return } tx.Commit() return } func DeleteDevice(id string) (err error) { queryStmt := fmt.Sprintf(`DELETE FROM device WHERE id = '%s'`, id) tx, err := database.DB.Begin() if err != nil { return } _, err = tx.Exec(queryStmt) if err != nil { tx.Rollback() return } tx.Commit() return }