homescript

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2023 License: GPL-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const IO_WRITER_BYTES_CAP = 5 * 1_000_000 // X * 1 Megabyte

Variables

This section is empty.

Functions

func ActivateAutomationSystem added in v0.8.0

func ActivateAutomationSystem() error

Activates all jobs saved in the database, will be used when the server was restarted If a non-critical error occurs, for example the failure to setup a job, it will be returned This function will not cancel directly if an error occurs in order to preserve the automation system's uptime

func CreateNewAutomation added in v0.8.0

func CreateNewAutomation(
	name string,
	description string,
	hour uint8,
	minute uint8,
	days []uint8,
	homescriptId string,
	owner string,
	enabled bool,
	timingMode database.TimingMode,
) (uint, error)

Creates a new automation which an according database entry Sets up the scheduler based on the provided hour, minute, and days of the week on which the automation should run

func CreateNewSchedule added in v0.8.0

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

Creates and starts a schedule based on the provided input data

func DeactivateAutomationSystem added in v0.8.0

func DeactivateAutomationSystem() error

Stops all jobs in the automation scheduler

func GetUserScheduleById added in v0.8.0

func GetUserScheduleById(username string, id uint) (database.Schedule, bool, error)

Gets a schedule based on its id and its owner's username

func HasDependentAutomations added in v0.0.30

func HasDependentAutomations(homescriptId string) (bool, error)

Checks whether a given Homescript has automations which rely on it Is used to decide whether a Homescript is safe to delete or not

func InitAutomations added in v0.8.0

func InitAutomations() error

Initializes the scheduler

func InitLogger

func InitLogger(logger *logrus.Logger)

func InitManager added in v0.0.47

func InitManager()

Initializes the Homescript manager

func InitScheduler added in v0.8.0

func InitScheduler() error

func ModifyAutomationById added in v0.8.0

func ModifyAutomationById(automationId uint, newAutomation database.AutomationData) error

Changes the metadata of a given automation, then restarts it so that it uses the updated values such as execution time Is also used after an automation with non-normal timing has been added

func ModifyScheduleById added in v0.8.0

func ModifyScheduleById(id uint, newSchedule database.ScheduleData) error

Modify an already set up schedule After the modification was performed, the schedule is restarted

func RemoveAutomation added in v0.8.0

func RemoveAutomation(automationId uint) error

Removes an automation from the database and prevents its further execution

func RemoveScheduleById added in v0.8.0

func RemoveScheduleById(id uint) error

Aborts and deletes a schedule based on its id

func StartUrlCacheGC added in v0.0.52

func StartUrlCacheGC() error

Sets up a scheduler which triggers the flushing of the HMS URL cache every 12 hours

func UpdateJobTime added in v0.8.0

func UpdateJobTime(id uint, useSunRise bool) error

Given a jobId and whether sunrise or sunset should is activated, the next execution time is modified Used when an automation with non-normal Timing-Mode is executed in order to update its next start time

Types

type AnalyzerExecutor added in v0.4.1

type AnalyzerExecutor struct {
	Username string
}

func (AnalyzerExecutor) Exec added in v0.4.1

func (self AnalyzerExecutor) Exec(homescriptId string, args map[string]string) (homescript.ExecResponse, error)

Executes another Homescript based on its Id

func (*AnalyzerExecutor) Get added in v0.4.1

func (self *AnalyzerExecutor) Get(requestUrl string) (homescript.HttpResponse, error)

func (*AnalyzerExecutor) GetStorage added in v0.8.0

func (self *AnalyzerExecutor) GetStorage(key string) (*string, error)

func (*AnalyzerExecutor) GetSwitch added in v0.4.1

func (self *AnalyzerExecutor) GetSwitch(switchId string) (homescript.SwitchResponse, error)

func (*AnalyzerExecutor) GetUser added in v0.4.1

func (self *AnalyzerExecutor) GetUser() string

Returns the name of the user who is currently running the script

func (*AnalyzerExecutor) GetWeather added in v0.4.1

func (self *AnalyzerExecutor) GetWeather() (homescript.Weather, error)

func (*AnalyzerExecutor) Http added in v0.4.1

func (self *AnalyzerExecutor) Http(
	requestUrl string,
	method string,
	body string,
	headers map[string]string,
	cookies map[string]string,
) (homescript.HttpResponse, error)

