database

package
v0.0.49 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2022 License: GPL-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Contains the database backend for static automation

Index

Constants

This section is empty.

Variables

View Source
var (
	Permissions = []Permission{
		{

			Permission:  PermissionPower,
			Name:        "Power",
			Description: "Interact with switches",
		},
		{

			Permission:  PermissionLogs,
			Name:        "Manage Logging",
			Description: "Use and manage the internal logging system",
		},
		{

			Permission:  PermissionDebug,
			Name:        "Debug Features",
			Description: "Obtain debug information about the system",
		},
		{

			Permission:  PermissionManageUsers,
			Name:        "Manage Users",
			Description: "Create / remove and manage users and manage their permissions",
		},
		{

			Permission:  PermissionHomescript,
			Name:        "Homescript",
			Description: "List, add, delete, run, and modify Homescripts",
		},
		{

			Permission:  PermissionHomescriptNetwork,
			Name:        "Homescript Network",
			Description: "Make network requests inside Homescript, use http functions",
		},
		{

			Permission:  PermissionAutomation,
			Name:        "Automations",
			Description: "List, add, delete, and modify automations",
		},
		{

			Permission:  PermissionScheduler,
			Name:        "Scheduler",
			Description: "List, add, delete, and modify schedules",
		},
		{

			Permission:  PermissionReminder,
			Name:        "Reminders",
			Description: "List, add, delete, and modify reminders",
		},
		{

			Permission:  PermissionModifyRooms,
			Name:        "Manage Rooms",
			Description: "View, add, modify and delete rooms and room like switches and cameras. If enabled, the user also has access to every switch of the system.",
		},
		{

			Permission:  PermissionViewCameras,
			Name:        "View Cameras",
			Description: "View camera video feed. However, which camera can be viewed still depends on the camera permissions.",
		},
		{

			Permission:  PermissionModifyServerConfig,
			Name:        "Manage Server Config",
			Description: "Change global server configuration values and export system configuration (includes sensitive data).",
		},
		{

			Permission:  PermissionWildCard,
			Name:        "Permission Wildcard",
			Description: "Allows all permissions",
		},
	}
)

Functions

func AddHomescriptArg added in v0.0.40

func AddHomescriptArg(data HomescriptArgData) (uint, error)

Adds a new item to the argument list of a given Homescript Returns the newly created ID of the argument

func AddLogEvent

func AddLogEvent(name string, description string, level int) error

Add a logged internal event based on `name`, `description`, and `level`

func AddNotification

func AddNotification(receiverUsername string, name string, description string, priority uint8) error

Adds a new notification to a user's `inbox`, can return an error if the database fails

func AddUser

func AddUser(user FullUser) error

Helper function to create a User which is given a set of basic permissions Will return an error if the database fails TODO: Remove business logic from here, move to core/user

func AddUserCameraPermission

func AddUserCameraPermission(username string, cameraId string) (modified bool, err error)

Adds a given cameraId to an arbitrary user's camera permissions The existence of the camera and the user should be validated beforehand

func AddUserPermission

func AddUserPermission(username string, permission PermissionType) error

Adds a permission to a user, if database fails, then an error is returned Does not check for username or presence of the permission, => additional checks should be completed beforehand

func AddUserSwitchPermission

func AddUserSwitchPermission(username string, switchId string) (bool, error)

Adds a given switchId to a given user The existence of the switch should be validated beforehand If this permission already resides inside the table, it is ignored and modified=false, error=nil is returned TODO: Remove useless check if user already has permission

func CheckDatabase

func CheckDatabase() error

Executes a ping to the database in order to check if it is online A nil response means success whereas an error indicates a database failure

func CreateCamera

func CreateCamera(data Camera) error

Creates a new camera Checks, for example if the camera already exists should be completed beforehand If the camera already exists, some values are updated

func CreateHardwareNode

func CreateHardwareNode(node HardwareNode) error

Adds a new hardware node to the database If the node already exists (same url), its name will be updated

func CreateNewAutomation

func CreateNewAutomation(automation Automation) (uint, error)

Creates a new automation item using the raw data provided

func CreateNewHomescript

func CreateNewHomescript(homescript Homescript) error

