Compare commits
78 commits
Author | SHA1 | Date | |
---|---|---|---|
|
03b616622e | ||
|
50e1da01fe | ||
|
f8f50b26d8 | ||
|
a3bc133bcb | ||
|
50dae22ff4 | ||
|
5a91154eab | ||
|
d5b89d512a | ||
|
97f43f88eb | ||
|
3177af9524 | ||
|
f99d22738c | ||
|
ea7124db52 | ||
|
b1247e5de6 | ||
|
5ab962634e | ||
|
d99944dcff | ||
|
920bcb06dc | ||
|
3679cc21ab | ||
|
07e5626469 | ||
|
6bb6f87800 | ||
|
cb6b52ff4c | ||
|
03c377dff3 | ||
|
0e3f172032 | ||
|
fd704419d9 | ||
|
32ac72f592 | ||
|
9c77b87435 | ||
|
d4d9e94f44 | ||
|
47cef2abf0 | ||
|
0a5cdf380f | ||
|
9da7967158 | ||
|
964744a9ae | ||
|
779304d035 | ||
|
f15d7445bd | ||
|
26d68ba3fc | ||
|
958805a1fd | ||
|
dd74c173a5 | ||
|
bd020c93f5 | ||
|
75555f0426 | ||
|
233de7fc37 | ||
|
c6e0230e5d | ||
|
ca2732668e | ||
|
456b76ac96 | ||
|
a2c58bea82 | ||
|
7276b3d5ef | ||
|
1ef8315462 | ||
|
2f88ac419b | ||
|
cee7c85780 | ||
|
b2c5205035 | ||
|
2be59c3eb6 | ||
|
176fc896ae | ||
|
a943555d86 | ||
|
58bbfbbc42 | ||
|
026b644630 | ||
|
1483b355af | ||
|
6a5bb635bb | ||
|
0e0aca3844 | ||
|
1512718d41 | ||
|
4731b90899 | ||
|
844e32a11e | ||
|
0b2cfc45c1 | ||
|
c8be41ce6c | ||
|
ec2f710d06 | ||
|
71112173b9 | ||
|
1615c20e66 | ||
|
fbcea12786 | ||
|
047d13afd1 | ||
|
4c1165533c | ||
|
14bdcf71fe | ||
|
1b3f022b2d | ||
|
b6d93a7f09 | ||
|
4b2438c298 | ||
|
3b79c8e09f | ||
|
78ad88a245 | ||
|
99660aeee8 | ||
|
65a412eb59 | ||
|
2002ed1c9c | ||
|
e643a44b59 | ||
|
72c1ebf66d | ||
|
008c4a3ab7 | ||
|
38d3d11571 |
31 changed files with 1428 additions and 285 deletions
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.23.6-alpine3.21 AS builder
|
||||
FROM golang:1.24.2-alpine3.21 AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY . /app
|
||||
|
|
117
README.md
117
README.md
|
@ -1,6 +1,7 @@
|
|||
<p align="center"><em>What if you could see everything at a...</em></p>
|
||||
<h1 align="center">Glance</h1>
|
||||
<p align="center"><a href="#installation">Install</a> • <a href="docs/configuration.md">Configuration</a> • <a href="docs/preconfigured-pages.md">Preconfigured pages</a> • <a href="docs/themes.md">Themes</a> • <a href="https://discord.com/invite/7KQ7Xa9kJd">Discord</a></p>
|
||||
<p align="center"><a href="#installation">Install</a> • <a href="docs/configuration.md">Configuration</a> • <a href="https://discord.com/invite/7KQ7Xa9kJd">Discord</a> • <a href="https://github.com/sponsors/glanceapp">Sponsor</a></p>
|
||||
<p align="center"><a href="https://github.com/glanceapp/community-widgets">Community widgets</a> • <a href="docs/preconfigured-pages.md">Preconfigured pages</a> • <a href="docs/themes.md">Themes</a></p>
|
||||
|
||||