func (AnalyzerExecutor) IsAnalyzer added in v0.8.0

func (self AnalyzerExecutor) IsAnalyzer() bool

func (*AnalyzerExecutor) Log added in v0.4.1

func (self *AnalyzerExecutor) Log(
	title string,
	description string,
	level homescript.LogLevel,
) error

func (*AnalyzerExecutor) Notify added in v0.4.1

func (self *AnalyzerExecutor) Notify(
	title string,
	description string,
	level homescript.NotificationLevel,
) error

func (*AnalyzerExecutor) Ping added in v0.4.1

func (self *AnalyzerExecutor) Ping(ip string, timeoutSecs float64) (bool, error)

func (*AnalyzerExecutor) Print added in v0.4.1

func (self *AnalyzerExecutor) Print(args ...string) error

func (*AnalyzerExecutor) Println added in v0.4.1

func (self *AnalyzerExecutor) Println(args ...string) error

func (*AnalyzerExecutor) ReadFile added in v0.8.0

func (self *AnalyzerExecutor) ReadFile(path string) (string, error)

Resolves a Homescript module

func (*AnalyzerExecutor) Remind added in v0.6.0

func (self *AnalyzerExecutor) Remind(
	title string,
	description string,
	urgency homescript.ReminderUrgency,
	dueDate time.Time,
) (uint, error)

func (*AnalyzerExecutor) ResolveModule added in v0.4.1

func (self *AnalyzerExecutor) ResolveModule(id string) (string, string, bool, bool, error)

Resolves a Homescript module

func (*AnalyzerExecutor) SetStorage added in v0.8.0

func (self *AnalyzerExecutor) SetStorage(key string, value string) error

func (*AnalyzerExecutor) Sleep added in v0.4.1

func (self *AnalyzerExecutor) Sleep(seconds float64)

func (*AnalyzerExecutor) Switch added in v0.4.1

func (self *AnalyzerExecutor) Switch(switchId string, powerOn bool) error

type ApiJob added in v0.0.59

type ApiJob struct {
	Id           uint64              `json:"id"`
	Initiator    HomescriptInitiator `json:"initiator"`
	HomescriptId string              `json:"homescriptId"`
}

type Automation added in v0.8.0

type Automation struct {
	Id              uint                `json:"id"`
	Name            string              `json:"name"`
	Description     string              `json:"description"`
	CronExpression  string              `json:"cronExpression"`
	CronDescription string              `json:"cronDescription"`
	HomescriptId    string              `json:"homescriptId"`
	Owner           string              `json:"owner"`
	Enabled         bool                `json:"enabled"`
	DisableOnce     bool                `json:"disableOnce"`
	TimingMode      database.TimingMode `json:"timingMode"`
}

func GetUserAutomationById added in v0.8.0

func GetUserAutomationById(username string, automationId uint) (Automation, bool, error)

Given an username and id, it returns a matching automation, whether it exists and an error

func GetUserAutomations added in v0.8.0

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

Returns a slice of automations which a given user has set up Does not check the validity of the user

type Executor

type Executor struct {
	// Is required for error handling and recursion prevention
	// Allows pretty-print for potential errors
	ScriptName string

	// Specifies the time a script was started
	// Can be used to keep track of the script's runtime
	StartTime time.Time

	// The Username is required for functions which rely on permissions-check
	// or need to access the username for other reasons, e.g. `notify`
	Username string

	// Output writer for asynchronous Homescript output (for example via the Web-UI)
	OutputWriter io.Writer

	// How many bytes were already written to the io writer
	BytesWritten uint

	// If set to true, a script will only check its correctness
	// Does not actually modify or wait for any data
	DryRun bool

	// Holds the script's arguments as a map
	// Is filled by a helper function like `Run`
	// Is used by the `CheckArg` and `GetArg` methods for providing args
	Args map[string]string

	// The CallStack saves the history of which script called another
	// Additionally, it specifies which Homescripts have to be excluded from the `exec` function
	// Is required in order to prevent recursion until the system's database runs out of resources
	// Acts like a blacklist which holds the blacklisted Homescript ids
	// The last item in the CallStack is the script which was called the most recently (from script exit)
	CallStack []string

	// Sigterm receiver which is visible to the outside
	// Any signal will be forwarded to the internal `sigTermPtr`
	SigTerm chan int

	// Is set to true as soon as a sigTerm is received
	// Is required and read by the manager's run functions and by HMS `exec` calls
	// Used in order to determine whether a script has been terminated using a sigTerm or if it exited conventionally
	WasTerminated bool

	// Specifies if the executor is currently inside a builtin function
	// Is required in the manager to dispatch the sigTerm to the correct channel
	InExpensiveBuiltin struct {
		Mutex sync.Mutex
		Value bool
	}
	// contains filtered or unexported fields
}

