database

package
v1.18.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2024 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PasswordMinimumLength = 4
	PasswordMaximumLength = 128
	UsernameMinimumLength = 1
	UsernameMaximumLength = 32
)

Variables

View Source
var (
	ErrPasswordInvalidLength = errors.New("password has invalid length")
	ErrUsernameInvalidLength = errors.New("username has invalid length")
	ErrUsernameInvalid       = errors.New("username is not valid")
	ErrNoUser                = errors.New("no user attached")
)
View Source
var ErrInvalidData = errors.New("could not convert data to a GPX structure")
View Source
var ErrUnsuportedDriver = errors.New("unsupported driver")

Functions

func Connect

func Connect(driver, dsn string, debug bool, logger *slog.Logger) (*gorm.DB, error)

Types

type BreakdownItem added in v0.13.0

type BreakdownItem struct {
	UnitCount     float64       // Count of the unit per item
	UnitName      string        // Unit name
	Counter       int           // Counter of this item in the list of items
	Distance      float64       // Distance in this item
	TotalDistance float64       // Total distance in all items up to and including this item
	Duration      time.Duration // Duration in this item
	TotalDuration time.Duration // Total duration in all items up to and including this item
	Speed         float64       // Speed in this item
	FirstPoint    *MapPoint     // First GPS point in this item
	LastPoint     *MapPoint     // Last GPS point in this item
	IsBest        bool          // Whether this item is the best of the list
	IsWorst       bool          // Whether this item is the worst of the list
}

func (*BreakdownItem) CalcultateSpeed added in v0.13.0

func (bi *BreakdownItem) CalcultateSpeed()

type Bucket added in v0.11.3

type Bucket struct {
	Bucket              string        `json:",omitempty"` // The name of the bucket
	WorkoutType         WorkoutType   // The type of the workout
	Workouts            int           // The number of workouts in the bucket
	Distance            float64       `json:",omitempty"` // The total distance in the bucket
	Up                  float64       `json:",omitempty"` // The total up elevation in the bucket
	Duration            time.Duration `json:",omitempty"` // The total duration in the bucket
	AverageSpeed        float64       `json:",omitempty"` // The average speed in the bucket
	AverageSpeedNoPause float64       `json:",omitempty"` // The average speed without pause in the bucket
	MaxSpeed            float64       `json:",omitempty"` // The max speed in the bucket
}

Bucket is the consolidation of workout information for a given time bucket

type Config added in v0.13.4

type Config struct {
	gorm.Model

	// These options can be changed at runtime, configured through the database
	// If they are set through the environment to a non-default value, that will
	// take precedence
	RegistrationDisabled bool `mapstructure:"registration_disabled" form:"registration_disabled"`
	SocialsDisabled      bool `mapstructure:"socials_disabled" form:"socials_disabled"`

	// These options are read from the config file or environment only
	Logging          bool   `mapstructure:"logging" gorm:"-"`
	Debug            bool   `mapstructure:"debug" gorm:"-"`
	Bind             string `mapstructure:"bind" gorm:"-"`
	JWTEncryptionKey string `mapstructure:"jwt_encryption_key" gorm:"-"`
	DatabaseDriver   string `mapstructure:"database_driver" gorm:"-"`
	DSN              string `mapstructure:"dsn" gorm:"-"`
}

func (*Config) Save added in v0.13.4

func (c *Config) Save(db *gorm.DB) error

func (*Config) UpdateFromDatabase added in v0.13.4

func (c *Config) UpdateFromDatabase(db *gorm.DB) error

type Equipment added in v0.15.1

type Equipment struct {
	gorm.Model
	Name        string        `gorm:"not null;uniqueIndex" json:"name" form:"name"`          // The name of the gear
	UserID      uint          `gorm:"not null;index"`                                        // The ID of the user who owns the workout
	Description string        `gorm:"" json:"description" form:"description"`                // More information about the equipment
	Active      bool          `gorm:"default:true" json:"active" form:"active"`              // Whether this equipment is active
	DefaultFor  []WorkoutType `gorm:"serializer:json;column:default_for" form:"default_for"` // Which workout types to add this equipment by default

	User     User
	Workouts []Workout `gorm:"many2many:workout_equipment"`
	// contains filtered or unexported fields
}