Creates a new homescript entry

func CreateNewReminder

func CreateNewReminder(name string, description string, dueDate time.Time, owner string, priority ReminderPriority) (uint, error)

Creates a new reminder in the database

func CreateNewSchedule

func CreateNewSchedule(
	owner string,
	data ScheduleData,
) (uint, error)

Creates a new schedule which represents a job of the scheduler

func CreateNewScheduleSwitch added in v0.0.49

func CreateNewScheduleSwitch(
	scheduleId uint,
	switchId string,
	powerOn bool,
) (uint, error)

Creates a new power job for a corresponding schedule All data must be validated beforehand

func CreateRoom

func CreateRoom(room RoomData) error

Creates a new room given an arbitrary, non-existing id

func CreateSwitch

func CreateSwitch(id string, name string, roomId string, watts uint16) error

Creates a new switch Will return an error if the database fails

func DeleteAllAutomationsFromUser

func DeleteAllAutomationsFromUser(username string) error

Deletes all automations from a given user Used when deleting a user An invalid username will lead to no deletions

func DeleteAllHomescriptArgsFromScript added in v0.0.40

func DeleteAllHomescriptArgsFromScript(homescriptId string) error

Deletes all arguments referencing a given Homescript Used before deleting a Homescript from the database

func DeleteAllHomescriptsOfUser

func DeleteAllHomescriptsOfUser(username string) error

Deletes all Homescripts of a given user Uses the `DeleteHomescriptById` function

func DeleteAllNotificationsFromUser

func DeleteAllNotificationsFromUser(username string) error

If the user requests to empty their notification area, all hist notifications will be deleted

func DeleteAllRemindersFromUser

func DeleteAllRemindersFromUser(username string) error

Deletes all reminders of a given user

func DeleteAllSchedulesFromUser

func DeleteAllSchedulesFromUser(username string) error

Deletes all schedules from a given user

func DeleteAllSwitchesFromSchedule added in v0.0.49

func DeleteAllSwitchesFromSchedule(scheduleId uint) error

Deletes all switch items from a given schedule Used when a schedule is deleted

func DeleteAutomationById

func DeleteAutomationById(id uint) error

Deletes an automation item given its Id Does not validate the validity of the provided Id If an invalid id is specified, nothing will be deleted

func DeleteCamera

func DeleteCamera(id string) error

Deletes a camera and removes dependent camera-permission first Used in deleting all room cameras and deleting one camera

func DeleteHardwareNode

func DeleteHardwareNode(url string) error

Deletes a node given its url

func DeleteHomescriptArg added in v0.0.40

func DeleteHomescriptArg(id uint) error

Deletes an arbitrary Homescript argument given its id

func DeleteHomescriptById

func DeleteHomescriptById(homescriptId string) error

Deletes a homescript by its Id, does not check if the user has access to the homescript

func DeleteNotificationFromUserById

func DeleteNotificationFromUserById(notificationId uint, username string) error

Deletes a given notification, can return an error

func DeleteRoom

func DeleteRoom(id string) error

func DeleteRoomCameras

func DeleteRoomCameras(roomId string) error

Deletes all cameras in an arbitrary room Uses `DeleteCamera` in order to remove the camera's dependencies beforehand Used when deleting a room

func DeleteRoomQuery

func DeleteRoomQuery(id string) error

Deletes a room and all entities that depend on the room

func DeleteRoomSwitches

func DeleteRoomSwitches(roomId string) error

Deletes all switches from an arbitrary room Before deleting the switch, dependencies like switch-permissions are deleted

func DeleteScheduleById

func DeleteScheduleById(id uint) error

Deletes a schedule item given its Id Deletes all switch jobs first Does not validate the validity of the provided Id

func DeleteSwitch

func DeleteSwitch(switchId string) error

Delete a given switch after all data which depends on this switch has been deleted

func DeleteSwitchFromSchedule added in v0.0.49

func DeleteSwitchFromSchedule(
	switchId string,
	scheduleId uint,
) error

Deletes an existent switch job from a given schedule All data has to be validated beforehand

func DeleteTables

func DeleteTables() error