func (*Executor) Exec

func (self *Executor) Exec(homescriptId string, args map[string]string) (homescript.ExecResponse, error)

Executes another Homescript based on its Id

func (*Executor) Get added in v0.0.33

func (self *Executor) Get(requestUrl string) (homescript.HttpResponse, error)

Makes a GET request to an arbitrary URL and returns the result

func (*Executor) GetStorage added in v0.8.0

func (self *Executor) GetStorage(key string) (*string, error)

func (*Executor) GetSwitch added in v0.4.1

func (self *Executor) GetSwitch(switchId string) (homescript.SwitchResponse, error)

Returns an object with contains data about the requested switch Returns an error if the provided switch does not exist

func (*Executor) GetUser

func (self *Executor) GetUser() string

Returns the name of the user who is currently running the script

func (*Executor) GetWeather

func (self *Executor) GetWeather() (homescript.Weather, error)

func (*Executor) Http added in v0.0.33

func (self *Executor) Http(requestUrl string, method string, body string, headers map[string]string, cookies map[string]string) (homescript.HttpResponse, error)

Makes a request to an arbitrary URL using a custom method and body in order to return the result

func (*Executor) IsAnalyzer added in v0.8.0

func (self *Executor) IsAnalyzer() bool

func (*Executor) Log

func (self *Executor) Log(
	title string,
	description string,
	level homescript.LogLevel,
) error

Adds a log entry to the internal logging system

func (*Executor) Notify

func (self *Executor) Notify(
	title string,
	description string,
	level homescript.NotificationLevel,
) error

Sends a notification to the user who issues this command

func (*Executor) Ping added in v0.0.57

func (self *Executor) Ping(ip string, timeoutSecs float64) (bool, error)

Performs a ICMP ping and returns a boolean which states whether the target host is online or offline

func (*Executor) Print

func (self *Executor) Print(args ...string) error

Emulates printing to the console Instead, appends the provided message to the output of the executor Exists in order to return the script's output to the user

func (*Executor) Println added in v0.4.1

func (self *Executor) Println(args ...string) error

Emulates printing to the console Instead, appends the provided message to the output of the executor Exists in order to return the script's output to the user Just like `Print` but appends a newline to the end

func (*Executor) ReadFile added in v0.8.0

func (self *Executor) ReadFile(path string) (string, error)

Resolves a Homescript module

func (*Executor) Remind added in v0.6.0

func (self *Executor) Remind(
	title string,
	description string,
	urgency homescript.ReminderUrgency,
	dueDate time.Time,
) (uint, error)

Add a reminder to the user's reminders.

func (*Executor) ResolveModule added in v0.4.1

func (self *Executor) ResolveModule(id string) (string, string, bool, bool, error)

Resolves a Homescript module

func (*Executor) SetStorage added in v0.8.0

func (self *Executor) SetStorage(key string, value string) error

func (*Executor) Sleep added in v0.0.46

func (self *Executor) Sleep(seconds float64)

Pauses the execution of the current script for the amount of the specified seconds Implements special checks to cancel the sleep function during its execution

func (*Executor) Switch

func (self *Executor) Switch(switchId string, powerOn bool) error

Changes the power state of an arbitrary switch Checks if the switch exists, if the user is allowed to interact with switches and if the user has the matching switch-permission If a check fails, an error is returned

type HmsError added in v0.4.1

type HmsError struct {
	Kind         string         `json:"kind"`
	Message      string         `json:"message"`
	Span         hmsErrors.Span `json:"span"`
	FileContents string         `json:"code"`
}

type HmsExecRes added in v0.4.1

type HmsExecRes struct {
	ReturnValue   homescript.Value
	RootScope     map[string]*homescript.Value
	ExitCode      int
	WasTerminated bool
	Errors        []HmsError
}