func GetEquipment added in v0.15.1

func GetEquipment(db *gorm.DB, id int) (*Equipment, error)

func GetEquipmentByIDs added in v0.15.1

func GetEquipmentByIDs(db *gorm.DB, userID uint, ids []uint) ([]*Equipment, error)

func (*Equipment) Delete added in v0.15.1

func (e *Equipment) Delete(db *gorm.DB) error

func (*Equipment) GetTotals added in v0.15.1

func (e *Equipment) GetTotals() (WorkoutTotals, error)

func (*Equipment) Save added in v0.15.1

func (e *Equipment) Save(db *gorm.DB) error

func (*Equipment) SetDB added in v0.15.1

func (e *Equipment) SetDB(db *gorm.DB)

func (*Equipment) ValidFor added in v0.15.1

func (e *Equipment) ValidFor(wt *WorkoutType) bool

type ExtraMetrics added in v0.15.0

type ExtraMetrics map[string]float64

func (ExtraMetrics) Get added in v0.15.0

func (em ExtraMetrics) Get(key string) float64

func (ExtraMetrics) ParseGPXExtensions added in v0.15.0

func (em ExtraMetrics) ParseGPXExtensions(extension gpx.Extension)

func (ExtraMetrics) Set added in v0.15.0

func (em ExtraMetrics) Set(key string, value float64)

type GPXData added in v0.10.0

type GPXData struct {
	gorm.Model
	WorkoutID uint   `gorm:"not null;uniqueIndex"` // The ID of the workout
	Content   []byte `gorm:"type:text"`            // The file content
	Checksum  []byte `gorm:"not null;uniqueIndex"` // The checksum of the content
	Filename  string // The filename of the file
}

func (*GPXData) Save added in v0.10.0

func (d *GPXData) Save(db *gorm.DB) error

type MapCenter

type MapCenter struct {
	Lat float64 // The latitude of the center of the workout
	Lng float64 // The longitude of the center of the workout
}

func (*MapCenter) Address

func (m *MapCenter) Address() *geo.Address

func (*MapCenter) IsZero added in v1.17.1

func (m *MapCenter) IsZero() bool

type MapData

type MapData struct {
	gorm.Model
	WorkoutID        uint            `gorm:"not null;uniqueIndex"` // The workout this data belongs to
	Creator          string          // The tool that created this workout
	Name             string          // The name of the workout
	Center           MapCenter       `gorm:"serializer:json"` // The center of the workout (in coordinates)
	Address          *geo.Address    `gorm:"serializer:json"` // The address of the workout
	AddressString    string          // The generic location of the workout
	TotalDistance    float64         // The total distance of the workout
	TotalDuration    time.Duration   // The total duration of the workout
	MaxSpeed         float64         // The maximum speed of the workout
	PauseDuration    time.Duration   // The total pause duration of the workout
	MinElevation     float64         // The minimum elevation of the workout
	MaxElevation     float64         // The maximum elevation of the workout
	TotalUp          float64         // The total distance up of the workout
	TotalDown        float64         // The total distance down of the workout
	Details          *MapDataDetails `json:",omitempty"` // The details of the workout
	TotalRepetitions int             // The number of repetitions of the workout
	TotalWeight      float64         // The weight of the workout
}

func (*MapData) AverageSpeed

func (m *MapData) AverageSpeed() float64

func (*MapData) AverageSpeedNoPause

func (m *MapData) AverageSpeedNoPause() float64

func (*MapData) Save added in v0.11.0

func (m *MapData) Save(db *gorm.DB) error

func (*MapData) UpdateAddress added in v1.17.0

func (m *MapData) UpdateAddress()

type MapDataDetails added in v0.11.0

type MapDataDetails struct {
	gorm.Model
	MapDataID uint       // The ID of the map data these details belong to
	Points    []MapPoint `gorm:"serializer:json"` // The GPS points of the workout
}

func (*MapDataDetails) Save added in v0.11.0

func (d *MapDataDetails) Save(db *gorm.DB) error

type MapPoint

