database

package
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2024 License: MIT Imports: 29 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 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

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
	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

	Points []MapPoint `gorm:"serializer:json" json:"-"` // To be removed
}

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

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
	Elevation     float64       // The elevation of the 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) 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
	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
	// 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) 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) 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
}

func (UserPreferredUnits) Distance added in v0.12.0

func (u UserPreferredUnits) Distance() string

func (UserPreferredUnits) Elevation added in v0.12.0

func (u UserPreferredUnits) Elevation() 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

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

	MapData  *MapData `gorm:"serializer:json;column:data" json:"-"` // To be removed
	GPXData  []byte   `gorm:"type:text" json:"-"`                   // To be removed
	Filename string   `json:"-"`                                    // To be removed
	Checksum []byte   `gorm:"default:'legacy'" json:"-"`            // To be removed
}

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) 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) MarkdownNotes added in v0.10.5

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

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

type WorkoutBreakdown added in v0.12.1

type WorkoutBreakdown struct {
	Unit  string
	Items []BreakdownItem
}

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 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"
)

func AsWorkoutType added in v0.11.3

func AsWorkoutType(s string) WorkoutType

func DistanceWorkoutTypes

func DistanceWorkoutTypes() []WorkoutType

func WorkoutTypes

func WorkoutTypes() []WorkoutType

func (WorkoutType) IsDistance

func (wt WorkoutType) IsDistance() bool

func (WorkoutType) String

func (wt WorkoutType) String() string

Jump to

Keyboard shortcuts

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