Deletes all tables in the active `smarthome` database This function is used in testing and could be used in the future to allow for a system reset

func DeleteUser

func DeleteUser(username string) error

Deletes a User based on a given Username, can return an error if the database fails The function does not validate the existence of this username itself, so additional checks should be done beforehand The avatar is removed in `core/user/user`

func DeleteUserReminderById

func DeleteUserReminderById(owner string, id uint) error

Delete a single reminder, for example if its task is finished

func DoesHomescriptExist

func DoesHomescriptExist(homescriptId string) (bool, error)

TODO: remove and intigrate into get user homescript Checks if a Homescript with an id exists in the database

func DoesPermissionExist

func DoesPermissionExist(permission string) bool

Checks the validity of a given permission string

func FlushAllLogs

func FlushAllLogs() error

Deletes all logs which are currently stored in the database

func FlushOldLogs

func FlushOldLogs() error

Deletes log events older than 30 days in order to free storage space This function will later be used by a scheduler for daily jobs

func GetAvatarPathByUsername

func GetAvatarPathByUsername(username string) (string, error)

Returns the path of the avatar image of a given user, does not check if the user exists, additional checks needed beforehand

func GetUserCameraPermissions added in v0.0.30

func GetUserCameraPermissions(username string) ([]string, error)

Returns the camera-permissions of an arbitrary user in the form of a slice of strings Each slice element references a camera's id to which the user has access to

func GetUserNotificationCount

func GetUserNotificationCount(username string) (uint16, error)

Used for displaying the notification count for a given user Used in the frontend before the actual permissions are fetched

func GetUserPasswordHash

func GetUserPasswordHash(username string) (string, error)

Returns the password of a given user

func GetUserPermissions

func GetUserPermissions(username string) ([]string, error)

Returns a list of permissions assigned to a given user, if it exists

func GetUserSwitchPermissions

func GetUserSwitchPermissions(username string) ([]string, error)

Returns a list of strings which resemble switch permissions

func Init

func Init(databaseConfig DatabaseConfig, adminPassword string) error

func InitLogger

func InitLogger(logger *logrus.Logger)

func InsertUser

func InsertUser(user FullUser) error

Creates a new user based on a the supplied `User` struct Won't return an error if user already exists, but will change the password

func ModifyAutomation

func ModifyAutomation(id uint, newItem AutomationData) error

Modifies the metadata of a given automation item given its raw id Does not validate the provided metadata If an invalid id is specified, no data will be modified

func ModifyCamera

func ModifyCamera(id string, newName string, newUrl string) error

Modifies a cameras name annd URL Does not modify other metadata due to it being used immutably

func ModifyHardwareNode

func ModifyHardwareNode(url string, node HardwareNode) error

Changes the metadata of a given node Does not affect the online boolean For changing the online status, use `SetNodeOnline`

func ModifyHomescriptArg added in v0.0.40

func ModifyHomescriptArg(id uint, newData HomescriptArgData) error

Modifies the data of a given Homescript argument

func ModifyHomescriptById

func ModifyHomescriptById(id string, homescript HomescriptData) error

Modifies the metadata of a given homescript Does not check the validity of the homescript's id

func ModifyReminder

func ModifyReminder(id uint, name string, description string, dueDate time.Time, priority ReminderPriority) error

Modifies a given reminder to possess the new metadata

func ModifyRoomData

func ModifyRoomData(id string, newName string, newDescription string) error

Updates the room's name and description

func ModifySchedule

func ModifySchedule(id uint, newData ScheduleData) error

Modifies the metadata of a given schedule Does not validate the provided metadata

func ModifySwitch

func ModifySwitch(id string, name string, watts uint16) error

Modifies the metadata of a given switch

func RemoveAllCameraPermissionsOfUser

func RemoveAllCameraPermissionsOfUser(username string) error

Removes all camera permissions of a given user, used when deleting a user Providing an invalid user will lead to no deletions

func RemoveAllPermissionsOfUser

func RemoveAllPermissionsOfUser(username string) error

Removes all permissions of a given user, used when deleting a user in order to prevent foreign key failure Does not validate username, additional checks required, returns an error if the database fails

func RemoveAllSwitchPermissionsOfUser