type MapPoint struct {
	Lat           float64       // The latitude of the point
	Lng           float64       // The longitude of the point
	Distance      float64       // The distance from the previous point
	TotalDistance float64       // The total distance of the workout up to this point
	Duration      time.Duration // The duration from the previous point
	TotalDuration time.Duration // The total duration of the workout up to this point
	Time          time.Time     // The time the point was recorded

	ExtraMetrics ExtraMetrics // Extra metrics at this point
}

func (*MapPoint) AverageSpeed

func (m *MapPoint) AverageSpeed() float64

type Profile

type Profile struct {
	gorm.Model
	UserID              uint        // The ID of the user who owns this profile
	APIActive           bool        `form:"api_active"`            // Whether the user's API key is active
	Language            string      `form:"language"`              // The user's preferred language
	TotalsShow          WorkoutType `form:"totals_show"`           // What workout type of totals to show
	Timezone            string      `form:"timezone"`              // The user's preferred timezone
	AutoImportDirectory string      `form:"auto_import_directory"` // The user's preferred directory for auto-import
	SocialsDisabled     bool        `form:"socials_disabled"`      // Whether social sharing buttons are disabled when viewing a workout
	PreferFullDate      bool        `form:"prefer_full_date"`      // Whether to show full dates in the workout details

	PreferredUnits UserPreferredUnits `gorm:"serializer:json"` // The user's preferred units

	User *User `gorm:"foreignKey:UserID" json:"-"` // The user who owns this profile
}

func (*Profile) CanImportFromDirectory added in v0.10.5

func (p *Profile) CanImportFromDirectory() (bool, error)

func (*Profile) ResetBools added in v1.15.2

func (p *Profile) ResetBools()

func (*Profile) Save

func (p *Profile) Save(db *gorm.DB) error

type StatConfig added in v0.11.3

type StatConfig struct {
	Since string `query:"since"`
	Per   string `query:"per"`
}

func (*StatConfig) GetBucketFormatExpression added in v0.13.0

func (sc *StatConfig) GetBucketFormatExpression(sqlDialect string) string

func (*StatConfig) GetBucketString added in v0.11.3

func (sc *StatConfig) GetBucketString(sqlDialect string) string

func (*StatConfig) GetDateLimitExpression added in v0.13.0

func (sc *StatConfig) GetDateLimitExpression(sqlDialect string) string

func (*StatConfig) GetSince added in v0.11.3

func (sc *StatConfig) GetSince() string

type Statistics added in v0.11.3

type Statistics struct {
	UserID       uint                              // The user ID
	BucketFormat string                            // The bucket format in strftime format
	Buckets      map[WorkoutType]map[string]Bucket // The statistics buckets
}

Statistics represents the statistics for a user for a given time range and bucket size, per workout type

type User

type User struct {
	gorm.Model

	LastVersion string `gorm:"last_version"` // Which version of the app the user has last seen and acknowledged

	Password string `form:"-"        gorm:"type:varchar(128);not null"`            // The user's password as bcrypt hash
	Salt     string `form:"-"        gorm:"type:varchar(16);not null"`             // The salt used to hash the user's password
	Username string `form:"username" gorm:"uniqueIndex;not null;type:varchar(32)"` // The user's username
	Name     string `form:"name"     gorm:"type:varchar(64);not null"`             // The user's name
	APIKey   string `gorm:"type:varchar(32)"`                                      // The user's API key
	Active   bool   `form:"active"`                                                // Whether the user is active
	Admin    bool   `form:"admin"`                                                 // Whether the user is an admin

	Profile   Profile     // The user's profile settings
	Workouts  []Workout   `json:"-"` // The user's workouts
	Equipment []Equipment `json:"-"` // The user's equipment
	// contains filtered or unexported fields
}

func GetUser

func GetUser(db *gorm.DB, username string) (*User, error)

func GetUserByAPIKey added in v0.11.1

func GetUserByAPIKey(db *gorm.DB, key string) (*User, error)

func GetUserByID

func GetUserByID(db *gorm.DB, userID int) (*User, error)

func GetUsers

func GetUsers(db *gorm.DB) ([]User, error)

func (*User) APIActive added in v0.9.2