|
||||
|
||||
|
@ -194,6 +195,7 @@ services:
|
|||
glance:
|
||||
container_name: glance
|
||||
image: glanceapp/glance
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./config:/app/config
|
||||
ports:
|
||||
|
@ -264,59 +266,31 @@ Glance can also be installed through the following 3rd party channels:
|
|||
|
||||
<br>
|
||||
|
||||
## Building from source
|
||||
|
||||
Choose one of the following methods:
|
||||
|
||||
## Common issues
|
||||
<details>
|
||||
<summary><strong>Build binary with Go</strong></summary>
|
||||
<br>
|
||||
<summary><strong>Requests timing out</strong></summary>
|
||||
|
||||
Requirements: [Go](https://go.dev/dl/) >= v1.23
|
||||
The most common cause of this is when using Pi-Hole, AdGuard Home or other ad-blocking DNS services, which by default have a fairly low rate limit. Depending on the number of widgets you have in a single page, this limit can very easily be exceeded. To fix this, increase the rate limit in the settings of your DNS service.
|
||||
|
||||
To build the project for your current OS and architecture, run:
|
||||
|
||||
```bash
|
||||
go build -o build/glance .
|
||||
If using Podman, in some rare cases the timeout can be caused by an unknown issue, in which case it may be resolved by adding the following to the bottom of your `docker-compose.yml` file:
|
||||
```yaml
|
||||
networks:
|
||||
podman:
|
||||
external: true
|
||||
```
|
||||
|
||||
To build for a specific OS and architecture, run:
|
||||
|
||||
```bash
|
||||
GOOS=linux GOARCH=amd64 go build -o build/glance .
|
||||
```
|
||||
|
||||
[*click here for a full list of GOOS and GOARCH combinations*](https://go.dev/doc/install/source#:~:text=$GOOS%20and%20$GOARCH)
|
||||
|
||||
Alternatively, if you just want to run the app without creating a binary, like when you're testing out changes, you can run:
|
||||
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
<hr>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Build project and Docker image with Docker</strong></summary>
|
||||
<br>
|
||||
<summary><strong>Broken layout for markets, bookmarks or other widgets</strong></summary>
|
||||
|
||||
Requirements: [Docker](https://docs.docker.com/engine/install/)
|
||||
This is almost always caused by the browser extension Dark Reader. To fix this, disable dark mode for the domain where Glance is hosted.
|
||||
</details>
|
||||
|
||||
To build the project and image using just Docker, run:
|
||||
<details>
|
||||
<summary><strong>cannot unmarshal !!map into []glance.page</strong></summary>
|
||||
|
||||
*(replace `owner` with your name or organization)*
|
||||
The most common cause of this is having a `pages` key in your `glance.yml` and then also having a `pages` key inside one of your included pages. To fix this, remove the `pages` key from the top of your included pages.
|
||||
|
||||
```bash
|
||||
docker build -t owner/glance:latest .
|
||||
```
|
||||
|
||||
If you wish to push the image to a registry (by default Docker Hub), run:
|
||||
|
||||
```bash
|
||||
docker push owner/glance:latest
|
||||
```
|
||||
|
||||
<hr>
|
||||
</details>
|
||||
|
||||
<br>
|
||||
|
@ -375,6 +349,63 @@ Feature requests are tagged with one of the following:
|
|||
|
||||
<br>
|
||||
|
||||
## Building from source
|
||||
|
||||
Choose one of the following methods:
|
||||
|
||||
<details>
|
||||
<summary><strong>Build binary with Go</strong></summary>
|
||||
<br>
|
||||
|
||||
Requirements: [Go](https://go.dev/dl/) >= v1.23
|
||||
|
||||
To build the project for your current OS and architecture, run:
|
||||
|
||||
```bash
|
||||
go build -o build/glance .
|
||||
```
|
||||
|
||||
To build for a specific OS and architecture, run:
|
||||
|
||||
```bash
|
||||
GOOS=linux GOARCH=amd64 go build -o build/glance .
|
||||
```
|
||||
|
||||
[*click here for a full list of GOOS and GOARCH combinations*](https://go.dev/doc/install/source#:~:text=$GOOS%20and%20$GOARCH)
|
||||
|
||||
Alternatively, if you just want to run the app without creating a binary, like when you're testing out changes, you can run:
|
||||
|
||||
```bash
|
||||
go run .
|
||||
```
|
||||
<hr>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Build project and Docker image with Docker</strong></summary>
|
||||
<br>
|
||||
|
||||
Requirements: [Docker](https://docs.docker.com/engine/install/)
|
||||
|
||||
To build the project and image using just Docker, run:
|
||||
|
||||
*(replace `owner` with your name or organization)*
|
||||
|
||||
```bash
|
||||
docker build -t owner/glance:latest .
|
||||
```
|
||||
|
||||
If you wish to push the image to a registry (by default Docker Hub), run:
|
||||
|
||||
```bash
|
||||
docker push owner/glance:latest
|
||||
```
|
||||
|
||||
<hr>
|
||||
</details>
|
||||
|
||||
<br>
|
||||
|
||||
## Contributing guidelines
|
||||
|
||||
* Before working on a new feature it's preferable to submit a feature request first and state that you'd like to implement it yourself
|
||||
|
|
|
@ -9,7 +9,7 @@
|
|||
- [Document](#document)
|
||||
- [Branding](#branding)
|
||||
- [Theme](#theme)
|
||||
- [Themes](#themes)
|
||||
- [Available themes](#available-themes)
|
||||
- [Pages & Columns](#pages--columns)
|
||||
- [Widgets](#widgets)
|
||||
- [RSS](#rss)
|
||||
|
@ -274,7 +274,7 @@ theme:
|
|||
contrast-multiplier: 1.1
|
||||
```
|
||||
|
||||
### Themes
|
||||
### Available themes
|
||||
If you don't want to spend time configuring your own theme, there are [several available themes](themes.md) which you can simply copy the values for.
|
||||
|
||||
### Properties
|
||||
|
@ -365,7 +365,7 @@ pages:
|
|||
| show-mobile-header | boolean | no | false |
|
||||
| columns | array | yes | |
|
||||
|
||||
#### `title`
|
||||
#### `name`
|
||||
The name of the page which gets shown in the navigation bar.
|
||||
|
||||
#### `slug`
|
||||
|
@ -1292,8 +1292,15 @@ Examples:
|
|||
| ---- | ---- | -------- | ------- |
|
||||
| url | string | yes | |
|
||||
| headers | key (string) & value (string) | no | |
|
||||
| method | string | no | GET |
|
||||
| body-type | string | no | json |
|
||||
| body | any | no | |
|
||||
| frameless | boolean | no | false |
|
||||
| allow-insecure | boolean | no | false |
|
||||
| skip-json-validation | boolean | no | false |
|
||||
| template | string | yes | |
|
||||
| parameters | key (string) & value (string|array) | no | |
|
||||
| subrequests | map of requests | no | |
|
||||
|
||||
##### `url`
|
||||
The URL to fetch the data from. It must be accessible from the server that Glance is running on.
|
||||
|
@ -1307,12 +1314,92 @@ headers:
|
|||
Accept: application/json
|
||||
```
|
||||
|
||||
##### `method`
|
||||
The HTTP method to use when making the request. Possible values are `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` and `HEAD`.
|
||||
|
||||
##### `body-type`
|
||||
The type of the body that will be sent with the request. Possible values are `json`, and `string`.
|
||||
|
||||
##### `body`
|
||||
The body that will be sent with the request. It can be a string or a map. Example:
|
||||
|
||||
```yaml
|
||||
body-type: json
|
||||
body:
|
||||
key1: value1
|
||||
key2: value2
|
||||
multiple-items:
|
||||
- item1
|
||||
- item2
|
||||
```
|
||||
|
||||
```yaml
|
||||
body-type: string
|
||||
body: |
|
||||
key1=value1&key2=value2
|
||||
```
|
||||
|
||||
##### `frameless`
|
||||
When set to `true`, removes the border and padding around the widget.
|
||||
|
||||
##### `allow-insecure`
|
||||
Whether to ignore invalid/self-signed certificates.
|
||||
|
||||
##### `skip-json-validation`
|
||||
When set to `true`, skips the JSON validation step. This is useful when the API returns JSON Lines/newline-delimited JSON, which is a format that consists of several JSON objects separated by newlines.
|
||||
|
||||
##### `template`
|
||||
The template that will be used to display the data. It relies on Go's `html/template` package so it's recommended to go through [its documentation](https://pkg.go.dev/text/template) to understand how to do basic things such as conditionals, loops, etc. In addition, it also uses [tidwall's gjson](https://github.com/tidwall/gjson) package to parse the JSON data so it's worth going through its documentation if you want to use more advanced JSON selectors. You can view additional examples with explanations and function definitions [here](custom-api.md).
|
||||
|
||||
##### `parameters`
|
||||
A list of keys and values that will be sent to the custom-api as query paramters.
|
||||
|
||||
##### `subrequests`
|
||||
A map of additional requests that will be executed concurrently and then made available in the template via the `.Subrequest` property. Example:
|
||||
|
||||
```yaml
|
||||
- type: custom-api
|
||||
cache: 2h
|
||||
subrequests:
|
||||
another-one:
|
||||
url: https://uselessfacts.jsph.pl/api/v2/facts/random
|
||||
title: Random Fact
|
||||
url: https://uselessfacts.jsph.pl/api/v2/facts/random
|
||||
template: |
|
||||
<p class="size-h4 color-paragraph">{{ .JSON.String "text" }}</p>
|
||||
<p class="size-h4 color-paragraph margin-top-15">{{ (.Subrequest "another-one").JSON.String "text" }}</p>
|
||||
```
|
||||
|
||||
The subrequests support all the same properties as the main request, except for `subrequests` itself, so you can use `headers`, `parameters`, etc.
|
||||
|
||||
`(.Subrequest "key")` can be a little cumbersome to write, so you can define a variable to make it easier:
|
||||
|
||||
```yaml
|
||||
template: |
|
||||
{{ $anotherOne := .Subrequest "another-one" }}
|
||||
<p>{{ $anotherOne.JSON.String "text" }}</p>
|
||||
```
|
||||
|
||||
You can also access the `.Response` property of a subrequest as you would with the main request:
|
||||
|
||||
```yaml
|
||||
template: |
|
||||
{{ $anotherOne := .Subrequest "another-one" }}
|
||||
<p>{{ $anotherOne.Response.StatusCode }}</p>
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> Setting this property will override any query parameters that are already in the URL.
|
||||
|
||||
```yaml
|
||||
parameters:
|
||||
param1: value1
|
||||
param2:
|
||||
- item1
|
||||
- item2
|
||||
```
|
||||
|
||||
### Extension
|
||||
Display a widget provided by an external source (3rd party). If you want to learn more about developing extensions, checkout the [extensions documentation](extensions.md) (WIP).
|
||||
|
||||
|
@ -1330,6 +1417,7 @@ Display a widget provided by an external source (3rd party). If you want to lear
|
|||
| url | string | yes | |
|
||||
| fallback-content-type | string | no | |
|
||||
| allow-potentially-dangerous-html | boolean | no | false |
|
||||
| headers | key & value | no | |
|
||||
| parameters | key & value | no | |
|
||||
|
||||
##### `url`
|
||||
|
@ -1338,6 +1426,14 @@ The URL of the extension. **Note that the query gets stripped from this URL and
|
|||
##### `fallback-content-type`
|
||||
Optionally specify the fallback content type of the extension if the URL does not return a valid `Widget-Content-Type` header. Currently the only supported value for this property is `html`.
|
||||
|
||||
##### `headers`
|
||||
Optionally specify the headers that will be sent with the request. Example:
|
||||
|
||||
```yaml
|
||||
headers:
|
||||
x-api-key: ${SECRET_KEY}
|
||||
```
|
||||
|
||||
##### `allow-potentially-dangerous-html`
|
||||
Whether to allow the extension to display HTML.
|
||||
|
||||
|
@ -1765,29 +1861,31 @@ Preview:
|
|||
| allow-insecure | bool | no | false |
|
||||
| url | string | yes | |
|
||||
| username | string | when service is `adguard` | |
|
||||
| password | string | when service is `adguard` | |
|
||||
| password | string | when service is `adguard` or `pihole-v6` | |
|
||||
| token | string | when service is `pihole` | |
|
||||
| hide-graph | bool | no | false |
|
||||
| hide-top-domains | bool | no | false |
|
||||
| hour-format | string | no | 12h |
|
||||
|
||||
##### `service`
|
||||
Either `adguard` or `pihole`.
|
||||
Either `adguard`, or `pihole` (major version 5 and below) or `pihole-v6` (major version 6 and above).
|
||||
|
||||
##### `allow-insecure`
|
||||
Whether to allow invalid/self-signed certificates when making the request to the service.
|
||||
|
||||
##### `url`
|
||||
The base URL of the service. Can be specified from an environment variable using the syntax `${VARIABLE_NAME}`.
|
||||
The base URL of the service.
|
||||
|
||||
##### `username`
|
||||
Only required when using AdGuard Home. The username used to log into the admin dashboard. Can be specified from an environment variable using the syntax `${VARIABLE_NAME}`.
|
||||
Only required when using AdGuard Home. The username used to log into the admin dashboard.
|
||||
|
||||
##### `password`
|
||||
Only required when using AdGuard Home. The password used to log into the admin dashboard. Can be specified from an environment variable using the syntax `${VARIABLE_NAME}`.
|
||||
Required when using AdGuard Home, where the password is the one used to log into the admin dashboard.
|
||||
|
||||
Also requried 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`
|
||||
Only required when using Pi-hole. The API token which can be found in `Settings -> API -> Show API token`. Can be specified from an environment variable using the syntax `${VARIABLE_NAME}`.
|
||||
Only required when using Pi-hole major version 5 or earlier. The API token which can be found in `Settings -> API -> Show API token`.
|
||||
|
||||
##### `hide-graph`
|
||||
Whether to hide the graph showing the number of queries over time.
|
||||
|
@ -1852,7 +1950,7 @@ Whether to hide the swap usage.
|
|||
| Name | Type | Required | Default |
|
||||
| ---- | ---- | -------- | ------- |
|
||||
| cpu-temp-sensor | string | no | |
|
||||
| hide-mointpoints-by-default | boolean | no | false |
|
||||
| hide-mountpoints-by-default | boolean | no | false |
|
||||
| mountpoints | map\[string\]object | no | |
|
||||
|
||||
###### `cpu-temp-sensor`
|
||||
|
|
|
@ -226,10 +226,10 @@ JSON response:
|
|||
}
|
||||
```
|
||||
|
||||
Calculations can be performed, however all numbers must be converted to floats first if they are not already:
|
||||
Calculations can be performed on either ints or floats. If both numbers are ints, an int will be returned, otherwise a float will be returned. If you try to divide by zero, 0 will be returned. If you provide non-numeric values, `NaN` will be returned.
|
||||
|
||||
```html
|
||||
<div>{{ sub (.JSON.Int "price" | toFloat) (.JSON.Int "discount" | toFloat) }}</div>
|
||||
<div>{{ sub (.JSON.Int "price") (.JSON.Int "discount") }}</div>
|
||||
```
|
||||
|
||||
Output:
|
||||
|
@ -242,6 +242,57 @@ Other operations include `add`, `mul`, and `div`.
|
|||
|
||||
<hr>
|
||||
|
||||
JSON response:
|
||||
|
||||
```json
|
||||
{
|
||||
"posts": [
|
||||
{
|
||||
"title": "Exploring the Depths of Quantum Computing",
|
||||
"date": "2023-10-27T10:00:00Z"
|
||||
},
|
||||
{
|
||||
"title": "A Beginner's Guide to Sustainable Living",
|
||||
"date": "2023-11-15T14:30:00+01:00"
|
||||
},
|
||||
{
|
||||
"title": "The Art of Baking Sourdough Bread",
|
||||
"date": "2023-12-03T08:45:22-08:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
To parse the date and display the relative time (e.g. 2h, 1d, etc), you would use the following:
|
||||
|
||||
```
|
||||
{{ range .JSON.Array "posts" }}
|
||||
<div>{{ .String "title" }}</div>
|
||||
<div {{ .String "date" | parseTime "rfc3339" | toRelativeTime }}></div>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
The `parseTime` function takes two arguments: the layout of the date string and the date string itself. The layout can be one of the following: "RFC3339", "RFC3339Nano", "DateTime", "DateOnly", "TimeOnly" or a custom layout in Go's [date format](https://pkg.go.dev/time#pkg-constants).
|
||||
|
||||
Output:
|
||||
|
||||
```html
|
||||
<div>Exploring the Depths of Quantum Computing</div>
|
||||
<div data-dynamic-relative-time="1698400800"></div>
|
||||
|
||||
<div>A Beginner's Guide to Sustainable Living</div>
|
||||
<div data-dynamic-relative-time="1700055000"></div>
|
||||
|
||||
<div>The Art of Baking Sourdough Bread</div>
|
||||
<div data-dynamic-relative-time="1701621922"></div>
|
||||
```
|
||||
|
||||
You don't have to worry about the internal implementation, this will then be dynamically populated by Glance on the client side to show the correct relative time.
|
||||
|
||||
The important thing to notice here is that the return value of `toRelativeTime` must be used as an attribute in an HTML tag, be it a `div`, `li`, `span`, etc.
|
||||
|
||||
<hr>
|
||||
|
||||
In some instances, you may want to know the status code of the response. This can be done using the following:
|
||||
|
||||
```html
|
||||
|
@ -258,6 +309,55 @@ You can also access the response headers:
|
|||
<div>{{ .Response.Header.Get "Content-Type" }}</div>
|
||||
```
|
||||
|
||||
<hr>
|
||||
|
||||
JSON response:
|
||||
|
||||
```json
|
||||
{"name": "Steve", "age": 30}
|
||||
{"name": "Alex", "age": 25}
|
||||
{"name": "John", "age": 35}
|
||||
```
|
||||
|
||||
The above format is "[ndjson](https://docs.mulesoft.com/dataweave/latest/dataweave-formats-ndjson)" or "[JSON Lines](https://jsonlines.org/)", where each line is a separate JSON object. To parse this format, you must first disable the JSON validation check in your config, since by default the response is expected to be a single valid JSON object:
|
||||
|
||||
```yaml
|
||||
- type: custom-api
|
||||
skip-json-validation: true
|
||||
```
|
||||
|
||||
Then, to iterate over each object you can use `.JSONLines`:
|
||||
|
||||
```html
|
||||
{{ range .JSONLines }}
|
||||
<p>{{ .String "name" }} is {{ .Int "age" }} years old</p>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```html
|
||||
<p>Steve is 30 years old</p>
|
||||
<p>Alex is 25 years old</p>
|
||||
<p>John is 35 years old</p>
|
||||
```
|
||||
|
||||
For other ways of selecting data from a JSON Lines response, have a look at the docs for [tidwall/gjson](https://github.com/tidwall/gjson/tree/master?tab=readme-ov-file#json-lines). For example, to get an array of all names, you can use the following:
|
||||
|
||||
```html
|
||||
{{ range .JSON.Array "..#.name" }}
|
||||
<p>{{ .String "" }}</p>
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```html
|
||||
<p>Steve</p>
|
||||
<p>Alex</p>
|
||||
<p>John</p>
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
The following functions are available on the `JSON` object:
|
||||
|
@ -273,12 +373,31 @@ The following helper functions provided by Glance are available:
|
|||
|
||||
- `toFloat(i int) float`: Converts an integer to a float.
|
||||
- `toInt(f float) int`: Converts a float to an integer.
|
||||
- `toRelativeTime(t time.Time) template.HTMLAttr`: Converts Time to a relative time such as 2h, 1d, etc which dynamically updates. **NOTE:** the value of this function should be used as an attribute in an HTML tag, e.g. `<span {{ toRelativeTime .Time }}></span>`.
|
||||
- `now() time.Time`: Returns the current time.
|
||||
- `offsetNow(offset string) time.Time`: Returns the current time with an offset. The offset can be positive or negative and must be in the format "3h" "-1h" or "2h30m10s".
|
||||
- `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".
|
||||
- `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.
|
||||
- `mul(a, b float) float`: Multiplies two numbers.
|
||||
- `div(a, b float) float`: Divides two numbers.
|
||||
- `formatApproxNumber(n int) string`: Formats a number to be more human-readable, e.g. 1000 -> 1k.
|
||||
- `formatNumber(n float|int) string`: Formats a number with commas, e.g. 1000 -> 1,000.
|
||||
- `trimPrefix(prefix string, str string) string`: Trims the prefix from a string.
|
||||
- `trimSuffix(suffix string, str string) string`: Trims the suffix from a string.
|
||||
- `trimSpace(str string) string`: Trims whitespace from a string on both ends.
|
||||
- `replaceAll(old string, new string, str string) string`: Replaces all occurrences of a string in a string.
|
||||
- `replaceMatches(pattern string, replacement string, str string) string`: Replaces all occurrences of a regular expression in a string.
|
||||
- `findMatch(pattern string, str string) string`: Finds the first match of a regular expression in a string.
|
||||
- `findSubmatch(pattern string, str string) string`: Finds the first submatch of a regular expression in a string.
|
||||
- `sortByString(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by a string key in either ascending or descending order.
|
||||
- `sortByInt(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by an integer key in either ascending or descending order.
|
||||
- `sortByFloat(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by a float key in either ascending or descending order.
|
||||
- `sortByTime(key string, layout string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by a time key in either ascending or descending order. The format must be provided in Go's [date format](https://pkg.go.dev/time#pkg-constants).
|
||||
- `concat(strings ...string) string`: Concatenates multiple strings together.
|
||||
- `unique(key string, arr []JSON) []JSON`: Returns a unique array of JSON objects based on the given key.
|
||||
|
||||
The following helper functions provided by Go's `text/template` are available:
|
||||
|
||||
|
|
|
@ -26,6 +26,9 @@ If you know how to setup an HTTP server and a bit of HTML and CSS you're ready t
|
|||
### `Widget-Title`
|
||||
Used to specify the title of the widget. If not provided, the widget's title will be "Extension".
|
||||
|
||||
### `Widget-Title-URL`
|
||||
Used to specify the URL that will be opened when the widget's title is clicked. If the user has specified a `title-url` in their config, it will take precedence over this header.
|
||||
|
||||
### `Widget-Content-Type`
|
||||
Used to specify the content type that will be returned by the extension. If not provided, the content will be shown as plain text.
|
||||
|
||||
|
|
|
@ -66,9 +66,6 @@ pages:
|
|||
# hide-location: true
|
||||
|
||||
- type: markets
|
||||
# The link to go to when clicking on the symbol in the UI,
|
||||
# {SYMBOL} will be substituded with the symbol for each market
|
||||
symbol-link-template: https://www.tradingview.com/symbols/{SYMBOL}/news
|
||||
markets:
|
||||
- symbol: SPY
|
||||
name: S&P 500
|
||||
|
|
BIN
docs/images/themes/dracula.png
Normal file
BIN
docs/images/themes/dracula.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.1 MiB |
|
@ -82,6 +82,17 @@ theme:
|
|||
negative-color: 209 88 54
|
||||
```
|
||||
|
||||
### Dracula
|
||||

|
||||
```yaml
|
||||
theme:
|
||||
background-color: 231 15 21
|
||||
primary-color: 265 89 79
|
||||
contrast-multiplier: 1.2
|
||||
positive-color: 135 94 66
|
||||
negative-color: 0 100 67
|
||||
```
|
||||
|
||||
## Light
|
||||
|
||||
### Catppuccin Latte
|
||||
|
|
20
go.mod
20
go.mod
|
@ -1,32 +1,32 @@
|
|||
module github.com/glanceapp/glance
|
||||
|
||||
go 1.23.6
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
github.com/fsnotify/fsnotify v1.8.0
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/mmcdole/gofeed v1.3.0
|
||||
github.com/shirou/gopsutil/v4 v4.25.1
|
||||
github.com/shirou/gopsutil/v4 v4.25.3
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
golang.org/x/text v0.22.0
|
||||
golang.org/x/text v0.24.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/PuerkitoBio/goquery v1.10.1 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.10.2 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/ebitengine/purego v0.8.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect
|
||||
github.com/mmcdole/goxpp v1.1.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.14 // indirect
|
||||
github.com/tklauser/numcpus v0.9.0 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.15 // indirect
|
||||
github.com/tklauser/numcpus v0.10.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
golang.org/x/net v0.34.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/net v0.39.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
)
|
||||
|
|
19
go.sum
19
go.sum
|
@ -1,5 +1,7 @@
|
|||
github.com/PuerkitoBio/goquery v1.10.1 h1:Y8JGYUkXWTGRB6Ars3+j3kN0xg1YqqlwvdTV8WTFQcU=
|
||||
github.com/PuerkitoBio/goquery v1.10.1/go.mod h1:IYiHrOMps66ag56LEH7QYDDupKXyo5A8qrjIx3ZtujY=
|
||||
github.com/PuerkitoBio/goquery v1.10.2 h1:7fh2BdHcG6VFZsK7toXBT/Bh1z5Wmy8Q9MV9HqT2AM8=
|
||||
github.com/PuerkitoBio/goquery v1.10.2/go.mod h1:0guWGjcLu9AYC7C1GHnpysHy056u9aEkUHwhdnePMCU=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
@ -9,16 +11,21 @@ github.com/ebitengine/purego v0.8.2 h1:jPPGWs2sZ1UgOSgD2bClL0MJIqu58nOmIcBuXr62z
|
|||
github.com/ebitengine/purego v0.8.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 h1:7UMa6KCCMjZEMDtTVdcGu0B1GmmC7QJKiCCjyTAWQy0=
|
||||
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
|
||||
github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc=
|
||||
github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/mmcdole/gofeed v1.3.0 h1:5yn+HeqlcvjMeAI4gu6T+crm7d0anY85+M+v6fIFNG4=
|
||||
github.com/mmcdole/gofeed v1.3.0/go.mod h1:9TGv2LcJhdXePDzxiuMnukhV2/zb6VtnZt1mS+SjkLE=
|
||||
github.com/mmcdole/goxpp v1.1.1 h1:RGIX+D6iQRIunGHrKqnA2+700XMCnNv0bAOOv5MUhx8=
|
||||
|
@ -34,6 +41,8 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt
|
|||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/shirou/gopsutil/v4 v4.25.1 h1:QSWkTc+fu9LTAWfkZwZ6j8MSUk4A2LV7rbH0ZqmLjXs=
|
||||
github.com/shirou/gopsutil/v4 v4.25.1/go.mod h1:RoUCUpndaJFtT+2zsZzzmhvbfGoDCJ7nFXKJf8GqJbI=
|
||||
github.com/shirou/gopsutil/v4 v4.25.3 h1:SeA68lsu8gLggyMbmCn8cmp97V1TI9ld9sVzAUcKcKE=
|
||||
github.com/shirou/gopsutil/v4 v4.25.3/go.mod h1:xbuxyoZj+UsgnZrENu3lQivsngRR5BdjbJwf2fv4szA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
|
@ -47,8 +56,12 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
|||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
|
||||
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
|
||||
github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=
|
||||
github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=
|
||||
github.com/tklauser/numcpus v0.9.0 h1:lmyCHtANi8aRUgkckBgoDk1nHCux3n2cgkJLXdQGPDo=
|
||||
github.com/tklauser/numcpus v0.9.0/go.mod h1:SN6Nq1O3VychhC1npsWostA+oW+VOQTxZrS604NSRyI=
|
||||
github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=
|
||||
github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
|
@ -74,6 +87,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
|||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
|
||||
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
|
||||
golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
|
||||
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
@ -97,6 +112,8 @@ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
|
@ -117,6 +134,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
|
|
|
@ -5,23 +5,39 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
"github.com/shirou/gopsutil/v4/sensors"
|
||||
)
|
||||
|
||||
type cliIntent uint8
|
||||
|
||||
const (
|
||||
cliIntentServe cliIntent = iota
|
||||
cliIntentConfigValidate = iota
|
||||
cliIntentConfigPrint = iota
|
||||
cliIntentDiagnose = iota
|
||||
cliIntentVersionPrint cliIntent = iota
|
||||
cliIntentServe
|
||||
cliIntentConfigValidate
|
||||
cliIntentConfigPrint
|
||||
cliIntentDiagnose
|
||||
cliIntentSensorsPrint
|
||||
cliIntentMountpointInfo
|
||||
)
|
||||
|
||||
type cliOptions struct {
|
||||
intent cliIntent
|
||||
configPath string
|
||||
args []string
|
||||
}
|
||||
|
||||
func parseCliOptions() (*cliOptions, error) {
|
||||
var args []string
|
||||
|
||||
args = os.Args[1:]
|
||||
if len(args) == 1 && (args[0] == "--version" || args[0] == "-v" || args[0] == "version") {
|
||||
return &cliOptions{
|
||||
intent: cliIntentVersionPrint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
flags := flag.NewFlagSet("", flag.ExitOnError)
|
||||
flags.Usage = func() {
|
||||
fmt.Println("Usage: glance [options] command")
|
||||
|
@ -32,6 +48,8 @@ func parseCliOptions() (*cliOptions, error) {
|
|||
fmt.Println("\nCommands:")
|
||||
fmt.Println(" config:validate Validate the config file")
|
||||
fmt.Println(" config:print Print the parsed config file with embedded includes")
|
||||
fmt.Println(" sensors:print List all sensors")
|
||||
fmt.Println(" mountpoint:info Print information about a given mountpoint path")
|
||||
fmt.Println(" diagnose Run diagnostic checks")
|
||||
}
|
||||
configPath := flags.String("config", "glance.yml", "Set config path")
|
||||
|
@ -41,7 +59,7 @@ func parseCliOptions() (*cliOptions, error) {
|
|||
}
|
||||
|
||||
var intent cliIntent
|
||||
var args = flags.Args()
|
||||
args = flags.Args()
|
||||
unknownCommandErr := fmt.Errorf("unknown command: %s", strings.Join(args, " "))
|
||||
|
||||
if len(args) == 0 {
|
||||
|
@ -51,11 +69,19 @@ func parseCliOptions() (*cliOptions, error) {
|
|||
intent = cliIntentConfigValidate
|
||||
} else if args[0] == "config:print" {
|
||||
intent = cliIntentConfigPrint
|
||||
} else if args[0] == "sensors:print" {
|
||||
intent = cliIntentSensorsPrint
|
||||
} else if args[0] == "diagnose" {
|
||||
intent = cliIntentDiagnose
|
||||
} else {
|
||||
return nil, unknownCommandErr
|
||||
}
|
||||
} else if len(args) == 2 {
|
||||
if args[0] == "mountpoint:info" {
|
||||
intent = cliIntentMountpointInfo
|
||||
} else {
|
||||
return nil, unknownCommandErr
|
||||
}
|
||||
} else {
|
||||
return nil, unknownCommandErr
|
||||
}
|
||||
|
@ -63,5 +89,51 @@ func parseCliOptions() (*cliOptions, error) {
|
|||
return &cliOptions{
|
||||
intent: intent,
|
||||
configPath: *configPath,
|
||||
args: args,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func cliSensorsPrint() int {
|
||||
tempSensors, err := sensors.SensorsTemperatures()
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to retrieve list of sensors: %v\n", err)
|
||||
if warns, ok := err.(*sensors.Warnings); ok {
|
||||
for _, w := range warns.List {
|
||||
fmt.Printf(" - %v\n", w)
|
||||
}
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
if len(tempSensors) == 0 {
|
||||
fmt.Println("No sensors found")
|
||||
return 0
|
||||
}
|
||||
|
||||
for _, sensor := range tempSensors {
|
||||
fmt.Printf("%s: %.1f°C\n", sensor.SensorKey, sensor.Temperature)
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func cliMountpointInfo(requestedPath string) int {
|
||||
usage, err := disk.Usage(requestedPath)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to retrieve info for path %s: %v\n", requestedPath, err)
|
||||
if warns, ok := err.(*disk.Warnings); ok {
|
||||
for _, w := range warns.List {
|
||||
fmt.Printf(" - %v\n", w)
|
||||
}
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
fmt.Println("Path:", usage.Path)
|
||||
fmt.Println("FS type:", ternary(usage.Fstype == "", "unknown", usage.Fstype))
|
||||
fmt.Printf("Used percent: %.1f%%\n", usage.UsedPercent)
|
||||
|
||||
return 0
|
||||
}
|
||||
|
|
|
@ -219,3 +219,58 @@ func (p *proxyOptionsField) UnmarshalYAML(node *yaml.Node) error {
|
|||
|
||||
return nil
|
||||
}
|
||||
|
||||
type queryParametersField map[string][]string
|
||||
|
||||
func (q *queryParametersField) UnmarshalYAML(node *yaml.Node) error {
|
||||
var decoded map[string]any
|
||||
|
||||
if err := node.Decode(&decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*q = make(queryParametersField)
|
||||
|
||||
// TODO: refactor the duplication in the switch cases if any more types get added
|
||||
for key, value := range decoded {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
(*q)[key] = []string{v}
|
||||
case int, int8, int16, int32, int64, float32, float64:
|
||||
(*q)[key] = []string{fmt.Sprintf("%v", v)}
|
||||
case bool:
|
||||
(*q)[key] = []string{fmt.Sprintf("%t", v)}
|
||||
case []string:
|
||||
(*q)[key] = append((*q)[key], v...)
|
||||
case []any:
|
||||
for _, item := range v {
|
||||
switch item := item.(type) {
|
||||
case string:
|
||||
(*q)[key] = append((*q)[key], item)
|
||||
case int, int8, int16, int32, int64, float32, float64:
|
||||
(*q)[key] = append((*q)[key], fmt.Sprintf("%v", item))
|
||||
case bool:
|
||||
(*q)[key] = append((*q)[key], fmt.Sprintf("%t", item))
|
||||
default:
|
||||
return fmt.Errorf("invalid query parameter value type: %T", item)
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("invalid query parameter value type: %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *queryParametersField) toQueryString() string {
|
||||
query := url.Values{}
|
||||
|
||||
for key, values := range *q {
|
||||
for _, value := range values {
|
||||
query.Add(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
return query.Encode()
|
||||
}
|
||||
|
|
|
@ -81,7 +81,9 @@ var diagnosticSteps = []diagnosticStep{
|
|||
{
|
||||
name: "fetch data from Yahoo finance API",
|
||||
fn: func() (string, error) {
|
||||
return testHttpRequest("GET", "https://query1.finance.yahoo.com/v8/finance/chart/NVDA", 200)
|
||||
return testHttpRequestWithHeaders("GET", "https://query1.finance.yahoo.com/v8/finance/chart/NVDA", map[string]string{
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0",
|
||||
}, 200)
|
||||
},
|
||||
},
|
||||
{
|
||||
|
@ -103,7 +105,7 @@ func runDiagnostic() {
|
|||
fmt.Println("Glance version: " + buildVersion)
|
||||
fmt.Println("Go version: " + runtime.Version())
|
||||
fmt.Printf("Platform: %s / %s / %d CPUs\n", runtime.GOOS, runtime.GOARCH, runtime.NumCPU())
|
||||
fmt.Println("In Docker container: " + boolToString(isRunningInsideDockerContainer(), "yes", "no"))
|
||||
fmt.Println("In Docker container: " + ternary(isRunningInsideDockerContainer(), "yes", "no"))
|
||||
|
||||
fmt.Printf("\nChecking network connectivity, this may take up to %d seconds...\n\n", int(httpTestRequestTimeout.Seconds()))
|
||||
|
||||
|
@ -129,7 +131,7 @@ func runDiagnostic() {
|
|||
|
||||
fmt.Printf(
|
||||
"%s %s %s| %dms\n",
|
||||
boolToString(step.err == nil, "✓ Can", "✗ Can't"),
|
||||
ternary(step.err == nil, "✓ Can", "✗ Can't"),
|
||||
step.name,
|
||||
extraInfo,
|
||||
step.elapsed.Milliseconds(),
|
||||
|
|
|
@ -18,6 +18,8 @@ func Main() int {
|
|||
}
|
||||
|
||||
switch options.intent {
|
||||
case cliIntentVersionPrint:
|
||||
fmt.Println(buildVersion)
|
||||
case cliIntentServe:
|
||||
// remove in v0.10.0
|
||||
if serveUpdateNoticeIfConfigLocationNotMigrated(options.configPath) {
|
||||
|
@ -47,6 +49,10 @@ func Main() int {
|
|||
}
|
||||
|
||||
fmt.Println(string(contents))
|
||||
case cliIntentSensorsPrint:
|
||||
return cliSensorsPrint()
|
||||
case cliIntentMountpointInfo:
|
||||
return cliMountpointInfo(options.args[1])
|
||||
case cliIntentDiagnose:
|
||||
runDiagnostic()
|
||||
}
|
||||
|
|
|
@ -649,7 +649,7 @@ function setupTruncatedElementTitles() {
|
|||
|
||||
for (let i = 0; i < elements.length; i++) {
|
||||
const element = elements[i];
|
||||
if (element.title === "") element.title = element.textContent;
|
||||
if (element.getAttribute("title") === null) element.title = element.textContent;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -552,6 +552,10 @@ kbd:active {
|
|||
z-index: 1;
|
||||
}
|
||||
|
||||
.summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.details[open] .summary {
|
||||
margin-bottom: .8rem;
|
||||
}
|
||||
|
@ -1128,7 +1132,7 @@ details[open] .summary::after {
|
|||
|
||||
.calendar-date {
|
||||
padding: 0.4rem 0;
|
||||
color: var(--color-text-paragraph);
|
||||
color: var(--color-text-base);
|
||||
position: relative;
|
||||
border-radius: var(--border-radius);
|
||||
background: none;
|
||||
|
@ -1269,6 +1273,7 @@ details[open] .summary::after {
|
|||
|
||||
.dns-stats-graph-bar > .blocked {
|
||||
background-color: var(--color-negative);
|
||||
flex-basis: calc(var(--percent) - 1px);
|
||||
}
|
||||
|
||||
.dns-stats-graph-column:nth-child(even) .dns-stats-graph-time {
|
||||
|
@ -1834,7 +1839,7 @@ details[open] .summary::after {
|
|||
transform: translateY(calc(100% - var(--mobile-navigation-height)));
|
||||
left: var(--content-bounds-padding);
|
||||
right: var(--content-bounds-padding);
|
||||
z-index: 10;
|
||||
z-index: 11;
|
||||
background-color: var(--color-widget-background);
|
||||
border: 1px solid var(--color-widget-content-border);
|
||||
border-bottom: 0;
|
||||
|
@ -1980,7 +1985,7 @@ details[open] .summary::after {
|
|||
|
||||
@media (max-width: 550px) {
|
||||
:root {
|
||||
font-size: 9px;
|
||||
font-size: 9.4px;
|
||||
--widget-gap: 15px;
|
||||
--widget-content-vertical-padding: 10px;
|
||||
--widget-content-horizontal-padding: 10px;
|
||||
|
@ -2033,6 +2038,7 @@ details[open] .summary::after {
|
|||
.color-primary { color: var(--color-primary); }
|
||||
|
||||
.cursor-help { cursor: help; }
|
||||
.rounded { border-radius: var(--border-radius); }
|
||||
.break-all { word-break: break-all; }
|
||||
.text-left { text-align: left; }
|
||||
.text-right { text-align: right; }
|
||||
|
|
|
@ -27,9 +27,10 @@ var globalTemplateFunctions = template.FuncMap{
|
|||
"formatPrice": func(price float64) string {
|
||||
return intl.Sprintf("%.2f", price)
|
||||
},
|
||||
"dynamicRelativeTimeAttrs": func(t interface{ Unix() int64 }) template.HTMLAttr {
|
||||
return template.HTMLAttr(`data-dynamic-relative-time="` + strconv.FormatInt(t.Unix(), 10) + `"`)
|
||||
"formatPriceWithPrecision": func(precision int, price float64) string {
|
||||
return intl.Sprintf("%."+strconv.Itoa(precision)+"f", price)
|
||||
},
|
||||
"dynamicRelativeTimeAttrs": dynamicRelativeTimeAttrs,
|
||||
"formatServerMegabytes": func(mb uint64) template.HTML {
|
||||
var value string
|
||||
var label string
|
||||
|
@ -81,3 +82,7 @@ func formatApproxNumber(count int) string {
|
|||
|
||||
return strconv.FormatFloat(float64(count)/1_000_000, 'f', 1, 64) + "m"
|
||||
}
|
||||
|
||||
func dynamicRelativeTimeAttrs(t interface{ Unix() int64 }) template.HTMLAttr {
|
||||
return template.HTMLAttr(`data-dynamic-relative-time="` + strconv.FormatInt(t.Unix(), 10) + `"`)
|
||||
}
|
||||
|
|
|
@ -59,8 +59,8 @@
|
|||
{{ if ne $column.Queries $column.Blocked }}
|
||||
<div class="queries"></div>
|
||||
{{ end }}
|
||||
{{ if or (gt $column.Blocked 0) (and (lt $column.PercentTotal 15) (lt $column.PercentBlocked 10)) }}
|
||||
<div class="blocked" style="flex-basis: {{ $column.PercentBlocked }}%"></div>
|
||||
{{ if gt $column.PercentBlocked 0 }}
|
||||
<div class="blocked" style="--percent: {{ $column.PercentBlocked }}%"></div>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
{{ template "widget-base.html" . }}
|
||||
|
||||
{{- define "widget-content" }}
|
||||
<div class="dynamic-columns list-gap-20 list-with-separator">
|
||||
<ul class="dynamic-columns list-gap-20 list-with-separator">
|
||||
{{- range .Containers }}
|
||||
<div 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">
|
||||
<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">
|
||||
<img class="docker-container-icon{{ if .Icon.IsFlatIcon }} flat-icon{{ end }}" src="{{ .Icon.URL }}" alt="" loading="lazy">
|
||||
<div data-popover-html>
|
||||
<div class="color-highlight text-truncate block">{{ .Image }}</div>
|
||||
|
@ -22,7 +22,7 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div class="min-width-0">
|
||||
<div class="min-width-0 grow">
|
||||
{{- if .URL }}
|
||||
<a href="{{ .URL | safeURL }}" class="color-highlight size-title-dynamic block text-truncate" {{ if not .SameTab }}target="_blank"{{ end }} rel="noreferrer">{{ .Title }}</a>
|
||||
{{- else }}
|
||||
|
@ -33,31 +33,33 @@
|
|||
{{- end }}
|
||||
</div>
|
||||
|
||||
<div class="margin-left-auto shrink-0" data-popover-type="text" data-popover-position="above" data-popover-text="{{ .State }}">
|
||||
<div class="margin-left-auto shrink-0" data-popover-type="text" data-popover-position="above" data-popover-text="{{ .State }}" aria-label="{{ .State }}">
|
||||
{{ template "state-icon" .StateIcon }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="visually-hidden" aria-label="{{ .StateText }}"></div>
|
||||
</li>
|
||||
{{- else }}
|
||||
<div class="text-center">No containers available to show.</div>
|
||||
{{- end }}
|
||||
</div>
|
||||
</ul>
|
||||
{{- end }}
|
||||
|
||||
{{- define "state-icon" }}
|
||||
{{- if eq . "ok" }}
|
||||
<svg class="docker-container-status-icon" fill="var(--color-positive)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
|
||||
<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="docker-container-status-icon" fill="var(--color-negative)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
|
||||
<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="docker-container-status-icon" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
|
||||
<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="docker-container-status-icon" fill="var(--color-text-base)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
|
||||
<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 }}
|
||||
|
|
|
@ -17,7 +17,7 @@
|
|||
|
||||
<div class="market-values shrink-0">
|
||||
<div class="size-h3 text-right {{ if eq .PercentChange 0.0 }}{{ else if gt .PercentChange 0.0 }}color-positive{{ else }}color-negative{{ end }}">{{ printf "%+.2f" .PercentChange }}%</div>
|
||||
<div class="text-right">{{ .Currency }}{{ .Price | formatPrice }}</div>
|
||||
<div class="text-right">{{ .Currency }}{{ .Price | formatPriceWithPrecision .PriceHint }}</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
<li class="flex thumbnail-parent gap-10 items-center">
|
||||
<img class="video-horizontal-list-thumbnail thumbnail" loading="lazy" src="{{ .ThumbnailUrl }}" alt="">
|
||||
<div class="min-width-0">
|
||||
<a class="block text-truncate color-primary-if-not-visited" href="{{ .Url }}">{{ .Title }}</a>
|
||||
<a class="block text-truncate color-primary-if-not-visited" href="{{ .Url }}" target="_blank" rel="noreferrer">{{ .Title }}</a>
|
||||
<ul class="list-horizontal-text flex-nowrap">
|
||||
<li class="shrink-0" {{ dynamicRelativeTimeAttrs .TimePosted }}></li>
|
||||
<li class="min-width-0">
|
||||
|
|
|
@ -119,14 +119,6 @@ func parseRFC3339Time(t string) time.Time {
|
|||
return parsed
|
||||
}
|
||||
|
||||
func boolToString(b bool, trueValue, falseValue string) string {
|
||||
if b {
|
||||
return trueValue
|
||||
}
|
||||
|
||||
return falseValue
|
||||
}
|
||||
|
||||
func normalizeVersionFormat(version string) string {
|
||||
version = strings.ToLower(strings.TrimSpace(version))
|
||||
|
||||
|
@ -186,3 +178,7 @@ func ternary[T any](condition bool, a, b T) T {
|
|||
|
||||
return b
|
||||
}
|
||||
|
||||
// Having compile time errors about unused variables is cool and all, but I don't want to
|
||||
// have to constantly comment out my code while I'm working on it and testing things out
|
||||
func ItsUsedTrustMeBro(...any) {}
|
||||
|
|
|
@ -3,6 +3,7 @@ package glance
|
|||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
|
@ -10,6 +11,11 @@ import (
|
|||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
@ -17,13 +23,26 @@ import (
|
|||
|
||||
var customAPIWidgetTemplate = mustParseTemplate("custom-api.html", "widget-base.html")
|
||||
|
||||
// Needs to be exported for the YAML unmarshaler to work
|
||||
type CustomAPIRequest struct {
|
||||
URL string `yaml:"url"`
|
||||
AllowInsecure bool `yaml:"allow-insecure"`
|
||||
Headers map[string]string `yaml:"headers"`
|
||||
Parameters queryParametersField `yaml:"parameters"`
|
||||
Method string `yaml:"method"`
|
||||
BodyType string `yaml:"body-type"`
|
||||
Body any `yaml:"body"`
|
||||
SkipJSONValidation bool `yaml:"skip-json-validation"`
|
||||
bodyReader io.ReadSeeker `yaml:"-"`
|
||||
httpRequest *http.Request `yaml:"-"`
|
||||
}
|
||||
|
||||
type customAPIWidget struct {
|
||||
widgetBase `yaml:",inline"`
|
||||
URL string `yaml:"url"`
|
||||
*CustomAPIRequest `yaml:",inline"` // the primary request
|
||||
Subrequests map[string]*CustomAPIRequest `yaml:"subrequests"`
|
||||
Template string `yaml:"template"`
|
||||
Frameless bool `yaml:"frameless"`
|
||||
Headers map[string]string `yaml:"headers"`
|
||||
APIRequest *http.Request `yaml:"-"`
|
||||
compiledTemplate *template.Template `yaml:"-"`
|
||||
CompiledHTML template.HTML `yaml:"-"`
|
||||
}
|
||||
|
@ -31,8 +50,14 @@ type customAPIWidget struct {
|
|||
func (widget *customAPIWidget) initialize() error {
|
||||
widget.withTitle("Custom API").withCacheDuration(1 * time.Hour)
|
||||
|
||||
if widget.URL == "" {
|
||||
return errors.New("URL is required")
|
||||
if err := widget.CustomAPIRequest.initialize(); err != nil {
|
||||
return fmt.Errorf("initializing primary request: %v", err)
|
||||
}
|
||||
|
||||
for key := range widget.Subrequests {
|
||||
if err := widget.Subrequests[key].initialize(); err != nil {
|
||||
return fmt.Errorf("initializing subrequest %q: %v", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
if widget.Template == "" {
|
||||
|
@ -46,22 +71,11 @@ func (widget *customAPIWidget) initialize() error {
|
|||
|
||||
widget.compiledTemplate = compiledTemplate
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, widget.URL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for key, value := range widget.Headers {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
|
||||
widget.APIRequest = req
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (widget *customAPIWidget) update(ctx context.Context) {
|
||||
compiledHTML, err := fetchAndParseCustomAPI(widget.APIRequest, widget.compiledTemplate)
|
||||
compiledHTML, err := fetchAndParseCustomAPI(widget.CustomAPIRequest, widget.Subrequests, widget.compiledTemplate)
|
||||
if !widget.canContinueUpdateAfterHandlingErr(err) {
|
||||
return
|
||||
}
|
||||
|
@ -73,39 +87,207 @@ func (widget *customAPIWidget) Render() template.HTML {
|
|||
return widget.renderTemplate(widget, customAPIWidgetTemplate)
|
||||
}
|
||||
|
||||
func fetchAndParseCustomAPI(req *http.Request, tmpl *template.Template) (template.HTML, error) {
|
||||
emptyBody := template.HTML("")
|
||||
func (req *CustomAPIRequest) initialize() error {
|
||||
if req.URL == "" {
|
||||
return errors.New("URL is required")
|
||||
}
|
||||
|
||||
resp, err := defaultHTTPClient.Do(req)
|
||||
if req.Body != nil {
|
||||
if req.Method == "" {
|
||||
req.Method = http.MethodPost
|
||||
}
|
||||
|
||||
if req.BodyType == "" {
|
||||
req.BodyType = "json"
|
||||
}
|
||||
|
||||
if req.BodyType != "json" && req.BodyType != "string" {
|
||||
return errors.New("invalid body type, must be either 'json' or 'string'")
|
||||
}
|
||||
|
||||
switch req.BodyType {
|
||||
case "json":
|
||||
encoded, err := json.Marshal(req.Body)
|
||||
if err != nil {
|
||||
return emptyBody, err
|
||||
return fmt.Errorf("marshaling body: %v", err)
|
||||
}
|
||||
|
||||
req.bodyReader = bytes.NewReader(encoded)
|
||||
case "string":
|
||||
bodyAsString, ok := req.Body.(string)
|
||||
if !ok {
|
||||
return errors.New("body must be a string when body-type is 'string'")
|
||||
}
|
||||
|
||||
req.bodyReader = strings.NewReader(bodyAsString)
|
||||
}
|
||||
|
||||
} else if req.Method == "" {
|
||||
req.Method = http.MethodGet
|
||||
}
|
||||
|
||||
httpReq, err := http.NewRequest(strings.ToUpper(req.Method), req.URL, req.bodyReader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(req.Parameters) > 0 {
|
||||
httpReq.URL.RawQuery = req.Parameters.toQueryString()
|
||||
}
|
||||
|
||||
if req.BodyType == "json" {
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
for key, value := range req.Headers {
|
||||
httpReq.Header.Add(key, value)
|
||||
}
|
||||
|
||||
req.httpRequest = httpReq
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type customAPIResponseData struct {
|
||||
JSON decoratedGJSONResult
|
||||
Response *http.Response
|
||||
}
|
||||
|
||||
type customAPITemplateData struct {
|
||||
*customAPIResponseData
|
||||
subrequests map[string]*customAPIResponseData
|
||||
}
|
||||
|
||||
func (data *customAPITemplateData) JSONLines() []decoratedGJSONResult {
|
||||
result := make([]decoratedGJSONResult, 0, 5)
|
||||
|
||||
gjson.ForEachLine(data.JSON.Raw, func(line gjson.Result) bool {
|
||||
result = append(result, decoratedGJSONResult{line})
|
||||
return true
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (data *customAPITemplateData) Subrequest(key string) *customAPIResponseData {
|
||||
req, exists := data.subrequests[key]
|
||||
if !exists {
|
||||
// We have to panic here since there's nothing sensible we can return and the
|
||||
// lack of an error would cause requested data to return zero values which
|
||||
// would be confusing from the user's perspective. Go's template module
|
||||
// handles recovering from panics and will return the panic message as an
|
||||
// error during template execution.
|
||||
panic(fmt.Sprintf("subrequest with key %q has not been defined", key))
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
func fetchCustomAPIRequest(ctx context.Context, req *CustomAPIRequest) (*customAPIResponseData, error) {
|
||||
if req.bodyReader != nil {
|
||||
req.bodyReader.Seek(0, io.SeekStart)
|
||||
}
|
||||
|
||||
client := ternary(req.AllowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)
|
||||
resp, err := client.Do(req.httpRequest.WithContext(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
bodyBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return emptyBody, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body := string(bodyBytes)
|
||||
body := strings.TrimSpace(string(bodyBytes))
|
||||
|
||||
if !gjson.Valid(body) {
|
||||
if !req.SkipJSONValidation && body != "" && !gjson.Valid(body) {
|
||||
truncatedBody, isTruncated := limitStringLength(body, 100)
|
||||
if isTruncated {
|
||||
truncatedBody += "... <truncated>"
|
||||
}
|
||||
|
||||
slog.Error("Invalid response JSON in custom API widget", "url", req.URL.String(), "body", truncatedBody)
|
||||
return emptyBody, errors.New("invalid response JSON")
|
||||
slog.Error("Invalid response JSON in custom API widget", "url", req.httpRequest.URL.String(), "body", truncatedBody)
|
||||
return nil, errors.New("invalid response JSON")
|
||||
}
|
||||
|
||||
var templateBuffer bytes.Buffer
|
||||
|
||||
data := customAPITemplateData{
|
||||
data := &customAPIResponseData{
|
||||
JSON: decoratedGJSONResult{gjson.Parse(body)},
|
||||
Response: resp,
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func fetchAndParseCustomAPI(
|
||||
primaryReq *CustomAPIRequest,
|
||||
subReqs map[string]*CustomAPIRequest,
|
||||
tmpl *template.Template,
|
||||
) (template.HTML, error) {
|
||||
var primaryData *customAPIResponseData
|
||||
subData := make(map[string]*customAPIResponseData, len(subReqs))
|
||||
var err error
|
||||
|
||||
if len(subReqs) == 0 {
|
||||
// If there are no subrequests, we can fetch the primary request in a much simpler way
|
||||
primaryData, err = fetchCustomAPIRequest(context.Background(), primaryReq)
|
||||
} else {
|
||||
// If there are subrequests, we need to fetch them concurrently
|
||||
// and cancel all requests if any of them fail. There's probably
|
||||
// a more elegant way to do this, but this works for now.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex // protects subData and err
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var localErr error
|
||||
primaryData, localErr = fetchCustomAPIRequest(ctx, primaryReq)
|
||||
mu.Lock()
|
||||
if localErr != nil && err == nil {
|
||||
err = localErr
|
||||
cancel()
|
||||
}
|
||||
mu.Unlock()
|
||||
}()
|
||||
|
||||
for key, req := range subReqs {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var localErr error
|
||||
var data *customAPIResponseData
|
||||
data, localErr = fetchCustomAPIRequest(ctx, req)
|
||||
mu.Lock()
|
||||
if localErr == nil {
|
||||
subData[key] = data
|
||||
} else if err == nil {
|
||||
err = localErr
|
||||
cancel()
|
||||
}
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
emptyBody := template.HTML("")
|
||||
|
||||
if err != nil {
|
||||
return emptyBody, err
|
||||
}
|
||||
|
||||
data := customAPITemplateData{
|
||||
customAPIResponseData: primaryData,
|
||||
subrequests: subData,
|
||||
}
|
||||
|
||||
var templateBuffer bytes.Buffer
|
||||
err = tmpl.Execute(&templateBuffer, &data)
|
||||
if err != nil {
|
||||
return emptyBody, err
|
||||
|
@ -118,11 +300,6 @@ type decoratedGJSONResult struct {
|
|||
gjson.Result
|
||||
}
|
||||
|
||||
type customAPITemplateData struct {
|
||||
JSON decoratedGJSONResult
|
||||
Response *http.Response
|
||||
}
|
||||
|
||||
func gJsonResultArrayToDecoratedResultArray(results []gjson.Result) []decoratedGJSONResult {
|
||||
decoratedResults := make([]decoratedGJSONResult, len(results))
|
||||
|
||||
|
@ -153,12 +330,12 @@ func (r *decoratedGJSONResult) String(key string) string {
|
|||
return r.Get(key).String()
|
||||
}
|
||||
|
||||
func (r *decoratedGJSONResult) Int(key string) int64 {
|
||||
func (r *decoratedGJSONResult) Int(key string) int {
|
||||
if key == "" {
|
||||
return r.Result.Int()
|
||||
return int(r.Result.Int())
|
||||
}
|
||||
|
||||
return r.Get(key).Int()
|
||||
return int(r.Get(key).Int())
|
||||
}
|
||||
|
||||
func (r *decoratedGJSONResult) Float(key string) float64 {
|
||||
|
@ -177,29 +354,206 @@ func (r *decoratedGJSONResult) Bool(key string) bool {
|
|||
return r.Get(key).Bool()
|
||||
}
|
||||
|
||||
var customAPITemplateFuncs = func() template.FuncMap {
|
||||
funcs := template.FuncMap{
|
||||
"toFloat": func(a int64) float64 {
|
||||
return float64(a)
|
||||
},
|
||||
"toInt": func(a float64) int64 {
|
||||
return int64(a)
|
||||
},
|
||||
"add": func(a, b float64) float64 {
|
||||
func customAPIDoMathOp[T int | float64](a, b T, op string) T {
|
||||
switch op {
|
||||
case "add":
|
||||
return a + b
|
||||
},
|
||||
"sub": func(a, b float64) float64 {
|
||||
case "sub":
|
||||
return a - b
|
||||
},
|
||||
"mul": func(a, b float64) float64 {
|
||||
case "mul":
|
||||
return a * b
|
||||
},
|
||||
"div": func(a, b float64) float64 {
|
||||
case "div":
|
||||
if b == 0 {
|
||||
return math.NaN()
|
||||
return 0
|
||||
}
|
||||
return a / b
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var customAPITemplateFuncs = func() template.FuncMap {
|
||||
var regexpCacheMu sync.Mutex
|
||||
var regexpCache = make(map[string]*regexp.Regexp)
|
||||
|
||||
getCachedRegexp := func(pattern string) *regexp.Regexp {
|
||||
regexpCacheMu.Lock()
|
||||
defer regexpCacheMu.Unlock()
|
||||
|
||||
regex, exists := regexpCache[pattern]
|
||||
if !exists {
|
||||
regex = regexp.MustCompile(pattern)
|
||||
regexpCache[pattern] = regex
|
||||
}
|
||||
|
||||
return a / b
|
||||
return regex
|
||||
}
|
||||
|
||||
doMathOpWithAny := func(a, b any, op string) any {
|
||||
switch at := a.(type) {
|
||||
case int:
|
||||
switch bt := b.(type) {
|
||||
case int:
|
||||
return customAPIDoMathOp(at, bt, op)
|
||||
case float64:
|
||||
return customAPIDoMathOp(float64(at), bt, op)
|
||||
default:
|
||||
return math.NaN()
|
||||
}
|
||||
case float64:
|
||||
switch bt := b.(type) {
|
||||
case int:
|
||||
return customAPIDoMathOp(at, float64(bt), op)
|
||||
case float64:
|
||||
return customAPIDoMathOp(at, bt, op)
|
||||
default:
|
||||
return math.NaN()
|
||||
}
|
||||
default:
|
||||
return math.NaN()
|
||||
}
|
||||
}
|
||||
|
||||
funcs := template.FuncMap{
|
||||
"toFloat": func(a int) float64 {
|
||||
return float64(a)
|
||||
},
|
||||
"toInt": func(a float64) int {
|
||||
return int(a)
|
||||
},
|
||||
"add": func(a, b any) any {
|
||||
return doMathOpWithAny(a, b, "add")
|
||||
},
|
||||
"sub": func(a, b any) any {
|
||||
return doMathOpWithAny(a, b, "sub")
|
||||
},
|
||||
"mul": func(a, b any) any {
|
||||
return doMathOpWithAny(a, b, "mul")
|
||||
},
|
||||
"div": func(a, b any) any {
|
||||
return doMathOpWithAny(a, b, "div")
|
||||
},
|
||||
"now": func() time.Time {
|
||||
return time.Now()
|
||||
},
|
||||
"offsetNow": func(offset string) time.Time {
|
||||
d, err := time.ParseDuration(offset)
|
||||
if err != nil {
|
||||
return time.Now()
|
||||
}
|
||||
return time.Now().Add(d)
|
||||
},
|
||||
"duration": func(str string) time.Duration {
|
||||
d, err := time.ParseDuration(str)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return d
|
||||
},
|
||||
"parseTime": customAPIFuncParseTime,
|
||||
"toRelativeTime": dynamicRelativeTimeAttrs,
|
||||
"parseRelativeTime": func(layout, value string) template.HTMLAttr {
|
||||
// Shorthand to do both of the above with a single function call
|
||||
return dynamicRelativeTimeAttrs(customAPIFuncParseTime(layout, value))
|
||||
},
|
||||
// The reason we flip the parameter order is so that you can chain multiple calls together like this:
|
||||
// {{ .JSON.String "foo" | trimPrefix "bar" | doSomethingElse }}
|
||||
// instead of doing this:
|
||||
// {{ trimPrefix (.JSON.String "foo") "bar" | doSomethingElse }}
|
||||
// since the piped value gets passed as the last argument to the function.
|
||||
"trimPrefix": func(prefix, s string) string {
|
||||
return strings.TrimPrefix(s, prefix)
|
||||
},
|
||||
"trimSuffix": func(suffix, s string) string {
|
||||
return strings.TrimSuffix(s, suffix)
|
||||
},
|
||||
"trimSpace": strings.TrimSpace,
|
||||
"replaceAll": func(old, new, s string) string {
|
||||
return strings.ReplaceAll(s, old, new)
|
||||
},
|
||||
"replaceMatches": func(pattern, replacement, s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return getCachedRegexp(pattern).ReplaceAllString(s, replacement)
|
||||
},
|
||||
"findMatch": func(pattern, s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return getCachedRegexp(pattern).FindString(s)
|
||||
},
|
||||
"findSubmatch": func(pattern, s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
regex := getCachedRegexp(pattern)
|
||||
return itemAtIndexOrDefault(regex.FindStringSubmatch(s), 1, "")
|
||||
},
|
||||
"sortByString": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {
|
||||
sort.Slice(results, func(a, b int) bool {
|
||||
if order == "asc" {
|
||||
return results[a].String(key) < results[b].String(key)
|
||||
}
|
||||
|
||||
return results[a].String(key) > results[b].String(key)
|
||||
})
|
||||
|
||||
return results
|
||||
},
|
||||
"sortByInt": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {
|
||||
sort.Slice(results, func(a, b int) bool {
|
||||
if order == "asc" {
|
||||
return results[a].Int(key) < results[b].Int(key)
|
||||
}
|
||||
|
||||
return results[a].Int(key) > results[b].Int(key)
|
||||
})
|
||||
|
||||
return results
|
||||
},
|
||||
"sortByFloat": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {
|
||||
sort.Slice(results, func(a, b int) bool {
|
||||
if order == "asc" {
|
||||
return results[a].Float(key) < results[b].Float(key)
|
||||
}
|
||||
|
||||
return results[a].Float(key) > results[b].Float(key)
|
||||
})
|
||||
|
||||
return results
|
||||
},
|
||||
"sortByTime": func(key, layout, order string, results []decoratedGJSONResult) []decoratedGJSONResult {
|
||||
sort.Slice(results, func(a, b int) bool {
|
||||
timeA := customAPIFuncParseTime(layout, results[a].String(key))
|
||||
timeB := customAPIFuncParseTime(layout, results[b].String(key))
|
||||
|
||||
if order == "asc" {
|
||||
return timeA.Before(timeB)
|
||||
}
|
||||
|
||||
return timeA.After(timeB)
|
||||
})
|
||||
|
||||
return results
|
||||
},
|
||||
"concat": func(items ...string) string {
|
||||
return strings.Join(items, "")
|
||||
},
|
||||
"unique": func(key string, results []decoratedGJSONResult) []decoratedGJSONResult {
|
||||
seen := make(map[string]struct{})
|
||||
out := make([]decoratedGJSONResult, 0, len(results))
|
||||
for _, result := range results {
|
||||
val := result.String(key)
|
||||
if _, ok := seen[val]; !ok {
|
||||
seen[val] = struct{}{}
|
||||
out = append(out, result)
|
||||
}
|
||||
}
|
||||
return out
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -211,3 +565,30 @@ var customAPITemplateFuncs = func() template.FuncMap {
|
|||
|
||||
return funcs
|
||||
}()
|
||||
|
||||
func customAPIFuncParseTime(layout, value string) time.Time {
|
||||
switch strings.ToLower(layout) {
|
||||
case "unix":
|
||||
asInt, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
return time.Unix(0, 0)
|
||||
}
|
||||
|
||||
return time.Unix(asInt, 0)
|
||||
case "rfc3339":
|
||||
layout = time.RFC3339
|
||||
case "rfc3339nano":
|
||||
layout = time.RFC3339Nano
|
||||
case "datetime":
|
||||
layout = time.DateTime
|
||||
case "dateonly":
|
||||
layout = time.DateOnly
|
||||
}
|
||||
|
||||
parsed, err := time.Parse(layout, value)
|
||||
if err != nil {
|
||||
return time.Unix(0, 0)
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
|
|
@ -1,24 +1,35 @@
|
|||
package glance
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var dnsStatsWidgetTemplate = mustParseTemplate("dns-stats.html", "widget-base.html")
|
||||
|
||||
const (
|
||||
dnsStatsBars = 8
|
||||
dnsStatsHoursSpan = 24
|
||||
dnsStatsHoursPerBar int = dnsStatsHoursSpan / dnsStatsBars
|
||||
)
|
||||
|
||||
type dnsStatsWidget struct {
|
||||
widgetBase `yaml:",inline"`
|
||||
|
||||
TimeLabels [8]string `yaml:"-"`
|
||||
Stats *dnsStats `yaml:"-"`
|
||||
piholeSessionID string `yaml:"-"`
|
||||
|
||||
HourFormat string `yaml:"hour-format"`
|
||||
HideGraph bool `yaml:"hide-graph"`
|
||||
|
@ -31,11 +42,17 @@ type dnsStatsWidget struct {
|
|||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
const (
|
||||
dnsServiceAdguard = "adguard"
|
||||
dnsServicePihole = "pihole"
|
||||
dnsServicePiholeV6 = "pihole-v6"
|
||||
)
|
||||
|
||||
func makeDNSWidgetTimeLabels(format string) [8]string {
|
||||
now := time.Now()
|
||||
var labels [8]string
|
||||
var labels [dnsStatsBars]string
|
||||
|
||||
for h := 24; h > 0; h -= 3 {
|
||||
for h := dnsStatsHoursSpan; h > 0; h -= dnsStatsHoursPerBar {
|
||||
labels[7-(h/3-1)] = strings.ToLower(now.Add(-time.Duration(h) * time.Hour).Format(format))
|
||||
}
|
||||
|
||||
|
@ -48,8 +65,12 @@ func (widget *dnsStatsWidget) initialize() error {
|
|||
withTitleURL(string(widget.URL)).
|
||||
withCacheDuration(10 * time.Minute)
|
||||
|
||||
if widget.Service != "adguard" && widget.Service != "pihole" {
|
||||
return errors.New("service must be either 'adguard' or 'pihole'")
|
||||
switch widget.Service {
|
||||
case dnsServiceAdguard:
|
||||
case dnsServicePiholeV6:
|
||||
case dnsServicePihole:
|
||||
default:
|
||||
return fmt.Errorf("service must be one of: %s, %s, %s", dnsServiceAdguard, dnsServicePihole, dnsServicePiholeV6)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@ -59,10 +80,24 @@ func (widget *dnsStatsWidget) update(ctx context.Context) {
|
|||
var stats *dnsStats
|
||||
var err error
|
||||
|
||||
if widget.Service == "adguard" {
|
||||
switch widget.Service {
|
||||
case dnsServiceAdguard:
|
||||
stats, err = fetchAdguardStats(widget.URL, widget.AllowInsecure, widget.Username, widget.Password, widget.HideGraph)
|
||||
} else {
|
||||
stats, err = fetchPiholeStats(widget.URL, widget.AllowInsecure, widget.Token, widget.HideGraph)
|
||||
case dnsServicePihole:
|
||||
stats, err = fetchPihole5Stats(widget.URL, widget.AllowInsecure, widget.Token, widget.HideGraph)
|
||||
case dnsServicePiholeV6:
|
||||
var newSessionID string
|
||||
stats, newSessionID, err = fetchPiholeStats(
|
||||
widget.URL,
|
||||
widget.AllowInsecure,
|
||||
widget.Password,
|
||||
widget.piholeSessionID,
|
||||
!widget.HideGraph,
|
||||
!widget.HideTopDomains,
|
||||
)
|
||||
if err == nil {
|
||||
widget.piholeSessionID = newSessionID
|
||||
}
|
||||
}
|
||||
|
||||
if !widget.canContinueUpdateAfterHandlingErr(err) {
|
||||
|
@ -84,11 +119,11 @@ func (widget *dnsStatsWidget) Render() template.HTML {
|
|||
|
||||
type dnsStats struct {
|
||||
TotalQueries int
|
||||
BlockedQueries int
|
||||
BlockedQueries int // we don't actually use this anywhere in templates, maybe remove it later?
|
||||
BlockedPercent int
|
||||
ResponseTime int
|
||||
DomainsBlocked int
|
||||
Series [8]dnsStatsSeries
|
||||
Series [dnsStatsBars]dnsStatsSeries
|
||||
TopBlockedDomains []dnsStatsBlockedDomain
|
||||
}
|
||||
|
||||
|
@ -123,13 +158,7 @@ func fetchAdguardStats(instanceURL string, allowInsecure bool, username, passwor
|
|||
|
||||
request.SetBasicAuth(username, password)
|
||||
|
||||
var client requestDoer
|
||||
if !allowInsecure {
|
||||
client = defaultHTTPClient
|
||||
} else {
|
||||
client = defaultInsecureHTTPClient
|
||||
}
|
||||
|
||||
var client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)
|
||||
responseJson, err := decodeJsonFromRequest[adguardStatsResponse](client, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -150,7 +179,7 @@ func fetchAdguardStats(instanceURL string, allowInsecure bool, username, passwor
|
|||
|
||||
stats.BlockedPercent = int(float64(responseJson.BlockedQueries) / float64(responseJson.TotalQueries) * 100)
|
||||
|
||||
for i := 0; i < topBlockedDomainsCount; i++ {
|
||||
for i := range topBlockedDomainsCount {
|
||||
domain := responseJson.TopBlockedDomains[i]
|
||||
var firstDomain string
|
||||
|
||||
|
@ -179,31 +208,27 @@ func fetchAdguardStats(instanceURL string, allowInsecure bool, username, passwor
|
|||
queriesSeries := responseJson.QueriesSeries
|
||||
blockedSeries := responseJson.BlockedSeries
|
||||
|
||||
const bars = 8
|
||||
const hoursSpan = 24
|
||||
const hoursPerBar int = hoursSpan / bars
|
||||
|
||||
if len(queriesSeries) > hoursSpan {
|
||||
queriesSeries = queriesSeries[len(queriesSeries)-hoursSpan:]
|
||||
} else if len(queriesSeries) < hoursSpan {
|
||||
queriesSeries = append(make([]int, hoursSpan-len(queriesSeries)), queriesSeries...)
|
||||
if len(queriesSeries) > dnsStatsHoursSpan {
|
||||
queriesSeries = queriesSeries[len(queriesSeries)-dnsStatsHoursSpan:]
|
||||
} else if len(queriesSeries) < dnsStatsHoursSpan {
|
||||
queriesSeries = append(make([]int, dnsStatsHoursSpan-len(queriesSeries)), queriesSeries...)
|
||||
}
|
||||
|
||||
if len(blockedSeries) > hoursSpan {
|
||||
blockedSeries = blockedSeries[len(blockedSeries)-hoursSpan:]
|
||||
} else if len(blockedSeries) < hoursSpan {
|
||||
blockedSeries = append(make([]int, hoursSpan-len(blockedSeries)), blockedSeries...)
|
||||
if len(blockedSeries) > dnsStatsHoursSpan {
|
||||
blockedSeries = blockedSeries[len(blockedSeries)-dnsStatsHoursSpan:]
|
||||
} else if len(blockedSeries) < dnsStatsHoursSpan {
|
||||
blockedSeries = append(make([]int, dnsStatsHoursSpan-len(blockedSeries)), blockedSeries...)
|
||||
}
|
||||
|
||||
maxQueriesInSeries := 0
|
||||
|
||||
for i := 0; i < bars; i++ {
|
||||
for i := range dnsStatsBars {
|
||||
queries := 0
|
||||
blocked := 0
|
||||
|
||||
for j := 0; j < hoursPerBar; j++ {
|
||||
queries += queriesSeries[i*hoursPerBar+j]
|
||||
blocked += blockedSeries[i*hoursPerBar+j]
|
||||
for j := range dnsStatsHoursPerBar {
|
||||
queries += queriesSeries[i*dnsStatsHoursPerBar+j]
|
||||
blocked += blockedSeries[i*dnsStatsHoursPerBar+j]
|
||||
}
|
||||
|
||||
stats.Series[i] = dnsStatsSeries{
|
||||
|
@ -220,20 +245,21 @@ func fetchAdguardStats(instanceURL string, allowInsecure bool, username, passwor
|
|||
}
|
||||
}
|
||||
|
||||
for i := 0; i < bars; i++ {
|
||||
for i := range dnsStatsBars {
|
||||
stats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
type piholeStatsResponse struct {
|
||||
// Legacy Pi-hole stats response (before v6)
|
||||
type pihole5StatsResponse struct {
|
||||
TotalQueries int `json:"dns_queries_today"`
|
||||
QueriesSeries piholeQueriesSeries `json:"domains_over_time"`
|
||||
QueriesSeries pihole5QueriesSeries `json:"domains_over_time"`
|
||||
BlockedQueries int `json:"ads_blocked_today"`
|
||||
BlockedSeries map[int64]int `json:"ads_over_time"`
|
||||
BlockedPercentage float64 `json:"ads_percentage_today"`
|
||||
TopBlockedDomains piholeTopBlockedDomains `json:"top_ads"`
|
||||
TopBlockedDomains pihole5TopBlockedDomains `json:"top_ads"`
|
||||
DomainsBlocked int `json:"domains_being_blocked"`
|
||||
}
|
||||
|
||||
|
@ -241,14 +267,14 @@ type piholeStatsResponse struct {
|
|||
// empty array rather than a map which will prevent unmashalling the rest of the data so we use
|
||||
// custom unmarshal behavior to fallback to an empty map.
|
||||
// See https://github.com/glanceapp/glance/issues/289
|
||||
type piholeQueriesSeries map[int64]int
|
||||
type pihole5QueriesSeries map[int64]int
|
||||
|
||||
func (p *piholeQueriesSeries) UnmarshalJSON(data []byte) error {
|
||||
func (p *pihole5QueriesSeries) UnmarshalJSON(data []byte) error {
|
||||
temp := make(map[int64]int)
|
||||
|
||||
err := json.Unmarshal(data, &temp)
|
||||
if err != nil {
|
||||
*p = make(piholeQueriesSeries)
|
||||
*p = make(pihole5QueriesSeries)
|
||||
} else {
|
||||
*p = temp
|
||||
}
|
||||
|
@ -258,16 +284,16 @@ func (p *piholeQueriesSeries) UnmarshalJSON(data []byte) error {
|
|||
|
||||
// If user has some level of privacy enabled on Pihole, `json:"top_ads"` is an empty array
|
||||
// Use custom unmarshal behavior to avoid not getting the rest of the valid data when unmarshalling
|
||||
type piholeTopBlockedDomains map[string]int
|
||||
type pihole5TopBlockedDomains map[string]int
|
||||
|
||||
func (p *piholeTopBlockedDomains) UnmarshalJSON(data []byte) error {
|
||||
func (p *pihole5TopBlockedDomains) UnmarshalJSON(data []byte) error {
|
||||
// NOTE: do not change to piholeTopBlockedDomains type here or it will cause a stack overflow
|
||||
// because of the UnmarshalJSON method getting called recursively
|
||||
temp := make(map[string]int)
|
||||
|
||||
err := json.Unmarshal(data, &temp)
|
||||
if err != nil {
|
||||
*p = make(piholeTopBlockedDomains)
|
||||
*p = make(pihole5TopBlockedDomains)
|
||||
} else {
|
||||
*p = temp
|
||||
}
|
||||
|
@ -275,7 +301,7 @@ func (p *piholeTopBlockedDomains) UnmarshalJSON(data []byte) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func fetchPiholeStats(instanceURL string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) {
|
||||
func fetchPihole5Stats(instanceURL string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) {
|
||||
if token == "" {
|
||||
return nil, errors.New("missing API token")
|
||||
}
|
||||
|
@ -288,14 +314,8 @@ func fetchPiholeStats(instanceURL string, allowInsecure bool, token string, noGr
|
|||
return nil, err
|
||||
}
|
||||
|
||||
var client requestDoer
|
||||
if !allowInsecure {
|
||||
client = defaultHTTPClient
|
||||
} else {
|
||||
client = defaultInsecureHTTPClient
|
||||
}
|
||||
|
||||
responseJson, err := decodeJsonFromRequest[piholeStatsResponse](client, request)
|
||||
var client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)
|
||||
responseJson, err := decodeJsonFromRequest[pihole5StatsResponse](client, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -339,7 +359,6 @@ func fetchPiholeStats(instanceURL string, allowInsecure bool, token string, noGr
|
|||
}
|
||||
|
||||
var lowestTimestamp int64 = 0
|
||||
|
||||
for timestamp := range responseJson.QueriesSeries {
|
||||
if lowestTimestamp == 0 || timestamp < lowestTimestamp {
|
||||
lowestTimestamp = timestamp
|
||||
|
@ -348,11 +367,11 @@ func fetchPiholeStats(instanceURL string, allowInsecure bool, token string, noGr
|
|||
|
||||
maxQueriesInSeries := 0
|
||||
|
||||
for i := 0; i < 8; i++ {
|
||||
for i := range dnsStatsBars {
|
||||
queries := 0
|
||||
blocked := 0
|
||||
|
||||
for j := 0; j < 18; j++ {
|
||||
for j := range 18 {
|
||||
index := lowestTimestamp + int64(i*10800+j*600)
|
||||
|
||||
queries += responseJson.QueriesSeries[index]
|
||||
|
@ -373,9 +392,283 @@ func fetchPiholeStats(instanceURL string, allowInsecure bool, token string, noGr
|
|||
}
|
||||
}
|
||||
|
||||
for i := 0; i < 8; i++ {
|
||||
for i := range dnsStatsBars {
|
||||
stats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func fetchPiholeStats(
|
||||
instanceURL string,
|
||||
allowInsecure bool,
|
||||
password string,
|
||||
sessionID string,
|
||||
includeGraph bool,
|
||||
includeTopDomains bool,
|
||||
) (*dnsStats, string, error) {
|
||||
instanceURL = strings.TrimRight(instanceURL, "/")
|
||||
var client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)
|
||||
|
||||
fetchNewSessionID := func() error {
|
||||
newSessionID, err := fetchPiholeSessionID(instanceURL, client, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sessionID = newSessionID
|
||||
return nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
type statsResponseJson struct {
|
||||
Queries struct {
|
||||
Total int `json:"total"`
|
||||
Blocked int `json:"blocked"`
|
||||
PercentBlocked float64 `json:"percent_blocked"`
|
||||
} `json:"queries"`
|
||||
Gravity struct {
|
||||
DomainsBlocked int `json:"domains_being_blocked"`
|
||||
} `json:"gravity"`
|
||||
}
|
||||
|
||||
statsRequest, _ := http.NewRequestWithContext(ctx, "GET", instanceURL+"/api/stats/summary", nil)
|
||||
statsRequest.Header.Set("x-ftl-sid", sessionID)
|
||||
|
||||
var statsResponse statsResponseJson
|
||||
var statsErr error
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
statsResponse, statsErr = decodeJsonFromRequest[statsResponseJson](client, statsRequest)
|
||||
if statsErr != nil {
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
|
||||
type seriesResponseJson struct {
|
||||
History []struct {
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Total int `json:"total"`
|
||||
Blocked int `json:"blocked"`
|
||||
} `json:"history"`
|
||||
}
|
||||
|
||||
var seriesResponse seriesResponseJson
|
||||
var seriesErr error
|
||||
|
||||
if includeGraph {
|
||||
seriesRequest, _ := http.NewRequestWithContext(ctx, "GET", instanceURL+"/api/history", nil)
|
||||
seriesRequest.Header.Set("x-ftl-sid", sessionID)
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
seriesResponse, seriesErr = decodeJsonFromRequest[seriesResponseJson](client, seriesRequest)
|
||||
}()
|
||||
}
|
||||
|
||||
type topDomainsResponseJson struct {
|
||||
Domains []struct {
|
||||
Domain string `json:"domain"`
|
||||
Count int `json:"count"`
|
||||
} `json:"domains"`
|
||||
TotalQueries int `json:"total_queries"`
|
||||
BlockedQueries int `json:"blocked_queries"`
|
||||
Took float64 `json:"took"`
|
||||
}
|
||||
|
||||
var topDomainsResponse topDomainsResponseJson
|
||||
var topDomainsErr error
|
||||
|
||||
if includeTopDomains {
|
||||
topDomainsRequest, _ := http.NewRequestWithContext(ctx, "GET", instanceURL+"/api/stats/top_domains?blocked=true", nil)
|
||||
topDomainsRequest.Header.Set("x-ftl-sid", sessionID)
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
topDomainsResponse, topDomainsErr = decodeJsonFromRequest[topDomainsResponseJson](client, topDomainsRequest)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
partialContent := false
|
||||
|
||||
if statsErr != nil {
|
||||
return nil, "", fmt.Errorf("fetching stats: %v", statsErr)
|
||||
}
|
||||
|
||||
if includeGraph && seriesErr != nil {
|
||||
slog.Error("Failed to fetch Pihole v6 graph data", "error", seriesErr)
|
||||
partialContent = true
|
||||
}
|
||||
|
||||
if includeTopDomains && topDomainsErr != nil {
|
||||
slog.Error("Failed to fetch Pihole v6 top domains", "error", topDomainsErr)
|
||||
partialContent = true
|
||||
}
|
||||
|
||||
stats := &dnsStats{
|
||||
TotalQueries: statsResponse.Queries.Total,
|
||||
BlockedQueries: statsResponse.Queries.Blocked,
|
||||
BlockedPercent: int(statsResponse.Queries.PercentBlocked),
|
||||
DomainsBlocked: statsResponse.Gravity.DomainsBlocked,
|
||||
}
|
||||
|
||||
if includeGraph && seriesErr == nil {
|
||||
if len(seriesResponse.History) != 145 {
|
||||
slog.Error(
|
||||
"Pihole v6 graph data has unexpected length",
|
||||
"length", len(seriesResponse.History),
|
||||
"expected", 145,
|
||||
)
|
||||
partialContent = true
|
||||
} else {
|
||||
// The API from v5 used to return 144 data points, but v6 returns 145.
|
||||
// We only show data from the last 24 hours hours, Pihole returns data
|
||||
// points in a 10 minute interval, 24*(60/10) = 144. Why is there an extra
|
||||
// data point? I don't know, but we'll just ignore the first one since it's
|
||||
// the oldest data point.
|
||||
history := seriesResponse.History[1:]
|
||||
|
||||
const interval = 10
|
||||
const dataPointsPerBar = dnsStatsHoursPerBar * (60 / interval)
|
||||
|
||||
maxQueriesInSeries := 0
|
||||
|
||||
for i := range dnsStatsBars {
|
||||
queries := 0
|
||||
blocked := 0
|
||||
for j := range dataPointsPerBar {
|
||||
index := i*dataPointsPerBar + j
|
||||
queries += history[index].Total
|
||||
blocked += history[index].Blocked
|
||||
}
|
||||
if queries > maxQueriesInSeries {
|
||||
maxQueriesInSeries = queries
|
||||
}
|
||||
stats.Series[i] = dnsStatsSeries{
|
||||
Queries: queries,
|
||||
Blocked: blocked,
|
||||
}
|
||||
if queries > 0 {
|
||||
stats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100)
|
||||
}
|
||||
}
|
||||
|
||||
for i := range dnsStatsBars {
|
||||
stats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if includeTopDomains && topDomainsErr == nil && len(topDomainsResponse.Domains) > 0 {
|
||||
domains := make([]dnsStatsBlockedDomain, 0, len(topDomainsResponse.Domains))
|
||||
for i := range topDomainsResponse.Domains {
|
||||
d := &topDomainsResponse.Domains[i]
|
||||
domains = append(domains, dnsStatsBlockedDomain{
|
||||
Domain: d.Domain,
|
||||
PercentBlocked: int(float64(d.Count) / float64(statsResponse.Queries.Blocked) * 100),
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(domains, func(a, b int) bool {
|
||||
return domains[a].PercentBlocked > domains[b].PercentBlocked
|
||||
})
|
||||
stats.TopBlockedDomains = domains[:min(len(domains), 5)]
|
||||
}
|
||||
|
||||
return stats, sessionID, ternary(partialContent, errPartialContent, nil)
|
||||
}
|
||||
|
||||
func fetchPiholeSessionID(instanceURL string, client *http.Client, password string) (string, error) {
|
||||
requestBody := []byte(`{"password":"` + password + `"}`)
|
||||
|
||||
request, err := http.NewRequest("POST", instanceURL+"/api/auth", bytes.NewBuffer(requestBody))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("creating authentication request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("sending authentication request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reading authentication response: %v", err)
|
||||
}
|
||||
|
||||
var jsonResponse struct {
|
||||
Session struct {
|
||||
SID string `json:"sid"`
|
||||
Message string `json:"message"`
|
||||
} `json:"session"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &jsonResponse); err != nil {
|
||||
return "", fmt.Errorf("parsing authentication response: %v", err)
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf(
|
||||
"authentication request returned status %s with message '%s'",
|
||||
response.Status, jsonResponse.Session.Message,
|
||||
)
|
||||
}
|
||||
|
||||
if jsonResponse.Session.SID == "" {
|
||||
return "", fmt.Errorf(
|
||||
"authentication response returned empty session ID, status code %d, message '%s'",
|
||||
response.StatusCode, jsonResponse.Session.Message,
|
||||
)
|
||||
}
|
||||
|
||||
return jsonResponse.Session.SID, nil
|
||||
}
|
||||
|
||||
func checkPiholeSessionIDIsValid(instanceURL string, client *http.Client, sessionID string) (bool, error) {
|
||||
request, err := http.NewRequest("GET", instanceURL+"/api/auth", nil)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("creating session ID check request: %v", err)
|
||||
}
|
||||
request.Header.Set("x-ftl-sid", sessionID)
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusUnauthorized {
|
||||
return false, fmt.Errorf("session ID check request returned status %s", response.Status)
|
||||
}
|
||||
|
||||
return response.StatusCode == http.StatusOK, nil
|
||||
}
|
||||
|
|
|
@ -21,7 +21,8 @@ type extensionWidget struct {
|
|||
widgetBase `yaml:",inline"`
|
||||
URL string `yaml:"url"`
|
||||
FallbackContentType string `yaml:"fallback-content-type"`
|
||||
Parameters map[string]string `yaml:"parameters"`
|
||||
Parameters queryParametersField `yaml:"parameters"`
|
||||
Headers map[string]string `yaml:"headers"`
|
||||
AllowHtml bool `yaml:"allow-potentially-dangerous-html"`
|
||||
Extension extension `yaml:"-"`
|
||||
cachedHTML template.HTML `yaml:"-"`
|
||||
|
@ -46,6 +47,7 @@ func (widget *extensionWidget) update(ctx context.Context) {
|
|||
URL: widget.URL,
|
||||
FallbackContentType: widget.FallbackContentType,
|
||||
Parameters: widget.Parameters,
|
||||
Headers: widget.Headers,
|
||||
AllowHtml: widget.AllowHtml,
|
||||
})
|
||||
|
||||
|
@ -57,6 +59,10 @@ func (widget *extensionWidget) update(ctx context.Context) {
|
|||
widget.Title = extension.Title
|
||||
}
|
||||
|
||||
if widget.TitleURL == "" && extension.TitleURL != "" {
|
||||
widget.TitleURL = extension.TitleURL
|
||||
}
|
||||
|
||||
widget.cachedHTML = widget.renderTemplate(widget, extensionWidgetTemplate)
|
||||
}
|
||||
|
||||
|
@ -68,7 +74,7 @@ type extensionType int
|
|||
|
||||
const (
|
||||
extensionContentHTML extensionType = iota
|
||||
extensionContentUnknown = iota
|
||||
extensionContentUnknown
|
||||
)
|
||||
|
||||
var extensionStringToType = map[string]extensionType{
|
||||
|
@ -77,6 +83,7 @@ var extensionStringToType = map[string]extensionType{
|
|||
|
||||
const (
|
||||
extensionHeaderTitle = "Widget-Title"
|
||||
extensionHeaderTitleURL = "Widget-Title-URL"
|
||||
extensionHeaderContentType = "Widget-Content-Type"
|
||||
extensionHeaderContentFrameless = "Widget-Content-Frameless"
|
||||
)
|
||||
|
@ -84,12 +91,14 @@ const (
|
|||
type extensionRequestOptions struct {
|
||||
URL string `yaml:"url"`
|
||||
FallbackContentType string `yaml:"fallback-content-type"`
|
||||
Parameters map[string]string `yaml:"parameters"`
|
||||
Parameters queryParametersField `yaml:"parameters"`
|
||||
Headers map[string]string `yaml:"headers"`
|
||||
AllowHtml bool `yaml:"allow-potentially-dangerous-html"`
|
||||
}
|
||||
|
||||
type extension struct {
|
||||
Title string
|
||||
TitleURL string
|
||||
Content template.HTML
|
||||
Frameless bool
|
||||
}
|
||||
|
@ -109,14 +118,13 @@ func convertExtensionContent(options extensionRequestOptions, content []byte, co
|
|||
|
||||
func fetchExtension(options extensionRequestOptions) (extension, error) {
|
||||
request, _ := http.NewRequest("GET", options.URL, nil)
|
||||
|
||||
query := url.Values{}
|
||||
|
||||
for key, value := range options.Parameters {
|
||||
query.Set(key, value)
|
||||
if len(options.Parameters) > 0 {
|
||||
request.URL.RawQuery = options.Parameters.toQueryString()
|
||||
}
|
||||
|
||||
request.URL.RawQuery = query.Encode()
|
||||
for key, value := range options.Headers {
|
||||
request.Header.Add(key, value)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
|
@ -140,6 +148,10 @@ func fetchExtension(options extensionRequestOptions) (extension, error) {
|
|||
extension.Title = response.Header.Get(extensionHeaderTitle)
|
||||
}
|
||||
|
||||
if response.Header.Get(extensionHeaderTitleURL) != "" {
|
||||
extension.TitleURL = response.Header.Get(extensionHeaderTitleURL)
|
||||
}
|
||||
|
||||
contentType, ok := extensionStringToType[response.Header.Get(extensionHeaderContentType)]
|
||||
|
||||
if !ok {
|
||||
|
|
|
@ -79,6 +79,7 @@ type market struct {
|
|||
Name string
|
||||
Currency string
|
||||
Price float64
|
||||
PriceHint int
|
||||
PercentChange float64
|
||||
SvgChartPoints string
|
||||
}
|
||||
|
@ -106,6 +107,7 @@ type marketResponseJson struct {
|
|||
RegularMarketPrice float64 `json:"regularMarketPrice"`
|
||||
ChartPreviousClose float64 `json:"chartPreviousClose"`
|
||||
ShortName string `json:"shortName"`
|
||||
PriceHint int `json:"priceHint"`
|
||||
} `json:"meta"`
|
||||
Indicators struct {
|
||||
Quote []struct {
|
||||
|
@ -152,13 +154,14 @@ func fetchMarketsDataFromYahoo(marketRequests []marketRequest) (marketList, erro
|
|||
continue
|
||||
}
|
||||
|
||||
prices := response.Chart.Result[0].Indicators.Quote[0].Close
|
||||
result := &response.Chart.Result[0]
|
||||
prices := result.Indicators.Quote[0].Close
|
||||
|
||||
if len(prices) > marketChartDays {
|
||||
prices = prices[len(prices)-marketChartDays:]
|
||||
}
|
||||
|
||||
previous := response.Chart.Result[0].Meta.RegularMarketPrice
|
||||
previous := result.Meta.RegularMarketPrice
|
||||
|
||||
if len(prices) >= 2 && prices[len(prices)-2] != 0 {
|
||||
previous = prices[len(prices)-2]
|
||||
|
@ -166,21 +169,22 @@ func fetchMarketsDataFromYahoo(marketRequests []marketRequest) (marketList, erro
|
|||
|
||||
points := svgPolylineCoordsFromYValues(100, 50, maybeCopySliceWithoutZeroValues(prices))
|
||||
|
||||
currency, exists := currencyToSymbol[strings.ToUpper(response.Chart.Result[0].Meta.Currency)]
|
||||
currency, exists := currencyToSymbol[strings.ToUpper(result.Meta.Currency)]
|
||||
if !exists {
|
||||
currency = response.Chart.Result[0].Meta.Currency
|
||||
currency = result.Meta.Currency
|
||||
}
|
||||
|
||||
markets = append(markets, market{
|
||||
marketRequest: marketRequests[i],
|
||||
Price: response.Chart.Result[0].Meta.RegularMarketPrice,
|
||||
Price: result.Meta.RegularMarketPrice,
|
||||
Currency: currency,
|
||||
PriceHint: result.Meta.PriceHint,
|
||||
Name: ternary(marketRequests[i].CustomName == "",
|
||||
response.Chart.Result[0].Meta.ShortName,
|
||||
result.Meta.ShortName,
|
||||
marketRequests[i].CustomName,
|
||||
),
|
||||
PercentChange: percentChange(
|
||||
response.Chart.Result[0].Meta.RegularMarketPrice,
|
||||
result.Meta.RegularMarketPrice,
|
||||
previous,
|
||||
),
|
||||
SvgChartPoints: points,
|
||||
|
|
|
@ -331,6 +331,7 @@ func fetchItemsFromRSSFeeds(requests []rssFeedRequest) (rssFeedItemList, error)
|
|||
|
||||
failed := 0
|
||||
entries := make(rssFeedItemList, 0, len(feeds)*10)
|
||||
seen := make(map[string]struct{})
|
||||
|
||||
for i := range feeds {
|
||||
if errs[i] != nil {
|
||||
|
@ -339,7 +340,13 @@ func fetchItemsFromRSSFeeds(requests []rssFeedRequest) (rssFeedItemList, error)
|
|||
continue
|
||||
}
|
||||
|
||||
entries = append(entries, feeds[i]...)
|
||||
for _, item := range feeds[i] {
|
||||
if _, exists := seen[item.Link]; exists {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, item)
|
||||
seen[item.Link] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if failed == len(requests) {
|
||||
|
|
|
@ -196,6 +196,10 @@ func fetchChannelFromTwitchTask(channel string) (twitchChannel, error) {
|
|||
slog.Warn("Failed to parse Twitch stream started at", "error", err, "started_at", streamMetadata.UserOrNull.Stream.StartedAt)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This prevents live channels with 0 viewers from being
|
||||
// incorrectly sorted lower than offline channels
|
||||
result.ViewersCount = -1
|
||||
}
|
||||
|
||||
return result, nil
|
||||
|
|
|
@ -181,6 +181,11 @@ func workerPoolDo[I any, O any](job *workerPoolJob[I, O]) ([]O, []error, error)
|
|||
return results, errs, nil
|
||||
}
|
||||
|
||||
if len(job.data) == 1 {
|
||||
results[0], errs[0] = job.task(job.data[0])
|
||||
return results, errs, nil
|
||||
}
|
||||
|
||||
tasksQueue := make(chan *workerPoolTask[I, O])
|
||||
resultsQueue := make(chan *workerPoolTask[I, O])
|
||||
|
||||
|
|
|
@ -56,7 +56,7 @@ func (widget *videosWidget) initialize() error {
|
|||
widget.Channels = append(widget.Channels, make([]string, len(widget.Playlists))...)
|
||||
|
||||
for i := range widget.Playlists {
|
||||
widget.Channels[initialLen+i] = "playlist:" + widget.Playlists[i]
|
||||
widget.Channels[initialLen+i] = videosWidgetPlaylistPrefix + widget.Playlists[i]
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -227,22 +227,24 @@ func Collect(req *SystemInfoRequest) (*SystemInfo, []error) {
|
|||
}
|
||||
}
|
||||
|
||||
filesystems, err := disk.Partitions(false)
|
||||
if err == nil {
|
||||
for _, fs := range filesystems {
|
||||
mpReq, ok := req.Mountpoints[fs.Mountpoint]
|
||||
addedMountpoints := map[string]struct{}{}
|
||||
addMountpointInfo := func(requestedPath string, mpReq MointpointRequest) {
|
||||
if _, exists := addedMountpoints[requestedPath]; exists {
|
||||
return
|
||||
}
|
||||
|
||||
isHidden := req.HideMountpointsByDefault
|
||||
if ok && mpReq.Hide != nil {
|
||||
if mpReq.Hide != nil {
|
||||
isHidden = *mpReq.Hide
|
||||
}
|
||||
if isHidden {
|
||||
continue
|
||||
return
|
||||
}
|
||||
|
||||
usage, err := disk.Usage(fs.Mountpoint)
|
||||
usage, err := disk.Usage(requestedPath)
|
||||
if err == nil {
|
||||
mpInfo := MountpointInfo{
|
||||
Path: fs.Mountpoint,
|
||||
Path: requestedPath,
|
||||
Name: mpReq.Name,
|
||||
TotalMB: usage.Total / 1024 / 1024,
|
||||
UsedMB: usage.Used / 1024 / 1024,
|
||||
|
@ -250,13 +252,26 @@ func Collect(req *SystemInfoRequest) (*SystemInfo, []error) {
|
|||
}
|
||||
|
||||
info.Mountpoints = append(info.Mountpoints, mpInfo)
|
||||
addedMountpoints[requestedPath] = struct{}{}
|
||||
} else {
|
||||
addErr(fmt.Errorf("getting filesystem usage for %s: %v", fs.Mountpoint, err))
|
||||
addErr(fmt.Errorf("getting filesystem usage for %s: %v", requestedPath, err))
|
||||
}
|
||||
}
|
||||
|
||||
if !req.HideMountpointsByDefault {
|
||||
filesystems, err := disk.Partitions(false)
|
||||
if err == nil {
|
||||
for _, fs := range filesystems {
|
||||
addMountpointInfo(fs.Mountpoint, req.Mountpoints[fs.Mountpoint])
|
||||
}
|
||||
} else {
|
||||
addErr(fmt.Errorf("getting filesystems: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
for mountpoint, mpReq := range req.Mountpoints {
|
||||
addMountpointInfo(mountpoint, mpReq)
|
||||
}
|
||||
|
||||
sort.Slice(info.Mountpoints, func(a, b int) bool {
|
||||
return info.Mountpoints[a].UsedPercent > info.Mountpoints[b].UsedPercent
|
||||
|
|
Loading…
Add table
Reference in a new issue