func RemoveAllSwitchPermissionsOfUser(username string) error

Removes all switch permissions of a given user, used when deleting a user Does not validate the existence of said user

func RemoveCameraFromPermissions

func RemoveCameraFromPermissions(cameraId string) error

Deletes all occurrences of a given camera-id in the camera permissions => Used if a camera is deleted

func RemoveSwitchFromPermissions

func RemoveSwitchFromPermissions(switchId string) error

Deletes all occurrences of a given switch, used if a certain switch is deleted

func RemoveUserCameraPermission

func RemoveUserCameraPermission(username string, cameraId string) (modified bool, err error)

Removes a camera permission of an arbitrary user An invalid user or an invalid camera id will lead to no deletions

func RemoveUserPermission

func RemoveUserPermission(username string, permission PermissionType) error

Attempts to remove a provided permission from a provided user Fails if permission does not exist or if the database fails Warns and returns `false` for the `modified` boolean the user does not have the permission

func RemoveUserSwitchPermission

func RemoveUserSwitchPermission(username string, switchId string) (bool, error)

TODO: Remove useless check if user already has permission TODO: check naming consistency of `ADD / CREATE` and `DELETE / REMOVE` Removes a switch permission from a user, but does not delete if from the switch permission list

func SetAutomationSystemActivation

func SetAutomationSystemActivation(enabled bool) error

Change the state of the automation system

func SetNodeOnline

func SetNodeOnline(nodeUrl string, online bool) error

Updates the online / offline state of a given node (using its url)

func SetPowerState

func SetPowerState(switchId string, isPoweredOn bool) (bool, error)

Used when marking a power state of a switch Does not check the validity of the switch Id The returned boolean indicates if the power state had changed

func SetReminderUserWasNotified

func SetReminderUserWasNotified(id uint, wasNotified bool, wasNotifiedAt time.Time) error

Modifies the reminders status its owner has been informed about urgency

func SetServerConfiguration

func SetServerConfiguration(config ServerConfig) error

Updates the servers configuration

func SetUserAvatarPath

func SetUserAvatarPath(username string, avatarPath string) error

Sets the path of the avatar for a given user, does not check if the user exists, additional checks needed beforehand

func SetUserDarkThemeEnabled

func SetUserDarkThemeEnabled(username string, useDarkTheme bool) error

Set whether the user uses the dark theme or the light theme

func SetUserSchedulerEnabled

func SetUserSchedulerEnabled(username string, enabled bool) error

Set whether the scheduler is enabled for the current user

func Shutdown

func Shutdown() error

Closes the database connection

func UpdateLocation

func UpdateLocation(lat float32, lon float32) error

Changes the location of the server

func UpdateUserMetadata

func UpdateUserMetadata(username string, forename string, surname string, primaryColorDark string, primaryColorLight string) error

Sets the users primary colors

func UserHasCameraPermission

func UserHasCameraPermission(username string, cameraId string) (bool, error)

Returns a boolean indicating whether a user is in possession of a given camera permission Also accounts for the special case that a usaer does not have explicit permission to a camera, but is in possession of the `manageRooms` or `*` permission, which grants the user access

func UserHasCameraPermissionQuery

func UserHasCameraPermissionQuery(username string, cameraId string) (bool, error)

Returns a boolean indicating whether the user has access to a given camera or not. This function just regards database occurrences and does not cover special rules for which the `userHasCameraPermission` function accounts => Used in userHasCameraPermission

func UserHasPermission

func UserHasPermission(username string, permission PermissionType) (bool, error)

Checks if a provided user is in possession of a provided permission, can return an error, if the database fails

func UserHasSwitchPermission

func UserHasSwitchPermission(username string, switchId string) (bool, error)

Returns a boolean if a user has a switch permission

func UserHasSwitchPermissionQuery

func UserHasSwitchPermissionQuery(username string, switchId string) (bool, error)

Used in userHasSwitchPermission

Types

type Automation

type Automation struct {
	// The ID is automatically generated
	Id    uint           `json:"id"`
	Owner string         `json:"owner"`
	Data  AutomationData `json:"data"`
}

func GetAutomationById