func (u *User) APIActive() bool

func (*User) AddSalt

func (u *User) AddSalt(password string) string

func (*User) AddWorkout

func (u *User) AddWorkout(db *gorm.DB, workoutType WorkoutType, notes string, filename string, content []byte) (*Workout, error)

func (*User) BeforeSave

func (u *User) BeforeSave(_ *gorm.DB) error

func (*User) Create

func (u *User) Create(db *gorm.DB) error

func (*User) Delete

func (u *User) Delete(db *gorm.DB) error

func (*User) GenerateAPIKey added in v0.9.2

func (u *User) GenerateAPIKey(force bool)

func (*User) GenerateSalt

func (u *User) GenerateSalt()

func (*User) GetAllEquipment added in v0.15.1

func (u *User) GetAllEquipment(db *gorm.DB) ([]*Equipment, error)

func (*User) GetAllRecords added in v0.12.0

func (u *User) GetAllRecords() ([]*WorkoutRecord, error)

func (*User) GetDefaultStatistics added in v0.12.0

func (u *User) GetDefaultStatistics() (*Statistics, error)

func (*User) GetDefaultTotals added in v0.12.0

func (u *User) GetDefaultTotals() (*Bucket, error)

func (*User) GetEquipment added in v0.15.1

func (u *User) GetEquipment(db *gorm.DB, id int) (*Equipment, error)

func (*User) GetHighestWorkoutType added in v0.14.1

func (u *User) GetHighestWorkoutType() (*WorkoutType, error)

func (*User) GetRecords added in v0.11.3

func (u *User) GetRecords(t WorkoutType) (*WorkoutRecord, error)

func (*User) GetStatistics added in v0.11.3

func (u *User) GetStatistics(statConfig StatConfig) (*Statistics, error)

func (*User) GetStatisticsFor added in v0.12.3

func (u *User) GetStatisticsFor(since, per string) (*Statistics, error)

func (*User) GetTotals added in v0.11.3

func (u *User) GetTotals(t WorkoutType) (*Bucket, error)

func (*User) GetWorkout

func (u *User) GetWorkout(db *gorm.DB, id int) (*Workout, error)

func (*User) GetWorkouts

func (u *User) GetWorkouts(db *gorm.DB) ([]*Workout, error)

func (*User) IsActive

func (u *User) IsActive() bool

func (*User) IsValid

func (u *User) IsValid() error

func (*User) MarkWorkoutsDirty

func (u *User) MarkWorkoutsDirty(db *gorm.DB) error

func (*User) PreferredUnits added in v0.12.0

func (u *User) PreferredUnits() *UserPreferredUnits

func (*User) Save

func (u *User) Save(db *gorm.DB) error

func (*User) SetDB added in v0.12.0

func (u *User) SetDB(db *gorm.DB)

func (*User) SetPassword

func (u *User) SetPassword(password string) error

func (*User) ShowFullDate added in v0.14.1

func (u *User) ShowFullDate() bool

func (*User) Timezone added in v0.10.0

func (u *User) Timezone() *time.Location

func (*User) ValidLogin

func (u *User) ValidLogin(password string) bool

type UserPreferredUnits added in v0.12.0

type UserPreferredUnits struct {
	SpeedRaw     string `form:"speed" json:"speed"`         // The user's preferred speed unit
	DistanceRaw  string `form:"distance" json:"distance"`   // The user's preferred distance unit
	ElevationRaw string `form:"elevation" json:"elevation"` // The user's preferred elevation unit
	WeightRaw    string `form:"weight" json:"weight"`       // The user's preferred weight unit
}

func (UserPreferredUnits) Cadence added in v0.15.0

func (u UserPreferredUnits) Cadence() string

func (UserPreferredUnits) Distance added in v0.12.0

func (u UserPreferredUnits) Distance() string

func (UserPreferredUnits) DistanceToDatabase added in v1.17.1

func (u UserPreferredUnits) DistanceToDatabase(d float64) float64

func (UserPreferredUnits) Elevation added in v0.12.0

func (u UserPreferredUnits) Elevation() string

func (UserPreferredUnits) HeartRate added in v0.15.0

func (u UserPreferredUnits) HeartRate() string