type HomescriptInitiator added in v0.0.47

type HomescriptInitiator string
var (
	InitiatorAutomation HomescriptInitiator = "automation"
	InitiatorScheduler  HomescriptInitiator = "scheduler"
	InitiatorExec       HomescriptInitiator = "exec_target"
	InitiatorInternal   HomescriptInitiator = "internal"
	InitiatorAPI        HomescriptInitiator = "api"
	InitiatorWidget     HomescriptInitiator = "widget"
)

type HomescriptWithArguments added in v0.0.40

type HomescriptWithArguments struct {
	Data      database.Homescript      `json:"data"`
	Arguments []database.HomescriptArg `json:"arguments"`
}

func ListPersonalHomescriptWithArgs added in v0.0.40

func ListPersonalHomescriptWithArgs(username string) ([]HomescriptWithArguments, error)

Returns a slice containing the user's Homescripts Each Homescript also contains its arguments as a slice

type Job added in v0.0.47

type Job struct {
	Id        uint64              `json:"id"`
	Initiator HomescriptInitiator `json:"initiator"`
	Executor  *Executor           `json:"executor"`
}

type Manager added in v0.0.47

type Manager struct {
	Lock sync.RWMutex
	Jobs []Job
}
var HmsManager Manager

Global manager

func (*Manager) Analyze added in v0.4.1

func (m *Manager) Analyze(
	scriptLabel string,
	scriptCode string,
	callStack []string,
	initiator HomescriptInitiator,
	username string,
	moduleStack []string,
	moduleName string,
) []HmsError

func (*Manager) AnalyzeById added in v0.4.1

func (m *Manager) AnalyzeById(
	scriptId string,
	username string,
	callStack []string,
	initiator HomescriptInitiator,
) ([]HmsError, error)

func (*Manager) GetJobById added in v0.0.47

func (m *Manager) GetJobById(jobId uint64) (Job, bool)

Returns a job given its ID

func (*Manager) GetJobList added in v0.0.51

func (m *Manager) GetJobList() []Job

Can be used to access the manager's jobs from the outside in a safe manner

func (*Manager) GetUserDirectJobs added in v0.0.59

func (m *Manager) GetUserDirectJobs(username string) []ApiJob

Returns just the jobs which are executed by the specified user Filter out any indirect runtimes which are managed by this manager

func (*Manager) Kill added in v0.0.47

func (m *Manager) Kill(jobId uint64) bool

Terminates a job given its internal job ID This method operates on all types of run-type The returned boolean indicates whether a job was killed or not

func (*Manager) KillAllId added in v0.0.47

func (m *Manager) KillAllId(hmsId string) (count uint64, success bool)

Terminates all jobs which are executing a given Homescript-ID / Homescript-label The returned boolean indicates whether a job was killed or not

func (*Manager) PushJob added in v0.0.47

func (m *Manager) PushJob(
	executor *Executor,
	initiator HomescriptInitiator,
	idReceiver chan uint64,
) uint64

func (*Manager) Run added in v0.0.47

func (m *Manager) Run(
	username string,
	scriptLabel string,
	scriptCode string,
	arguments map[string]string,
	callStack []string,
	initiator HomescriptInitiator,
	sigTerm chan int,
	outputWriter io.Writer,
	idChan *chan uint64,
) HmsExecRes

Executes arbitrary Homescript-code as a given user, returns the output and a possible error slice The `scriptLabel` argument is used internally to allow for better error-display The `excludedCalls` argument specifies which Homescripts may not be called by this Homescript in order to prevent recursion

func (*Manager) RunById added in v0.0.47

func (m *Manager) RunById(
	scriptId string,
	username string,
	callStack []string,
	arguments map[string]string,
	initiator HomescriptInitiator,
	sigTerm chan int,
	outputWriter io.Writer,
	idChan *chan uint64,
) (HmsExecRes, error)

Executes a given Homescript from the database and returns its output, exit-code and possible error

type UserSchedule added in v0.8.0

type UserSchedule struct {
	Id             uint   `json:"id"`
	Name           string `json:"name"`
	Hour           uint   `json:"hour"`
	Minute         uint   `json:"minute"`
	NextRun        string `json:"nextRun"`
	HomescriptCode string `json:"homescriptCode"` // Will be executed if the scheduler runs the job
}

Used for listing personal schedules

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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