func GetAutomationById(id uint) (Automation, bool, error)

Returns a Automation struct which matches the given Id If the id does not match a struct, an empty struct and `false` (for found) is returned

func GetAutomations

func GetAutomations() ([]Automation, error)

Returns a slice with automations of all users Used for activating persistent automations when the server starts

func GetUserAutomations

func GetUserAutomations(username string) ([]Automation, error)

Returns a list containing automations of a given user (must be valid) An invalid user will yield an empty list

type AutomationData added in v0.0.29

type AutomationData struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	// Saves the underlying cron-expression to wrap the time and days of execution
	CronExpression string `json:"cronExpression"`
	// Specifies which Homescript is to be executed when the automation runs
	HomescriptId string     `json:"homescriptId"`
	Enabled      bool       `json:"enabled"`
	TimingMode   TimingMode `json:"timingMode"`
}

type Camera

type Camera struct {
	Id     string `json:"id"`
	Name   string `json:"name"`
	Url    string `json:"url"`
	RoomId string `json:"roomId"`
}

func GetCameraById

func GetCameraById(id string) (cam Camera, exists bool, err error)

Returns the metadata of a given camera, whether it could be found and a potential error

func ListCameras

func ListCameras() ([]Camera, error)

Returns a list containing all cameras Used when deleting all cameras in a room

func ListUserCameras

func ListUserCameras(username string) ([]Camera, error)

Combines the logic from `ListUserCamerasQuery` with other permission logic which cannot be expressed through SQL Manages an exception: if the user has the permission to modify rooms, all cameras are granted

func ListUserCamerasQuery

func ListUserCamerasQuery(username string) ([]Camera, error)

Like `ListCameras` but takes a user string as a filter Only returns cameras to which the user has access to Used in `ListUserCameras`

type DBStatus

type DBStatus struct {
	OpenConnections int `json:"openConnections"`
	InUse           int `json:""`
	Idle            int `json:""`
}

func GetDatabaseStats

func GetDatabaseStats() DBStatus

Returns common database statistics Is used in the debug function

type DatabaseConfig

type DatabaseConfig struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Hostname string `json:"hostname"`
	Database string `json:"database"`
	Port     uint16 `json:"port"`
}

type FullUser

type FullUser struct {
	Username          string `json:"username"`
	Forename          string `json:"forename"`
	Surname           string `json:"surname"`
	PrimaryColorDark  string `json:"primaryColorDark"`
	PrimaryColorLight string `json:"primaryColorLight"`
	Password          string `json:"password"`
	AvatarPath        string `json:"avatarPath"`
	SchedulerEnabled  bool   `json:"schedulerEnabled"` // Specifies whether the user's schedules and automations may be executed
	DarkTheme         bool   `json:"darkTheme"`
}

Identified by a username, has a password and an avatar path

type HardwareNode

type HardwareNode struct {
	Name    string `json:"name"`
	Online  bool   `json:"online"`
	Enabled bool   `json:"enabled"` // Can be used to temporarily deactivate a node in case of maintenance
	Url     string `json:"url"`
	Token   string `json:"token"`
}

Hardware node

func GetHardwareNodeByUrl

func GetHardwareNodeByUrl(url string) (HardwareNode, bool, error)

Returns a hardware node given its url

func GetHardwareNodes

func GetHardwareNodes() ([]HardwareNode, error)

Returns a list of hardware nodes

type HmsArgDisplay added in v0.0.39

type HmsArgDisplay string
var (
	TypeDefault    HmsArgDisplay = "type_default"    // Uses a normal input field matching the specified data type
	StringSwitches HmsArgDisplay = "string_switches" // Shows a list of switches from which the user can select one as a string
	BooleanYesNo   HmsArgDisplay = "boolean_yes_no"  // Uses `yes` and `no` as substitutes for true and false
	BooleanOnOff   HmsArgDisplay = "boolean_on_off"  // Uses `on` and `off` as substitutes for true and false
	NumberHour     HmsArgDisplay = "number_hour"     // Displays a hour picker (0 <= h <= 24)
	NumberMinute   HmsArgDisplay = "number_minute"   // Displays a minute picker (0 <= m <= 60)
)