func (UserPreferredUnits) Speed added in v0.12.0

func (u UserPreferredUnits) Speed() string

func (UserPreferredUnits) Tempo added in v0.12.1

func (u UserPreferredUnits) Tempo() string

func (UserPreferredUnits) Weight added in v1.16.0

func (u UserPreferredUnits) Weight() string

type Workout

type Workout struct {
	gorm.Model
	Name      string      `gorm:"not null"`                                  // The name of the workout
	Date      *time.Time  `gorm:"not null;uniqueIndex:idx_start_user"`       // The timestamp the workout was recorded
	UserID    uint        `gorm:"not null;index;uniqueIndex:idx_start_user"` // The ID of the user who owns the workout
	Dirty     bool        // Whether the workout has been modified and the details should be re-rendered
	User      *User       // The user who owns the workout
	Notes     string      // The notes associated with the workout, in markdown
	Type      WorkoutType // The type of the workout
	Data      *MapData    `json:",omitempty"`                                    // The map data associated with the workout
	GPX       *GPXData    `json:",omitempty"`                                    // The file data associated with the workout
	Equipment []Equipment `json:",omitempty" gorm:"many2many:workout_equipment"` // Which equipment is used for this workout
}

func GetRecentWorkouts

func GetRecentWorkouts(db *gorm.DB, count int) ([]Workout, error)

func GetWorkout

func GetWorkout(db *gorm.DB, id int) (*Workout, error)

func GetWorkoutDetails added in v0.11.0

func GetWorkoutDetails(db *gorm.DB, id int) (*Workout, error)

func GetWorkoutWithGPX added in v0.10.1

func GetWorkoutWithGPX(db *gorm.DB, id int) (*Workout, error)

func GetWorkouts added in v0.10.0

func GetWorkouts(db *gorm.DB) ([]*Workout, error)

func NewWorkout

func NewWorkout(u *User, workoutType WorkoutType, notes string, filename string, content []byte) (*Workout, error)

func (*Workout) Address added in v1.17.0

func (w *Workout) Address() string

func (*Workout) AsGPX

func (w *Workout) AsGPX() (*gpx.GPX, error)

func (*Workout) Create

func (w *Workout) Create(db *gorm.DB) error

func (*Workout) Delete

func (w *Workout) Delete(db *gorm.DB) error

func (*Workout) Distance added in v0.12.2

func (w *Workout) Distance() float64

func (*Workout) Duration added in v0.15.1

func (w *Workout) Duration() time.Duration

func (*Workout) EquipmentIDs added in v0.15.1

func (w *Workout) EquipmentIDs() []uint

func (*Workout) Filename added in v0.9.1

func (w *Workout) Filename() string

func (*Workout) FullAddress added in v1.17.0

func (w *Workout) FullAddress() string

func (*Workout) HasCadence added in v1.16.4

func (w *Workout) HasCadence() bool

func (*Workout) HasElevation added in v1.16.4

func (w *Workout) HasElevation() bool

func (*Workout) HasExtraMetric added in v1.16.4

func (w *Workout) HasExtraMetric(name string) bool

func (*Workout) HasFile added in v1.18.0

func (w *Workout) HasFile() bool

func (*Workout) HasHeading added in v1.16.5

func (w *Workout) HasHeading() bool

func (*Workout) HasHeartRate added in v1.16.4

func (w *Workout) HasHeartRate() bool

func (*Workout) HasTracks added in v1.17.1

func (w *Workout) HasTracks() bool

func (*Workout) MarkdownNotes added in v0.10.5

func (w *Workout) MarkdownNotes() template.HTML

func (*Workout) Repetitions added in v1.16.0

func (w *Workout) Repetitions() int

func (*Workout) Save

func (w *Workout) Save(db *gorm.DB) error

func (*Workout) StatisticsPer added in v0.12.1

func (w *Workout) StatisticsPer(count float64, unit string) (WorkoutBreakdown, error)

func (*Workout) UpdateData

func (w *Workout) UpdateData(db *gorm.DB) error

func (*Workout) Uses added in v0.15.1

func (w *Workout) Uses(e Equipment) bool

