models

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package models provides various abstractions/representations of real-world concepts or objects.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppInfo added in v1.1.0

type AppInfo struct {
	IsUpdateAvailable   bool
	LastUpdatedAt       time.Time
	LastCheckedUpdateAt time.Time
}

AppInfo holds information on the application.

type AuthToken

type AuthToken struct {
	ID            int64
	Selector      string
	HashValidator string
	Expires       time.Time
	UserID        int64
}

AuthToken holds details on an authentication token.

func NewAuthToken

func NewAuthToken(id int64, selector, hashValidator string, expiresSeconds, userID int64) *AuthToken

NewAuthToken creates a new AuthToken.

func (*AuthToken) IsExpired

func (a *AuthToken) IsExpired() bool

IsExpired verifies whether the auth token is expired.

type AzureVision

type AzureVision struct {
	ModelVersion  string `json:"modelVersion"`
	CaptionResult struct {
		Text       string  `json:"text"`
		Confidence float64 `json:"confidence"`
	} `json:"captionResult"`
	Metadata struct {
		Width  int `json:"width"`
		Height int `json:"height"`
	} `json:"metadata"`
	ReadResult struct {
		Blocks []struct {
			Lines []struct {
				Text            string `json:"text"`
				BoundingPolygon []struct {
					X int `json:"x"`
					Y int `json:"y"`
				} `json:"boundingPolygon"`
				Words []struct {
					Text            string `json:"text"`
					BoundingPolygon []struct {
						X int `json:"x"`
						Y int `json:"y"`
					} `json:"boundingPolygon"`
					Confidence float64 `json:"confidence"`
				} `json:"words"`
			} `json:"lines"`
		} `json:"blocks"`
	} `json:"readResult"`
}

AzureVision holds the data contained in the response of a call to the Computer Vision API's image analysis endpoint.

func (*AzureVision) Recipe

func (a *AzureVision) Recipe() Recipe

Recipe converts an AzureVision to a Recipe.

type Broker

type Broker struct {
	// contains filtered or unexported fields
}

Broker represents a client connection and its associated information.

func NewBroker

func NewBroker(userID int64, brokers map[int64]*Broker, conn *websocket.Conn) *Broker

NewBroker creates a new Broker instance for a specific user and adds it to the brokers map. The userID is used for identification and cleanup purposes.

func (*Broker) HideNotification

func (b *Broker) HideNotification()

HideNotification hides the websocket's frontend notification.

func (*Broker) SendFile

func (b *Broker) SendFile(fileName string, data *bytes.Buffer)

SendFile sends a file to the connected client.

func (*Broker) SendProgress

func (b *Broker) SendProgress(title string, value, numValues int)

SendProgress sends a progress update with a title and value to the client. The isToastVisible parameter controls whether the progress bar is displayed in a toast notification.

func (*Broker) SendProgressStatus

func (b *Broker) SendProgressStatus(title string, isToastVisible bool, value, numValues int)

SendProgressStatus sends a progress update with a title and value, optionally hiding the toast notification.

func (*Broker) SendToast

func (b *Broker) SendToast(toast Toast)

SendToast sends a toast notification to the user.

type Category

type Category struct {
	Value string
}

Category holds a recipe's category.

func (*Category) MarshalJSON

func (c *Category) MarshalJSON() ([]byte, error)

MarshalJSON encodes the category.

func (*Category) UnmarshalJSON

func (c *Category) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the category according to the schema (https://schema.org/recipeCategory). The schema specifies that the expected value is of type Text. However, some websites send the category in an array, which explains the need for this function.

type Cookbook

type Cookbook struct {
	ID      int64
	Count   int64
	Image   uuid.UUID
	Recipes Recipes
	Title   string
}

Cookbook is the struct that holds information on a cookbook.

func (Cookbook) DominantCategories

func (c Cookbook) DominantCategories(n int) []string

DominantCategories returns the `n` most common categories of recipes in the cookbook. If there are fewer than `n` categories, all categories are returned.

type CookingMethod

type CookingMethod struct {
	Value string
}

CookingMethod holds a recipe's category.

func (*CookingMethod) MarshalJSON

func (c *CookingMethod) MarshalJSON() ([]byte, error)

MarshalJSON encodes the cuisine.

func (*CookingMethod) UnmarshalJSON

func (c *CookingMethod) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the cooking method according to the schema (https://schema.org/cookingMethod). The schema specifies that the expected value is of type Text. However, some websites send the cuisine in an array, which explains the need for this function.

type Counts

type Counts struct {
	Cookbooks uint64
	Recipes   uint64
}

Counts holds the number of recipes and cookbooks.

type Cuisine

type Cuisine struct {
	Value string
}

Cuisine holds a recipe's category.

func (*Cuisine) MarshalJSON

func (c *Cuisine) MarshalJSON() ([]byte, error)

MarshalJSON encodes the cuisine.

func (*Cuisine) UnmarshalJSON

func (c *Cuisine) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the cuisine according to the schema (https://schema.org/recipeCuisine). The schema specifies that the expected value is of type Text. However, some websites send the cuisine in an array, which explains the need for this function.

type Description

type Description struct {
	Value string
}

Description holds a description.

func (*Description) MarshalJSON

func (d *Description) MarshalJSON() ([]byte, error)

MarshalJSON encodes the description.

func (*Description) UnmarshalJSON

func (d *Description) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the description field of a recipe.

type FileType

type FileType int64

FileType is an alias for a file type, e.g. JSON and PDF.

const (
	JSON FileType = iota
	PDF
	MXP
	TXT
	InvalidFileType
)

These constants enumerate all possible file types used by the software.

func NewFileType

func NewFileType(fileType string) FileType

NewFileType creates a FileType from the file type name.

func (FileType) Ext

func (f FileType) Ext() string

Ext returns the FileType's extension.

type Image

type Image struct {
	Value string
}

Image holds a recipe's image. The JSON fields correspond.

func (*Image) MarshalJSON

func (i *Image) MarshalJSON() ([]byte, error)

MarshalJSON encodes the image.

func (*Image) UnmarshalJSON

func (i *Image) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the image according to the schema (https://schema.org/image).

type Ingredients

type Ingredients struct {
	Values []string
}

Ingredients holds a recipe's list of ingredients.

func (*Ingredients) MarshalJSON

func (i *Ingredients) MarshalJSON() ([]byte, error)

MarshalJSON encodes the ingredients.

func (*Ingredients) UnmarshalJSON

func (i *Ingredients) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the ingredients according to the schema (https://schema.org/recipeInstructions).

type Instructions

type Instructions struct {
	Values []string
}

Instructions holds a recipe's list of instructions.

func (*Instructions) MarshalJSON

func (i *Instructions) MarshalJSON() ([]byte, error)

MarshalJSON encodes the list of instructions.

func (*Instructions) UnmarshalJSON

func (i *Instructions) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the instructions according to the schema (https://schema.org/recipeInstructions).

type Keywords

type Keywords struct {
	Values string
}

Keywords holds keywords as a single string.

func (*Keywords) MarshalJSON

func (k *Keywords) MarshalJSON() ([]byte, error)

MarshalJSON encodes the keywords.

func (*Keywords) UnmarshalJSON

func (k *Keywords) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the recipe's keywords according to the schema (https://schema.org/keywords). Some websites store the keywords in an array, which explains the need for a custom decoder.

type Message

type Message struct {
	Type     string `json:"type"`     // Message type, e.g. file.
	FileName string `json:"fileName"` // File name (applicable for "file" type).
	Data     string `json:"data"`     // Message data to pass. Base64-encoded if type is "file".
	Toast    Toast  `json:"toast"`    // Toast to display to the user.
}

Message represents the data format for file and progress updates sent to the client.

type NextcloudRecipes

type NextcloudRecipes struct {
	Category            string `json:"category"`
	DateCreated         string `json:"dateCreated"`
	DateModified        string `json:"dateModified"`
	ID                  int64  `json:"recipe_id"`
	ImagePlaceholderURL string `json:"imagePlaceholderUrl"`
	ImageURL            string `json:"imageUrl"`
	Keywords            string `json:"keywords"`
}

NextcloudRecipes holds a Nextcloud recipe's metadata obtained from the Nextcloud Cookbook's /recipes endpoint.

type NutrientFDC

type NutrientFDC struct {
	ID        int64
	Name      string
	Amount    float64
	UnitName  string
	Reference units.Measurement
}

NutrientFDC holds the nutrient data from the FDC database.

func (NutrientFDC) Value

func (n NutrientFDC) Value() float64

Value calculates the amount of the nutrient scaled to the reference, in grams.

type NutrientsFDC

type NutrientsFDC []NutrientFDC

NutrientsFDC is a type alias for a slice of NutrientFDC.

func (NutrientsFDC) NutritionFact

func (n NutrientsFDC) NutritionFact(weight float64) Nutrition

NutritionFact calculates the nutrition facts from the nutrients. The values in the nutrition table are per 100 grams. The weight is the sum of all ingredient quantities in grams.

type Nutrition

type Nutrition struct {
	Calories           string
	Cholesterol        string
	Fiber              string
	IsPerServing       bool
	Protein            string
	SaturatedFat       string
	Sodium             string
	Sugars             string
	TotalCarbohydrates string
	TotalFat           string
	UnsaturatedFat     string
}

Nutrition holds nutrition facts.

func (*Nutrition) Equal

func (n *Nutrition) Equal(other Nutrition) bool

Equal verifies whether the Nutrition struct is equal to the other.

func (*Nutrition) Scale added in v1.0.1

func (n *Nutrition) Scale(multiplier float64)

Scale scales the nutrition by the given multiplier.

func (*Nutrition) Schema

func (n *Nutrition) Schema(servings string) NutritionSchema

Schema creates the schema representation of the Nutrition.

type NutritionSchema

type NutritionSchema struct {
	Calories       string `json:"calories"`
	Carbohydrates  string `json:"carbohydrateContent"`
	Cholesterol    string `json:"cholesterolContent"`
	Fat            string `json:"fatContent"`
	Fiber          string `json:"fiberContent"`
	Protein        string `json:"proteinContent"`
	SaturatedFat   string `json:"saturatedFatContent"`
	Servings       string `json:"servingSize"`
	Sodium         string `json:"sodiumContent"`
	Sugar          string `json:"sugarContent"`
	TransFat       string `json:"transFatContent"`
	UnsaturatedFat string `json:"unsaturatedFatContent"`
}

NutritionSchema is a representation of the nutrition schema (https://schema.org/NutritionInformation).

func (*NutritionSchema) UnmarshalJSON

func (n *NutritionSchema) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the nutrition according to the schema.

type Progress

type Progress struct {
	Value int
	Total int
}

Progress represents a current value and the total number of values. It is used to calculate progress as a percentage.

type Recipe

type Recipe struct {
	Category     string
	CreatedAt    time.Time
	Cuisine      string
	Description  string
	ID           int64
	Image        uuid.UUID
	Ingredients  []string
	Instructions []string
	Keywords     []string
	Name         string
	Nutrition    Nutrition
	Times        Times
	Tools        []string
	UpdatedAt    time.Time
	URL          string
	Yield        int16
}

Recipe is the struct that holds a recipe's information.

func NewBaseRecipe added in v1.1.0

func NewBaseRecipe() Recipe

NewBaseRecipe creates a new, empty Recipe.

func NewRecipeFromTextFile added in v1.1.0

func NewRecipeFromTextFile(r io.Reader) (Recipe, error)

NewRecipeFromTextFile extracts the recipe from a text file.

func (*Recipe) ConvertMeasurementSystem

func (r *Recipe) ConvertMeasurementSystem(to units.System) (*Recipe, error)

ConvertMeasurementSystem converts a recipe to another units.System.

func (*Recipe) Copy

func (r *Recipe) Copy() Recipe

Copy deep copies the Recipe.

func (*Recipe) IsEmpty

func (r *Recipe) IsEmpty() bool

IsEmpty verifies whether all the Recipe fields are empty.

func (*Recipe) Normalize

func (r *Recipe) Normalize()

Normalize normalizes texts for readability. It normalizes quantities, i.e. 1l -> 1L and 1 ml -> 1 mL.

func (*Recipe) Scale

func (r *Recipe) Scale(yield int16)

Scale scales the recipe to the given yield.

func (*Recipe) Schema

func (r *Recipe) Schema() RecipeSchema

Schema creates the schema representation of the Recipe.

type RecipeSchema

type RecipeSchema struct {
	AtContext       string          `json:"@context"`
	AtType          SchemaType      `json:"@type"`
	Category        Category        `json:"recipeCategory"`
	CookTime        string          `json:"cookTime"`
	CookingMethod   CookingMethod   `json:"cookingMethod"`
	Cuisine         Cuisine         `json:"recipeCuisine"`
	DateCreated     string          `json:"dateCreated"`
	DateModified    string          `json:"dateModified"`
	DatePublished   string          `json:"datePublished"`
	Description     Description     `json:"description"`
	Keywords        Keywords        `json:"keywords"`
	Image           Image           `json:"image"`
	Ingredients     Ingredients     `json:"recipeIngredient"`
	Instructions    Instructions    `json:"recipeInstructions"`
	Name            string          `json:"name"`
	NutritionSchema NutritionSchema `json:"nutrition"`
	PrepTime        string          `json:"prepTime"`
	Tools           Tools           `json:"tool"`
	TotalTime       string          `json:"totalTime"`
	Yield           Yield           `json:"recipeYield"`
	URL             string          `json:"url"`
}

RecipeSchema is a representation of the Recipe schema (https://schema.org/Recipe).

func (*RecipeSchema) Recipe

func (r *RecipeSchema) Recipe() (*Recipe, error)

Recipe transforms the RecipeSchema to a Recipe.

type Recipes

type Recipes []Recipe

Recipes is the type for a slice of recipes.

func NewRecipesFromMasterCook

func NewRecipesFromMasterCook(r io.Reader) Recipes

NewRecipesFromMasterCook extracts the recipes from a MasterCook file.

func (Recipes) Categories

func (r Recipes) Categories() []string

Categories returns the category of every recipe. The resulting slice has no duplicates.

type Report added in v1.1.0

type Report struct {
	CreatedAt time.Time
	ExecTime  time.Duration
	ID        int64
	Logs      []ReportLog
	Type      ReportType
}

Report holds information on a report.

func NewReport added in v1.1.0

func NewReport(reportType ReportType) Report

NewReport creates a new, initialized and empty Report of the given ReportType.

type ReportLog added in v1.1.0

type ReportLog struct {
	Error     string
	ID        int64
	IsSuccess bool
	Title     string
}

ReportLog holds information on a report's log.

type ReportType added in v1.1.0

type ReportType int64

ReportType represents

const ImportReportType ReportType = 1

ImportReportType is the ReportType for importing recipes, either from files or the web.

type SchemaType

type SchemaType struct {
	Value string
}

SchemaType holds the type of the schema. It should be "Recipe".

func (*SchemaType) MarshalJSON

func (s *SchemaType) MarshalJSON() ([]byte, error)

MarshalJSON encodes the schema's type.

func (*SchemaType) UnmarshalJSON

func (s *SchemaType) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the type of the schema. The type "Recipe" will be searched for if the data is an array.

type SearchOptionsRecipes

type SearchOptionsRecipes struct {
	CookbookID   int64
	IsByName     bool
	IsFullSearch bool
	Page         uint64
	Sort         Sort
}

SearchOptionsRecipes defines the options for searching recipes.

func NewSearchOptionsRecipe added in v1.1.0

func NewSearchOptionsRecipe(mode, sort string, page uint64) SearchOptionsRecipes

NewSearchOptionsRecipe creates a SearchOptionsRecipe struct configured for the search method.

type Share

type Share struct {
	CookbookID int64
	Link       string
	RecipeID   int64
	UserID     int64
}

Share stores the ID of a recipe and the ID of the user who shared it.

type Sort added in v1.1.0

type Sort struct {
	IsAToZ bool
	IsZToA bool

	IsNewestToOldest bool
	IsOldestToNewest bool

	IsDefault bool
	IsRandom  bool
}

Sort defines sorting options.

func (*Sort) IsSort added in v1.1.0

func (s *Sort) IsSort() bool

IsSort verifies whether there is a sort option enabled.

type Times

type Times struct {
	Prep  time.Duration
	Cook  time.Duration
	Total time.Duration
}

Times holds a variety of intervals.

func NewTimes

func NewTimes(prep, cook string) (Times, error)

NewTimes creates a struct of Times from the Schema Duration fields for prep and cook time.

func (Times) Equal

func (t Times) Equal(other Times) bool

Equal verifies whether the Times is equal to the other Times.

type Toast added in v1.1.0

type Toast struct {
	Action     string `json:"action"`
	Background string `json:"background"`
	Message    string `json:"message"`
	Title      string `json:"title"`
}

Toast holds data related to a notification toast.

func NewErrorAuthToast added in v1.1.0

func NewErrorAuthToast(message string) Toast

NewErrorAuthToast creates an action-less error Toast with the title of "Auth Error".

func NewErrorDBToast added in v1.1.0

func NewErrorDBToast(message string) Toast

NewErrorDBToast creates an action-less error Toast with the title of "Database Error".

func NewErrorFilesToast added in v1.1.0

func NewErrorFilesToast(message string) Toast

NewErrorFilesToast creates an action-less error Toast with the title of "Files Error".

func NewErrorFormToast added in v1.1.0

func NewErrorFormToast(message string) Toast

NewErrorFormToast creates an action-less error Toast with the title of "Form Error".

func NewErrorGeneralToast added in v1.1.0

func NewErrorGeneralToast(message string) Toast

NewErrorGeneralToast creates an action-less error Toast with the title of "General Error".

func NewErrorReqToast added in v1.1.0

func NewErrorReqToast(message string) Toast

NewErrorReqToast creates an action-less error Toast with the title of "Request Error".

func NewErrorToast added in v1.1.0

func NewErrorToast(title, message, action string) Toast

NewErrorToast creates a new error notification.

func NewInfoToast added in v1.1.0

func NewInfoToast(title, message, action string) Toast

NewInfoToast creates a new info notification.

func NewWarningToast added in v1.1.0

func NewWarningToast(title, message, action string) Toast

NewWarningToast creates a new warning notification.

func NewWarningWSToast added in v1.1.0

func NewWarningWSToast(message string) Toast

NewWarningWSToast creates an action-less warning Toast with the title of "Websocket".

func (Toast) Render added in v1.1.0

func (t Toast) Render() string

Render returns the JSON encoding of the toast.

type Tools

type Tools struct {
	Values []string
}

Tools holds the list of tools used for a recipe.

func (*Tools) MarshalJSON

func (t *Tools) MarshalJSON() ([]byte, error)

MarshalJSON encodes the list of tools.

func (*Tools) UnmarshalJSON

func (t *Tools) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the tools according to the schema (https://schema.org/tool).

type User

type User struct {
	ID    int64
	Email string
}

User holds data related to a user.

type UserBackup added in v1.1.0

type UserBackup struct {
	DeleteSQL  string
	ImagesPath string
	InsertSQL  string
	Recipes    Recipes
	UserID     int64
}

UserBackup holds components related to a user backup.

type UserSettings

type UserSettings struct {
	CalculateNutritionFact bool
	ConvertAutomatically   bool
	CookbooksViewMode      ViewMode
	MeasurementSystem      units.System
}

UserSettings holds the user's settings.

func (*UserSettings) IsCalculateNutrition

func (u *UserSettings) IsCalculateNutrition(recipe *Recipe) bool

IsCalculateNutrition verifies whether the nutrition facts should be calculated for the recipe.

type ViewMode

type ViewMode int

ViewMode is an integer type alias for various data view modes.

const (
	GridViewMode ViewMode = iota
	ListViewMode
)

These constants enumerate all possible viewing modes.

func ViewModeFromInt

func ViewModeFromInt(num int64) ViewMode

ViewModeFromInt returns the ViewMode for the respective integer.

func ViewModeFromString

func ViewModeFromString(s string) ViewMode

ViewModeFromString returns the ViewMode for the respective string.

type Website

type Website struct {
	ID   int64
	Host string
	URL  string
}

Website represents a website with its hostname and URL.

type Websites

type Websites []Website

Websites is the type for a slice of Website.

func (Websites) TableHTML

func (w Websites) TableHTML() string

TableHTML renders the websites to a string of table rows.

type Yield

type Yield struct {
	Value int16
}

Yield holds a recipe's yield.

func (*Yield) MarshalJSON

func (y *Yield) MarshalJSON() ([]byte, error)

MarshalJSON encodes the value of the yield.

func (*Yield) UnmarshalJSON

func (y *Yield) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the yield according to the schema (https://schema.org/recipeYield).

Jump to

Keyboard shortcuts

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