type HmsArgInputType added in v0.0.39

type HmsArgInputType string
var (
	String  HmsArgInputType = "string"
	Number  HmsArgInputType = "number"
	Boolean HmsArgInputType = "boolean"
)

Datatypes which a Homescript argument can use Type conversion is handled by the target Homescript These types act as a hint for the user and are required for the GUI to display an adequate input

type Homescript

type Homescript struct {
	Owner string         `json:"owner"`
	Data  HomescriptData `json:"data"`
}

func GetUserHomescriptById

func GetUserHomescriptById(homescriptId string, username string) (Homescript, bool, error)

Returns a Homescript given its id Returns Homescript, has been found, error TODO: replace with query row

func ListHomescriptFiles

func ListHomescriptFiles() ([]Homescript, error)

Lists all Homescript files in the database

func ListHomescriptOfUser

func ListHomescriptOfUser(username string) ([]Homescript, error)

Returns a list of homescripts owned by a given user

type HomescriptArg added in v0.0.39

type HomescriptArg struct {
	Id   uint              `json:"id"`   // The Id is automatically generated
	Data HomescriptArgData `json:"data"` // The main data of the argument
}

func GetUserHomescriptArgById added in v0.0.40

func GetUserHomescriptArgById(id uint, username string) (data HomescriptArg, found bool, err error)

Returns the data matching the id of an argument which is associated with a given user

func ListAllHomescriptArgsOfUser added in v0.0.39

func ListAllHomescriptArgsOfUser(username string) ([]HomescriptArg, error)

Returns all HomescriptArgs of a given user as a slice

func ListArgsOfHomescript added in v0.0.40

func ListArgsOfHomescript(homescriptId string) ([]HomescriptArg, error)

Returns the arguments of a given Homescript as a slice

type HomescriptArgData added in v0.0.40

type HomescriptArgData struct {
	ArgKey       string          `json:"argKey"`       // The unique key of the argument
	HomescriptId string          `json:"homescriptId"` // The Homescript to which the argument belongs to
	Prompt       string          `json:"prompt"`       // The prompt the user will see
	MDIcon       string          `json:"mdIcon"`       // A Google MD icon which will be displayed
	InputType    HmsArgInputType `json:"inputType"`    // Specifies the expected data type
	Display      HmsArgDisplay   `json:"display"`      // Specifies the visual display of the prompt (handled by GUI)
}

type HomescriptData

type HomescriptData struct {
	Id                  string `json:"id"`
	Name                string `json:"name"`
	Description         string `json:"description"`
	QuickActionsEnabled bool   `json:"quickActionsEnabled"`
	SchedulerEnabled    bool   `json:"schedulerEnabled"`
	Code                string `json:"code"`
	MDIcon              string `json:"mdIcon"`
}

type LogEvent