func (*Workout) Weight added in v1.17.0

func (w *Workout) Weight() float64

type WorkoutBreakdown added in v0.12.1

type WorkoutBreakdown struct {
	Unit  string
	Items []BreakdownItem
}

type WorkoutEquipment added in v0.15.1

type WorkoutEquipment struct {
	gorm.Model
	WorkoutID   uint `gorm:"not null;uniqueIndex:idx_workout_equipment"` // The ID of the workout
	Workout     Workout
	EquipmentID uint `gorm:"not null;uniqueIndex:idx_workout_equipment"` // The ID of the equipment
	Equipment   Equipment
}

type WorkoutRecord

type WorkoutRecord struct {
	WorkoutType         WorkoutType    // The type of the workout
	Active              bool           // Whether there is any data in the record
	AverageSpeed        float64Record  // The record with the maximum average speed
	AverageSpeedNoPause float64Record  // The record with the maximum average speed without pause
	MaxSpeed            float64Record  // The record with the maximum max speed
	Distance            float64Record  // The record with the maximum distance
	TotalUp             float64Record  // The record with the maximum up elevation
	Duration            durationRecord // The record with the maximum duration
}

WorkoutRecord is the collection of records for a single workout type

type WorkoutTotals added in v0.15.1

type WorkoutTotals struct {
	Distance    float64
	Duration    time.Duration
	Repetitions int
}

type WorkoutType

type WorkoutType string
const (
	// We need to add each of these types to the "messages.html" partial view.
	// Then it gets picked up by the i18n system, added to the list of translatable
	// strings, etc.
	WorkoutTypeAutoDetect    WorkoutType = "auto"
	WorkoutTypeRunning       WorkoutType = "running"
	WorkoutTypeCycling       WorkoutType = "cycling"
	WorkoutTypeWalking       WorkoutType = "walking"
	WorkoutTypeSkiing        WorkoutType = "skiing"
	WorkoutTypeSnowboarding  WorkoutType = "snowboarding"
	WorkoutTypeSwimming      WorkoutType = "swimming"
	WorkoutTypeKayaking      WorkoutType = "kayaking"
	WorkoutTypeGolfing       WorkoutType = "golfing"
	WorkoutTypeHiking        WorkoutType = "hiking"
	WorkoutTypePushups       WorkoutType = "push-ups"
	WorkoutTypeWeightLifting WorkoutType = "weight lifting"

	WorkoutTypeClassLocation   = "location"
	WorkoutTypeClassDistance   = "distance"
	WorkoutTypeClassRepetition = "repetition"
	WorkoutTypeClassWeight     = "weight"
	WorkoutTypeClassDuration   = "duration"
)

func AsWorkoutType added in v0.11.3

func AsWorkoutType(s string) WorkoutType

func DistanceWorkoutTypes

func DistanceWorkoutTypes() []WorkoutType

func DurationWorkoutTypes added in v0.15.1

func DurationWorkoutTypes() []WorkoutType

func LocationWorkoutTypes added in v1.16.0

func LocationWorkoutTypes() []WorkoutType

func RepetitionWorkoutTypes added in v1.16.2

func RepetitionWorkoutTypes() []WorkoutType

func WeightWorkoutTypes added in v1.16.2

func WeightWorkoutTypes() []WorkoutType

func WorkoutTypes

func WorkoutTypes() []WorkoutType

func (WorkoutType) IsDistance

func (wt WorkoutType) IsDistance() bool

func (WorkoutType) IsDuration added in v0.15.1

func (wt WorkoutType) IsDuration() bool

func (WorkoutType) IsLocation added in v1.16.0

func (wt WorkoutType) IsLocation() bool

func (WorkoutType) IsRepetition added in v1.16.0

func (wt WorkoutType) IsRepetition() bool

func (WorkoutType) IsWeight added in v1.16.0

func (wt WorkoutType) IsWeight() bool

func (WorkoutType) String

func (wt WorkoutType) String() string

type WorkoutTypeConfiguration added in v1.16.0

type WorkoutTypeConfiguration struct {
	Location   bool
	Distance   bool
	Repetition bool
	Weight     bool
}

Jump to

Keyboard shortcuts

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