A self-hosted dashboard that puts all your feeds in one place
Go aggregatordashboarddockerfeed-readergohomelabhomepagemonitoringredditrssrss-readerself-hostedstartpageyoutube
Revert "Merge pull request #1037 from TowyTowy/fix/forum-post-time-depreciation-dev"
Svilen Markov3c86d691709f
diff --git a/README.md b/README.mdindex fc555d3..9c937a0 100644--- a/README.md+++ b/README.md@@ -90,7 +90,7 @@ pages:channels:- theprimeagen- j_blow- - giantwaffle+ - piratesoftware- cohhcarnage- christitustech- EJ_SA@@ -208,7 +208,6 @@ services:restart: unless-stoppedvolumes:- ./config:/app/config- - /etc/localtime:/etc/localtime:roports:- 8080:8080```diff --git a/docs/configuration.md b/docs/configuration.mdindex 8813e1d..5a6bcbf 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -34,8 +34,6 @@- [DNS Stats](#dns-stats)- [Server Stats](#server-stats)- [Repository](#repository)- <!-- TODO: add docs -->- - [Trending Repositories](#trending-repositories)- [Bookmarks](#bookmarks)- [Calendar](#calendar)- [Calendar (legacy)](#calendar-legacy)@@ -212,12 +210,6 @@ icon: auto-invert sh:glance-dark # with a selfh.st iconThis expects the icon to be black and will automatically invert it to white when using a dark theme.-If there is no `.svg` version available for a `selfh.st` or `Dashboard` icon, then you can add the image extension of the format you wish to use.-```yaml-icon: sh:glance.png # use the .png version of the icon-icon: sh:glance.webp # use the .webp version of the icon-```-## Config schemaFor property descriptions, validation and autocompletion of the config within your IDE, @not-first has kindly created a [schema](https://github.com/not-first/glance-schema). Massive thanks to them for this, go check it out and give them a star!@@ -878,7 +870,6 @@ Preview:| playlists | array | no | || limit | integer | no | 25 || style | string | no | horizontal-cards |-| sort-by | string | no | posted || collapse-after | integer | no | 7 || collapse-after-rows | integer | no | 4 || include-shorts | boolean | no | false |@@ -914,10 +905,6 @@ https://www.youtube.com...&list={ID}&...##### `limit`The maximum number of videos to show.-##### `sort-by`-Used to specify the order in which the videos should get returned. Possible values are `none`, `updated`, and `posted`.-Default value is `posted`.-##### `collapse-after`Specify the number of videos to show when using the `vertical-list` style before the "SHOW MORE" button appears.@@ -2369,7 +2356,7 @@ Only required when using AdGuard Home. The username used to log into the admin d##### `password`Required when using AdGuard Home, where the password is the one used to log into the admin dashboard.-For Pi-hole version 6+, this field is required if you have set a password to log into Pi-hole. You can either use the password you use to log into the admin dashboard or the application password, which can be found in `Settings -> Web Interface / API -> Configure app password`.+Also required when using Pi-hole major version 6 and above, where the password is the one used to log into the admin dashboard or the application password, which can be found in `Settings -> Web Interface / API -> Configure app password`.##### `token`Required when using Pi-hole major version 5 or earlier. The API token which can be found in `Settings -> API -> Show API token`.@@ -2514,7 +2501,6 @@ Example:pull-requests-limit: 5issues-limit: 3commits-limit: 3- exclude-draft-pull-requests: true```Preview:@@ -2530,7 +2516,6 @@ Preview:| pull-requests-limit | integer | no | 3 || issues-limit | integer | no | 3 || commits-limit | integer | no | -1 |-| exclude-draft-pull-requests | boolean | no | false |##### `repository`The owner and repository name that will have their information displayed.@@ -2547,9 +2532,6 @@ The maximum number of latest open issues to show. Set to `-1` to not show any.##### `commits-limit`The maximum number of lastest commits to show from the default branch. Set to `-1` to not show any.-##### `exclude-draft-pull-requests`-Wheter to exclude draft pull requests from the list. Set to `false` by default to include them.-### BookmarksDisplay a list of links which can be grouped.diff --git a/docs/custom-api.md b/docs/custom-api.mdindex 67c706b..ba294e1 100644--- a/docs/custom-api.md+++ b/docs/custom-api.md@@ -219,38 +219,6 @@ Output:JSON response:-```json-{- "user": {- "id": 42,- "name": "Alice",- "active": true- }-}-```--To loop through each property of the object, you would use the following:--```html-{{ range $key, $value := .JSON.Entries "user" }}- <div>{{ $key }}: {{ $value.String "" }}</div>-{{ end }}-```--Output:--```html-<div>id: 42</div>-<div>name: Alice</div>-<div>active: true</div>-```--Each property in the object is exposed as a pair, with `$key` being a string and `$value` providing access to the value using the usual JSON methods.--<hr>--JSON response:-```json{"price": 100,@@ -446,7 +414,6 @@ The following functions are available on the `JSON` object:- `Bool(key string) bool`: Returns the value of the key as a boolean.- `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects.- `Exists(key string) bool`: Returns true if the key exists in the JSON object.-- `Entries(key string)`: Returns an iterator that allows you to loop through each property of the object. Example: `{{ range $key, $value := .JSON.Entries "user" }}`. This will yield pairs of key and value, where `$key` is a string and `$value` is a `JSON` object.The following functions are available on the `Options` object:@@ -466,7 +433,7 @@ The following helper functions provided by Glance are available:- `duration(str string) time.Duration`: Parses a string such as `1h`, `24h`, `5h30m`, etc into a `time.Duration`.- `parseTime(layout string, s string) time.Time`: Parses a string into time.Time. The layout must be provided in Go's [date format](https://pkg.go.dev/time#pkg-constants). You can alternatively use these values instead of the literal format: "unix", "RFC3339", "RFC3339Nano", "DateTime", "DateOnly".- `formatTime(layout string, s string) time.Time`: Formats a `time.Time` into a string. The layout uses the same format as `parseTime`.-- `parseLocalTime(layout string, s string) time.Time`: Same as the above, except it will automatically convert the time to the server's timezone and in the absence of a timezone, it will use the local timezone instead of UTC.+- `parseLocalTime(layout string, s string) time.Time`: Same as the above, except in the absence of a timezone, it will use the local timezone instead of UTC.- `parseRelativeTime(layout string, s string) time.Time`: A shorthand for `{{ .String "date" | parseTime "rfc3339" | toRelativeTime }}`.- `add(a, b float) float`: Adds two numbers.- `sub(a, b float) float`: Subtracts two numbers.diff --git a/docs/images/trending-repositories-widget-preview.png b/docs/images/trending-repositories-widget-preview.pngdeleted file mode 100644index 3760b83..0000000Binary files a/docs/images/trending-repositories-widget-preview.png and /dev/null differdiff --git a/internal/glance/config-fields.go b/internal/glance/config-fields.goindex f01e179..2eec599 100644--- a/internal/glance/config-fields.go+++ b/internal/glance/config-fields.go@@ -2,14 +2,11 @@ package glanceimport ("crypto/tls"- "errors""fmt""html/template"- "maps""net/http""net/url""regexp"- "slices""strconv""strings""time"@@ -18,7 +15,6 @@ import ()var hslColorFieldPattern = regexp.MustCompile(`^(?:hsla?\()?([\d\.]+)(?: |,)+([\d\.]+)%?(?: |,)+([\d\.]+)%?\)?$`)-var inStringPropertyPattern = regexp.MustCompile(`(?m)([a-zA-Z]+)\[(.*?)\]`)const (hslHueMax = 360@@ -52,7 +48,6 @@ func (c1 *hslColorField) SameAs(c2 *hslColorField) bool {func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {var value string- errorLine := fmt.Sprintf("line %d:", node.Line)if err := node.Decode(&value); err != nil {return err@@ -61,7 +56,7 @@ func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {matches := hslColorFieldPattern.FindStringSubmatch(value)if len(matches) != 4 {- return fmt.Errorf("%s invalid HSL color format: %s", errorLine, value)+ return fmt.Errorf("invalid HSL color format: %s", value)}hue, err := strconv.ParseFloat(matches[1], 64)@@ -70,7 +65,7 @@ func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {}if hue > hslHueMax {- return fmt.Errorf("%s HSL hue must be between 0 and %d", errorLine, hslHueMax)+ return fmt.Errorf("HSL hue must be between 0 and %d", hslHueMax)}saturation, err := strconv.ParseFloat(matches[2], 64)@@ -79,7 +74,7 @@ func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {}if saturation > hslSaturationMax {- return fmt.Errorf("%s HSL saturation must be between 0 and %d", errorLine, hslSaturationMax)+ return fmt.Errorf("HSL saturation must be between 0 and %d", hslSaturationMax)}lightness, err := strconv.ParseFloat(matches[3], 64)@@ -88,7 +83,7 @@ func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {}if lightness > hslLightnessMax {- return fmt.Errorf("%s HSL lightness must be between 0 and %d", errorLine, hslLightnessMax)+ return fmt.Errorf("HSL lightness must be between 0 and %d", hslLightnessMax)}c.H = hue@@ -98,84 +93,47 @@ func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {return nil}-var durationFieldPattern = regexp.MustCompile(`^(\d+)(s|m|h|d|w|mo|y)$`)+var durationFieldPattern = regexp.MustCompile(`^(\d+)(s|m|h|d)$`)type durationField time.Duration-func parseDurationValue(value string) (time.Duration, error) {+func (d *durationField) UnmarshalYAML(node *yaml.Node) error {+ var value string++ if err := node.Decode(&value); err != nil {+ return err+ }+matches := durationFieldPattern.FindStringSubmatch(value)+if len(matches) != 3 {- return 0, fmt.Errorf("invalid format for value `%s`, must be a number followed by one of: s, m, h, d, w, mo, y", value)+ return fmt.Errorf("invalid duration format: %s", value)}duration, err := strconv.Atoi(matches[1])if err != nil {- return 0, err+ return err}switch matches[2] {case "s":- return time.Duration(duration) * time.Second, nil+ *d = durationField(time.Duration(duration) * time.Second)case "m":- return time.Duration(duration) * time.Minute, nil+ *d = durationField(time.Duration(duration) * time.Minute)case "h":- return time.Duration(duration) * time.Hour, nil+ *d = durationField(time.Duration(duration) * time.Hour)case "d":- return time.Duration(duration) * 24 * time.Hour, nil- case "w":- return time.Duration(duration) * 7 * 24 * time.Hour, nil- case "mo":- return time.Duration(duration) * 30 * 24 * time.Hour, nil- case "y":- return time.Duration(duration) * 365 * 24 * time.Hour, nil- default:- return 0, fmt.Errorf("unknown duration unit: %s", matches[2])+ *d = durationField(time.Duration(duration) * 24 * time.Hour)}-}--func (d *durationField) UnmarshalYAML(node *yaml.Node) error {- var value string-- if err := node.Decode(&value); err != nil {- return err- }-- parsedDuration, err := parseDurationValue(value)- if err != nil {- return fmt.Errorf("line %d: %w", node.Line, err)- }-- *d = durationField(parsedDuration)return nil}type customIconField struct {URL template.URL- Color stringAutoInvert bool}-func (h *customIconField) Elem() template.HTML {- return h.ElemWithClass("")-}--func (h *customIconField) ElemWithClass(class string) template.HTML {- if h.AutoInvert && h.Color == "" {- class = "flat-icon " + class- }-- if h.Color != "" {- return template.HTML(- `<div class="icon colored-icon ` + class + `" style="--icon-color: ` + h.Color + `; --icon-url: url('` + string(h.URL) + `')"></div>`,- )- }-- return template.HTML(- `<img class="icon ` + class + `" src="` + string(h.URL) + `" alt="" loading="lazy">`,- )-}-func newCustomIconField(value string) customIconField {const autoInvertPrefix = "auto-invert "field := customIconField{}@@ -185,25 +143,6 @@ func newCustomIconField(value string) customIconField {value = strings.TrimPrefix(value, autoInvertPrefix)}- value, properties := parseInStringProperties(value)-- if color, ok := properties["color"]; ok {- switch color {- case "primary":- color = "var(--color-primary)"- case "positive":- color = "var(--color-positive)"- case "negative":- color = "var(--color-negative)"- case "base":- color = "var(--color-text-base)"- case "subdue":- color = "var(--color-text-subdue)"- }-- field.Color = color- }-prefix, icon, found := strings.Cut(value, ":")if !found {field.URL = template.URL(value)@@ -216,7 +155,7 @@ func newCustomIconField(value string) customIconField {basename = icon}- if ext != "svg" && ext != "png" && ext != "webp" {+ if ext != "svg" && ext != "png" {ext = "svg"}@@ -231,9 +170,6 @@ func newCustomIconField(value string) customIconField {field.URL = template.URL("https://cdn.jsdelivr.net/npm/@mdi/svg@latest/svg/" + basename + ".svg")case "sh":field.URL = template.URL("https://cdn.jsdelivr.net/gh/selfhst/icons/" + ext + "/" + basename + "." + ext)- case "hi":- field.AutoInvert = true- field.URL = template.URL("https://cdn.jsdelivr.net/npm/heroicons@latest/24/" + basename + ".svg")default:field.URL = template.URL(value)}@@ -251,23 +187,6 @@ func (i *customIconField) UnmarshalYAML(node *yaml.Node) error {return nil}-func parseInStringProperties(value string) (string, map[string]string) {- properties := make(map[string]string)-- value = inStringPropertyPattern.ReplaceAllStringFunc(value, func(match string) string {- matches := inStringPropertyPattern.FindStringSubmatch(match)- if len(matches) != 3 {- return ""- }-- properties[matches[1]] = matches[2]-- return ""- })-- return strings.TrimSpace(value), properties-}-type proxyOptionsField struct {URL string `yaml:"url"`AllowInsecure bool `yaml:"allow-insecure"`@@ -326,8 +245,6 @@ func (q *queryParametersField) UnmarshalYAML(node *yaml.Node) error {*q = make(queryParametersField)- errorLine := fmt.Sprintf("line %d:", node.Line)-// TODO: refactor the duplication in the switch cases if any more types get addedfor key, value := range decoded {switch v := value.(type) {@@ -349,22 +266,17 @@ func (q *queryParametersField) UnmarshalYAML(node *yaml.Node) error {case bool:(*q)[key] = append((*q)[key], fmt.Sprintf("%t", item))default:- return fmt.Errorf("%s invalid query parameter value type: %T", errorLine, item)+ return fmt.Errorf("invalid query parameter value type: %T", item)}}default:- return fmt.Errorf("%s invalid query parameter value type: %T", errorLine, value)+ return fmt.Errorf("invalid query parameter value type: %T", value)}}return nil}-type sortKey struct {- name string- dir int // 1 for asc, -1 for desc-}-func (q *queryParametersField) toQueryString() string {query := url.Values{}@@ -376,346 +288,3 @@ func (q *queryParametersField) toQueryString() string {return query.Encode()}--type sortableFields[T any] struct {- keys []sortKey- fields map[string]func(a, b T) int-}--func (s *sortableFields[T]) UnmarshalYAML(node *yaml.Node) error {- var raw string- if err := node.Decode(&raw); err != nil {- return errors.New("sort-by must be a string")- }-- return s.parse(raw)-}--func (s *sortableFields[T]) parse(raw string) error {- split := strings.Split(raw, ",")-- for i := range split {- key := strings.TrimSpace(split[i])- direction := "asc"- name, dir, ok := strings.Cut(key, ":")- if ok {- key = strings.TrimSpace(name)- direction = strings.TrimSpace(dir)- if direction != "asc" && direction != "desc" {- return fmt.Errorf("unsupported sort direction `%s` in sort-by option `%s`, must be `asc` or `desc`", direction, key)- }- }-- if key == "" {- continue- }-- s.keys = append(s.keys, sortKey{- name: key,- dir: ternary(direction == "asc", 1, -1),- })- }-- return nil-}--func (s *sortableFields[T]) Default(sort string) error {- if len(s.keys) == 0 {- return s.parse(sort)- }-- return nil-}--func (s *sortableFields[T]) Fields(fields map[string]func(a, b T) int) error {- for i := range s.keys {- option := s.keys[i].name- if _, ok := fields[option]; !ok {- keys := slices.Collect(maps.Keys(fields))- slices.Sort(keys)- formatted := strings.Join(keys, ", ")- return fmt.Errorf("unsupported sort-by option `%s`, must be one or more of [%s] separated by comma", option, formatted)- }- }-- s.fields = fields-- return nil-}--func (s *sortableFields[T]) Apply(data []T) {- slices.SortStableFunc(data, func(a, b T) int {- for _, key := range s.keys {- field, ok := s.fields[key.name]- if !ok {- continue- }-- if result := field(a, b) * key.dir; result != 0 {- return result- }- }-- return 0- })-}--type filterableData interface {- filterableField(field string) any-}--type filterableFields[T filterableData] struct {- filters []func(T) bool- FilteredCount int `yaml:"-"`- AllFiltered bool `yaml:"-"`-}--func (f *filterableFields[T]) Apply(items []T) []T {- if len(f.filters) == 0 {- f.FilteredCount = 0- f.AllFiltered = false- return items- }-- filtered := make([]T, 0, len(items))-- for _, item := range items {- include := true- for _, shouldInclude := range f.filters {- if !shouldInclude(item) {- include = false- break- }- }- if include {- filtered = append(filtered, item)- }- }-- f.FilteredCount = len(items) - len(filtered)- f.AllFiltered = f.FilteredCount == len(items)-- return filtered-}--func (f *filterableFields[T]) UnmarshalYAML(node *yaml.Node) error {- untypedFilters := make(map[string]any)- if err := node.Decode(&untypedFilters); err != nil {- return errors.New("filters must be defined as an object where each key is the name of a field")- }-- rawFilters := make(map[string][]string)- for key, value := range untypedFilters {- rawFilters[key] = []string{}-- switch vt := value.(type) {- case string:- rawFilters[key] = append(rawFilters[key], vt)- case []any:- for _, item := range vt {- if str, ok := item.(string); ok {- rawFilters[key] = append(rawFilters[key], str)- } else {- return fmt.Errorf("filter value in array for %s must be a string, got %T", key, item)- }- }- case nil:- continue // skip empty filters- default:- return fmt.Errorf("filter value for %s must be a string or an array, got %T", key, value)- }- }-- makeStringFilter := func(key string, values []string) (func(T) bool, error) {- parsedFilters := []func(string) bool{}-- for _, value := range values {- value, negative := strings.CutPrefix(value, "!")-- if value == "" {- return nil, errors.New("value is empty")- }-- if pattern, ok := strings.CutPrefix(value, "re:"); ok {- re, err := regexp.Compile(pattern)- if err != nil {- return nil, fmt.Errorf("value `%s`: %w", value, err)- }-- parsedFilters = append(parsedFilters, func(s string) bool {- return negative != re.MatchString(s)- })-- continue- }-- value = strings.ToLower(value)- parsedFilters = append(parsedFilters, func(s string) bool {- return negative != strings.Contains(strings.ToLower(s), value)- })- }-- return func(item T) bool {- value, ok := item.filterableField(key).(string)- if !ok {- return false- }-- for i := range parsedFilters {- if !parsedFilters[i](value) {- return false- }- }-- return true- }, nil- }-- makeIntFilter := func(key string, values []string) (func(T) bool, error) {- parsedFilters := []func(int) bool{}-- parseNumber := func(value string) (int, error) {- var multiplier int- if strings.HasSuffix(value, "k") {- multiplier = 1_000- value = strings.TrimSuffix(value, "k")- } else if strings.HasSuffix(value, "m") {- multiplier = 1_000_000- value = strings.TrimSuffix(value, "m")- } else {- multiplier = 1- }-- num, err := strconv.Atoi(value)- if err != nil {- return 0, fmt.Errorf("invalid number format for key %s: %w", key, err)- }-- return num * multiplier, nil- }-- for _, value := range values {- if number, ok := strings.CutPrefix(value, "<"); ok {- num, err := parseNumber(number)- if err != nil {- return nil, err- }-- parsedFilters = append(parsedFilters, func(v int) bool {- return v < num- })- } else if number, ok := strings.CutPrefix(value, ">"); ok {- num, err := parseNumber(number)- if err != nil {- return nil, err- }-- parsedFilters = append(parsedFilters, func(v int) bool {- return v > num- })- } else {- num, err := parseNumber(value)- if err != nil {- return nil, err- }-- parsedFilters = append(parsedFilters, func(v int) bool {- return v == num- })- }- }-- return func(item T) bool {- value, ok := item.filterableField(key).(int)- if !ok {- return false- }-- for i := range parsedFilters {- if !parsedFilters[i](value) {- return false- }- }-- return true- }, nil- }-- makeTimeFilter := func(key string, values []string) (func(T) bool, error) {- parsedFilters := []func(time.Time) bool{}-- for _, value := range values {- if number, ok := strings.CutPrefix(value, "<"); ok {- duration, err := parseDurationValue(number)- if err != nil {- return nil, err- }-- parsedFilters = append(parsedFilters, func(t time.Time) bool {- return time.Since(t) < duration- })- } else if number, ok := strings.CutPrefix(value, ">"); ok {- duration, err := parseDurationValue(number)- if err != nil {- return nil, err- }-- parsedFilters = append(parsedFilters, func(t time.Time) bool {- return time.Since(t) > duration- })- } else {- return nil, fmt.Errorf("invalid time filter format for value `%s`", value)- }- }-- return func(item T) bool {- value, ok := item.filterableField(key).(time.Time)- if !ok {- return false- }-- for i := range parsedFilters {- if !parsedFilters[i](value) {- return false- }- }-- return true- }, nil- }-- var data T- for key, values := range rawFilters {- if len(values) == 0 {- continue- }-- value := data.filterableField(key)-- if value == nil {- return fmt.Errorf("filter with key `%s` is not supported", key)- }-- var filter func(T) bool- var err error-- switch v := value.(type) {- case string:- filter, err = makeStringFilter(key, values)- case int:- filter, err = makeIntFilter(key, values)- case time.Time:- filter, err = makeTimeFilter(key, values)- default:- return fmt.Errorf("unsupported filter type for key %s: %T", key, v)- }-- if err != nil {- return fmt.Errorf("failed to create filter for key %s: %w", key, err)- }-- f.filters = append(f.filters, filter)- }-- return nil-}diff --git a/internal/glance/glance.go b/internal/glance/glance.goindex 0688eda..9047625 100644--- a/internal/glance/glance.go+++ b/internal/glance/glance.go@@ -438,7 +438,7 @@ func (a *application) StaticAssetPath(asset string) string {}func (a *application) VersionedAssetPath(asset string) string {- return a.Config.Server.BaseURL + "/" + asset ++ return a.Config.Server.BaseURL + asset +"?v=" + strconv.FormatInt(a.CreatedAt.Unix(), 10)}diff --git a/internal/glance/main.go b/internal/glance/main.goindex ae79f81..6d73a83 100644--- a/internal/glance/main.go+++ b/internal/glance/main.go@@ -6,9 +6,6 @@ import ("log""net/http""os"- "regexp"- "strconv"- "strings""golang.org/x/crypto/bcrypt")@@ -108,13 +105,7 @@ func serveApp(configPath string) error {config, err := newConfigFromYAML(newContents)if err != nil {- errStr := strings.ReplaceAll(err.Error(), "\n", "")- errStr = sequentialWhitespacePattern.ReplaceAllString(errStr, " ")- errStr = strings.ReplaceAll(errStr, "!!seq", "array")- errStr = strings.ReplaceAll(errStr, "!!str", "string")-- log.Printf("Config has errors: %v", errStr)- printConfigLinesNearErrorIfAvailable(err, newContents)+ log.Printf("Config has errors: %v", err)if !hadValidConfigOnStartup {close(exitChannel)@@ -189,41 +180,6 @@ func serveApp(configPath string) error {return nil}-var errorLinePattern = regexp.MustCompile(`line (\d+)`)--func printConfigLinesNearErrorIfAvailable(err error, configContents []byte) {- if err == nil {- return- }-- matches := errorLinePattern.FindStringSubmatch(err.Error())- if len(matches) < 2 {- return- }-- errorAtLine, err := strconv.Atoi(matches[1])- if err != nil {- return- }-- contents := strings.ReplaceAll(string(configContents), "\r\n", "\n")- lines := strings.Split(contents, "\n")-- if errorAtLine < 1 || errorAtLine > len(lines) {- return- }-- contextLength := 3-- for i := max(0, errorAtLine-contextLength-1); i < min(len(lines), errorAtLine+contextLength); i++ {- if i == errorAtLine-1 {- fmt.Printf("-> %s\n", lines[i])- } else {- fmt.Printf("| %s\n", lines[i])- }- }-}-func serveUpdateNoticeIfConfigLocationNotMigrated(configPath string) bool {if !isRunningInsideDockerContainer() {return falsediff --git a/internal/glance/searchable-node.go b/internal/glance/searchable-node.godeleted file mode 100644index 83f002a..0000000--- a/internal/glance/searchable-node.go+++ /dev/null@@ -1,161 +0,0 @@-package glance--import (- "strings"-- "golang.org/x/net/html"-)--type searchableNode html.Node--func (n *searchableNode) findFirst(tag string, attrs ...string) *searchableNode {- if tag == "" || n == nil {- return nil- }-- if len(attrs)%2 != 0 {- panic("attributes must be in key-value pairs")- }-- if n.matches(tag, attrs...) {- return n- }-- for child := n.FirstChild; child != nil; child = child.NextSibling {- if child.Type != html.ElementNode {- continue- }-- if found := (*searchableNode)(child).findFirst(tag, attrs...); found != nil {- return found- }- }-- return nil-}--func (n *searchableNode) nthChild(index int) *searchableNode {- if n == nil || index < 0 {- return nil- }-- if index == 0 {- return n- }-- count := 0- for child := n.FirstChild; child != nil; child = child.NextSibling {- if child.Type != html.ElementNode {- continue- }-- count++- if count == index {- return (*searchableNode)(child)- }- }-- return nil-}--func (n *searchableNode) findFirstChild(tag string, attrs ...string) *searchableNode {- if tag == "" || n == nil {- return nil- }-- if len(attrs)%2 != 0 {- panic("attributes must be in key-value pairs")- }-- for child := n.FirstChild; child != nil; child = child.NextSibling {- if child.Type != html.ElementNode {- continue- }-- if child.Type == html.ElementNode && (*searchableNode)(child).matches(tag, attrs...) {- return (*searchableNode)(child)- }- }-- return nil-}--func (n *searchableNode) findAll(tag string, attrs ...string) []*searchableNode {- if tag == "" || n == nil {- return nil- }-- if len(attrs)%2 != 0 {- panic("attributes must be in key-value pairs")- }-- var results []*searchableNode-- if n.matches(tag, attrs...) {- results = append(results, n)- }-- for child := n.FirstChild; child != nil; child = child.NextSibling {- if child.Type != html.ElementNode {- continue- }-- results = append(results, (*searchableNode)(child).findAll(tag, attrs...)...)- }-- return results-}--func (n *searchableNode) matches(tag string, attrs ...string) bool {- if tag == "" || n == nil {- return false- }-- if len(attrs)%2 != 0 {- panic("attributes must be in key-value pairs")- }-- if n.Data != tag {- return false- }-- for i := 0; i < len(attrs); i += 2 {- key := attrs[i]- value := attrs[i+1]- found := false- for _, attr := range n.Attr {- if attr.Key == key && attr.Val == value {- found = true- break- }- }- if !found {- return false- }- }-- return true-}--func (n *searchableNode) text() string {- if n == nil {- return ""- }-- if n.Type == html.TextNode {- return strings.TrimSpace(n.Data)- }-- var builder strings.Builder-- for child := n.FirstChild; child != nil; child = child.NextSibling {- switch child.Type {- case html.TextNode:- builder.WriteString(strings.TrimSpace(child.Data))- case html.ElementNode:- builder.WriteString((*searchableNode)(child).text())- }- }-- return builder.String()-}diff --git a/internal/glance/static/css/site.css b/internal/glance/static/css/site.cssindex cd30823..fbf3c8a 100644--- a/internal/glance/static/css/site.css+++ b/internal/glance/static/css/site.css@@ -61,10 +61,6 @@ button {width: 10px;}-*:active {- -webkit-tap-highlight-color: transparent;-}-*:focus-visible {outline: 2px solid var(--color-primary);outline-offset: 0.1rem;@@ -279,20 +275,15 @@ kbd:active {max-height: 2.7rem;}-.desktop-navigation {+.nav {overflow-x: auto;min-width: 0;height: 100%;gap: var(--header-items-gap);}-.desktop-navigation .nav-item {- display: flex;- align-items: center;-}--.desktop-navigation .nav-item-text {- margin-top: 3px;+.nav .nav-item {+ line-height: var(--header-height);}.footer {diff --git a/internal/glance/static/css/utils.css b/internal/glance/static/css/utils.cssindex d243f77..3bbb48c 100644--- a/internal/glance/static/css/utils.css+++ b/internal/glance/static/css/utils.css@@ -38,10 +38,6 @@top: 0.1rem;}-.horizontal-text-gap-5 > *:not(:last-child)::after {- margin: 0 0.5rem;-}-.summary {width: 100%;cursor: pointer;@@ -380,28 +376,7 @@ details[open] .summary::after {gap: 0.5rem;}-.icon {- object-fit: contain;- user-select: none;-}--.icon:not(.colored-icon) {- opacity: 0.85;- filter: grayscale(0.2);- transition: opacity 0.2s, filter 0.2s;-}--.icon-parent:hover .icon {- opacity: 1;- filter: none;-}--.colored-icon {- mask: var(--icon-url) no-repeat center / contain;- background-color: var(--icon-color);-}--:root:not([data-scheme=light]) .flat-icon:not(.colored-icon) {+:root:not([data-scheme=light]) .flat-icon {filter: invert(1);}@@ -428,11 +403,6 @@ details[open] .summary::after {height: 3rem;}-.progress-bar-mini {- height: .9rem;- border-radius: .3rem;-}-.popover-active > .progress-bar {transition: border-color .3s;border-color: var(--color-text-subdue);@@ -447,10 +417,6 @@ details[open] .summary::after {flex: 1;}-.progress-bar-mini > .progress-value {- --half-border-radius: .2rem;-}-.progress-value:first-child {border-top-left-radius: var(--half-border-radius);}@@ -493,6 +459,7 @@ details[open] .summary::after {filter: none;}+.hide-scrollbars {scrollbar-width: none;}@@ -525,8 +492,6 @@ details[open] .summary::after {.color-positive { color: var(--color-positive); }.color-primary { color: var(--color-primary); }-.bg-highlight { background-color: var(--color-widget-background-highlight); }-.color-primary-if-not-visited:not(:visited) {color: var(--color-primary);}@@ -582,13 +547,6 @@ details[open] .summary::after {visibility: hidden;}-.square-18 { width: 1.8rem; height: 1.8rem; }-.square-20 { width: 2rem; height: 2rem; }-.square-27 { width: 2.7rem; height: 2.7rem; }-.square-30 { width: 3rem; height: 3rem; }-.square-32 { width: 3.2rem; height: 3.2rem; }-.square-40 { width: 4rem; height: 4rem; }-.cursor-help { cursor: help; }.rounded { border-radius: var(--border-radius); }.break-all { word-break: break-all; }@@ -602,7 +560,6 @@ details[open] .summary::after {.shrink { flex-shrink: 1; }.shrink-0 { flex-shrink: 0; }.min-width-0 { min-width: 0; }-.width-max-content { width: max-content; }.max-width-100 { max-width: 100%; }.block { display: block; }.inline-block { display: inline-block; }@@ -631,15 +588,10 @@ details[open] .summary::after {.gap-15 { gap: 1.5rem; }.gap-20 { gap: 2rem; }.gap-25 { gap: 2.5rem; }-.gap-30 { gap: 3rem; }.gap-35 { gap: 3.5rem; }-.gap-40 { gap: 4rem; }.gap-45 { gap: 4.5rem; }-.gap-50 { gap: 5rem; }.gap-55 { gap: 5.5rem; }.margin-left-auto { margin-left: auto; }-.margin-inline-auto { margin-inline: auto; }-.margin-top-2 { margin-top: 0.2rem; }.margin-top-3 { margin-top: 0.3rem; }.margin-top-5 { margin-top: 0.5rem; }.margin-top-7 { margin-top: 0.7rem; }@@ -666,11 +618,9 @@ details[open] .summary::after {.padding-widget { padding: var(--widget-content-padding); }.padding-block-widget { padding-block: var(--widget-content-vertical-padding); }.padding-inline-widget { padding-inline: var(--widget-content-horizontal-padding); }-.padding-inline-10 { padding-inline: 1rem; }.pointer-events-none { pointer-events: none; }.select-none { user-select: none; }.padding-block-5 { padding-block: 0.5rem; }-.padding-10 { padding: 1rem; }.scale-half { transform: scale(0.5); }.list { --list-half-gap: 0rem; }.list-gap-2 { --list-half-gap: 0.1rem; }diff --git a/internal/glance/static/css/widget-bookmarks.css b/internal/glance/static/css/widget-bookmarks.cssindex d0431d2..7f2dabd 100644--- a/internal/glance/static/css/widget-bookmarks.css+++ b/internal/glance/static/css/widget-bookmarks.css@@ -20,11 +20,12 @@background-color: var(--color-widget-background-highlight);border-radius: var(--border-radius);padding: 0.5rem;+ opacity: 0.7;flex-shrink: 0;}-.bookmarks-grid {- display: grid;- gap: 2.5rem 0;- grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr));+.bookmarks-icon {+ width: 20px;+ height: 20px;+ opacity: 0.8;}diff --git a/internal/glance/static/css/widget-docker-containers.css b/internal/glance/static/css/widget-docker-containers.cssnew file mode 100644index 0000000..ae08788--- /dev/null+++ b/internal/glance/static/css/widget-docker-containers.css@@ -0,0 +1,26 @@+.docker-container-icon {+ display: block;+ filter: grayscale(0.4);+ object-fit: contain;+ aspect-ratio: 1 / 1;+ width: 2.7rem;+ opacity: 0.8;+ transition: filter 0.3s, opacity 0.3s;+}++.docker-container-icon.flat-icon {+ opacity: 0.7;+}++.docker-container:hover .docker-container-icon {+ opacity: 1;+}++.docker-container:hover .docker-container-icon:not(.flat-icon) {+ filter: grayscale(0);+}++.docker-container-status-icon {+ width: 2rem;+ height: 2rem;+}diff --git a/internal/glance/static/css/widget-monitor.css b/internal/glance/static/css/widget-monitor.cssnew file mode 100644index 0000000..8bc629b--- /dev/null+++ b/internal/glance/static/css/widget-monitor.css@@ -0,0 +1,36 @@+.monitor-site-icon {+ display: block;+ opacity: 0.8;+ filter: grayscale(0.4);+ object-fit: contain;+ aspect-ratio: 1 / 1;+ width: 3.2rem;+ position: relative;+ top: -0.1rem;+ transition: filter 0.3s, opacity 0.3s;+}++.monitor-site-icon.flat-icon {+ opacity: 0.7;+}++.monitor-site:hover .monitor-site-icon {+ opacity: 1;+}++.monitor-site:hover .monitor-site-icon:not(.flat-icon) {+ filter: grayscale(0);+}++.monitor-site-status-icon {+ flex-shrink: 0;+ margin-left: auto;+ width: 2rem;+ height: 2rem;+}++.monitor-site-status-icon-compact {+ width: 1.8rem;+ height: 1.8rem;+ flex-shrink: 0;+}diff --git a/internal/glance/static/css/widgets.css b/internal/glance/static/css/widgets.cssindex 3c231c4..07b41c8 100644--- a/internal/glance/static/css/widgets.css+++ b/internal/glance/static/css/widgets.css@@ -2,8 +2,10 @@@import "widget-calendar.css";@import "widget-clock.css";@import "widget-dns-stats.css";+@import "widget-docker-containers.css";@import "widget-group.css";@import "widget-markets.css";+@import "widget-monitor.css";@import "widget-reddit.css";@import "widget-releases.css";@import "widget-rss.css";@@ -13,6 +15,7 @@@import "widget-videos.css";@import "widget-weather.css";@import "widget-todo.css";+@import "forum-posts.css";.widget-error-header {diff --git a/internal/glance/static/js/login.js b/internal/glance/static/js/login.jsindex 5b58748..e077fe9 100644--- a/internal/glance/static/js/login.js+++ b/internal/glance/static/js/login.js@@ -70,21 +70,8 @@ function enableLoginButtonIfCriteriaMet() {);}-function handleLoginWithEnter(event) {- if (event.key !== "Enter") return;- if (loginButton.disabled) return;-- document.activeElement.blur();- handleLoginAttempt();-}--usernameInput- .on("input", enableLoginButtonIfCriteriaMet)- .on("keydown", handleLoginWithEnter);--passwordInput- .on("input", enableLoginButtonIfCriteriaMet)- .on("keydown", handleLoginWithEnter);+usernameInput.on("input", enableLoginButtonIfCriteriaMet);+passwordInput.on("input", enableLoginButtonIfCriteriaMet);async function handleLoginAttempt() {state.lastUsername = usernameInput.value;diff --git a/internal/glance/templates.go b/internal/glance/templates.goindex 097be00..97c3229 100644--- a/internal/glance/templates.go+++ b/internal/glance/templates.go@@ -35,8 +35,26 @@ var globalTemplateFunctions = template.FuncMap{},"dynamicRelativeTimeAttrs": dynamicRelativeTimeAttrs,"formatServerMegabytes": func(mb uint64) template.HTML {- value, unit := formatBytes(mb * 1000 * 1000)- return template.HTML(value + ` <span class="color-base size-h5">` + unit + `</span>`)+ var value string+ var label string++ if mb < 1_000 {+ value = strconv.FormatUint(mb, 10)+ label = "MB"+ } else if mb < 1_000_000 {+ if mb < 10_000 {+ value = fmt.Sprintf("%.1f", float64(mb)/1_000)+ } else {+ value = strconv.FormatUint(mb/1_000, 10)+ }++ label = "GB"+ } else {+ value = fmt.Sprintf("%.1f", float64(mb)/1_000_000)+ label = "TB"+ }++ return template.HTML(value + ` <span class="color-base size-h5">` + label + `</span>`)},}@@ -71,41 +89,3 @@ func formatApproxNumber(count int) string {func dynamicRelativeTimeAttrs(t interface{ Unix() int64 }) template.HTMLAttr {return template.HTMLAttr(`data-dynamic-relative-time="` + strconv.FormatInt(t.Unix(), 10) + `"`)}--func formatBytes(bytes uint64) (value, unit string) {- const oneKB = 1000- const oneMB = oneKB * 1000- const oneGB = oneMB * 1000- const oneTB = oneGB * 1000-- if bytes < oneKB {- value = strconv.FormatUint(bytes, 10)- unit = "B"- } else if bytes < oneMB {- if bytes < 10*oneKB {- value = fmt.Sprintf("%.1f", float64(bytes)/oneKB)- } else {- value = strconv.FormatUint(bytes/oneKB, 10)- }- unit = "KB"- } else if bytes < oneGB {- if bytes < 10*oneMB {- value = fmt.Sprintf("%.1f", float64(bytes)/oneMB)- } else {- value = strconv.FormatUint(bytes/(oneMB), 10)- }- unit = "MB"- } else if bytes < oneTB {- if bytes < 10*oneGB {- value = fmt.Sprintf("%.1f", float64(bytes)/oneGB)- } else {- value = strconv.FormatUint(bytes/oneGB, 10)- }- unit = "GB"- } else {- value = fmt.Sprintf("%.1f", float64(bytes)/oneTB)- unit = "TB"- }-- return value, unit-}diff --git a/internal/glance/templates/bookmarks-grid.html b/internal/glance/templates/bookmarks-grid.htmldeleted file mode 100644index cf33ebc..0000000--- a/internal/glance/templates/bookmarks-grid.html+++ /dev/null@@ -1,21 +0,0 @@-{{ template "widget-base.html" . }}--{{ define "widget-content" }}-<ul class="bookmarks-grid">-{{- range .Links }}-<li class="icon-parent text-center padding-inline-10">- <a href="{{ .URL | safeURL }}" class="block" {{ if .Target }}target="{{ .Target }}"{{ end }} rel="noreferrer">- {{- if ne "" .Icon.URL }}- <div class="padding-10 rounded bg-highlight width-max-content margin-inline-auto">- {{ .Icon.ElemWithClass "square-40" }}- </div>- {{- end }}- <p class="margin-top-7 block text-truncate color-highlight size-h4">{{ .Title }}</p>- </a>- {{- if .Description }}- <div class="margin-top-5 text-truncate-2-lines text-compact">{{ .Description }}</div>- {{- end }}-</li>-{{- end }}-</ul>-{{ end }}diff --git a/internal/glance/templates/bookmarks.html b/internal/glance/templates/bookmarks.htmlindex 43821ed..a1c9c51 100644--- a/internal/glance/templates/bookmarks.html+++ b/internal/glance/templates/bookmarks.html@@ -10,10 +10,10 @@<ul class="list list-gap-2">{{- range .Links }}<li>- <div class="flex items-center gap-10 icon-parent">+ <div class="flex items-center gap-10">{{- if ne "" .Icon.URL }}<div class="bookmarks-icon-container">- {{ .Icon.ElemWithClass "square-20" }}+ <img class="bookmarks-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}" src="{{ .Icon.URL }}" alt="" loading="lazy"></div>{{- end }}<a href="{{ .URL | safeURL }}" class="bookmarks-link {{ if .HideArrow }}bookmarks-link-no-arrow {{ end }}color-highlight size-h4" {{ if .Target }}target="{{ .Target }}"{{ end }} rel="noreferrer">{{ .Title }}</a>diff --git a/internal/glance/templates/docker-containers.html b/internal/glance/templates/docker-containers.htmlindex f7c8d7c..1e694ae 100644--- a/internal/glance/templates/docker-containers.html+++ b/internal/glance/templates/docker-containers.html@@ -3,9 +3,9 @@{{- define "widget-content" }}<ul class="dynamic-columns list-gap-20 list-with-separator">{{- range .Containers }}- <li class="flex items-center gap-15 icon-parent">+ <li class="docker-container flex items-center gap-15"><div class="shrink-0" data-popover-type="html" data-popover-position="above" data-popover-offset="0.25" data-popover-margin="0.1rem" data-popover-max-width="400px" aria-hidden="true">- {{ .Icon.ElemWithClass "square-27" }}+ <img class="docker-container-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}" src="{{ .Icon.URL }}" alt="" loading="lazy"><div data-popover-html><div class="color-highlight text-truncate block">{{ .Image }}</div><div>{{ .StateText }}</div>@@ -47,19 +47,19 @@{{- define "state-icon" }}{{- if eq . "ok" }}-<svg class="square-20" fill="var(--color-positive)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true">+<svg class="docker-container-status-icon" fill="var(--color-positive)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z" clip-rule="evenodd" /></svg>{{- else if eq . "warn" }}-<svg class="square-20" fill="var(--color-negative)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true">+<svg class="docker-container-status-icon" fill="var(--color-negative)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" clip-rule="evenodd" /></svg>{{- else if eq . "paused" }}-<svg class="square-20" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true">+<svg class="docker-container-status-icon" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill-rule="evenodd" d="M2 10a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm5-2.25A.75.75 0 0 1 7.75 7h.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1-.75-.75v-4.5Zm4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1-.75-.75v-4.5Z" clip-rule="evenodd" /></svg>{{- else }}-<svg class="square-20" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true">+<svg class="docker-container-status-icon" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill-rule="evenodd" d="M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0ZM8.94 6.94a.75.75 0 1 1-1.061-1.061 3 3 0 1 1 2.871 5.026v.345a.75.75 0 0 1-1.5 0v-.5c0-.72.57-1.172 1.081-1.287A1.5 1.5 0 1 0 8.94 6.94ZM10 15a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" clip-rule="evenodd" /></svg>{{- end }}diff --git a/internal/glance/templates/forum-posts.html b/internal/glance/templates/forum-posts.htmlindex c8169b4..5b65b69 100644--- a/internal/glance/templates/forum-posts.html+++ b/internal/glance/templates/forum-posts.html@@ -1,9 +1,6 @@{{ template "widget-base.html" . }}{{- define "widget-content" }}-{{ if .Filters.AllFiltered }}-<p>No posts match the specified filters ({{ .Filters.FilteredCount }} filtered)</p>-{{ else }}<ul class="list list-gap-14 collapsible-container" data-collapse-after="{{ .CollapseAfter }}">{{- range .Posts }}<li>@@ -49,5 +46,4 @@</li>{{- end }}</ul>-{{ end }}{{- end }}diff --git a/internal/glance/templates/monitor-compact.html b/internal/glance/templates/monitor-compact.htmlindex c7ac5e7..dca5683 100644--- a/internal/glance/templates/monitor-compact.html+++ b/internal/glance/templates/monitor-compact.html@@ -2,7 +2,7 @@{{ define "widget-content" }}{{ if not (and .ShowFailingOnly (not .HasFailing)) }}-<ul class="dynamic-columns list-gap-10">+<ul class="dynamic-columns list-gap-8">{{ range .Sites }}{{ if and $.ShowFailingOnly (eq .StatusStyle "ok" ) }}{{ continue }}{{ end }}<div class="flex items-center gap-12">@@ -21,19 +21,16 @@{{ end }}{{ define "site" }}-{{ if .Icon.URL }}-{{ .Icon.ElemWithClass "square-20" }}-{{ end }}<a class="size-title-dynamic color-highlight text-truncate block grow" href="{{ .URL | safeURL }}" {{ if not .SameTab }}target="_blank"{{ end }} rel="noreferrer">{{ .Title }}</a>{{ if not .Status.TimedOut }}<div>{{ .Status.ResponseTime.Milliseconds | formatNumber }}ms</div>{{ end }}{{ if eq .StatusStyle "ok" }}-<div class="square-18 shrink-0" title="{{ .Status.Code }}">+<div class="monitor-site-status-icon-compact" title="{{ .Status.Code }}"><svg fill="var(--color-positive)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z" clip-rule="evenodd" /></svg></div>{{ else }}-<div class="square-18 shrink-0" title="{{ if .Status.Error }}{{ .Status.Error }}{{ else }}{{ .Status.Code }}{{ end }}">+<div class="monitor-site-status-icon-compact" title="{{ if .Status.Error }}{{ .Status.Error }}{{ else }}{{ .Status.Code }}{{ end }}"><svg fill="var(--color-negative)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" clip-rule="evenodd" /></svg>diff --git a/internal/glance/templates/monitor.html b/internal/glance/templates/monitor.htmlindex da9907c..cbdcbae 100644--- a/internal/glance/templates/monitor.html+++ b/internal/glance/templates/monitor.html@@ -5,7 +5,7 @@<ul class="dynamic-columns list-gap-20 list-with-separator">{{ range .Sites }}{{ if and $.ShowFailingOnly (eq .StatusStyle "ok" ) }} {{ continue }} {{ end }}- <div class="monitor-site flex items-center gap-15 icon-parent">+ <div class="monitor-site flex items-center gap-15">{{ template "site" . }}</div>{{ end }}@@ -22,7 +22,7 @@{{ define "site" }}{{ if .Icon.URL }}-{{ .Icon.ElemWithClass "square-32" }}+<img class="monitor-site-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}" src="{{ .Icon.URL }}" alt="" loading="lazy">{{ end }}<div class="grow min-width-0"><a class="size-h3 color-highlight text-truncate block" href="{{ .URL | safeURL }}" {{ if not .SameTab }}target="_blank"{{ end }} rel="noreferrer">{{ .Title }}</a>@@ -38,13 +38,13 @@</ul></div>{{ if eq .StatusStyle "ok" }}-<div class="square-20 shrink-0 margin-left-auto">+<div class="monitor-site-status-icon"><svg fill="var(--color-positive)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z" clip-rule="evenodd" /></svg></div>{{ else }}-<div class="square-20 shrink-0 margin-left-auto">+<div class="monitor-site-status-icon"><svg fill="var(--color-negative)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" clip-rule="evenodd" /></svg>diff --git a/internal/glance/templates/page.html b/internal/glance/templates/page.htmlindex 45619e9..0f83183 100644--- a/internal/glance/templates/page.html+++ b/internal/glance/templates/page.html@@ -8,7 +8,7 @@{{ define "navigation-links" }}{{ range .App.Config.Pages }}-<a href="{{ $.App.Config.Server.BaseURL }}/{{ .Slug }}" class="nav-item{{ if eq .Slug $.Page.Slug }} nav-item-current{{ end }}"{{ if eq .Slug $.Page.Slug }} aria-current="page"{{ end }}><div class="nav-item-text">{{ .Title }}</div></a>+<a href="{{ $.App.Config.Server.BaseURL }}/{{ .Slug }}" class="nav-item{{ if eq .Slug $.Page.Slug }} nav-item-current{{ end }}"{{ if eq .Slug $.Page.Slug }} aria-current="page"{{ end }}>{{ .Title }}</a>{{ end }}{{ end }}@@ -30,7 +30,7 @@</svg>{{- end }}</div>- <nav class="desktop-navigation flex grow hide-scrollbars">+ <nav class="nav flex grow hide-scrollbars">{{ template "navigation-links" . }}</nav>{{ if not .App.Config.Theme.DisablePicker }}diff --git a/internal/glance/templates/theme-preset-preview.html b/internal/glance/templates/theme-preset-preview.htmlindex 4538344..ac17f98 100644--- a/internal/glance/templates/theme-preset-preview.html+++ b/internal/glance/templates/theme-preset-preview.html@@ -12,7 +12,7 @@{{- end }}{{- end }}{{- if .NegativeColor }}{{ $negative = .NegativeColor.String | safeCSS }}{{ end }}-<button class="theme-preset{{ if .Light }} theme-preset-light{{ end }}" style="--color: {{ $background }}" data-key="{{ .Key }}" title="{{ .Key }}">+<button class="theme-preset{{ if .Light }} theme-preset-light{{ end }}" style="--color: {{ $background }}" data-key="{{ .Key }}"><div class="theme-color" style="--color: {{ $primary }}"></div><div class="theme-color" style="--color: {{ $positive }}"></div><div class="theme-color" style="--color: {{ $negative }}"></div>diff --git a/internal/glance/templates/torrents.html b/internal/glance/templates/torrents.htmldeleted file mode 100644index df27e80..0000000--- a/internal/glance/templates/torrents.html+++ /dev/null@@ -1,33 +0,0 @@-{{ template "widget-base.html" . }}--{{ define "widget-content" }}-{{- if .Torrents }}-<ul class="list list-gap-20 collapsible-container" data-collapse-after="5">-{{- range .Torrents }}- <li>- <div class="size-title-dynamic text-truncate{{ if not .Downloaded }} color-highlight{{ end }}">{{ .Name }}</div>- <ul class="list-horizontal-text horizontal-text-gap-5 text-compact margin-top-2">- {{- if not .Downloaded }}- <li>{{ .ProgressFormatted }}</li>- {{- else }}- <li title="{{ .StateDescription }}">{{ .State }}</li>- {{- end }}- {{- if .DownSpeedFormatted }}- <li>{{ .DownSpeedFormatted }}/s</li>- {{- end }}- {{- if eq .State "Downloading" }}- <li>{{ .ETAFormatted }} ETA</li>- {{- else if not .Downloaded }}- <li title="{{ .StateDescription }}">{{ .State }}</li>- {{- end }}- </ul>- <div class="progress-bar progress-bar-mini margin-top-5">- <div class="progress-value" style="--percent: {{ .Progress }};"></div>- </div>- </li>- {{- end }}-</ul>-{{- else }}-<div class="text-center">No active torrents</div>-{{- end }}-{{ end }}diff --git a/internal/glance/templates/trending-repositories.html b/internal/glance/templates/trending-repositories.htmldeleted file mode 100644index e9cac4e..0000000--- a/internal/glance/templates/trending-repositories.html+++ /dev/null@@ -1,22 +0,0 @@-{{ template "widget-base.html" . }}--{{ define "widget-content" }}-<ul class="list list-gap-14 collapsible-container" data-collapse-after="{{ .CollapseAfter }}">- {{ range .Repositories }}- <li>- <a class="size-h4 block text-truncate color-primary-if-not-visited" href="https://github.com/{{ .Slug }}" target="_blank" rel="noreferrer">{{ .Slug }}</a>- {{ if .Description}}- <p class="text-truncate-2-lines margin-top-3">{{ .Description }}</p>- {{ end }}- <ul class="list-horizontal-text margin-top-3">- {{ if .Language }}- <li>{{ .Language }}</li>- {{ end }}- <li>{{ .Stars | formatNumber }} stars</li>- </ul>- </li>- {{ else }}- <p>No repositories found.</p>- {{ end }}-</ul>-{{ end }}diff --git a/internal/glance/templates/videos-grid.html b/internal/glance/templates/videos-grid.htmlindex 4c87384..2819fe8 100644--- a/internal/glance/templates/videos-grid.html+++ b/internal/glance/templates/videos-grid.html@@ -1,11 +1,8 @@{{ template "widget-base.html" . }}-{{ define "widget-content-classes" }}{{ if not .Filters.AllFiltered }}widget-content-frameless{{ end }}{{ end }}+{{ define "widget-content-classes" }}widget-content-frameless{{ end }}{{ define "widget-content" }}-{{ if .Filters.AllFiltered }}-<p>No videos match the specified filters ({{ .Filters.FilteredCount }} filtered)</p>-{{ else }}<div class="cards-grid collapsible-container" data-collapse-after-rows="{{ .CollapseAfterRows }}">{{ range .Videos }}<div class="card widget-content-frame thumbnail-parent">@@ -14,4 +11,3 @@{{ end }}</div>{{ end }}-{{ end }}diff --git a/internal/glance/templates/videos-vertical-list.html b/internal/glance/templates/videos-vertical-list.htmlindex a6639f2..cd760a4 100644--- a/internal/glance/templates/videos-vertical-list.html+++ b/internal/glance/templates/videos-vertical-list.html@@ -1,9 +1,6 @@{{ template "widget-base.html" . }}{{- define "widget-content" }}-{{ if .Filters.AllFiltered }}-<p>No videos match the specified filters ({{ .Filters.FilteredCount }} filtered)</p>-{{ else }}<ul class="list list-gap-14 collapsible-container" data-collapse-after="{{ .CollapseAfter }}">{{- range .Videos }}<li class="flex thumbnail-parent gap-10 items-center">@@ -20,5 +17,4 @@</li>{{- end }}</ul>-{{ end }}{{- end }}diff --git a/internal/glance/templates/videos.html b/internal/glance/templates/videos.htmlindex 8a09b18..16e7261 100644--- a/internal/glance/templates/videos.html+++ b/internal/glance/templates/videos.html@@ -1,11 +1,8 @@{{ template "widget-base.html" . }}-{{ define "widget-content-classes" }}{{ if not .Filters.AllFiltered }}widget-content-frameless{{ end }}{{ end }}+{{ define "widget-content-classes" }}widget-content-frameless{{ end }}{{ define "widget-content" }}-{{ if .Filters.AllFiltered }}-<p>No videos match the specified filters ({{ .Filters.FilteredCount }} filtered)</p>-{{ else }}<div class="carousel-container"><div class="cards-horizontal carousel-items-container">{{ range .Videos }}@@ -16,4 +13,3 @@</div></div>{{ end }}-{{ end }}diff --git a/internal/glance/utils.go b/internal/glance/utils.goindex c1276c3..21cd69b 100644--- a/internal/glance/utils.go+++ b/internal/glance/utils.go@@ -245,22 +245,3 @@ func hslToHex(h, s, l float64) string {return fmt.Sprintf("#%02x%02x%02x", ir, ig, ib)}--func numCompare[T int | uint64 | float64](a, b T) int {- if a < b {- return -1- } else if a > b {- return 1- }- return 0-}--func boolCompare(a, b bool) int {- if a == b {- return 0- } else if !a && b {- return -1- } else {- return 1- }-}diff --git a/internal/glance/widget-bookmarks.go b/internal/glance/widget-bookmarks.goindex 539f7d1..2245e2e 100644--- a/internal/glance/widget-bookmarks.go+++ b/internal/glance/widget-bookmarks.go@@ -1,52 +1,42 @@package glanceimport (- "errors""html/template")var bookmarksWidgetTemplate = mustParseTemplate("bookmarks.html", "widget-base.html")-var bookmarksGridWidgetTemplate = mustParseTemplate("bookmarks-grid.html", "widget-base.html")--type bookmarkLinks []struct {- Title string `yaml:"title"`- URL string `yaml:"url"`- Description string `yaml:"description"`- Icon customIconField `yaml:"icon"`- // we need a pointer to bool to know whether a value was provided,- // however there's no way to dereference a pointer in a template so- // {{ if not .SameTab }} would return true for any non-nil pointer- // which leaves us with no way of checking if the value is true or- // false, hence the duplicated fields below- SameTabRaw *bool `yaml:"same-tab"`- SameTab bool `yaml:"-"`- HideArrowRaw *bool `yaml:"hide-arrow"`- HideArrow bool `yaml:"-"`- Target string `yaml:"target"`-}type bookmarksWidget struct {widgetBase `yaml:",inline"`- cachedHTML template.HTML `yaml:"-"`- Style string `yaml:"style"`- Links *bookmarkLinks `yaml:"-"`+ cachedHTML template.HTML `yaml:"-"`Groups []struct {Title string `yaml:"title"`Color *hslColorField `yaml:"color"`SameTab bool `yaml:"same-tab"`HideArrow bool `yaml:"hide-arrow"`Target string `yaml:"target"`- Links bookmarkLinks `yaml:"links"`+ Links []struct {+ Title string `yaml:"title"`+ URL string `yaml:"url"`+ Description string `yaml:"description"`+ Icon customIconField `yaml:"icon"`+ // we need a pointer to bool to know whether a value was provided,+ // however there's no way to dereference a pointer in a template so+ // {{ if not .SameTab }} would return true for any non-nil pointer+ // which leaves us with no way of checking if the value is true or+ // false, hence the duplicated fields below+ SameTabRaw *bool `yaml:"same-tab"`+ SameTab bool `yaml:"-"`+ HideArrowRaw *bool `yaml:"hide-arrow"`+ HideArrow bool `yaml:"-"`+ Target string `yaml:"target"`+ } `yaml:"links"`} `yaml:"groups"`}func (widget *bookmarksWidget) initialize() error {widget.withTitle("Bookmarks").withError(nil)- if len(widget.Groups) == 0 {- return errors.New("must have at least one group")- }-for g := range widget.Groups {group := &widget.Groups[g]for l := range group.Links {@@ -77,16 +67,7 @@ func (widget *bookmarksWidget) initialize() error {}}- if widget.Style == "grid" {- if len(widget.Groups) != 1 {- return errors.New("grid style can only be used with a single group")- }-- widget.Links = &widget.Groups[0].Links- widget.cachedHTML = widget.renderTemplate(widget, bookmarksGridWidgetTemplate)- } else {- widget.cachedHTML = widget.renderTemplate(widget, bookmarksWidgetTemplate)- }+ widget.cachedHTML = widget.renderTemplate(widget, bookmarksWidgetTemplate)return nil}diff --git a/internal/glance/widget-custom-api.go b/internal/glance/widget-custom-api.goindex 28a20e0..3c2ca75 100644--- a/internal/glance/widget-custom-api.go+++ b/internal/glance/widget-custom-api.go@@ -8,10 +8,8 @@ import ("fmt""html/template""io"- "iter""log/slog""math"- "math/rand""net/http""regexp""sort"@@ -34,14 +32,9 @@ type CustomAPIRequest struct {Method string `yaml:"method"`BodyType string `yaml:"body-type"`Body any `yaml:"body"`- MockResponse string `yaml:"mock-response"`SkipJSONValidation bool `yaml:"skip-json-validation"`- BasicAuth struct {- Username string `yaml:"username"`- Password string `yaml:"password"`- } `yaml:"basic-auth"`- bodyReader io.ReadSeeker `yaml:"-"`- httpRequest *http.Request `yaml:"-"`+ bodyReader io.ReadSeeker `yaml:"-"`+ httpRequest *http.Request `yaml:"-"`}type customAPIWidget struct {@@ -194,10 +187,6 @@ func (req *CustomAPIRequest) initialize() error {httpReq.Header.Add(key, value)}- if req.BasicAuth.Username != "" || req.BasicAuth.Password != "" {- httpReq.SetBasicAuth(req.BasicAuth.Username, req.BasicAuth.Password)- }-req.httpRequest = httpReqreturn nil@@ -240,15 +229,6 @@ func (data *customAPITemplateData) Subrequest(key string) *customAPIResponseData}func fetchCustomAPIResponse(ctx context.Context, req *CustomAPIRequest) (*customAPIResponseData, error) {- if req != nil && req.MockResponse != "" {- return &customAPIResponseData{- JSON: decoratedGJSONResult{gjson.Parse(req.MockResponse)},- Response: &http.Response{- StatusCode: http.StatusOK,- },- }, nil- }-if req == nil || req.URL == "" {return &customAPIResponseData{JSON: decoratedGJSONResult{gjson.Result{}},@@ -435,21 +415,6 @@ func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult {return &decoratedGJSONResult{r.Result.Get(key)}}-func (r *decoratedGJSONResult) Entries(key string) iter.Seq2[string, *decoratedGJSONResult] {- var obj gjson.Result- if key == "" {- obj = r.Result- } else {- obj = r.Result.Get(key)- }-- return func(yield func(string, *decoratedGJSONResult) bool) {- obj.ForEach(func(k, v gjson.Result) bool {- return yield(k.String(), &decoratedGJSONResult{v})- })- }-}-func customAPIDoMathOp[T int | float64](a, b T, op string) T {switch op {case "add":@@ -534,10 +499,6 @@ var customAPITemplateFuncs = func() template.FuncMap {}return a % b},- "iconWithClass": func(name, class string) template.HTML {- i := newCustomIconField(name)- return i.ElemWithClass(class)- },"now": func() time.Time {return time.Now()},@@ -561,7 +522,7 @@ var customAPITemplateFuncs = func() template.FuncMap {},"formatTime": customAPIFuncFormatTime,"parseLocalTime": func(layout, value string) time.Time {- return customAPIFuncParseTimeInLocation(layout, value, time.Local).In(time.Local)+ return customAPIFuncParseTimeInLocation(layout, value, time.Local)},"toRelativeTime": dynamicRelativeTimeAttrs,"parseRelativeTime": func(layout, value string) template.HTMLAttr {@@ -674,11 +635,7 @@ var customAPITemplateFuncs = func() template.FuncMap {}return out},- "newRequest": func(url string, params ...any) *CustomAPIRequest {- if len(params) > 0 {- url = fmt.Sprintf(url, params...)- }-+ "newRequest": func(url string) *CustomAPIRequest {return &CustomAPIRequest{URL: url,}@@ -702,25 +659,6 @@ var customAPITemplateFuncs = func() template.FuncMap {req.BodyType = "string"return req},- "withAllowInsecure": func(val any, req *CustomAPIRequest) *CustomAPIRequest {- switch v := val.(type) {- case bool:- req.AllowInsecure = v- case string:- if strings.ToLower(v) == "true" {- req.AllowInsecure = true- }- default:- slog.Warn("withAllowInsecure called with non-boolean value, must be string or bool", "value", v)- }-- return req- },- "withBasicAuth": func(username, password string, req *CustomAPIRequest) *CustomAPIRequest {- req.BasicAuth.Username = username- req.BasicAuth.Password = password- return req- },"getResponse": func(req *CustomAPIRequest) *customAPIResponseData {err := req.initialize()if err != nil {@@ -740,13 +678,6 @@ var customAPITemplateFuncs = func() template.FuncMap {return data},- "randomElement": func(arr []decoratedGJSONResult) *decoratedGJSONResult {- if len(arr) == 0 {- return &decoratedGJSONResult{gjson.Result{}}- }-- return &arr[rand.Intn(len(arr))]- },}for key, value := range globalTemplateFunctions {diff --git a/internal/glance/widget-dns-stats.go b/internal/glance/widget-dns-stats.goindex d50e718..7311b1b 100644--- a/internal/glance/widget-dns-stats.go+++ b/internal/glance/widget-dns-stats.go@@ -429,24 +429,22 @@ func fetchPiholeStats(return nil}- if password != "" {- if sessionID == "" {- if err := fetchNewSessionID(); err != nil {- slog.Error("Failed to fetch Pihole v6 session ID", "error", err)- return nil, "", fmt.Errorf("fetching session ID: %v", err)- }- } else {- isValid, err := checkPiholeSessionIDIsValid(instanceURL, client, sessionID)- if err != nil {- slog.Error("Failed to check Pihole v6 session ID validity", "error", err)- return nil, "", fmt.Errorf("checking session ID: %v", err)- }+ if sessionID == "" {+ if err := fetchNewSessionID(); err != nil {+ slog.Error("Failed to fetch Pihole v6 session ID", "error", err)+ return nil, "", fmt.Errorf("fetching session ID: %v", err)+ }+ } else {+ isValid, err := checkPiholeSessionIDIsValid(instanceURL, client, sessionID)+ if err != nil {+ slog.Error("Failed to check Pihole v6 session ID validity", "error", err)+ return nil, "", fmt.Errorf("checking session ID: %v", err)+ }- if !isValid {- if err := fetchNewSessionID(); err != nil {- slog.Error("Failed to renew Pihole v6 session ID", "error", err)- return nil, "", fmt.Errorf("renewing session ID: %v", err)- }+ if !isValid {+ if err := fetchNewSessionID(); err != nil {+ slog.Error("Failed to renew Pihole v6 session ID", "error", err)+ return nil, "", fmt.Errorf("renewing session ID: %v", err)}}}diff --git a/internal/glance/widget-docker-containers.go b/internal/glance/widget-docker-containers.goindex 0a80f5c..702a34b 100644--- a/internal/glance/widget-docker-containers.go+++ b/internal/glance/widget-docker-containers.go@@ -49,7 +49,7 @@ func (widget *dockerContainersWidget) update(ctx context.Context) {return}- containers.sortByStateIconThenName()+ containers.sortByStateIconThenTitle()widget.Containers = containers}@@ -125,7 +125,7 @@ type dockerContainer struct {type dockerContainerList []dockerContainer-func (containers dockerContainerList) sortByStateIconThenName() {+func (containers dockerContainerList) sortByStateIconThenTitle() {p := &dockerContainerStateIconPrioritiessort.SliceStable(containers, func(a, b int) bool {@@ -137,17 +137,13 @@ func (containers dockerContainerList) sortByStateIconThenName() {})}-func dockerContainerStateToStateIcon(container *dockerContainerJsonResponse) string {- if strings.Contains(strings.ToLower(container.Status), "(unhealthy)") {- return dockerContainerStateIconWarn- }-- switch strings.ToLower(container.State) {+func dockerContainerStateToStateIcon(state string) string {+ switch state {case "running":return dockerContainerStateIconOKcase "paused":return dockerContainerStateIconPaused- case "exited", "dead":+ case "exited", "unhealthy", "dead":return dockerContainerStateIconWarndefault:return dockerContainerStateIconOther@@ -191,13 +187,13 @@ func fetchDockerContainers(dc.Children = append(dc.Children, dockerContainer{Name: deriveDockerContainerName(child, formatNames),StateText: child.Status,- StateIcon: dockerContainerStateToStateIcon(child),+ StateIcon: dockerContainerStateToStateIcon(strings.ToLower(child.State)),})}}}- dc.Children.sortByStateIconThenName()+ dc.Children.sortByStateIconThenTitle()stateIconSupersededByChild := falsefor i := range dc.Children {@@ -208,7 +204,7 @@ func fetchDockerContainers(}}if !stateIconSupersededByChild {- dc.StateIcon = dockerContainerStateToStateIcon(container)+ dc.StateIcon = dockerContainerStateToStateIcon(dc.State)}dockerContainers = append(dockerContainers, dc)@@ -282,6 +278,7 @@ func isDockerContainerHidden(container *dockerContainerJsonResponse, hideByDefaureturn hideByDefault}+func fetchDockerContainersFromSource(source string,category string,@@ -315,6 +312,7 @@ func fetchDockerContainersFromSource(}}+fetchAll := ternary(runningOnly, "false", "true")ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()diff --git a/internal/glance/widget-hacker-news.go b/internal/glance/widget-hacker-news.goindex 5269a85..ad00df0 100644--- a/internal/glance/widget-hacker-news.go+++ b/internal/glance/widget-hacker-news.go@@ -20,8 +20,6 @@ type hackerNewsWidget struct {CollapseAfter int `yaml:"collapse-after"`CommentsUrlTemplate string `yaml:"comments-url-template"`ShowThumbnails bool `yaml:"-"`-- Filters filterableFields[forumPost] `yaml:"filters"`}func (widget *hackerNewsWidget) initialize() error {@@ -47,21 +45,20 @@ func (widget *hackerNewsWidget) initialize() error {func (widget *hackerNewsWidget) update(ctx context.Context) {posts, err := fetchHackerNewsPosts(widget.SortBy, 40, widget.CommentsUrlTemplate)+if !widget.canContinueUpdateAfterHandlingErr(err) {return}- posts = widget.Filters.Apply(posts)-- if widget.Limit < len(posts) {- posts = posts[:widget.Limit]- }-if widget.ExtraSortBy == "engagement" {posts.calculateEngagement()posts.sortByEngagement()}+ if widget.Limit < len(posts) {+ posts = posts[:widget.Limit]+ }+widget.Posts = posts}diff --git a/internal/glance/widget-html.go b/internal/glance/widget-html.goindex ac268d0..0e32a46 100644--- a/internal/glance/widget-html.go+++ b/internal/glance/widget-html.go@@ -10,7 +10,7 @@ type htmlWidget struct {}func (widget *htmlWidget) initialize() error {- widget.withTitle("HTML").withError(nil)+ widget.withTitle("").withError(nil)return nil}diff --git a/internal/glance/widget-lobsters.go b/internal/glance/widget-lobsters.goindex 59405a4..786d1df 100644--- a/internal/glance/widget-lobsters.go+++ b/internal/glance/widget-lobsters.go@@ -18,8 +18,6 @@ type lobstersWidget struct {SortBy string `yaml:"sort-by"`Tags []string `yaml:"tags"`ShowThumbnails bool `yaml:"-"`-- Filters filterableFields[forumPost] `yaml:"filters"`}func (widget *lobstersWidget) initialize() error {@@ -53,8 +51,6 @@ func (widget *lobstersWidget) update(ctx context.Context) {return}- posts = widget.Filters.Apply(posts)-if widget.Limit < len(posts) {posts = posts[:widget.Limit]}diff --git a/internal/glance/widget-markets.go b/internal/glance/widget-markets.goindex b204d40..b53b10a 100644--- a/internal/glance/widget-markets.go+++ b/internal/glance/widget-markets.go@@ -106,7 +106,6 @@ type marketResponseJson struct {Symbol string `json:"symbol"`RegularMarketPrice float64 `json:"regularMarketPrice"`ChartPreviousClose float64 `json:"chartPreviousClose"`- ExchangeName string `json:"exchangeName"`ShortName string `json:"shortName"`PriceHint int `json:"priceHint"`} `json:"meta"`@@ -175,11 +174,6 @@ func fetchMarketsDataFromYahoo(marketRequests []marketRequest) (marketList, errocurrency = result.Meta.Currency}- // See https://github.com/glanceapp/glance/issues/757- if result.Meta.ExchangeName == "LSE" {- currency = ""- }-markets = append(markets, market{marketRequest: marketRequests[i],Price: result.Meta.RegularMarketPrice,diff --git a/internal/glance/widget-reddit.go b/internal/glance/widget-reddit.goindex e3a3d75..f9db357 100644--- a/internal/glance/widget-reddit.go+++ b/internal/glance/widget-reddit.go@@ -42,8 +42,6 @@ type redditWidget struct {CollapseAfter int `yaml:"collapse-after"`RequestURLTemplate string `yaml:"request-url-template"`- Filters filterableFields[forumPost] `yaml:"filters"`-AppAuth struct {Name string `yaml:"name"`ID string `yaml:"id"`@@ -106,17 +104,15 @@ func (widget *redditWidget) update(ctx context.Context) {return}- posts = widget.Filters.Apply(posts)+ if len(posts) > widget.Limit {+ posts = posts[:widget.Limit]+ }if widget.ExtraSortBy == "engagement" {posts.calculateEngagement()posts.sortByEngagement()}- if len(posts) > widget.Limit {- posts = posts[:widget.Limit]- }-widget.Posts = posts}diff --git a/internal/glance/widget-repository.go b/internal/glance/widget-repository.goindex 4f4cc9e..1eeb8b4 100644--- a/internal/glance/widget-repository.go+++ b/internal/glance/widget-repository.go@@ -19,7 +19,6 @@ type repositoryWidget struct {PullRequestsLimit int `yaml:"pull-requests-limit"`IssuesLimit int `yaml:"issues-limit"`CommitsLimit int `yaml:"commits-limit"`- ExcludeDraftPRs bool `yaml:"exclude-draft-pull-requests"`Repository repository `yaml:"-"`}@@ -48,7 +47,6 @@ func (widget *repositoryWidget) update(ctx context.Context) {widget.PullRequestsLimit,widget.IssuesLimit,widget.CommitsLimit,- widget.ExcludeDraftPRs,)if !widget.canContinueUpdateAfterHandlingErr(err) {@@ -113,18 +111,13 @@ type gitHubCommitResponseJson struct {} `json:"commit"`}-func fetchRepositoryDetailsFromGithub(repo string, token string, maxPRs int, maxIssues int, maxCommits int, excludeDraftPRs bool) (repository, error) {+func fetchRepositoryDetailsFromGithub(repo string, token string, maxPRs int, maxIssues int, maxCommits int) (repository, error) {repositoryRequest, err := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s", repo), nil)if err != nil {return repository{}, fmt.Errorf("%w: could not create request with repository: %v", errNoContent, err)}- RRsQuery := fmt.Sprintf("is:pr+is:open+repo:%s", repo)- if excludeDraftPRs {- RRsQuery += "+-is:draft"- }-- PRsRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/search/issues?q=%s&per_page=%d", RRsQuery, maxPRs), nil)+ PRsRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/search/issues?q=is:pr+is:open+repo:%s&per_page=%d", repo, maxPRs), nil)issuesRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/search/issues?q=is:issue+is:open+repo:%s&per_page=%d", repo, maxIssues), nil)CommitsRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s/commits?per_page=%d", repo, maxCommits), nil)diff --git a/internal/glance/widget-rss.go b/internal/glance/widget-rss.goindex c66dc16..fe17b2f 100644--- a/internal/glance/widget-rss.go+++ b/internal/glance/widget-rss.go@@ -44,8 +44,6 @@ type rssWidget struct {cachedFeedsMutex sync.MutexcachedFeeds map[string]*cachedRSSFeed `yaml:"-"`-- Filters filterableFields[rssFeedItem] `yaml:"filters"`}func (widget *rssWidget) initialize() error {@@ -73,14 +71,13 @@ func (widget *rssWidget) initialize() error {}}+ widget.NoItemsMessage = "No items were returned from the feeds."widget.cachedFeeds = make(map[string]*cachedRSSFeed)return nil}func (widget *rssWidget) update(ctx context.Context) {- widget.NoItemsMessage = "No items were returned from the feeds."-items, err := widget.fetchItemsFromFeeds()if !widget.canContinueUpdateAfterHandlingErr(err) {@@ -91,15 +88,6 @@ func (widget *rssWidget) update(ctx context.Context) {items.sortByNewest()}- items = widget.Filters.Apply(items)-- if widget.Filters.AllFiltered {- widget.NoItemsMessage = fmt.Sprintf(- "No items match the specified filters (%d filtered)",- widget.Filters.FilteredCount,- )- }-if len(items) > widget.Limit {items = items[:widget.Limit]}@@ -140,29 +128,15 @@ type rssFeedItem struct {PublishedAt time.Time}-func (i rssFeedItem) filterableField(field string) any {- switch field {- case "title":- return i.Title- case "description":- return i.Description- case "posted":- return i.PublishedAt- default:- return nil- }-}-type rssFeedRequest struct {- URL string `yaml:"url"`- Title string `yaml:"title"`- HideCategories bool `yaml:"hide-categories"`- HideDescription bool `yaml:"hide-description"`- Limit int `yaml:"limit"`- ItemLinkPrefix string `yaml:"item-link-prefix"`- ThumbnailLinkPrefix string `yaml:"thumbnail-link-prefix"`- Headers map[string]string `yaml:"headers"`- IsDetailed bool `yaml:"-"`+ URL string `yaml:"url"`+ Title string `yaml:"title"`+ HideCategories bool `yaml:"hide-categories"`+ HideDescription bool `yaml:"hide-description"`+ Limit int `yaml:"limit"`+ ItemLinkPrefix string `yaml:"item-link-prefix"`+ Headers map[string]string `yaml:"headers"`+ IsDetailed bool `yaml:"-"`}type rssFeedItemList []rssFeedItem@@ -347,24 +321,6 @@ func (widget *rssWidget) fetchItemsFromFeedTask(request rssFeedRequest) ([]rssFe}}- // For some reason gofeed sometimes converts absolute URLs to relative ones, so we need to fix- // that here and provide the user with an option to override the prefix in case we get it wrong- if strings.HasPrefix(rssItem.ImageURL, "/") {- prefix := strings.TrimPrefix(feed.Link, "/")- if request.ThumbnailLinkPrefix != "" {- prefix = strings.TrimPrefix(request.ThumbnailLinkPrefix, "/")- } else if prefix == "" {- parsed, err := url.Parse(request.URL)- if err != nil {- prefix = request.URL- } else {- prefix = parsed.Scheme + "://" + parsed.Host- }- }-- rssItem.ImageURL = strings.TrimRight(prefix, "/") + rssItem.ImageURL- }-if item.PublishedParsed != nil {rssItem.PublishedAt = *item.PublishedParsed} else {diff --git a/internal/glance/widget-search.go b/internal/glance/widget-search.goindex 66a4cfd..300361d 100644--- a/internal/glance/widget-search.go+++ b/internal/glance/widget-search.go@@ -35,10 +35,9 @@ var searchEngines = map[string]string{"duckduckgo": "https://duckduckgo.com/?q={QUERY}","google": "https://www.google.com/search?q={QUERY}","bing": "https://www.bing.com/search?q={QUERY}",- "brave": "https://search.brave.com/search?q={QUERY}","perplexity": "https://www.perplexity.ai/search?q={QUERY}",- "kagi": "https://kagi.com/search?q={QUERY}",- "startpage": "https://www.startpage.com/search?q={QUERY}",+ "kagi": "https://kagi.com/search?q={QUERY}",+ "startpage": "https://www.startpage.com/search?q={QUERY}",}func (widget *searchWidget) initialize() error {diff --git a/internal/glance/widget-shared.go b/internal/glance/widget-shared.goindex 8896ccb..45144ac 100644--- a/internal/glance/widget-shared.go+++ b/internal/glance/widget-shared.go@@ -27,21 +27,6 @@ type forumPost struct {type forumPostList []forumPost-func (p forumPost) filterableField(field string) any {- switch field {- case "title":- return p.Title- case "comments":- return p.CommentCount- case "points":- return p.Score- case "posted":- return p.TimePosted- default:- return nil- }-}-const depreciatePostsOlderThanHours = 7const maxDepreciation = 0.9const maxDepreciationAfterHours = 24@@ -68,7 +53,7 @@ func (p forumPostList) calculateEngagement() {continue}- p[i].Engagement *= 1.0 - (math.Min(elapsed.Hours()-depreciatePostsOlderThanHours, maxDepreciationAfterHours)/maxDepreciationAfterHours)*maxDepreciation+ p[i].Engagement *= 1.0 - (math.Max(elapsed.Hours()-depreciatePostsOlderThanHours, maxDepreciationAfterHours)/maxDepreciationAfterHours)*maxDepreciation}}diff --git a/internal/glance/widget-shared_test.go b/internal/glance/widget-shared_test.godeleted file mode 100644index ca95ac6..0000000--- a/internal/glance/widget-shared_test.go+++ /dev/null@@ -1,53 +0,0 @@-package glance--import (- "math"- "testing"- "time"-)--// Every post is given an identical comment count and score so that each post's-// pre-depreciation engagement is exactly 1.0. That isolates the time-based-// depreciation applied by calculateEngagement, which is the only thing that-// should differentiate the posts.-func TestCalculateEngagementTimeDepreciation(t *testing.T) {- now := time.Now()-- posts := forumPostList{- {Title: "fresh", CommentCount: 100, Score: 100, TimePosted: now.Add(-1 * time.Hour)},- {Title: "recent", CommentCount: 100, Score: 100, TimePosted: now.Add(-8 * time.Hour)},- {Title: "old", CommentCount: 100, Score: 100, TimePosted: now.Add(-50 * time.Hour)},- }-- posts.calculateEngagement()-- fresh := posts[0].Engagement- recent := posts[1].Engagement- old := posts[2].Engagement-- // A post younger than depreciatePostsOlderThanHours keeps its full engagement.- if math.Abs(fresh-1.0) > 1e-6 {- t.Errorf("fresh post engagement = %v, want 1.0", fresh)- }-- // Depreciation must be gradual: an 8h-old post is only ~1h past the 7h- // threshold, so it should lose only a few percent of its engagement rather- // than being immediately slammed to the maximum depreciation.- if recent < 0.9 {- t.Errorf("8h-old post engagement = %v, want > 0.9 (gradual depreciation)", recent)- }-- // Depreciation is capped at maxDepreciation (0.9), so engagement is floored- // at 1-0.9 = 0.1 and must never go negative no matter how old the post is.- if old < 0 {- t.Errorf("50h-old post engagement = %v, want >= 0 (depreciation must be capped, never negative)", old)- }- if math.Abs(old-(1.0-maxDepreciation)) > 1e-6 {- t.Errorf("50h-old post engagement = %v, want %v (floored at 1-maxDepreciation)", old, 1.0-maxDepreciation)- }-- // Engagement must decrease monotonically with age.- if !(fresh >= recent && recent > old) {- t.Errorf("engagement not decreasing with age: fresh=%v recent=%v old=%v", fresh, recent, old)- }-}diff --git a/internal/glance/widget-torrents.go b/internal/glance/widget-torrents.godeleted file mode 100644index 33f981e..0000000--- a/internal/glance/widget-torrents.go+++ /dev/null@@ -1,339 +0,0 @@-package glance--import (- "context"- "encoding/json"- "errors"- "fmt"- "html/template"- "io"- "net/http"- "net/url"- "slices"- "strconv"- "strings"- "time"-)--var torrentsWidgetTemplate = mustParseTemplate("torrents.html", "widget-base.html")--type torrentsWidget struct {- widgetBase `yaml:",inline"`-- URL string `yaml:"url"`- AllowInsecure bool `yaml:"allow-insecure"`- Username string `yaml:"username"`- Password string `yaml:"password"`- Limit int `yaml:"limit"`- CollapseAfter int `yaml:"collapse-after"`- Client string `yaml:"client"`-- SortBy sortableFields[torrent] `yaml:"sort-by"`-- Torrents []torrent `yaml:"-"`-- sessionID string-}--func (widget *torrentsWidget) initialize() error {- widget.- withTitle("Torrents").- withTitleURL(widget.URL).- withCacheDuration(time.Second * 5)-- if widget.URL == "" {- return errors.New("URL is required")- }-- if _, err := url.Parse(widget.URL); err != nil {- return fmt.Errorf("invalid URL: %v", err)- }-- widget.URL = strings.TrimSuffix(widget.URL, "/")-- if widget.Limit <= 0 {- widget.Limit = 10- }-- if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {- widget.CollapseAfter = 5- }-- if widget.Client == "" {- widget.Client = "qbittorrent"- }-- if !slices.Contains([]string{"qbittorrent"}, widget.Client) {- return fmt.Errorf("unsupported client: %s", widget.Client)- }-- if err := widget.SortBy.Default("downloaded, down-speed:desc, up-speed:desc"); err != nil {- return err- }-- if err := widget.SortBy.Fields(map[string]func(a, b torrent) int{- "name": func(a, b torrent) int {- return strings.Compare(a.Name, b.Name)- },- "progress": func(a, b torrent) int {- return numCompare(a.Progress, b.Progress)- },- "downloaded": func(a, b torrent) int {- return boolCompare(a.Downloaded, b.Downloaded)- },- "down-speed": func(a, b torrent) int {- return numCompare(a.DownSpeed, b.DownSpeed)- },- "up-speed": func(a, b torrent) int {- return numCompare(a.UpSpeed, b.UpSpeed)- },- }); err != nil {- return err- }-- return nil-}--func (widget *torrentsWidget) update(ctx context.Context) {- var torrents []torrent- var err error-- switch widget.Client {- case "qbittorrent":- torrents, err = widget.fetchQbtTorrents()- default:- err = fmt.Errorf("unsupported client: %s", widget.Client)- }-- if !widget.canContinueUpdateAfterHandlingErr(err) {- return- }-- widget.SortBy.Apply(torrents)-- if len(torrents) > widget.Limit {- torrents = torrents[:widget.Limit]- }-- widget.Torrents = torrents-}--func (widget *torrentsWidget) Render() template.HTML {- return widget.renderTemplate(widget, torrentsWidgetTemplate)-}--const (- torrentStatusDownloading = "Downloading"- torrentStatusDownloaded = "Downloaded"- torrentStatusSeeding = "Seeding"- torrentStatusPaused = "Paused"- torrentStatusStalled = "Stalled"- torrentStatusError = "Error"- torrentStatusOther = "Other"-)--// States taken from https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)#torrent-management-var qbittorrentStates = map[string][2]string{- // Downloading states- "downloading": {torrentStatusDownloading, "Torrent is being downloaded and data is being transferred"},- "metaDL": {torrentStatusDownloading, "Torrent has just started downloading and is fetching metadata"},- "forcedDL": {torrentStatusDownloading, "Torrent is forced to download, ignoring queue limit"},- "allocating": {torrentStatusDownloading, "Torrent is allocating disk space for download"},-- // Downloaded/Seeding states- "checkingUP": {torrentStatusDownloaded, "Torrent has finished downloading and is being checked"},- "uploading": {torrentStatusSeeding, "Torrent is being seeded and data is being transferred"},- "stalledUP": {torrentStatusSeeding, "Torrent is being seeded, but no connections were made"},- "forcedUP": {torrentStatusSeeding, "Torrent is forced to upload, ignoring queue limit"},-- // Stopped/Paused states- "stoppedDL": {torrentStatusPaused, "Torrent is stopped"},- "pausedDL": {torrentStatusPaused, "Torrent is paused and has not finished downloading"},- "pausedUP": {torrentStatusPaused, "Torrent is paused and has finished downloading"},- "queuedDL": {torrentStatusPaused, "Queuing is enabled and torrent is queued for download"},- "queuedUP": {torrentStatusPaused, "Queuing is enabled and torrent is queued for upload"},-- // Stalled states- "stalledDL": {torrentStatusStalled, "Torrent is being downloaded, but no connections were made"},-- // Error states- "error": {torrentStatusError, "An error occurred, applies to paused torrents"},- "missingFiles": {torrentStatusError, "Torrent data files are missing"},-- // Other states- "checkingDL": {torrentStatusOther, "Same as checkingUP, but torrent has not finished downloading"},- "checkingResumeData": {torrentStatusOther, "Checking resume data on qBittorrent startup"},- "moving": {torrentStatusOther, "Torrent is moving to another location"},- "unknown": {torrentStatusOther, "Unknown status"},-}--type torrent struct {- Name string- ProgressFormatted string- Downloaded bool- Progress float64- State string- StateDescription string- UpSpeed uint64- DownSpeed uint64- DownSpeedFormatted string- ETAFormatted string-}--func (widget *torrentsWidget) formatETA(seconds uint64) string {- if seconds < 60 {- return fmt.Sprintf("%ds", seconds)- } else if seconds < 60*60 {- return fmt.Sprintf("%dm", seconds/60)- } else if seconds < 60*60*24 {- return fmt.Sprintf("%dh", seconds/(60*60))- } else if seconds < 60*60*24*7 {- return fmt.Sprintf("%dd", seconds/(60*60*24))- }-- return fmt.Sprintf("%dw", seconds/(60*60*24*7))-}--func (widget *torrentsWidget) fetchQbtTorrents() ([]torrent, error) {- if widget.sessionID == "" {- if err := widget.fetchQbtSessionID(); err != nil {- return nil, fmt.Errorf("fetching qBittorrent session ID: %v", err)- }- }-- torrents, refetchSID, err := widget._fetchQbtTorrents()- if err != nil {- if refetchSID {- if err := widget.fetchQbtSessionID(); err != nil {- return nil, fmt.Errorf("refetching qBittorrent session ID: %v", err)- }- torrents, _, err = widget._fetchQbtTorrents()- if err != nil {- return nil, fmt.Errorf("refetching qBittorrent torrents: %v", err)- }- } else {- return nil, fmt.Errorf("fetching qBittorrent torrents: %v", err)- }- }-- return torrents, nil-}--func (widget *torrentsWidget) _fetchQbtTorrents() ([]torrent, bool, error) {- params := url.Values{}- params.Set("limit", strconv.Itoa(widget.Limit))- params.Set("sort", "dlspeed")- params.Set("reverse", "true")-- requestURL := fmt.Sprintf("%s%s?%s", widget.URL, "/api/v2/torrents/info", params.Encode())- req, err := http.NewRequest("GET", requestURL, nil)- if err != nil {- return nil, false, fmt.Errorf("creating torrents request: %v", err)- }-- req.Header.Set("Referer", widget.URL)- req.AddCookie(&http.Cookie{Name: "SID", Value: widget.sessionID})-- client := ternary(widget.AllowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)- resp, err := client.Do(req)- if err != nil {- return nil, false, fmt.Errorf("torrents request: %v", err)- }- defer resp.Body.Close()-- body, _ := io.ReadAll(resp.Body)- if resp.StatusCode != http.StatusOK {- // QBittorrent seems to return a 403 if the session ID is invalid or expired.- refetch := resp.StatusCode == http.StatusForbidden- return nil, refetch, fmt.Errorf("torrents request failed with status %d: %s", resp.StatusCode, string(body))- }-- type qbTorrent struct {- Name string `json:"name"`- Progress float64 `json:"progress"`- State string `json:"state"`- DownSpeed uint64 `json:"dlspeed"`- UpSpeed uint64 `json:"upspeed"`- ETA uint64 `json:"eta"` // in seconds- }-- var rawTorrents []qbTorrent- if err := json.Unmarshal(body, &rawTorrents); err != nil {- return nil, true, fmt.Errorf("decoding torrents response: %v", err)- }-- torrents := make([]torrent, len(rawTorrents))- for i, raw := range rawTorrents {- state := raw.State- stateDescription := "Unknown state"- if mappedState, exists := qbittorrentStates[raw.State]; exists {- state = mappedState[0]- stateDescription = mappedState[1]- }-- torrents[i] = torrent{- Name: raw.Name,- Progress: raw.Progress * 100,- Downloaded: raw.Progress >= 1.0,- ProgressFormatted: fmt.Sprintf("%.1f%%", raw.Progress*100),- State: state,- StateDescription: stateDescription,- ETAFormatted: widget.formatETA(raw.ETA),- DownSpeed: raw.DownSpeed,- UpSpeed: raw.UpSpeed,- }-- if raw.DownSpeed > 0 {- value, unit := formatBytes(raw.DownSpeed)- torrents[i].DownSpeedFormatted = fmt.Sprintf("%s %s", value, unit)- }- }-- return torrents, false, nil-}--func (widget *torrentsWidget) fetchQbtSessionID() error {- loginData := url.Values{}- loginData.Set("username", widget.Username)- loginData.Set("password", widget.Password)-- req, err := http.NewRequest(- "POST",- fmt.Sprintf("%s/api/v2/auth/login", widget.URL),- strings.NewReader(loginData.Encode()),- )- if err != nil {- return fmt.Errorf("creating login request: %v", err)- }-- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")- req.Header.Set("Referer", widget.URL)-- client := ternary(widget.AllowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)- resp, err := client.Do(req)- if err != nil {- return fmt.Errorf("login request: %v", err)- }- defer resp.Body.Close()-- body, _ := io.ReadAll(resp.Body)- if resp.StatusCode != http.StatusOK {- return fmt.Errorf("login failed with status %d: %s", resp.StatusCode, string(body))- }-- cookies := resp.Cookies()- if len(cookies) == 0 {- return errors.New("no session cookie received, maybe the username or password is incorrect?")- }-- for _, cookie := range cookies {- if cookie.Name == "SID" {- widget.sessionID = cookie.Value- }- }- if widget.sessionID == "" {- return errors.New("session ID not found in cookies")- }-- return nil-}diff --git a/internal/glance/widget-trending-repositories.go b/internal/glance/widget-trending-repositories.godeleted file mode 100644index 77b1373..0000000--- a/internal/glance/widget-trending-repositories.go+++ /dev/null@@ -1,113 +0,0 @@-package glance--import (- "context"- "fmt"- "html/template"- "slices"- "strconv"- "strings"- "time"-- "golang.org/x/net/html"-)--var trendingRepositoriesWidgetTemplate = mustParseTemplate("trending-repositories.html", "widget-base.html")--type trendingRepositoriesWidget struct {- widgetBase `yaml:",inline"`- Repositories []trendingRepository `yaml:"-"`-- Language string `yaml:"language"`- DateRange string `yaml:"date-range"`- CollapseAfter int `yaml:"collapse-after"`-}--func (widget *trendingRepositoriesWidget) initialize() error {- widget.withTitle("Trending Repositories").withCacheDuration(8 * time.Hour)-- if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {- widget.CollapseAfter = 4- }-- if !slices.Contains([]string{"daily", "weekly", "monthly"}, widget.DateRange) {- widget.DateRange = "daily"- }-- return nil-}--func (widget *trendingRepositoriesWidget) update(ctx context.Context) {- repositories, err := widget.fetchTrendingRepositories()-- if !widget.canContinueUpdateAfterHandlingErr(err) {- return- }-- widget.Repositories = repositories-}--func (widget *trendingRepositoriesWidget) Render() template.HTML {- return widget.renderTemplate(widget, trendingRepositoriesWidgetTemplate)-}--type trendingRepository struct {- Slug string- Description string- Language string- Stars int-}--func (widget *trendingRepositoriesWidget) fetchTrendingRepositories() ([]trendingRepository, error) {- url := fmt.Sprintf("https://github.com/trending/%s?since=%s", widget.Language, widget.DateRange)-- response, err := defaultHTTPClient.Get(url)- if err != nil {- return nil, fmt.Errorf("failed to fetch trending repositories: %w", err)- }- defer response.Body.Close()-- if response.StatusCode != 200 {- return nil, fmt.Errorf("unexpected status code %d for %s", response.StatusCode, url)- }-- parsedDoc, err := html.Parse(response.Body)- if err != nil {- return nil, fmt.Errorf("failed to parse HTML response: %w", err)- }-- doc := (*searchableNode)(parsedDoc)- repositories := make([]trendingRepository, 0, 15)-- repoElems := doc.- findFirst("main").- findFirst("div", "class", "Box").- findAll("article", "class", "Box-row")-- for _, repoElem := range repoElems {- nameElem := repoElem.findFirstChild("h2").findFirst("a", "class", "Link")- name := strings.ReplaceAll(nameElem.text(), " ", "")-- description := repoElem.findFirstChild("p").text()- metaElem := repoElem.findFirstChild("div", "class", "f6 color-fg-muted mt-2")-- language := metaElem.findFirst("span", "itemprop", "programmingLanguage").text()- starsIndex := 2- if language == "" {- starsIndex = 1- }-- starsText := metaElem.nthChild(starsIndex).text()- starsText = strings.ReplaceAll(starsText, ",", "")- stars, _ := strconv.Atoi(starsText)-- repositories = append(repositories, trendingRepository{- Slug: name,- Description: description,- Language: language,- Stars: stars,- })- }-- return repositories, nil-}diff --git a/internal/glance/widget-videos.go b/internal/glance/widget-videos.goindex 569f1da..ff79864 100644--- a/internal/glance/widget-videos.go+++ b/internal/glance/widget-videos.go@@ -31,9 +31,6 @@ type videosWidget struct {Playlists []string `yaml:"playlists"`Limit int `yaml:"limit"`IncludeShorts bool `yaml:"include-shorts"`- SortBy string `yaml:"sort-by"`-- Filters filterableFields[video] `yaml:"filters"`}func (widget *videosWidget) initialize() error {@@ -67,14 +64,12 @@ func (widget *videosWidget) initialize() error {}func (widget *videosWidget) update(ctx context.Context) {- videos, err := fetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate, widget.IncludeShorts, widget.SortBy)+ videos, err := fetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate, widget.IncludeShorts)if !widget.canContinueUpdateAfterHandlingErr(err) {return}- videos = widget.Filters.Apply(videos)-if len(videos) > widget.Limit {videos = videos[:widget.Limit]}@@ -103,7 +98,6 @@ type youtubeFeedResponseXml struct {Videos []struct {Title string `xml:"title"`Published string `xml:"published"`- Updated string `xml:"updated"`Link struct {Href string `xml:"href,attr"`} `xml:"link"`@@ -132,25 +126,11 @@ type video struct {Author stringAuthorUrl stringTimePosted time.Time- TimeUpdated time.Time-}--func (v video) filterableField(field string) any {- switch field {- case "title":- return v.Title- case "posted":- return v.TimePosted- case "updated":- return v.TimeUpdated- default:- return nil- }}type videoList []video-func (v videoList) sortByPosted() videoList {+func (v videoList) sortByNewest() videoList {sort.Slice(v, func(i, j int) bool {return v[i].TimePosted.After(v[j].TimePosted)})@@ -158,21 +138,14 @@ func (v videoList) sortByPosted() videoList {return v}-func (v videoList) sortByUpdated() videoList {- sort.Slice(v, func(i, j int) bool {- return v[i].TimeUpdated.After(v[j].TimeUpdated)- })-- return v-}--func fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplate string, includeShorts bool, sortBy string) (videoList, error) {+func fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplate string, includeShorts bool) (videoList, error) {requests := make([]*http.Request, 0, len(channelOrPlaylistIDs))for i := range channelOrPlaylistIDs {var feedUrl string- if after, ok := strings.CutPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix); ok {- feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" + after+ if strings.HasPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix) {+ feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" ++ strings.TrimPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix)} else if !includeShorts && strings.HasPrefix(channelOrPlaylistIDs[i], "UC") {playlistId := strings.Replace(channelOrPlaylistIDs[i], "UC", "UULF", 1)feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistId@@ -225,7 +198,6 @@ func fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplateAuthor: response.Channel,AuthorUrl: response.ChannelLink + "/videos",TimePosted: parseYoutubeFeedTime(v.Published),- TimeUpdated: parseYoutubeFeedTime(v.Updated),})}}@@ -234,15 +206,7 @@ func fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplatereturn nil, errNoContent}- switch sortBy {- case "none":- case "updated":- videos.sortByUpdated()- case "posted":- videos.sortByPosted()- default: // "posted"- videos.sortByPosted()- }+ videos.sortByNewest()if failed > 0 {return videos, fmt.Errorf("%w: missing videos from %d channels", errPartialContent, failed)diff --git a/internal/glance/widget.go b/internal/glance/widget.goindex 832ba21..50dc3cb 100644--- a/internal/glance/widget.go+++ b/internal/glance/widget.go@@ -79,12 +79,8 @@ func newWidget(widgetType string) (widget, error) {w = &dockerContainersWidget{}case "server-stats":w = &serverStatsWidget{}- case "torrents":- w = &torrentsWidget{}case "to-do":w = &todoWidget{}- case "trending-repositories":- w = &trendingRepositoriesWidget{}default:return nil, fmt.Errorf("unknown widget type: %s", widgetType)}