type LogEvent struct {
	Id          uint      `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Level       int       `json:"level"`
	Date        time.Time `json:"date"`
}

func GetLogs

func GetLogs() ([]LogEvent, error)

Returns all logs currently in the database

type Notification

type Notification struct {
	Id          uint      `json:"id"`
	Priority    uint8     `json:"priority"` // Includes 1: info, 2: warning, 3: alert
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Date        time.Time `json:"date"`
}

User notification

func GetUserNotifications

func GetUserNotifications(username string) ([]Notification, error)

Used when requesting the user's permissions in the frontend Returns a list containing the permissions of a given user

type Permission

type Permission struct {
	Permission  PermissionType `json:"permission"`
	Name        string         `json:"name"`
	Description string         `json:"description"`
}

This file defines which permissions exists and describes their attributes

type PermissionType

type PermissionType string
const (
	PermissionPower              PermissionType = "setPower"
	PermissionViewCameras        PermissionType = "viewCameras"
	PermissionLogs               PermissionType = "logs"
	PermissionManageUsers        PermissionType = "manageUsers"
	PermissionDebug              PermissionType = "debug"
	PermissionAutomation         PermissionType = "automation"
	PermissionScheduler          PermissionType = "scheduler"
	PermissionReminder           PermissionType = "reminder"
	PermissionModifyServerConfig PermissionType = "modifyServerConfig"
	PermissionModifyRooms        PermissionType = "modifyRooms"

	PermissionHomescript        PermissionType = "homescript"
	PermissionHomescriptNetwork PermissionType = "hmsNetwork"

	// Use with caution
	PermissionWildCard PermissionType = "*"
)

Different types of permissions

type PowerState

type PowerState struct {
	Switch  string `json:"switch"`
	PowerOn bool   `json:"powerOn"`
}

Contains the switch id and a matching boolean Used when requesting global power states

func GetPowerStates

func GetPowerStates() ([]PowerState, error)

Returns a list of PowerStates Can return a database error

type RedactedCamera added in v0.0.30

type RedactedCamera struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

Is used for listing available cameras without specifying sensitive information

func ListCamerasRedacted added in v0.0.30

func ListCamerasRedacted() ([]RedactedCamera, error)

Returns a list a list containing all cameras, just without the Url and RoomId Can be used to hide the confidential URL and roomId whilst still listing all cameras

type Reminder

type Reminder struct {
	Id                uint             `json:"id"`
	Name              string           `json:"name"`
	Description       string           `json:"description"`
	Priority          ReminderPriority `json:"priority"`
	CreatedDate       time.Time        `json:"createdDate"`
	DueDate           time.Time        `json:"dueDate"`
	Owner             string           `json:"owner"`
	UserWasNotified   bool             `json:"userWasNotified"` // Saves if the owner has been notified about the current urgency of the task
	UserWasNotifiedAt time.Time        `json:"userWasNotifiedAt"`
}

func GetReminderById

func GetReminderById(id uint, owner string) (Reminder, bool, error)

Given its id and owner, the function returns a reminder, if it was found and an error

func GetUserReminders

func GetUserReminders(username string) ([]Reminder, error)

Returns a slice of reminders which were set up by a given user

type ReminderPriority added in v0.0.49

type ReminderPriority uint
const (
	Low ReminderPriority = iota
	Normal
	Medium
	High
	Urgent
)

type Room

type Room struct {
	Data     RoomData `json:"data"`
	Switches []Switch `json:"switches"`
	Cameras  []Camera `json:"cameras"`
}

func ListAllRoomsWithData

func ListAllRoomsWithData() ([]Room, error)

Returns a complete list of rooms, includes its metadata like switches and cameras

func ListPersonalRoomsWithData

func ListPersonalRoomsWithData(username string) ([]Room, error)

Returns a complete list of rooms to which a user has access to, includes its metadata like switches and cameras

type RoomData

type RoomData struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

func GetRoomDataById

func GetRoomDataById(id string) (RoomData, bool, error)

Returns an arbitrary room given its id, whether it exists an a possible error

func ListRooms

func ListRooms() ([]RoomData, error)

Returns a list of room data

type Schedule

type Schedule struct {
	Id    uint         `json:"id"`
	Owner string       `json:"owner"`
	Data  ScheduleData `json:"data"`
}

func GetScheduleById

func GetScheduleById(id uint) (Schedule, bool, error)

Returns a schedule struct which matches the given id If the id does not match a struct, a `false“ is returned

func GetSchedules

func GetSchedules() ([]Schedule, error)

Returns a list of schedules of all users, used for activating schedules at the start of the server

func GetUserSchedules

func GetUserSchedules(username string) ([]Schedule, error)

Returns a list containing schedules of a given user

type ScheduleData added in v0.0.48

type ScheduleData struct {
	Name               string                  `json:"name"`
	Hour               uint                    `json:"hour"`
	Minute             uint                    `json:"minute"`
	TargetMode         ScheduleTargetMode      `json:"targetMode"`         // Specifies which actions are taken when the schedule is executed
	HomescriptCode     string                  `json:"homescriptCode"`     // Is read when using the `code` mode of the schedule
	HomescriptTargetId string                  `json:"homescriptTargetId"` // Is required when using the `hms` mode of the schedule
	SwitchJobs         []ScheduleSwitchJobData `json:"switchJobs"`
}

type ScheduleSwitchJob added in v0.0.49

type ScheduleSwitchJob struct {
	ScheduleId uint                  `json:"scheduleId"`
	Data       ScheduleSwitchJobData `json:"data"`
}

func ListAllScheduleSwitches added in v0.0.49

func ListAllScheduleSwitches() ([]ScheduleSwitchJob, error)

Returns a list of all schedule switches

func ListUserScheduleSwitches added in v0.0.49

func ListUserScheduleSwitches(username string) ([]ScheduleSwitchJob, error)

Returns a list of all schedule switch jobs owned by a given user

type ScheduleSwitchJobData added in v0.0.49

type ScheduleSwitchJobData struct {
	SwitchId string `json:"switchId"`
	PowerOn  bool   `json:"powerOn"`
}

func ListSwitchesOfSchedule added in v0.0.49

func ListSwitchesOfSchedule(scheduleId uint) ([]ScheduleSwitchJobData, error)

Returns a list of schedule switch jobs belonging to an arbitrary schedule

type ScheduleTargetMode added in v0.0.49

type ScheduleTargetMode string

Specifies which action will be performed as a target

const (
	ScheduleTargetModeCode     ScheduleTargetMode = "code"     // Will execute Homescript code as a target
	ScheduleTargetModeSwitches ScheduleTargetMode = "switches" // Will perform a series of power actions as a target
	ScheduleTargetModeHMS      ScheduleTargetMode = "hms"      // Will execute a Homescript by its id as a target
)

type ServerConfig

type ServerConfig struct {
	AutomationEnabled bool    `json:"automationEnabled"` // Sets the global state of the server's automation system
	LockDownMode      bool    `json:"lockDownMode"`      // If enabled, the server is unable to change power states and will not allow power actions
	Latitude          float32 `json:"latitude"`          // Specifies the physical location of the Smarthome server
	Longitude         float32 `json:"longitude"`         // Latitude and longitude are being used for calculating the sunset / sunrise times and for OpenWeatherMap's weather service
}

func GetServerConfiguration

func GetServerConfiguration() (ServerConfig, bool, error)

Retrieves the servers configuration

type Switch

type Switch struct {
	Id      string `json:"id"`
	Name    string `json:"name"`
	RoomId  string `json:"roomId"`
	PowerOn bool   `json:"powerOn"`
	Watts   uint16 `json:"watts"`
}

Identified by a Switch Id, has a name and belongs to a room

func GetSwitchById

func GetSwitchById(id string) (Switch, bool, error)

Returns an arbitrary switch given its id

func ListSwitches

func ListSwitches() ([]Switch, error)

Returns a list of all available switches with their attributes

func ListUserSwitches

func ListUserSwitches(username string) ([]Switch, error)

func ListUserSwitchesQuery

func ListUserSwitchesQuery(username string) ([]Switch, error)

Like `ListSwitches()` but takes a user string as a filter Only returns switches which are contained in the switch-permission table with the given user

type TimingMode

type TimingMode string

Represents the timing mode on which the automation operates

const (
	// Will not change, an automation will always execute based on this time
	TimingNormal TimingMode = "normal"
	// Uses the time of local sunrise
	// => Each run of a set automation will update the underlyingk time
	// => Each run will update and regenerate a cron-expression
	TimingSunrise TimingMode = "sunrise"
	// Same as above, just uses the time of local sunset
	TimingSunset TimingMode = "sunset"
)

type User

type User struct {
	Username          string `json:"username"`
	Forename          string `json:"forename"`
	Surname           string `json:"surname"`
	PrimaryColorDark  string `json:"primaryColorDark"`
	PrimaryColorLight string `json:"primaryColorLight"`
	SchedulerEnabled  bool   `json:"schedulerEnabled"`
	DarkTheme         bool   `json:"darkTheme"`
}

func GetUserByUsername

func GetUserByUsername(username string) (User, bool, error)

Returns a user struct based on a username, does not check if the user exists, additional checks needed beforehand

func ListUsers

func ListUsers() ([]User, error)

Lists users which are currently in the Database

type UserDetails

type UserDetails struct {
	User        User     `json:"user"`
	Permissions []string `json:"permissions"`
}

func GetUserDetails

func GetUserDetails(username string) (UserDetails, bool, error)

Returns the users information and their permissions

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL