diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 1f9515c..0000000 --- a/.dockerignore +++ /dev/null @@ -1,11 +0,0 @@ -# https://docs.docker.com/build/building/context/#dockerignore-files -# Ignore all files by default -* - -# Only add necessary files to the Docker build context (Dockerfiles are always included implicitly) -!/build/ -!/internal/ -!/pkg/ -!/go.mod -!/go.sum -!main.go diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md deleted file mode 100644 index d1b4aaa..0000000 --- a/.github/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,128 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -glanceapp@duck.com. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index cda2741..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: [glanceapp] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index bdd4fe6..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Bug report -description: Let us know if something isn't working as expected -labels: ["bug report"] -body: - - type: markdown - attributes: - value: | - > [!NOTE] - > - > Do not prefix your title with "[BUG]", "[Bug report]", etc., a label will be added automatically. - - If you're unsure whether you're experiencing a bug or not, consider using the [Discussions](https://github.com/glanceapp/glance/discussions) or [Discord](https://discord.com/invite/7KQ7Xa9kJd) to ask for help. - - Please include only the information you think is relevant to the bug: - - * How did you install Glance? (Docker container, manual binary install, etc) - * Which version of Glance are you using? - * Include the relevant parts of your `glance.yml` if applicable (widget, data source, properties used, etc) - * Include any relevant logs or screenshots if applicable - * Is the issue specific to a certain browser or OS? - * Steps to reliably reproduce the issue - * Are you hosting Glance on a VPS? - * Anything else you think might be relevant - - **No need to copy the above list into your description, it's just a guide to help you provide the most useful information.** - - - type: textarea - id: description - validations: - required: true - attributes: - label: Description - - - type: markdown - attributes: - value: | - Thank you for taking the time to submit a bug report. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index e8c34af..0000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: Discussions - url: https://github.com/glanceapp/glance/discussions - about: For help, feedback, guides, resources and more - - name: Discord - url: https://discord.com/invite/7KQ7Xa9kJd - about: Much like the discussions but more chatty diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index d8f5343..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Feature request -description: Share your ideas for new features or improvements -labels: ["feature request"] -body: - - type: markdown - attributes: - value: | - > [!NOTE] - > - > Do not prefix your title with "[REQUEST]", "[Feature request]", etc., a label will be added automatically. - - Please provide a detailed description of what the feature would do and what it would look like: - - * What problem would this feature solve? - * Are there any potential downsides to this feature? - * If applicable, what would the configuration for this feature look like? - * Are there any existing examples of this feature in other software? - * If applicable, include any external documentation required to implement this feature - * Anything else you think might be relevant - - **No need to copy the above list into your description, it's just a guide to help you provide the most useful information.** - - - type: textarea - id: description - validations: - required: true - attributes: - label: Description - - - type: markdown - attributes: - value: | - Thank you for taking the time to submit your idea. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 690586f..0000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index b06a6e3..0000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,9 +0,0 @@ -# Security Policy - -## Supported Versions - -Security updates will be applied to the latest as well as previous minor version release depending on severity and if applicable. - -## Reporting a Vulnerability - -Please report any suspected security vulnerabilities to [glanceapp@duck.com](mailto:glanceapp@duck.com) and do not disclose them publicly. You should receive a response within a few days and if confirmed the issue will be resolved as soon as possible. diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml deleted file mode 100644 index 608d82e..0000000 --- a/.github/workflows/release.yaml +++ /dev/null @@ -1,39 +0,0 @@ -name: Create release - -permissions: - contents: write - -on: - push: - tags: - - 'v*' - -jobs: - release: - runs-on: ubuntu-latest - steps: - - name: Checkout the target Git reference - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Log in to Docker Hub - uses: docker/login-action@v3 - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - - name: Set up Golang - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - - - name: Set up Docker buildx - uses: docker/setup-buildx-action@v3 - - - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - args: release diff --git a/.gitignore b/.gitignore index 2cd84fc..062999d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ /assets /build /playground -/.idea -/glance*.yml +glance.yml diff --git a/.goreleaser.yaml b/.goreleaser.yaml deleted file mode 100644 index 7153a4f..0000000 --- a/.goreleaser.yaml +++ /dev/null @@ -1,69 +0,0 @@ -project_name: glanceapp/glance - -checksum: - disable: true - -builds: - - binary: glance - env: - - CGO_ENABLED=0 - goos: - - linux - - openbsd - - freebsd - - windows - - darwin - goarch: - - amd64 - - arm64 - - arm - - 386 - goarm: - - 7 - ldflags: - - -s -w -X github.com/glanceapp/glance/internal/glance.buildVersion={{ .Tag }} - -archives: - - - name_template: "glance-{{ .Os }}-{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}" - files: - - nothing* - format_overrides: - - goos: windows - format: zip - -dockers: - - image_templates: - - &amd64_image "{{ .ProjectName }}:{{ .Tag }}-amd64" - build_flag_templates: - - --platform=linux/amd64 - goarch: amd64 - use: buildx - dockerfile: Dockerfile.goreleaser - - - image_templates: - - &arm64v8_image "{{ .ProjectName }}:{{ .Tag }}-arm64" - build_flag_templates: - - --platform=linux/arm64 - goarch: arm64 - use: buildx - dockerfile: Dockerfile.goreleaser - - - image_templates: - - &armv7_image "{{ .ProjectName }}:{{ .Tag }}-armv7" - build_flag_templates: - - --platform=linux/arm/v7 - goarch: arm - goarm: 7 - use: buildx - dockerfile: Dockerfile.goreleaser - -docker_manifests: - - name_template: "{{ .ProjectName }}:{{ .Tag }}" - image_templates: &multiarch_images - - *amd64_image - - *arm64v8_image - - *armv7_image - - name_template: "{{ .ProjectName }}:latest" - skip_push: auto - image_templates: *multiarch_images diff --git a/Dockerfile b/Dockerfile index 0c4cc63..17156a2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,10 @@ -FROM golang:1.24.2-alpine3.21 AS builder +FROM alpine:3.19 + +ARG TARGETOS +ARG TARGETARCH WORKDIR /app -COPY . /app -RUN CGO_ENABLED=0 go build . - -FROM alpine:3.21 - -WORKDIR /app -COPY --from=builder /app/glance . - -HEALTHCHECK --timeout=10s --start-period=60s --interval=60s \ - CMD wget --spider -q http://localhost:8080/api/healthz +COPY build/glance-$TARGETOS-$TARGETARCH /app/glance EXPOSE 8080/tcp -ENTRYPOINT ["/app/glance", "--config", "/app/config/glance.yml"] +ENTRYPOINT ["/app/glance"] diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser deleted file mode 100644 index bbfa8ad..0000000 --- a/Dockerfile.goreleaser +++ /dev/null @@ -1,10 +0,0 @@ -FROM alpine:3.21 - -WORKDIR /app -COPY glance . - -HEALTHCHECK --timeout=10s --start-period=60s --interval=60s \ - CMD wget --spider -q http://localhost:8080/api/healthz - -EXPOSE 8080/tcp -ENTRYPOINT ["/app/glance", "--config", "/app/config/glance.yml"] diff --git a/README.md b/README.md index ca16c49..23f085b 100644 --- a/README.md +++ b/README.md @@ -1,436 +1,90 @@

What if you could see everything at a...

Glance

-

InstallConfigurationDiscordSponsor

-

Community widgetsPreconfigured pagesThemes

+

InstallConfigurationThemes

-![](docs/images/readme-main-image.png) +![example homepage](docs/images/readme-main-image.png) -## Features -### Various widgets +### Features +#### Various widgets * RSS feeds * Subreddit posts -* Hacker News posts -* Weather forecasts -* YouTube channel uploads -* Twitch channels -* Market prices -* Docker containers status -* Server stats -* Custom widgets -* [and many more...](docs/configuration.md) +* Weather +* Bookmarks +* Latest YouTube videos from specific channels +* Calendar +* Stocks +* iframe +* Twitch channels & top games +* GitHub releases +* Site monitor -### Fast and lightweight -* Low memory usage -* Few dependencies -* Minimal vanilla JS -* Single <20mb binary available for multiple OSs & architectures and just as small Docker container -* Uncached pages usually load within ~1s (depending on internet speed and number of widgets) +#### Themeable +![multiple color schemes example](docs/images/themes-example.png) -### Tons of customizability -* Different layouts -* As many pages/tabs as you need -* Numerous configuration options for each widget -* Multiple styles for some widgets -* Custom CSS +#### Optimized for mobile devices +![mobile device previews](docs/images/mobile-preview.png) -### Optimized for mobile devices -Because you'll want to take it with you on the go. +#### Fast and lightweight +* Minimal JS, no bloated frameworks +* Very few dependencies +* Single, easily distributed <15mb binary and just as small docker container +* All requests are parallelized, uncached pages usually load within ~1s (depending on internet speed and number of widgets) -![](docs/images/mobile-preview.png) +### Configuration +Checkout the [configuration docs](docs/configuration.md) to learn more. A [preconfigured page](docs/configuration.md#preconfigured-page) is also available to get you started quickly. -### Themeable -Easily create your own theme by tweaking a few numbers or choose from one of the [already available themes](docs/themes.md). +### Installation +> [!CAUTION] +> +> The project is under active development, expect things to break every once in a while. -![](docs/images/themes-example.png) +#### Manual +Checkout the [releases page](https://github.com/glanceapp/glance/releases) for available binaries. You can place the binary inside `/opt/glance/` and have it start with your server via a [systemd service](https://linuxhandbook.com/create-systemd-services/). To specify a different path for the config file use the `--config` option: -
- -## Configuration -Configuration is done through YAML files, to learn more about how the layout works, how to add more pages and how to configure widgets, visit the [configuration documentation](docs/configuration.md). - -
-Preview example configuration file -
- -```yaml -pages: - - name: Home - columns: - - size: small - widgets: - - type: calendar - first-day-of-week: monday - - - type: rss - limit: 10 - collapse-after: 3 - cache: 12h - feeds: - - url: https://selfh.st/rss/ - title: selfh.st - limit: 4 - - url: https://ciechanow.ski/atom.xml - - url: https://www.joshwcomeau.com/rss.xml - title: Josh Comeau - - url: https://samwho.dev/rss.xml - - url: https://ishadeed.com/feed.xml - title: Ahmad Shadeed - - - type: twitch-channels - channels: - - theprimeagen - - j_blow - - piratesoftware - - cohhcarnage - - christitustech - - EJ_SA - - - size: full - widgets: - - type: group - widgets: - - type: hacker-news - - type: lobsters - - - type: videos - channels: - - UCXuqSBlHAE6Xw-yeJA0Tunw # Linus Tech Tips - - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling - - UCsBjURrPoezykLs9EqgamOA # Fireship - - UCBJycsmduvYEL83R_U4JriQ # Marques Brownlee - - UCHnyfMqiRRG1u-2MsSQLbXA # Veritasium - - - type: group - widgets: - - type: reddit - subreddit: technology - show-thumbnails: true - - type: reddit - subreddit: selfhosted - show-thumbnails: true - - - size: small - widgets: - - type: weather - location: London, United Kingdom - units: metric - hour-format: 12h - - - type: markets - markets: - - symbol: SPY - name: S&P 500 - - symbol: BTC-USD - name: Bitcoin - - symbol: NVDA - name: NVIDIA - - symbol: AAPL - name: Apple - - symbol: MSFT - name: Microsoft - - - type: releases - cache: 1d - repositories: - - glanceapp/glance - - go-gitea/gitea - - immich-app/immich - - syncthing/syncthing ``` -
- -
- -## Installation - -Choose one of the following methods: - -
-Docker compose using provided directory structure (recommended) -
- -Create a new directory called `glance` as well as the template files within it by running: - -```bash -mkdir glance && cd glance && curl -sL https://github.com/glanceapp/docker-compose-template/archive/refs/heads/main.tar.gz | tar -xzf - --strip-components 2 +/opt/glance/glance --config /etc/glance.yml ``` -*[click here to view the files that will be created](https://github.com/glanceapp/docker-compose-template/tree/main/root)* +#### Docker +> [!IMPORTANT] +> +> Make sure you have a valid `glance.yml` file before running the container. -Then, edit the following files as desired: -* `docker-compose.yml` to configure the port, volumes and other containery things -* `config/home.yml` to configure the widgets or layout of the home page -* `config/glance.yml` if you want to change the theme or add more pages - -
-Other files you may want to edit - -* `.env` to configure environment variables that will be available inside configuration files -* `assets/user.css` to add custom CSS -
- -When ready, run: - -```bash -docker compose up -d +```console +docker run -d -p 8080:8080 \ + -v ./glance.yml:/app/glance.yml \ + -v /etc/timezone:/etc/timezone:ro \ + -v /etc/localtime:/etc/localtime:ro \ + glanceapp/glance ``` -If you encounter any issues, you can check the logs by running: - -```bash -docker compose logs -``` - -
-
- -
-Docker compose manual -
- -Create a `docker-compose.yml` file with the following contents: +Or if you prefer docker compose: ```yaml services: glance: - container_name: glance image: glanceapp/glance - restart: unless-stopped volumes: - - ./config:/app/config + - ./glance.yml:/app/glance.yml + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro ports: - 8080:8080 + restart: unless-stopped ``` -Then, create a new directory called `config` and download the example starting [`glance.yml`](https://github.com/glanceapp/glance/blob/main/docs/glance.yml) file into it by running: +### Building from source -```bash -mkdir config && wget -O config/glance.yml https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml +Requirements: [Go](https://go.dev/dl/) >= v1.22 + +To build: + +``` +go build . ``` -Feel free to edit the `glance.yml` file to your liking, and when ready run: +To run: -```bash -docker compose up -d ``` - -If you encounter any issues, you can check the logs by running: - -```bash -docker logs glance -``` - -
-
- -
-Manual binary installation -
- -Precompiled binaries are available for Linux, Windows and macOS (x86, x86_64, ARM and ARM64 architectures). - -### Linux - -Visit the [latest release page](https://github.com/glanceapp/glance/releases/latest) for available binaries. You can place the binary in `/opt/glance/` and have it start with your server via a [systemd service](https://linuxhandbook.com/create-systemd-services/). By default, when running the binary, it will look for a `glance.yml` file in the directory it's placed in. To specify a different path for the config file, use the `--config` option: - -```bash -/opt/glance/glance --config /etc/glance.yml -``` - -To grab a starting template for the config file, run: - -```bash -wget https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml -``` - -### Windows - -Download and extract the executable from the [latest release](https://github.com/glanceapp/glance/releases/latest) (most likely the file called `glance-windows-amd64.zip` if you're on a 64-bit system) and place it in a folder of your choice. Then, create a new text file called `glance.yml` in the same folder and paste the content from [here](https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml) in it. You should then be able to run the executable and access the dashboard by visiting `http://localhost:8080` in your browser. - - - -
-
- -
-Other -
- -Glance can also be installed through the following 3rd party channels: -* [Proxmox VE Helper Script](https://community-scripts.github.io/ProxmoxVE/scripts?id=glance) -* [NixOS package](https://search.nixos.org/packages?channel=unstable&show=glance) -* [Coolify.io](https://coolify.io/docs/services/glance/) - -
-
- -
- -## Common issues -
-Requests timing out - -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. - -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 -``` -
- -
-Broken layout for markets, bookmarks or other widgets - -This is almost always caused by the browser extension Dark Reader. To fix this, disable dark mode for the domain where Glance is hosted. -
- -
-cannot unmarshal !!map into []glance.page - -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. - -
- -
- -## FAQ -
-Does the information on the page update automatically? -No, a page refresh is required to update the information. Some things do dynamically update where it makes sense, like the clock widget and the relative time showing how long ago something happened. -
- -
-How frequently do widgets update? -No requests are made periodically in the background, information is only fetched upon loading the page and then cached. The default cache lifetime is different for each widget and can be configured. -
- -
-Can I create my own widgets? - -Yes, there are multiple ways to create custom widgets: -* `iframe` widget - allows you to embed things from other websites -* `html` widget - allows you to insert your own static HTML -* `extension` widget - fetch HTML from a URL -* `custom-api` widget - fetch JSON from a URL and render it using custom HTML -
- -
-Can I change the title of a widget? - -Yes, the title of all widgets can be changed by specifying the `title` property in the widget's configuration: - -```yaml -- type: rss - title: My custom title - -- type: markets - title: My custom title - -- type: videos - title: My custom title - -# and so on for all widgets... -``` -
- -
- -## Feature requests - -New feature suggestions are always welcome and will be considered, though please keep in mind that some of them may be out of scope for what the project is trying to achieve (or is reasonably capable of). If you have an idea for a new feature and would like to share it, you can do so [here](https://github.com/glanceapp/glance/issues/new?template=feature_request.yml). - -Feature requests are tagged with one of the following: - -* [Roadmap](https://github.com/glanceapp/glance/labels/roadmap) - will be implemented in a future release -* [Backlog](https://github.com/glanceapp/glance/labels/backlog) - may be implemented in the future but needs further feedback or interest from the community -* [Icebox](https://github.com/glanceapp/glance/labels/icebox) - no plans to implement as it doesn't currently align with the project's goals or capabilities, may be revised at a later date - -
- -## Building from source - -Choose one of the following methods: - -
-Build binary with Go -
- -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 . ``` -
-
- -
-Build project and Docker image with Docker -
- -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 -``` - -
-
- -
- -## 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 -* Please don't submit PRs for feature requests that are either in the roadmap[1], backlog[2] or icebox[3] -* Use `dev` for the base branch if you're adding new features or fixing bugs, otherwise use `main` -* Avoid introducing new dependencies -* Avoid making backwards-incompatible configuration changes -* Avoid introducing new colors or hard-coding colors, use the standard `primary`, `positive` and `negative` -* For icons, try to use [heroicons](https://heroicons.com/) where applicable -* Provide a screenshot of the changes if UI related where possible -* No `package.json` - -
-[1] [2] [3] - -[1] The feature likely already has work put into it that may conflict with your implementation - -[2] The demand, implementation or functionality for this feature is not yet clear - -[3] No plans to add this feature for the time being - -
- -
- -## Thank you - -To all the people who were generous enough to [sponsor](https://github.com/sponsors/glanceapp) the project and to everyone who has contributed in any way, be it PRs, submitting issues, helping others in the discussions or Discord server, creating guides and tools or just mentioning Glance on social media. Your support is greatly appreciated and helps keep the project going. diff --git a/docs/configuration.md b/docs/configuration.md index 3999d8c..0022c82 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,153 +1,105 @@ -# Configuring Glance +# Configuration +- [Intro](#intro) - [Preconfigured page](#preconfigured-page) -- [The config file](#the-config-file) - - [Auto reload](#auto-reload) - - [Environment variables](#environment-variables) - - [Including other config files](#including-other-config-files) - [Server](#server) -- [Document](#document) -- [Branding](#branding) - [Theme](#theme) - - [Available themes](#available-themes) + - [Themes](#themes) - [Pages & Columns](#pages--columns) - [Widgets](#widgets) - [RSS](#rss) - [Videos](#videos) - [Hacker News](#hacker-news) - - [Lobsters](#lobsters) - [Reddit](#reddit) - - [Search](#search-widget) - - [Group](#group) - - [Split Column](#split-column) - - [Custom API](#custom-api) - - [Extension](#extension) - [Weather](#weather) - [Monitor](#monitor) - [Releases](#releases) - - [Docker Containers](#docker-containers) - - [DNS Stats](#dns-stats) - - [Server Stats](#server-stats) - - [Repository](#repository) - [Bookmarks](#bookmarks) - [Calendar](#calendar) - - [Calendar (legacy)](#calendar-legacy) - - [ChangeDetection.io](#changedetectionio) - - [Clock](#clock) - - [Markets](#markets) + - [Stocks](#stocks) - [Twitch Channels](#twitch-channels) - [Twitch Top Games](#twitch-top-games) - [iframe](#iframe) - - [HTML](#html) +## Intro +Configuration is done via a single YAML file and a server restart is required in order for any changes to take effect. Trying to start the server with an invalid config file will result in an error. ## Preconfigured page -If you don't want to spend time reading through all the available configuration options and just want something to get you going quickly you can use [this `glance.yml` file](glance.yml) and make changes to it as you see fit. It will give you a page that looks like the following: - -![](images/preconfigured-page-preview.png) - -Configure the widgets, add more of them, add extra pages, etc. Make it your own! - -## The config file - -### Auto reload -Automatic config reload is supported, meaning that you can make changes to the config file and have them take effect on save without having to restart the container/service. Making changes to environment variables does not trigger a reload and requires manual restart. Deleting a config file will stop that file from being watched, even if it is recreated. - -> [!NOTE] -> -> If you attempt to start Glance with an invalid config it will exit with an error outright. If you successfully started Glance with a valid config and then made changes to it which result in an error, you'll see that error in the console and Glance will continue to run with the old configuration. You can then continue to make changes and when there are no errors the new configuration will be loaded. - -> [!CAUTION] -> -> Reloading the configuration file clears your cached data, meaning that you have to request the data anew each time you do this. This can lead to rate limiting for some APIs if you do it too frequently. Having a cache that persists between reloads will be added in the future. - -### Environment variables -Inserting environment variables is supported anywhere in the config. This is done via the `${ENV_VAR}` syntax. Attempting to use an environment variable that doesn't exist will result in an error and Glance will either not start or load your new config on save. Example: - -```yaml -server: - host: ${HOST} - port: ${PORT} -``` - -Can also be in the middle of a string: - -```yaml -- type: rss - title: ${RSS_TITLE} - feeds: - - url: http://domain.com/rss/${RSS_CATEGORY}.xml -``` - -Works with any type of value, not just strings: - -```yaml -- type: rss - limit: ${RSS_LIMIT} -``` - -If you need to use the syntax `${NAME}` in your config without it being interpreted as an environment variable, you can escape it by prefixing with a backslash `\`: - -```yaml -something: \${NOT_AN_ENV_VAR} -``` - -### Including other config files -Including config files from within your main config file is supported. This is done via the `!include` directive along with a relative or absolute path to the file you want to include. If the path is relative, it will be relative to the main config file. Additionally, environment variables can be used within included files, and changes to the included files will trigger an automatic reload. Example: - -```yaml -pages: - !include: home.yml - !include: videos.yml - !include: homelab.yml -``` - -The file you are including should not have any additional indentation, its values should be at the top level and the appropriate amount of indentation will be added automatically depending on where the file is included. Example: - -`glance.yml` +If you don't want to spend time reading through all the available configuration options and just want something to get you going quickly you can use the following `glance.yml` and make changes as you see fit: ```yaml pages: - name: Home columns: + - size: small + widgets: + - type: calendar + + - type: rss + limit: 10 + collapse-after: 3 + cache: 3h + feeds: + - url: https://ciechanow.ski/atom.xml + - url: https://www.joshwcomeau.com/rss.xml + title: Josh Comeau + - url: https://samwho.dev/rss.xml + - url: https://awesomekling.github.io/feed.xml + - url: https://ishadeed.com/feed.xml + title: Ahmad Shadeed + + - type: twitch-channels + channels: + - theprimeagen + - cohhcarnage + - christitustech + - blurbs + - asmongold + - jembawls + - size: full widgets: - !include: rss.yml - - name: News - columns: - - size: full + - type: hacker-news + + - type: videos + channels: + - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling + - UCv6J_jJa8GJqFwQNgNrMuww # ServeTheHome + - UCOk-gHyjcWZNj3Br4oxwh0A # Techno Tim + + - type: reddit + subreddit: selfhosted + + - size: small widgets: - - type: group - widgets: - !include: rss.yml - - type: reddit - subreddit: news + - type: weather + location: London, United Kingdom + + - type: stocks + stocks: + - symbol: SPY + name: S&P 500 + - symbol: BTC-USD + name: Bitcoin + - symbol: NVDA + name: NVIDIA + - symbol: AAPL + name: Apple + - symbol: MSFT + name: Microsoft + - symbol: GOOGL + name: Google + - symbol: AMD + name: AMD + - symbol: RDDT + name: Reddit ``` -`rss.yml` +This will give you a page that looks like the following: -```yaml -- type: rss - title: News - feeds: - - url: ${RSS_URL} -``` +![](images/preconfigured-page-preview.png) -The `!include` directive can be used anywhere in the config file, not just in the `pages` property, however it must be on its own line and have the appropriate indentation. - -If you encounter YAML parsing errors when using the `!include` directive, the reported line numbers will likely be incorrect. This is because the inclusion of files is done before the YAML is parsed, as YAML itself does not support file inclusion. To help with debugging in cases like this, you can use the `config:print` command and pipe it into `less -N` to see the full config file with includes resolved and line numbers added: - -```sh -glance --config /path/to/glance.yml config:print | less -N -``` - -This is a bit more convoluted when running Glance inside a Docker container: - -```sh -docker run --rm -v ./glance.yml:/app/config/glance.yml glanceapp/glance config:print | less -N -``` - -This assumes that the config you want to print is in your current working directory and is named `glance.yml`. +Configure the widgets, add more of them, add extra pages, etc. Make it your own! ## Server Server configuration is done through a top level `server` property. Example: @@ -164,7 +116,6 @@ server: | ---- | ---- | -------- | ------- | | host | string | no | | | port | number | no | 8080 | -| base-url | string | no | | | assets-path | string | no | | #### `host` @@ -173,13 +124,6 @@ The address which the server will listen on. Setting it to `localhost` means tha #### `port` A number between 1 and 65,535, so long as that port isn't already used by anything else. -#### `base-url` -The base URL that Glance is hosted under. No need to specify this unless you're using a reverse proxy and are hosting Glance under a directory. If that's the case then you can set this value to `/glance` or whatever the directory is called. Note that the forward slash (`/`) in the beginning is required unless you specify the full domain and path. - -> [!IMPORTANT] -> You need to strip the `base-url` prefix before forwarding the request to the Glance server. -> In Caddy you can do this using [`handle_path`](https://caddyserver.com/docs/caddyfile/directives/handle_path) or [`uri strip_prefix`](https://caddyserver.com/docs/caddyfile/directives/uri). - #### `assets-path` The path to a directory that will be served by the server under the `/assets/` path. This is handy for widgets like the Monitor where you have to specify an icon URL and you want to self host all the icons rather than pointing to an external source. @@ -211,57 +155,12 @@ Say you have a directory `glance-assets` with a file `gitea-icon.png` in it and assets-path: /home/user/glance-assets ``` -To be able to point to an asset from your assets path, use the `/assets/` path like such: +To be able to point to an asset from your assets path, use the the `/assets/` path like such: ```yaml icon: /assets/gitea-icon.png ``` -## Document -If you want to insert custom HTML into the `` of the document for all pages, you can do so by using the `document` property. Example: - -```yaml -document: - head: | - -``` - -## Branding -You can adjust the various parts of the branding through a top level `branding` property. Example: - -```yaml -branding: - custom-footer: | -

Powered by Glance

- logo-url: /assets/logo.png - favicon-url: /assets/logo.png -``` - -### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| hide-footer | bool | no | false | -| custom-footer | string | no | | -| logo-text | string | no | G | -| logo-url | string | no | | -| favicon-url | string | no | | - -#### `hide-footer` -Hides the footer when set to `true`. - -#### `custom-footer` -Specify custom HTML to use for the footer. - -#### `logo-text` -Specify custom text to use instead of the "G" found in the navigation. - -#### `logo-url` -Specify a URL to a custom image to use instead of the "G" found in the navigation. If both `logo-text` and `logo-url` are set, only `logo-url` will be used. - -#### `favicon-url` -Specify a URL to a custom image to use for the favicon. - ## Theme Theming is done through a top level `theme` property. Values for the colors are in [HSL](https://giggster.com/guide/basics/hue-saturation-lightness/) (hue, saturation, lightness) format. You can use a color picker [like this one](https://hslpicker.com/) to convert colors from other formats to HSL. The values are separated by a space and `%` is not required for any of the numbers. @@ -274,7 +173,7 @@ theme: contrast-multiplier: 1.1 ``` -### Available themes +### 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 @@ -328,9 +227,6 @@ theme: > .widget-type-rss a { > font-size: 1.5rem; > } -> ``` -> -> In addition, you can also use the `css-class` property which is available on every widget to set custom class names for individual widgets. ## Pages & Columns @@ -354,50 +250,18 @@ pages: ``` ### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| name | string | yes | | -| slug | string | no | | -| width | string | no | | -| center-vertically | boolean | no | false | -| hide-desktop-navigation | boolean | no | false | -| expand-mobile-page-navigation | boolean | no | false | -| show-mobile-header | boolean | no | false | -| columns | array | yes | | +| Name | Type | Required | +| ---- | ---- | -------- | +| title | string | yes | +| slug | string | no | +| columns | array | yes | -#### `name` +#### `title` The name of the page which gets shown in the navigation bar. #### `slug` The URL friendly version of the title which is used to access the page. For example if the title of the page is "RSS Feeds" you can make the page accessible via `localhost:8080/feeds` by setting the slug to `feeds`. If not defined, it will automatically be generated from the title. -#### `width` -The maximum width of the page on desktop. Possible values are `slim` and `wide`. - -* default: `1600px` (when no value is specified) -* slim: `1100px` -* wide: `1920px` - -> [!NOTE] -> -> When using `slim`, the maximum number of columns allowed for that page is `2`. - -#### `center-vertically` -When set to `true`, vertically centers the content on the page. Has no effect if the content is taller than the height of the viewport. - -#### `hide-desktop-navigation` -Whether to show the navigation links at the top of the page on desktop. - -#### `expand-mobile-page-navigation` -Whether the mobile page navigation should be expanded by default. - -#### `show-mobile-header` -Whether to show a header displaying the name of the page on mobile. The header purposefully has a lot of vertical whitespace in order to push the content down and make it easier to reach on tall devices. - -Preview: - -![](images/mobile-header-preview.png) - ### Columns Columns are defined for each page using a `columns` property. There are two types of columns - `full` and `small`, which refers to their width. A small column takes up a fixed amount of width (300px) and a full column takes up the all of the remaining width. You can have up to 3 columns per page and you must have either 1 or 2 full columns. Example: @@ -475,9 +339,7 @@ pages: | ---- | ---- | -------- | | type | string | yes | | title | string | no | -| title-url | string | no | | cache | string | no | -| css-class | string | no | #### `type` Used to specify the widget. @@ -485,9 +347,6 @@ Used to specify the widget. #### `title` The title of the widget. If left blank it will be defined by the widget. -#### `title-url` -The URL to go to when clicking on the widget's title. If left blank it will be defined by the widget (if available). - #### `cache` How long to keep the fetched data in memory. The value is a string and must be a number followed by one of s, m, h, d. Examples: @@ -502,9 +361,6 @@ cache: 1d # 1 day > > Not all widgets can have their cache duration modified. The calendar and weather widgets update on the hour and this cannot be changed. -#### `css-class` -Set custom CSS classes for the specific widget instance. - ### RSS Display a list of articles from multiple RSS feeds. @@ -528,88 +384,35 @@ Example: | ---- | ---- | -------- | ------- | | style | string | no | vertical-list | | feeds | array | yes | -| thumbnail-height | float | no | 10 | -| card-height | float | no | 27 | | limit | integer | no | 25 | -| preserve-order | bool | no | false | -| single-line-titles | boolean | no | false | | collapse-after | integer | no | 5 | +##### `style` +Used to change the appearance of the widget. Possible values are `vertical-list` and `horizontal-cards` where the former is intended to be used within a small column and the latter a full column. Below are previews of each style. + +`vertical-list` + +![preview of vertical-list style for RSS widget](images/rss-feed-vertical-list-preview.png) + +`horizontal-cards` + +![preview of horizontal-cards style for RSS widget](images/rss-feed-horizontal-cards-preview.png) + +##### `feeds` +An array of RSS/atom feeds. The title can optionally be changed. + +###### Properties for each feed +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| url | string | yes | | +| title | string | no | the title provided by the feed | + ##### `limit` The maximum number of articles to show. ##### `collapse-after` How many articles are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. -##### `preserve-order` -When set to `true`, the order of the articles will be preserved as they are in the feeds. Useful if a feed uses its own sorting order which denotes the importance of the articles. If you use this property while having a lot of feeds, it's recommended to set a `limit` to each individual feed since if the first defined feed has 15 articles, the articles from the second feed will start after the 15th article in the list. - -##### `single-line-titles` -When set to `true`, truncates the title of each post if it exceeds one line. Only applies when the style is set to `vertical-list`. - -##### `style` -Used to change the appearance of the widget. Possible values are: - -* `vertical-list` - suitable for `full` and `small` columns -* `detailed-list` - suitable for `full` columns -* `horizontal-cards` - suitable for `full` columns -* `horizontal-cards-2` - suitable for `full` columns - -Below is a preview of each style: - -`vertical-list` - -![preview of vertical-list style for RSS widget](images/rss-feed-vertical-list-preview.png) - -`detailed-list` - -![preview of detailed-list style for RSS widget](images/rss-widget-detailed-list-preview.png) - -`horizontal-cards` - -![preview of horizontal-cards style for RSS widget](images/rss-feed-horizontal-cards-preview.png) - -`horizontal-cards-2` - -![preview of horizontal-cards-2 style for RSS widget](images/rss-widget-horizontal-cards-2-preview.png) - -##### `thumbnail-height` -Used to modify the height of the thumbnails. Works only when the style is set to `horizontal-cards`. The default value is `10` and the units are `rem`, if you want to for example double the height of the thumbnails you can set it to `20`. - -##### `card-height` -Used to modify the height of cards when using the `horizontal-cards-2` style. The default value is `27` and the units are `rem`. - -##### `feeds` -An array of RSS/atom feeds. The title can optionally be changed. - -###### Properties for each feed -| Name | Type | Required | Default | Notes | -| ---- | ---- | -------- | ------- | ----- | -| url | string | yes | | | -| title | string | no | the title provided by the feed | | -| hide-categories | boolean | no | false | Only applicable for `detailed-list` style | -| hide-description | boolean | no | false | Only applicable for `detailed-list` style | -| limit | integer | no | | | -| item-link-prefix | string | no | | | -| headers | key (string) & value (string) | no | | | - -###### `limit` -The maximum number of articles to show from that specific feed. Useful if you have a feed which posts a lot of articles frequently and you want to prevent it from excessively pushing down articles from other feeds. - -###### `item-link-prefix` -If an RSS feed isn't returning item links with a base domain and Glance has failed to automatically detect the correct domain you can manually add a prefix to each link with this property. - -###### `headers` -Optionally specify the headers that will be sent with the request. Example: - -```yaml -- type: rss - feeds: - - url: https://domain.com/rss - headers: - User-Agent: Custom User Agent -``` - ### Videos Display a list of the latest videos from specific YouTube channels. @@ -630,18 +433,11 @@ Preview: | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | channels | array | yes | | -| playlists | array | no | | | limit | integer | no | 25 | -| style | string | no | horizontal-cards | -| collapse-after | integer | no | 7 | -| collapse-after-rows | integer | no | 4 | -| include-shorts | boolean | no | false | | video-url-template | string | no | https://www.youtube.com/watch?v={VIDEO-ID} | ##### `channels` -A list of channels IDs. - -One way of getting the ID of a channel is going to the channel's page and clicking on its description: +A list of channel IDs. One way of getting the ID of a channel is going to the channel's page and clicking on its description: ![](images/videos-channel-description-example.png) @@ -649,37 +445,9 @@ Then scroll down and click on "Share channel", then "Copy channel ID": ![](images/videos-copy-channel-id-example.png) -##### `playlists` - -A list of playlist IDs: - -```yaml -- type: videos - playlists: - - PL8mG-RkN2uTyZZ00ObwZxxoG_nJbs3qec - - PL8mG-RkN2uTxTK4m_Vl2dYR9yE41kRdBg -``` - ##### `limit` The maximum number of videos to show. -##### `collapse-after` -Specify the number of videos to show when using the `vertical-list` style before the "SHOW MORE" button appears. - -##### `collapse-after-rows` -Specify the number of rows to show when using the `grid-cards` style before the "SHOW MORE" button appears. - -##### `style` -Used to change the appearance of the widget. Possible values are `horizontal-cards`, `vertical-list` and `grid-cards`. - -Preview of `vertical-list`: - -![](images/videos-widget-vertical-list-preview.png) - -Preview of `grid-cards`: - -![](images/videos-widget-grid-cards-preview.png) - ##### `video-url-template` Used to replace the default link for videos. Useful when you're running your own YouTube front-end. Example: @@ -711,8 +479,6 @@ Preview: | limit | integer | no | 15 | | collapse-after | integer | no | 5 | | comments-url-template | string | no | https://news.ycombinator.com/item?id={POST-ID} | -| sort-by | string | no | top | -| extra-sort-by | string | no | | ##### `comments-url-template` Used to replace the default link for post comments. Useful if you want to use an alternative front-end. Example: @@ -725,71 +491,12 @@ Placeholders: `{POST-ID}` - the ID of the post -##### `sort-by` -Used to specify the order in which the posts should get returned. Possible values are `top`, `new`, and `best`. - -##### `extra-sort-by` -Can be used to specify an additional sort which will be applied on top of the already sorted posts. By default does not apply any extra sorting and the only available option is `engagement`. - -The `engagement` sort tries to place the posts with the most points and comments on top, also prioritizing recent over old posts. - -### Lobsters -Display a list of posts from [Lobsters](https://lobste.rs). - -Example: - -```yaml -- type: lobsters - sort-by: hot - tags: - - go - - security - - linux - limit: 15 - collapse-after: 5 -``` - -Preview: -![](images/lobsters-widget-preview.png) - -#### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| instance-url | string | no | https://lobste.rs/ | -| custom-url | string | no | | -| limit | integer | no | 15 | -| collapse-after | integer | no | 5 | -| sort-by | string | no | hot | -| tags | array | no | | - -##### `instance-url` -The base URL for a lobsters instance hosted somewhere other than on lobste.rs. Example: - -```yaml -instance-url: https://www.journalduhacker.net/ -``` - -##### `custom-url` -A custom URL to retrieve lobsters posts from. If this is specified, the `instance-url`, `sort-by` and `tags` properties are ignored. - -##### `limit` -The maximum number of posts to show. - -##### `collapse-after` -How many posts are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. - -##### `sort-by` -The sort order in which posts are returned. Possible options are `hot` and `new`. - -##### `tags` -Limit to posts containing one of the given tags. **You cannot specify a sort order when filtering by tags, it will default to `hot`.** - ### Reddit Display a list of posts from a specific subreddit. > [!WARNING] > -> Reddit does not allow unauthorized API access from VPS IPs, if you're hosting Glance on a VPS you will get a 403 response. As a workaround you can route the traffic from Glance through a VPN or your own HTTP proxy using the `request-url-template` property. +> Reddit does not allow unauthorized API access from VPS IPs, if you're hosting Glance on a VPS you will get a 403 response. As a workaround you can route the traffic from Glance through a VPN. Example: @@ -804,16 +511,10 @@ Example: | subreddit | string | yes | | | style | string | no | vertical-list | | show-thumbnails | boolean | no | false | -| show-flairs | boolean | no | false | | limit | integer | no | 15 | | collapse-after | integer | no | 5 | | comments-url-template | string | no | https://www.reddit.com/{POST-PATH} | | request-url-template | string | no | | -| proxy | string or multiple parameters | no | | -| sort-by | string | no | hot | -| top-period | string | no | day | -| search | string | no | | -| extra-sort-by | string | no | | ##### `subreddit` The subreddit for which to fetch the posts from. @@ -842,9 +543,6 @@ Shows or hides thumbnails next to the post. This only works if the `style` is `v > > Thumbnails don't work for some subreddits due to Reddit's API not returning the thumbnail URL. No workaround for this yet. -##### `show-flairs` -Shows post flairs when set to `true`. - ##### `limit` The maximum number of posts to show. @@ -871,7 +569,7 @@ r/selfhosted/comments/bsp01i/welcome_to_rselfhosted_please_read_this_first/ `{SUBREDDIT}` - the subreddit name ##### `request-url-template` -A custom request URL that will be used to fetch the data. This is useful when you're hosting Glance on a VPS where Reddit is blocking the requests and you want to route them through a proxy that accepts the URL as either a part of the path or a query parameter. +A custom request url that will be used to fetch the data instead. This is useful when you're hosting Glance on a VPS and Reddit is blocking the requests, and you want to route it through an HTTP proxy. Placeholders: @@ -882,568 +580,6 @@ https://proxy/{REQUEST-URL} https://your.proxy/?url={REQUEST-URL} ``` -##### `proxy` -A custom HTTP/HTTPS proxy URL that will be used to fetch the data. This is useful when you're hosting Glance on a VPS where Reddit is blocking the requests and you want to bypass the restriction by routing the requests through a proxy. Example: - -```yaml -proxy: http://user:pass@proxy.com:8080 -proxy: https://user:pass@proxy.com:443 -``` - -Alternatively, you can specify the proxy URL as well as additional options by using multiple parameters: - -```yaml -proxy: - url: http://proxy.com:8080 - allow-insecure: true - timeout: 10s -``` - -###### `allow-insecure` -When set to `true`, allows the use of insecure connections such as when the proxy has a self-signed certificate. - -###### `timeout` -The maximum time to wait for a response from the proxy. The value is a string and must be a number followed by one of s, m, h, d. Example: `10s` for 10 seconds, `1m` for 1 minute, etc - -##### `sort-by` -Can be used to specify the order in which the posts should get returned. Possible values are `hot`, `new`, `top` and `rising`. - -##### `top-period` -Available only when `sort-by` is set to `top`. Possible values are `hour`, `day`, `week`, `month`, `year` and `all`. - -##### `search` -Keywords to search for. Searching within specific fields is also possible, **though keep in mind that Reddit may remove the ability to use any of these at any time**: - -![](images/reddit-field-search.png) - -##### `extra-sort-by` -Can be used to specify an additional sort which will be applied on top of the already sorted posts. By default does not apply any extra sorting and the only available option is `engagement`. - -The `engagement` sort tries to place the posts with the most points and comments on top, also prioritizing recent over old posts. - -### Search Widget -Display a search bar that can be used to search for specific terms on various search engines. - -Example: - -```yaml -- type: search - search-engine: duckduckgo - bangs: - - title: YouTube - shortcut: "!yt" - url: https://www.youtube.com/results?search_query={QUERY} -``` - -Preview: - -![](images/search-widget-preview.png) - -#### Keyboard shortcuts -| Keys | Action | Condition | -| ---- | ------ | --------- | -| S | Focus the search bar | Not already focused on another input field | -| Enter | Perform search in the same tab | Search input is focused and not empty | -| Ctrl + Enter | Perform search in a new tab | Search input is focused and not empty | -| Escape | Leave focus | Search input is focused | -| Up | Insert the last search query since the page was opened into the input field | Search input is focused | - -> [!TIP] -> -> You can use the property `new-tab` with a value of `true` if you want to show search results in a new tab by default. Ctrl + Enter will then show results in the same tab. - -#### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| search-engine | string | no | duckduckgo | -| new-tab | boolean | no | false | -| autofocus | boolean | no | false | -| placeholder | string | no | Type here to search… | -| bangs | array | no | | - -##### `search-engine` -Either a value from the table below or a URL to a custom search engine. Use `{QUERY}` to indicate where the query value gets placed. - -| Name | URL | -| ---- | --- | -| duckduckgo | `https://duckduckgo.com/?q={QUERY}` | -| google | `https://www.google.com/search?q={QUERY}` | - -##### `new-tab` -When set to `true`, swaps the shortcuts for showing results in the same or new tab, defaulting to showing results in a new tab. - -##### `autofocus` -When set to `true`, automatically focuses the search input on page load. - -##### `placeholder` -When set, modifies the text displayed in the input field before typing. - -##### `bangs` -What now? [Bangs](https://duckduckgo.com/bangs). They're shortcuts that allow you to use the same search box for many different sites. Assuming you have it configured, if for example you start your search input with `!yt` you'd be able to perform a search on YouTube: - -![](images/search-widget-bangs-preview.png) - -##### Properties for each bang -| Name | Type | Required | -| ---- | ---- | -------- | -| title | string | no | -| shortcut | string | yes | -| url | string | yes | - -###### `title` -Optional title that will appear on the right side of the search bar when the query starts with the associated shortcut. - -###### `shortcut` -Any value you wish to use as the shortcut for the search engine. It does not have to start with `!`. - -> [!IMPORTANT] -> -> In YAML some characters have special meaning when placed in the beginning of a value. If your shortcut starts with `!` (and potentially some other special characters) you'll have to wrap the value in quotes: -> ```yaml -> shortcut: "!yt" ->``` - -###### `url` -The URL of the search engine. Use `{QUERY}` to indicate where the query value gets placed. Examples: - -```yaml -url: https://www.reddit.com/search?q={QUERY} -url: https://store.steampowered.com/search/?term={QUERY} -url: https://www.amazon.com/s?k={QUERY} -``` - -### Group -Group multiple widgets into one using tabs. Widgets are defined using a `widgets` property exactly as you would on a page column. The only limitation is that you cannot place a group widget or a split column widget within a group widget. - -Example: - -```yaml -- type: group - widgets: - - type: reddit - subreddit: gamingnews - show-thumbnails: true - collapse-after: 6 - - type: reddit - subreddit: games - - type: reddit - subreddit: pcgaming - show-thumbnails: true -``` - -Preview: - -![](images/group-widget-preview.png) - -#### Sharing properties - -To avoid repetition you can use [YAML anchors](https://support.atlassian.com/bitbucket-cloud/docs/yaml-anchors/) and share properties between widgets. - -Example: - -```yaml -- type: group - define: &shared-properties - type: reddit - show-thumbnails: true - collapse-after: 6 - widgets: - - subreddit: gamingnews - <<: *shared-properties - - subreddit: games - <<: *shared-properties - - subreddit: pcgaming - <<: *shared-properties -``` - -### Split Column -Splits a full sized column in half, allowing you to place widgets side by side horizontally. This is converted to a single column on mobile devices or if not enough width is available. Widgets are defined using a `widgets` property exactly as you would on a page column. - -Two widgets side by side in a `full` column: - -![](images/split-column-widget-preview.png) - -
-View glance.yml -
- -```yaml -# ... -- size: full - widgets: - - type: split-column - widgets: - - type: hacker-news - collapse-after: 3 - - type: lobsters - collapse-after: 3 - - - type: videos -# ... -``` -
-
- -You can also achieve a number of different full page layouts using just this widget, such as: - -3 column layout where all columns have equal width: - -![](images/split-column-widget-3-columns.png) - -
-View glance.yml -
- -```yaml -pages: - - name: Home - columns: - - size: full - widgets: - - type: split-column - max-columns: 3 - widgets: - - type: reddit - subreddit: selfhosted - collapse-after: 15 - - type: reddit - subreddit: homelab - collapse-after: 15 - - type: reddit - subreddit: sysadmin - collapse-after: 15 -``` -
-
- -4 column layout where all columns have equal width (and the page is set to `width: wide`): - -![](images/split-column-widget-4-columns.png) - -
-View glance.yml -
- -```yaml -pages: - - name: Home - width: wide - columns: - - size: full - widgets: - - type: split-column - max-columns: 4 - widgets: - - type: reddit - subreddit: selfhosted - collapse-after: 15 - - type: reddit - subreddit: homelab - collapse-after: 15 - - type: reddit - subreddit: linux - collapse-after: 15 - - type: reddit - subreddit: sysadmin - collapse-after: 15 -``` -
-
- -Masonry layout with up to 5 columns where all columns have equal width (and the page is set to `width: wide`): - -![](images/split-column-widget-masonry.png) - -
-View glance.yml -
- -```yaml -define: - - &subreddit-settings - type: reddit - collapse-after: 5 - -pages: - - name: Home - width: wide - columns: - - size: full - widgets: - - type: split-column - max-columns: 5 - widgets: - - subreddit: selfhosted - <<: *subreddit-settings - - subreddit: homelab - <<: *subreddit-settings - - subreddit: linux - <<: *subreddit-settings - - subreddit: sysadmin - <<: *subreddit-settings - - subreddit: DevOps - <<: *subreddit-settings - - subreddit: Networking - <<: *subreddit-settings - - subreddit: DataHoarding - <<: *subreddit-settings - - subreddit: OpenSource - <<: *subreddit-settings - - subreddit: Privacy - <<: *subreddit-settings - - subreddit: FreeSoftware - <<: *subreddit-settings -``` -
-
- -Just like the `group` widget, you can insert any widget type, you can even insert a `group` widget inside of a `split-column` widget, but you can't insert a `split-column` widget inside of a `group` widget. - - -### Custom API - -Display data from a JSON API using a custom template. - -> [!NOTE] -> -> The configuration of this widget requires some basic knowledge of programming, HTML, CSS, the Go template language and Glance-specific concepts. - -Examples: - -![](images/custom-api-preview-1.png) - -
-View glance.yml -
- -```yaml -- type: custom-api - title: Random Fact - cache: 6h - url: https://uselessfacts.jsph.pl/api/v2/facts/random - template: | -

{{ .JSON.String "text" }}

-``` -
-
- -![](images/custom-api-preview-2.png) - -
-View glance.yml -
- -```yaml -- type: custom-api - title: Immich stats - cache: 1d - url: https://${IMMICH_URL}/api/server/statistics - headers: - x-api-key: ${IMMICH_API_KEY} - Accept: application/json - template: | -
-
-
{{ .JSON.Int "photos" | formatNumber }}
-
PHOTOS
-
-
-
{{ .JSON.Int "videos" | formatNumber }}
-
VIDEOS
-
-
-
{{ div (.JSON.Int "usage" | toFloat) 1073741824 | toInt | formatNumber }}GB
-
USAGE
-
-
-``` -
-
- -![](images/custom-api-preview-3.png) - -
-View glance.yml -
- -```yaml -- type: custom-api - title: Steam Specials - cache: 12h - url: https://store.steampowered.com/api/featuredcategories?cc=us - template: | - -``` -
- -#### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| 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. - -##### `headers` -Optionally specify the headers that will be sent with the request. Example: - -```yaml -headers: - x-api-key: your-api-key - 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: | -

{{ .JSON.String "text" }}

-

{{ (.Subrequest "another-one").JSON.String "text" }}

-``` - -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" }} -

{{ $anotherOne.JSON.String "text" }}

-``` - -You can also access the `.Response` property of a subrequest as you would with the main request: - -```yaml - template: | - {{ $anotherOne := .Subrequest "another-one" }} -

{{ $anotherOne.Response.StatusCode }}

-``` - -> [!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). - -```yaml -- type: extension - url: https://domain.com/widget/display-a-message - allow-potentially-dangerous-html: true - parameters: - message: Hello, world! -``` - -#### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| url | string | yes | | -| fallback-content-type | string | no | | -| allow-potentially-dangerous-html | boolean | no | false | -| headers | key & value | no | | -| parameters | key & value | no | | - -##### `url` -The URL of the extension. **Note that the query gets stripped from this URL and the one defined by `parameters` gets used instead.** - -##### `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. - -> [!WARNING] -> -> There's a reason this property is scary-sounding. It's intended to be used by developers who are comfortable with developing and using their own extensions. Do not enable it if you have no idea what it means or if you're not **absolutely sure** that the extension URL you're using is safe. - -##### `parameters` -A list of keys and values that will be sent to the extension as query paramters. - ### Weather Display weather information for a specific location. The data is provided by https://open-meteo.com/. @@ -1452,13 +588,12 @@ Example: ```yaml - type: weather units: metric - hour-format: 12h location: London, United Kingdom ``` > [!NOTE] > -> US cities which have common names can have their state specified as the second parameter as such: +> US cities which have common names can have their state specified as the second parameter like such: > > * Greenville, North Carolina, United States > * Greenville, South Carolina, United States @@ -1477,7 +612,6 @@ Each bar represents a 2 hour interval. The yellow background represents sunrise | ---- | ---- | -------- | ------- | | location | string | yes | | | units | string | no | metric | -| hour-format | string | no | 12h | | hide-location | boolean | no | false | | show-area-name | boolean | no | false | @@ -1487,9 +621,6 @@ The name of the city and country to fetch weather information for. Attempting to ##### `units` Whether to show the temperature in celsius or fahrenheit, possible values are `metric` or `imperial`. -#### `hour-format` -Whether to show the hours of the day in 12-hour format or 24-hour format. Possible values are `12h` and `24h`. - ##### `hide-location` Optionally don't display the location name on the widget. @@ -1507,7 +638,7 @@ Greenville, United States ``` ### Monitor -Display a list of sites and whether they are reachable (online) or not. This is determined by sending a GET request to the specified URL, if the response is 200 then the site is OK. The time it took to receive a response is also shown in milliseconds. +Display a list of sites and whether they are reachable (online) or not. This is determined by sending a HEAD request to the specified URL, if the response is 200 then the site is OK. The time it took to receive a response is also shown in milliseconds. Example: @@ -1542,21 +673,9 @@ You can hover over the "ERROR" text to view more information. #### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| sites | array | yes | | -| style | string | no | | -| show-failing-only | boolean | no | false | - -##### `show-failing-only` -Shows only a list of failing sites when set to `true`. - -##### `style` -Used to change the appearance of the widget. Possible values are `compact`. - -Preview of `compact`: - -![](images/monitor-widget-compact-preview.png) +| Name | Type | Required | +| ---- | ---- | -------- | +| sites | array | yes | | ##### `sites` @@ -1566,12 +685,8 @@ Properties for each site: | ---- | ---- | -------- | ------- | | title | string | yes | | | url | string | yes | | -| check-url | string | no | | -| error-url | string | no | | | icon | string | no | | -| allow-insecure | boolean | no | false | | same-tab | boolean | no | false | -| alt-status-codes | array | no | | `title` @@ -1579,62 +694,28 @@ The title used to indicate the site. `url` -The public facing URL of a monitored service, the user will be redirected here. If `check-url` is not specified, this is used as the status check. - -`check-url` - -The URL which will be requested and its response will determine the status of the site. If not specified, the `url` property is used. - -`error-url` - -If the monitored service returns an error, the user will be redirected here. If not specified, the `url` property is used. +The URL which will be requested and its response will determine the status of the site. `icon` -Optional URL to an image which will be used as the icon for the site. Can be an external URL or internal via [server configured assets](#assets-path). You can also directly use [Simple Icons](https://simpleicons.org/) via a `si:` prefix or [Dashboard Icons](https://github.com/walkxcode/dashboard-icons) via a `di:` prefix: - -```yaml -icon: si:jellyfin -icon: si:gitea -icon: si:adguard -``` - -> [!WARNING] -> -> Simple Icons are loaded externally and are hosted on `cdn.jsdelivr.net`, if you do not wish to depend on a 3rd party you are free to download the icons individually and host them locally. - -`allow-insecure` - -Whether to ignore invalid/self-signed certificates. +Optional URL to an image which will be used as the icon for the site. Can be an external URL or internal via [server configured assets](#assets-path). `same-tab` Whether to open the link in the same or a new tab. -`alt-status-codes` - -Status codes other than 200 that you want to return "OK". - -```yaml -alt-status-codes: - - 403 -``` - ### Releases -Display a list of latest releases for specific repositories on Github, GitLab, Codeberg or Docker Hub. +Display a list of releases for specific repositories on Github. Draft releases and prereleases will not be shown. Example: ```yaml - type: releases - show-source-icon: true repositories: + - immich-app/immich - go-gitea/gitea + - dani-garcia/vaultwarden - jellyfin/jellyfin - - glanceapp/glance - - codeberg:redict/redict - - gitlab:fdroid/fdroidclient - - dockerhub:gotify/server ``` Preview: @@ -1646,53 +727,12 @@ Preview: | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | repositories | array | yes | | -| show-source-icon | boolean | no | false | | | token | string | no | | -| gitlab-token | string | no | | | limit | integer | no | 10 | | collapse-after | integer | no | 5 | ##### `repositories` -A list of repositores to fetch the latest release for. Only the name/repo is required, not the full URL. A prefix can be specified for repositories hosted elsewhere such as GitLab, Codeberg and Docker Hub. Example: - -```yaml -repositories: - - gitlab:inkscape/inkscape - - dockerhub:glanceapp/glance - - codeberg:redict/redict -``` - -Official images on Docker Hub can be specified by omitting the owner: - -```yaml -repositories: - - dockerhub:nginx - - dockerhub:node - - dockerhub:alpine -``` - -You can also specify exact tags for Docker Hub images: - -```yaml -repositories: - - dockerhub:nginx:latest - - dockerhub:nginx:stable-alpine -``` - -To include prereleases you can specify the repository as an object and use the `include-prereleases` property: - -**Note: This feature is currently only available for GitHub repositories.** - -```yaml -repositories: - - gitlab:inkscape/inkscape - - repository: glanceapp/glance - include-prereleases: true - - codeberg:redict/redict -``` - -##### `show-source-icon` -Shows an icon of the source (GitHub/GitLab/Codeberg/Docker Hub) next to the repository name when set to `true`. +A list of repositores for which to fetch the latest release for. Only the name/repo is required, not the full URL. ##### `token` Without authentication Github allows for up to 60 requests per hour. You can easily exceed this limit and start seeing errors if you're tracking lots of repositories or your cache time is low. To circumvent this you can [create a read only token from your Github account](https://github.com/settings/personal-access-tokens/new) and provide it here. @@ -1704,7 +744,7 @@ services: glance: image: glanceapp/glance environment: - - GITHUB_TOKEN= + - GITHUB_TOKEN: ``` and then use it in your `glance.yml` like this: @@ -1717,345 +757,12 @@ and then use it in your `glance.yml` like this: This way you can safely check your `glance.yml` in version control without exposing the token. -##### `gitlab-token` -Same as the above but used when fetching GitLab releases. - ##### `limit` The maximum number of releases to show. #### `collapse-after` How many releases are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. -### Docker Containers - -Display the status of your Docker containers along with an icon and an optional short description. - -![](images/docker-containers-preview.png) - -```yaml -- type: docker-containers - hide-by-default: false -``` - -> [!NOTE] -> -> The widget requires access to `docker.sock`. If you're running Glance inside a container, this can be done by mounting the socket as a volume: -> -> ```yaml -> services: -> glance: -> image: glanceapp/glance -> volumes: -> - /var/run/docker.sock:/var/run/docker.sock -> ``` - -Configuration of the containers is done via labels applied to each container: - -```yaml - jellyfin: - image: jellyfin/jellyfin:latest - labels: - glance.name: Jellyfin - glance.icon: si:jellyfin - glance.url: https://jellyfin.domain.com - glance.description: Movies & shows -``` - -For services with multiple containers you can specify a `glance.id` on the "main" container and `glance.parent` on each "child" container: - -
-View docker-compose.yml -
- -```yaml -services: - immich-server: - image: ghcr.io/immich-app/immich-server - labels: - glance.name: Immich - glance.icon: si:immich - glance.url: https://immich.domain.com - glance.description: Image & video management - glance.id: immich - - redis: - image: docker.io/redis:6.2-alpine - labels: - glance.parent: immich - glance.name: Redis - - database: - image: docker.io/tensorchord/pgvecto-rs:pg14-v0.2.0 - labels: - glance.parent: immich - glance.name: DB - - proxy: - image: nginx:stable - labels: - glance.parent: immich - glance.name: Proxy -``` -
-
- -This will place all child containers under the `Immich` container when hovering over its icon: - -![](images/docker-container-parent.png) - -If any of the child containers are down, their status will propagate up to the parent container: - -![](images/docker-container-parent2.png) - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| hide-by-default | boolean | no | false | -| sock-path | string | no | /var/run/docker.sock | - -##### `hide-by-default` -Whether to hide the containers by default. If set to `true` you'll have to manually add a `glance.hide: false` label to each container you want to display. By default all containers will be shown and if you want to hide a specific container you can add a `glance.hide: true` label. - -##### `sock-path` -The path to the Docker socket. - -#### Labels -| Name | Description | -| ---- | ----------- | -| glance.name | The name displayed in the UI. If not specified, the name of the container will be used. | -| glance.icon | The icon displayed in the UI. Can be an external URL or an icon prefixed with si:, sh: or di: like with the bookmarks and monitor widgets | -| glance.url | The URL that the user will be redirected to when clicking on the container. | -| glance.same-tab | Whether to open the link in the same or a new tab. Default is `false`. | -| glance.description | A short description displayed in the UI. Default is empty. | -| glance.hide | Whether to hide the container. If set to `true` the container will not be displayed. Defaults to `false`. | -| glance.id | The custom ID of the container. Used to group containers under a single parent. | -| glance.parent | The ID of the parent container. Used to group containers under a single parent. | - -### DNS Stats -Display statistics from a self-hosted ad-blocking DNS resolver such as AdGuard Home or Pi-hole. - -Example: - -```yaml -- type: dns-stats - service: adguard - url: https://adguard.domain.com/ - username: admin - password: ${ADGUARD_PASSWORD} -``` - -Preview: - -![](images/dns-stats-widget-preview.png) - -> [!NOTE] -> -> When using AdGuard Home the 3rd statistic on top will be the average latency and when using Pi-hole it will be the total number of blocked domains from all adlists. - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| service | string | no | pihole | -| allow-insecure | bool | no | false | -| url | string | yes | | -| username | 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` (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. - -##### `username` -Only required when using AdGuard Home. The username used to log into the admin dashboard. - -##### `password` -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 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. - -##### `hide-top-domains` -Whether to hide the list of top blocked domains. - -##### `hour-format` -Whether to display the relative time in the graph in `12h` or `24h` format. - -### Server Stats -Display statistics such as CPU usage, memory usage and disk usage of the server Glance is running on or other servers. - -Example: - -```yaml -- type: server-stats - servers: - - type: local - name: Services -``` - -Preview: - -![](images/server-stats-preview.gif) - -> [!NOTE] -> -> This widget is currently under development, some features might not function as expected or may change. - -To display data from a remote server you need to have the Glance Agent running on that server. You can download the agent from [here](https://github.com/glanceapp/agent), though keep in mind that it is still in development and may not work as expected. Support for other providers such as Glances will be added in the future. - -In the event that the CPU temperature goes over 80°C, a flame icon will appear next to the CPU. The progress indicators will also turn red (or the equivalent of your negative color) to hopefully grab your attention if anything is unusually high: - -![](images/server-stats-flame-icon.png) - -#### Properties -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| servers | array | no | | - -##### `servers` -If not provided it will display the statistics of the server Glance is running on. - -##### Properties for both `local` and `remote` servers -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| type | string | yes | | -| name | string | no | | -| hide-swap | boolean | no | false | - -###### `type` -Whether to display statistics for the local server or a remote server. Possible values are `local` and `remote`. - -###### `name` -The name of the server which will be displayed on the widget. If not provided it will default to the server's hostname. - -###### `hide-swap` -Whether to hide the swap usage. - -##### Properties for the `local` server -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| cpu-temp-sensor | string | no | | -| hide-mountpoints-by-default | boolean | no | false | -| mountpoints | map\[string\]object | no | | - -###### `cpu-temp-sensor` -The name of the sensor to use for the CPU temperature. When not provided the widget will attempt to find the correct one, if it fails to do so the temperature will not be displayed. To view the available sensors you can use `sensors` command. - -###### `hide-mountpoints-by-default` -If set to `true` you'll have to manually make each mountpoint visible by adding a `hide: false` property to it like so: - -```yaml -- type: server-stats - servers: - - type: local - hide-mountpoints-by-default: true - mountpoints: - "/": - hide: false - "/mnt/data": - hide: false -``` - -This is useful if you're running Glance inside of a container which usually mounts a lot of irrelevant filesystems. - -###### `mountpoints` -A map of mountpoints to display disk usage for. The key is the path to the mountpoint and the value is an object with optional properties. Example: - -```yaml -mountpoints: - "/": - name: Root - "/mnt/data": - name: Data - "/boot/efi": - hide: true -``` - -##### Properties for each `mountpoint` -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| name | string | no | | -| hide | boolean | no | false | - -###### `name` -The name of the mountpoint which will be displayed on the widget. If not provided it will default to the mountpoint's path. - -###### `hide` -Whether to hide this mountpoint from the widget. - -##### Properties for `remote` servers -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| url | string | yes | | -| token | string | no | | -| timeout | string | no | 3s | - -###### `url` -The URL and port of the server to fetch the statistics from. - -###### `token` -The authentication token to use when fetching the statistics. - -###### `timeout` -The maximum time to wait for a response from the server. The value is a string and must be a number followed by one of s, m, h, d. Example: `10s` for 10 seconds, `1m` for 1 minute, etc - -### Repository -Display general information about a repository as well as a list of the latest open pull requests and issues. - -Example: - -```yaml -- type: repository - repository: glanceapp/glance - pull-requests-limit: 5 - issues-limit: 3 - commits-limit: 3 -``` - -Preview: - -![](images/repository-preview.png) - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| repository | string | yes | | -| token | string | no | | -| pull-requests-limit | integer | no | 3 | -| issues-limit | integer | no | 3 | -| commits-limit | integer | no | -1 | - -##### `repository` -The owner and repository name that will have their information displayed. - -##### `token` -Without authentication Github allows for up to 60 requests per hour. You can easily exceed this limit and start seeing errors if your cache time is low or you have many instances of this widget. To circumvent this you can [create a read only token from your Github account](https://github.com/settings/personal-access-tokens/new) and provide it here. - -##### `pull-requests-limit` -The maximum number of latest open pull requests to show. Set to `-1` to not show any. - -##### `issues-limit` -The maximum number of latest open issues to show. Set to `-1` to not show any. - -##### `commits-limit` -The maximum number of lastest commits to show from the default branch. Set to `-1` to not show any. - ### Bookmarks Display a list of links which can be grouped. @@ -2115,13 +822,6 @@ An array of groups which can optionally have a title and a custom color. | title | string | no | | | color | HSL | no | the primary color of the theme | | links | array | yes | | -| same-tab | boolean | no | false | -| hide-arrow | boolean | no | false | -| target | string | no | | - -> [!TIP] -> -> You can set `same-tab`, `hide-arrow` and `target` either on the group which will apply them to all links in that group, or on each individual link which will override the value set on the group. ###### Properties for each link | Name | Type | Required | Default | @@ -2131,11 +831,10 @@ An array of groups which can optionally have a title and a custom color. | icon | string | no | | | same-tab | boolean | no | false | | hide-arrow | boolean | no | false | -| target | string | no | | `icon` -URL pointing to an image. You can also directly use [Simple Icons](https://simpleicons.org/) via a `si:` prefix or [Dashboard Icons](https://github.com/walkxcode/dashboard-icons) via a `di:` prefix: +URL pointing to an image. You can also directly use [Simple Icons](https://simpleicons.org/) via a `si:` prefix: ```yaml icon: si:gmail @@ -2145,7 +844,7 @@ icon: si:reddit > [!WARNING] > -> Simple Icons are loaded externally and are hosted on `cdn.jsdelivr.net`, if you do not wish to depend on a 3rd party you are free to download the icons individually and host them locally. +> Simple Icons are loaded externally and are hosted on `cdnjs.cloudflare.com`, if you do not wish to depend on a 3rd party you are free to download the icons individually and host them locally. `same-tab` @@ -2155,102 +854,6 @@ Whether to open the link in the same tab or a new one. Whether to hide the colored arrow on each link. -`target` - -Set a custom value for the link's `target` attribute. Possible values are `_blank`, `_self`, `_parent` and `_top`, you can read more about what they do [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#target). This property has precedence over `same-tab`. - -### ChangeDetection.io -Display a list watches from changedetection.io. - -Example - -```yaml -- type: change-detection - instance-url: https://changedetection.mydomain.com/ - token: ${CHANGE_DETECTION_TOKEN} -``` - -Preview: - -![](images/change-detection-widget-preview.png) - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| instance-url | string | no | `https://www.changedetection.io` | -| token | string | no | | -| limit | integer | no | 10 | -| collapse-after | integer | no | 5 | -| watches | array of strings | no | | - -##### `instance-url` -The URL pointing to your instance of `changedetection.io`. - -##### `token` -The API access token which can be found in `SETTINGS > API`. Optionally, you can specify this using an environment variable with the syntax `${VARIABLE_NAME}`. - -##### `limit` -The maximum number of watches to show. - -##### `collapse-after` -How many watches are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. - -##### `watches` -By default all of the configured watches will be shown. Optionally, you can specify a list of UUIDs for the specific watches you want to have listed: - -```yaml - - type: change-detection - watches: - - 1abca041-6d4f-4554-aa19-809147f538d3 - - 705ed3e4-ea86-4d25-a064-822a6425be2c -``` - -### Clock -Display a clock showing the current time and date. Optionally, also display the the time in other timezones. - -Example: - -```yaml -- type: clock - hour-format: 24h - timezones: - - timezone: Europe/Paris - label: Paris - - timezone: America/New_York - label: New York - - timezone: Asia/Tokyo - label: Tokyo -``` - -Preview: - -![](images/clock-widget-preview.png) - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| hour-format | string | no | 24h | -| timezones | array | no | | - -##### `hour-format` -Whether to show the time in 12 or 24 hour format. Possible values are `12h` and `24h`. - -#### Properties for each timezone - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| timezone | string | yes | | -| label | string | no | | - -##### `timezone` -A timezone identifier such as `Europe/London`, `America/New_York`, etc. The full list of available identifiers can be found [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). - -##### `label` -Optionally, override the display value for the timezone to something more meaningful such as "Home", "Work" or anything else. - - ### Calendar Display a calendar. @@ -2258,113 +861,61 @@ Example: ```yaml - type: calendar - first-day-of-week: monday ``` Preview: ![](images/calendar-widget-preview.png) -#### Properties +> [!NOTE] +> +> There is currently no customizability available for the calendar. Extra features will be added in the future. -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| first-day-of-week | string | no | monday | - -##### `first-day-of-week` -The day of the week that the calendar starts on. All week days are available as possible values. - -### Calendar (legacy) -Display a calendar. +### Stocks +Display a list of stocks, their current value, change for the day and a small 21d chart. Data is taken from Yahoo Finance. Example: ```yaml -- type: calendar-legacy - start-sunday: false -``` - -Preview: - -![](images/calendar-legacy-widget-preview.png) - -> [!NOTE] -> -> This widget is deprecated and may be removed in a future version. - -#### Properties - -| Name | Type | Required | Default | -| ---- | ---- | -------- | ------- | -| start-sunday | boolean | no | false | - -##### `start-sunday` -Whether calendar weeks start on Sunday or Monday. - -> [!NOTE] -> -> There is currently little customizability available for the calendar. Extra features will be added in the future. - -### Markets -Display a list of markets, their current value, change for the day and a small 21d chart. Data is taken from Yahoo Finance. - -Example: - -```yaml -- type: markets - markets: +- type: stocks + stocks: - symbol: SPY name: S&P 500 - symbol: BTC-USD name: Bitcoin - chart-link: https://www.tradingview.com/chart/?symbol=INDEX:BTCUSD - symbol: NVDA name: NVIDIA - symbol: AAPL - symbol-link: https://www.google.com/search?tbm=nws&q=apple name: Apple + - symbol: MSFT + name: Microsoft + - symbol: GOOGL + name: Google + - symbol: AMD + name: AMD + - symbol: RDDT + name: Reddit ``` Preview: -![](images/markets-widget-preview.png) +![](images/stocks-widget-preview.png) #### Properties | Name | Type | Required | | ---- | ---- | -------- | -| markets | array | yes | +| stocks | array | yes | | sort-by | string | no | -| chart-link-template | string | no | -| symbol-link-template | string | no | -##### `markets` -An array of markets for which to display information about. +##### `stocks` +An array of stocks for which to display information about. -##### `sort-by` -By default the markets are displayed in the order they were defined. You can customize their ordering by setting the `sort-by` property to `change` for descending order based on the stock's percentage change (e.g. 1% would be sorted higher than -1%) or `absolute-change` for descending order based on the stock's absolute price change (e.g. -1% would be sorted higher than +0.5%). - -##### `chart-link-template` -A template for the link to go to when clicking on the chart that will be applied to all markets. The value `{SYMBOL}` will be replaced with the symbol of the market. You can override this on a per-market basis by specifying a `chart-link` property. Example: - -```yaml -chart-link-template: https://www.tradingview.com/chart/?symbol={SYMBOL} -``` - -##### `symbol-link-template` -A template for the link to go to when clicking on the symbol that will be applied to all markets. The value `{SYMBOL}` will be replaced with the symbol of the market. You can override this on a per-market basis by specifying a `symbol-link` property. Example: - -```yaml -symbol-link-template: https://www.google.com/search?tbm=nws&q={SYMBOL} -``` - -###### Properties for each market +###### Properties for each stock | Name | Type | Required | | ---- | ---- | -------- | | symbol | string | yes | | name | string | no | -| symbol-link | string | no | -| chart-link | string | no | `symbol` @@ -2374,13 +925,8 @@ The symbol, as seen in Yahoo Finance. The name that will be displayed under the symbol. -`symbol-link` - -The link to go to when clicking on the symbol. - -`chart-link` - -The link to go to when clicking on the chart. +##### `sort-by` +By default the stocks are displayed in the order they were defined. You can customize their ordering by setting the `sort-by` property to `absolute-change` for descending order based on the stock's absolute price change. ### Twitch Channels Display a list of channels from Twitch. @@ -2407,7 +953,6 @@ Preview: | ---- | ---- | -------- | ------- | | channels | array | yes | | | collapse-after | integer | no | 5 | -| sort-by | string | no | viewers | ##### `channels` A list of channels to display. @@ -2415,9 +960,6 @@ A list of channels to display. ##### `collapse-after` How many channels are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. -##### `sort-by` -Can be used to specify the order in which the channels are displayed. Possible values are `viewers` and `live`. - ### Twitch top games Display a list of games with the most viewers on Twitch. @@ -2480,16 +1022,3 @@ The source of the iframe. ##### `height` The height of the iframe. The minimum allowed height is 50. - -### HTML -Embed any HTML. - -Example: - -```yaml -- type: html - source: | -

Hello, World!

-``` - -Note the use of `|` after `source:`, this allows you to insert a multi-line string. diff --git a/docs/custom-api.md b/docs/custom-api.md deleted file mode 100644 index d42d1fc..0000000 --- a/docs/custom-api.md +++ /dev/null @@ -1,415 +0,0 @@ -[Jump to function definitions](#functions) - -## Examples - -The best way to get an idea of how the templates work would be with a bunch examples. Here are the most common use cases: - -JSON response: - -```json -{ - "title": "My Title", - "content": "My Content", -} -``` - -To access the two fields in the JSON response, you would use the following: - -```html -
{{ .JSON.String "title" }}
-
{{ .JSON.String "content" }}
-``` - -Output: - -```html -
My Title
-
My Content
-``` - -
- -JSON response: - -```json -{ - "author": "John Doe", - "posts": [ - { - "title": "My Title", - "content": "My Content" - }, - { - "title": "My Title 2", - "content": "My Content 2" - } - ] -} -``` - -To loop through the array of posts, you would use the following: - -```html -{{ range .JSON.Array "posts" }} -
{{ .String "title" }}
-
{{ .String "content" }}
-{{ end }} -``` - -Output: - -```html -
My Title
-
My Content
-
My Title 2
-
My Content 2
-``` - -Notice the missing `.JSON` when accessing the title and content, this is because the range function sets the context to the current array element. - -If you want to access the top-level context within the range, you can use the following: - -```html -{{ range .JSON.Array "posts" }} -
{{ .String "title" }}
-
{{ .String "content" }}
-
{{ $.JSON.String "author" }}
-{{ end }} -``` - -Output: - -```html -
My Title
-
My Content
-
John Doe
-
My Title 2
-
My Content 2
-
John Doe
-``` - -
- -JSON response: - -```json -[ - "Apple", - "Banana", - "Cherry", - "Watermelon" -] -``` - -Somewhat awkwardly, when the current context is a basic type that isn't an object, the way you specify its type is to use an empty string as the key. So, to loop through the array of strings, you would use the following: - -```html -{{ range .JSON.Array "" }} -
{{ .String "" }}
-{{ end }} -``` - -Output: - -```html -
Apple
-
Banana
-
Cherry
-
Watermelon
-``` - -To access an item at a specific index, you could use the following: - -```html -
{{ .JSON.String "0" }}
-``` - -Output: - -```html -
Apple
-``` - -
- -JSON response: - -```json -{ - "user": { - "address": { - "city": "New York", - "state": "NY" - } - } -} -``` - -To easily access deeply nested objects, you can use the following dot notation: - -```html -
{{ .JSON.String "user.address.city" }}
-
{{ .JSON.String "user.address.state" }}
-``` - -Output: - -```html -
New York
-
NY
-``` - -Using indexes anywhere in the path is also supported: - -```json -{ - "users": [ - { - "name": "John Doe" - }, - { - "name": "Jane Doe" - } - ] -} -``` - -```html -
{{ .JSON.String "users.0.name" }}
-
{{ .JSON.String "users.1.name" }}
-``` - -Output: - -```html -
John Doe
-
Jane Doe
-``` - -
- -JSON response: - -```json -{ - "user": { - "name": "John Doe", - "age": 30 - } -} -``` - -To check if a field exists, you can use the following: - -```html -{{ if .JSON.Exists "user.age" }} -
{{ .JSON.Int "user.age" }}
-{{ else }} -
Age not provided
-{{ end }} -``` - -Output: - -```html -
30
-``` - -
- -JSON response: - -```json -{ - "price": 100, - "discount": 10 -} -``` - -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 -
{{ sub (.JSON.Int "price") (.JSON.Int "discount") }}
-``` - -Output: - -```html -
90
-``` - -Other operations include `add`, `mul`, and `div`. - -
- -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" }} -
{{ .String "title" }}
-
-{{ 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 -
Exploring the Depths of Quantum Computing
-
- -
A Beginner's Guide to Sustainable Living
-
- -
The Art of Baking Sourdough Bread
-
-``` - -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. - -
- -In some instances, you may want to know the status code of the response. This can be done using the following: - -```html -{{ if eq .Response.StatusCode 200 }} -

Success!

-{{ else }} -

Failed to fetch data

-{{ end }} -``` - -You can also access the response headers: - -```html -
{{ .Response.Header.Get "Content-Type" }}
-``` - -
- -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 }} -

{{ .String "name" }} is {{ .Int "age" }} years old

-{{ end }} -``` - -Output: - -```html -

Steve is 30 years old

-

Alex is 25 years old

-

John is 35 years old

-``` - -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" }} -

{{ .String "" }}

-{{ end }} -``` - -Output: - -```html -

Steve

-

Alex

-

John

-``` - -## Functions - -The following functions are available on the `JSON` object: - -- `String(key string) string`: Returns the value of the key as a string. -- `Int(key string) int`: Returns the value of the key as an integer. -- `Float(key string) float`: Returns the value of the key as a float. -- `Bool(key string) bool`: Returns the value of the key as a boolean. -- `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects. -- `Exists(key string) bool`: Returns true if the key exists in the JSON object. - -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. ``. -- `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: - -- `eq(a, b any) bool`: Compares two values for equality. -- `ne(a, b any) bool`: Compares two values for inequality. -- `lt(a, b any) bool`: Compares two values for less than. -- `lte(a, b any) bool`: Compares two values for less than or equal to. -- `gt(a, b any) bool`: Compares two values for greater than. -- `gte(a, b any) bool`: Compares two values for greater than or equal to. -- `and(a, b bool) bool`: Returns true if both values are true. -- `or(a, b bool) bool`: Returns true if either value is true. -- `not(a bool) bool`: Returns the opposite of the value. -- `index(a any, b int) any`: Returns the value at the specified index of an array. -- `len(a any) int`: Returns the length of an array. -- `printf(format string, a ...any) string`: Returns a formatted string. diff --git a/docs/extensions.md b/docs/extensions.md deleted file mode 100644 index b6719c1..0000000 --- a/docs/extensions.md +++ /dev/null @@ -1,164 +0,0 @@ -# Extensions - -> [!IMPORTANT] -> -> **This document as well as the extensions feature are a work in progress. The API may change in the future. You are responsible for maintaining your own extensions.** - -## Overview - -With the intention of requiring minimal knowledge in order to develop extensions, rather than being a convoluted protocol they are nothing more than an HTTP request to a server that returns a few special headers. The exchange between Glance and extensions can be seen in the following diagram: - -![](images/extension-overview.png) - -If you know how to setup an HTTP server and a bit of HTML and CSS you're ready to start building your own extensions. - -> [!TIP] -> -> By default, the extension widget has a cache time of 30 minutes. To avoid having to restart Glance after every extension change you can set the cache time of the widget to 1 second: -> ```yaml -> - type: extension -> url: http://localhost:8081 -> cache: 1s -> ``` - -## Headers - -### `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. - -### `Widget-Content-Frameless` -When set to `true`, the widget's content will be displayed without the default background or "frame". - -## Content Types - -> [!NOTE] -> -> Currently, `html` is the only supported content type. The long-term goal is to have generic content types such as `videos`, `forum-posts`, `markets`, `streams`, etc. which will be returned in JSON format and displayed by Glance using existing styles and functionality, allowing extension developers to achieve a native look while only focusing on providing data from their preferred source. - -### `html` -Displays the content as HTML. This requires the user to have the `allow-potentially-dangerous-html` property set to `true`, otherwise the content will be shown as plain text. - - -#### Using existing classes and functionality -Most of the features seen throughout Glance can easily be used in your custom HTML extensions. Below is an example of some of these features: - -```html -

Text with subdued color

-

Text with base color

-

Text with highlighted color

-

Text with primary color

-

Text with positive color

-

Text with negative color

- -
- -

Font size 1

-

Font size 2

-

Font size 3

-

Font size 4

-

Font size base

-

Font size 5

-

Font size 6

- -
- -Link with visited indicator - -
- -Link with primary color if not visited - -
- -

Event happened ago

- -
- - - -
- - - -
- - - -
- -

Lazily loaded image:

- - - -
- -

List of posts:

- - -``` - -All of that will result in the following: - -![](images/extension-html-reusing-existing-features-preview.png) - -**Class names or features may change, once again, you are responsible for maintaining your own extensions.** diff --git a/docs/glance.yml b/docs/glance.yml deleted file mode 100644 index 35dc7cb..0000000 --- a/docs/glance.yml +++ /dev/null @@ -1,105 +0,0 @@ -pages: - - name: Home - # Optionally, if you only have a single page you can hide the desktop navigation for a cleaner look - # hide-desktop-navigation: true - columns: - - size: small - widgets: - - type: calendar - first-day-of-week: monday - - - type: rss - limit: 10 - collapse-after: 3 - cache: 12h - feeds: - - url: https://selfh.st/rss/ - title: selfh.st - limit: 4 - - url: https://ciechanow.ski/atom.xml - - url: https://www.joshwcomeau.com/rss.xml - title: Josh Comeau - - url: https://samwho.dev/rss.xml - - url: https://ishadeed.com/feed.xml - title: Ahmad Shadeed - - - type: twitch-channels - channels: - - theprimeagen - - j_blow - - piratesoftware - - cohhcarnage - - christitustech - - EJ_SA - - - size: full - widgets: - - type: group - widgets: - - type: hacker-news - - type: lobsters - - - type: videos - channels: - - UCXuqSBlHAE6Xw-yeJA0Tunw # Linus Tech Tips - - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling - - UCsBjURrPoezykLs9EqgamOA # Fireship - - UCBJycsmduvYEL83R_U4JriQ # Marques Brownlee - - UCHnyfMqiRRG1u-2MsSQLbXA # Veritasium - - - type: group - widgets: - - type: reddit - subreddit: technology - show-thumbnails: true - - type: reddit - subreddit: selfhosted - show-thumbnails: true - - - size: small - widgets: - - type: weather - location: London, United Kingdom - units: metric # alternatively "imperial" - hour-format: 12h # alternatively "24h" - # Optionally hide the location from being displayed in the widget - # hide-location: true - - - type: markets - markets: - - symbol: SPY - name: S&P 500 - - symbol: BTC-USD - name: Bitcoin - - symbol: NVDA - name: NVIDIA - - symbol: AAPL - name: Apple - - symbol: MSFT - name: Microsoft - - - type: releases - cache: 1d - # Without authentication the Github API allows for up to 60 requests per hour. You can create a - # read-only token from your Github account settings and use it here to increase the limit. - # token: ... - repositories: - - glanceapp/glance - - go-gitea/gitea - - immich-app/immich - - syncthing/syncthing - - # Add more pages here: - # - name: Your page name - # columns: - # - size: small - # widgets: - # # Add widgets here - - # - size: full - # widgets: - # # Add widgets here - - # - size: small - # widgets: - # # Add widgets here diff --git a/docs/images/calendar-legacy-widget-preview.png b/docs/images/calendar-legacy-widget-preview.png deleted file mode 100644 index 5a161bf..0000000 Binary files a/docs/images/calendar-legacy-widget-preview.png and /dev/null differ diff --git a/docs/images/calendar-widget-preview.png b/docs/images/calendar-widget-preview.png index 4922a9b..5a161bf 100644 Binary files a/docs/images/calendar-widget-preview.png and b/docs/images/calendar-widget-preview.png differ diff --git a/docs/images/change-detection-widget-preview.png b/docs/images/change-detection-widget-preview.png deleted file mode 100644 index 74b7fe7..0000000 Binary files a/docs/images/change-detection-widget-preview.png and /dev/null differ diff --git a/docs/images/clock-widget-preview.png b/docs/images/clock-widget-preview.png deleted file mode 100644 index bf809c5..0000000 Binary files a/docs/images/clock-widget-preview.png and /dev/null differ diff --git a/docs/images/custom-api-preview-1.png b/docs/images/custom-api-preview-1.png deleted file mode 100644 index 4cf4c30..0000000 Binary files a/docs/images/custom-api-preview-1.png and /dev/null differ diff --git a/docs/images/custom-api-preview-2.png b/docs/images/custom-api-preview-2.png deleted file mode 100644 index 481ef85..0000000 Binary files a/docs/images/custom-api-preview-2.png and /dev/null differ diff --git a/docs/images/custom-api-preview-3.png b/docs/images/custom-api-preview-3.png deleted file mode 100644 index 15d8cb2..0000000 Binary files a/docs/images/custom-api-preview-3.png and /dev/null differ diff --git a/docs/images/dns-stats-widget-preview.png b/docs/images/dns-stats-widget-preview.png deleted file mode 100644 index defd139..0000000 Binary files a/docs/images/dns-stats-widget-preview.png and /dev/null differ diff --git a/docs/images/docker-container-parent.png b/docs/images/docker-container-parent.png deleted file mode 100644 index 479b3e8..0000000 Binary files a/docs/images/docker-container-parent.png and /dev/null differ diff --git a/docs/images/docker-container-parent2.png b/docs/images/docker-container-parent2.png deleted file mode 100644 index 4562239..0000000 Binary files a/docs/images/docker-container-parent2.png and /dev/null differ diff --git a/docs/images/docker-containers-preview.png b/docs/images/docker-containers-preview.png deleted file mode 100644 index ba14fce..0000000 Binary files a/docs/images/docker-containers-preview.png and /dev/null differ diff --git a/docs/images/docker-widget-preview.png b/docs/images/docker-widget-preview.png deleted file mode 100644 index 5b644d4..0000000 Binary files a/docs/images/docker-widget-preview.png and /dev/null differ diff --git a/docs/images/extension-html-reusing-existing-features-preview.png b/docs/images/extension-html-reusing-existing-features-preview.png deleted file mode 100644 index 3fbdbef..0000000 Binary files a/docs/images/extension-html-reusing-existing-features-preview.png and /dev/null differ diff --git a/docs/images/extension-overview.png b/docs/images/extension-overview.png deleted file mode 100644 index 6c23452..0000000 Binary files a/docs/images/extension-overview.png and /dev/null differ diff --git a/docs/images/gaming-page-preview.png b/docs/images/gaming-page-preview.png deleted file mode 100644 index 343d22f..0000000 Binary files a/docs/images/gaming-page-preview.png and /dev/null differ diff --git a/docs/images/group-widget-preview.png b/docs/images/group-widget-preview.png deleted file mode 100644 index 4d1d86b..0000000 Binary files a/docs/images/group-widget-preview.png and /dev/null differ diff --git a/docs/images/lobsters-widget-preview.png b/docs/images/lobsters-widget-preview.png deleted file mode 100644 index 9648d6d..0000000 Binary files a/docs/images/lobsters-widget-preview.png and /dev/null differ diff --git a/docs/images/markets-page-preview.png b/docs/images/markets-page-preview.png deleted file mode 100644 index 51e9f99..0000000 Binary files a/docs/images/markets-page-preview.png and /dev/null differ diff --git a/docs/images/mobile-header-preview.png b/docs/images/mobile-header-preview.png deleted file mode 100644 index f829eda..0000000 Binary files a/docs/images/mobile-header-preview.png and /dev/null differ diff --git a/docs/images/mobile-preview.png b/docs/images/mobile-preview.png index c27a1d2..38acdcf 100644 Binary files a/docs/images/mobile-preview.png and b/docs/images/mobile-preview.png differ diff --git a/docs/images/monitor-widget-compact-preview.png b/docs/images/monitor-widget-compact-preview.png deleted file mode 100644 index 3e81fce..0000000 Binary files a/docs/images/monitor-widget-compact-preview.png and /dev/null differ diff --git a/docs/images/preconfigured-page-preview.png b/docs/images/preconfigured-page-preview.png index e10084c..0a57c14 100644 Binary files a/docs/images/preconfigured-page-preview.png and b/docs/images/preconfigured-page-preview.png differ diff --git a/docs/images/readme-main-image.png b/docs/images/readme-main-image.png index cce27fb..821c35b 100644 Binary files a/docs/images/readme-main-image.png and b/docs/images/readme-main-image.png differ diff --git a/docs/images/reddit-field-search.png b/docs/images/reddit-field-search.png deleted file mode 100644 index a84ee33..0000000 Binary files a/docs/images/reddit-field-search.png and /dev/null differ diff --git a/docs/images/releases-widget-preview.png b/docs/images/releases-widget-preview.png index ec712bb..47acfd0 100644 Binary files a/docs/images/releases-widget-preview.png and b/docs/images/releases-widget-preview.png differ diff --git a/docs/images/repository-preview.png b/docs/images/repository-preview.png deleted file mode 100644 index 5c43db5..0000000 Binary files a/docs/images/repository-preview.png and /dev/null differ diff --git a/docs/images/rss-widget-detailed-list-preview.png b/docs/images/rss-widget-detailed-list-preview.png deleted file mode 100644 index 8cf1f11..0000000 Binary files a/docs/images/rss-widget-detailed-list-preview.png and /dev/null differ diff --git a/docs/images/rss-widget-horizontal-cards-2-preview.png b/docs/images/rss-widget-horizontal-cards-2-preview.png deleted file mode 100644 index 5f029dd..0000000 Binary files a/docs/images/rss-widget-horizontal-cards-2-preview.png and /dev/null differ diff --git a/docs/images/search-widget-bangs-preview.png b/docs/images/search-widget-bangs-preview.png deleted file mode 100644 index 9490690..0000000 Binary files a/docs/images/search-widget-bangs-preview.png and /dev/null differ diff --git a/docs/images/search-widget-preview.png b/docs/images/search-widget-preview.png deleted file mode 100644 index 9672a77..0000000 Binary files a/docs/images/search-widget-preview.png and /dev/null differ diff --git a/docs/images/server-stats-flame-icon.png b/docs/images/server-stats-flame-icon.png deleted file mode 100644 index 28cf0b8..0000000 Binary files a/docs/images/server-stats-flame-icon.png and /dev/null differ diff --git a/docs/images/server-stats-preview.gif b/docs/images/server-stats-preview.gif deleted file mode 100644 index 829679b..0000000 Binary files a/docs/images/server-stats-preview.gif and /dev/null differ diff --git a/docs/images/split-column-widget-3-columns.png b/docs/images/split-column-widget-3-columns.png deleted file mode 100644 index 88192c3..0000000 Binary files a/docs/images/split-column-widget-3-columns.png and /dev/null differ diff --git a/docs/images/split-column-widget-4-columns.png b/docs/images/split-column-widget-4-columns.png deleted file mode 100644 index 450f53e..0000000 Binary files a/docs/images/split-column-widget-4-columns.png and /dev/null differ diff --git a/docs/images/split-column-widget-masonry.png b/docs/images/split-column-widget-masonry.png deleted file mode 100644 index 145b2d6..0000000 Binary files a/docs/images/split-column-widget-masonry.png and /dev/null differ diff --git a/docs/images/split-column-widget-preview.png b/docs/images/split-column-widget-preview.png deleted file mode 100644 index 1ee336d..0000000 Binary files a/docs/images/split-column-widget-preview.png and /dev/null differ diff --git a/docs/images/startpage-preview.png b/docs/images/startpage-preview.png deleted file mode 100644 index 2af87ed..0000000 Binary files a/docs/images/startpage-preview.png and /dev/null differ diff --git a/docs/images/markets-widget-preview.png b/docs/images/stocks-widget-preview.png similarity index 100% rename from docs/images/markets-widget-preview.png rename to docs/images/stocks-widget-preview.png diff --git a/docs/images/themes/catppuccin-frappe.png b/docs/images/themes/catppuccin-frappe.png deleted file mode 100644 index 93074ae..0000000 Binary files a/docs/images/themes/catppuccin-frappe.png and /dev/null differ diff --git a/docs/images/themes/catppuccin-latte.png b/docs/images/themes/catppuccin-latte.png deleted file mode 100644 index eb701fb..0000000 Binary files a/docs/images/themes/catppuccin-latte.png and /dev/null differ diff --git a/docs/images/themes/catppuccin-macchiato.png b/docs/images/themes/catppuccin-macchiato.png deleted file mode 100644 index c797fc6..0000000 Binary files a/docs/images/themes/catppuccin-macchiato.png and /dev/null differ diff --git a/docs/images/themes/catppuccin-mocha.png b/docs/images/themes/catppuccin.png similarity index 100% rename from docs/images/themes/catppuccin-mocha.png rename to docs/images/themes/catppuccin.png diff --git a/docs/images/themes/dracula.png b/docs/images/themes/dracula.png deleted file mode 100644 index 8dba452..0000000 Binary files a/docs/images/themes/dracula.png and /dev/null differ diff --git a/docs/images/themes/gruvbox.png b/docs/images/themes/gruvbox.png deleted file mode 100644 index 2e5b7a9..0000000 Binary files a/docs/images/themes/gruvbox.png and /dev/null differ diff --git a/docs/images/themes/kanagawa-dark.png b/docs/images/themes/kanagawa-dark.png deleted file mode 100644 index 7ca4bf1..0000000 Binary files a/docs/images/themes/kanagawa-dark.png and /dev/null differ diff --git a/docs/images/videos-widget-grid-cards-preview.png b/docs/images/videos-widget-grid-cards-preview.png deleted file mode 100644 index 5c4f109..0000000 Binary files a/docs/images/videos-widget-grid-cards-preview.png and /dev/null differ diff --git a/docs/images/videos-widget-vertical-list-preview.png b/docs/images/videos-widget-vertical-list-preview.png deleted file mode 100644 index e33ce86..0000000 Binary files a/docs/images/videos-widget-vertical-list-preview.png and /dev/null differ diff --git a/docs/preconfigured-pages.md b/docs/preconfigured-pages.md deleted file mode 100644 index b70610b..0000000 --- a/docs/preconfigured-pages.md +++ /dev/null @@ -1,226 +0,0 @@ -# Preconfigured pages - -Don't want to spend time configuring pages from scratch? No problem! Simply copy the config from the ones below. - -Pull requests with your page configurations are welcome! - -> [!NOTE] -> -> Pages must be placed under a top level `pages:` key, you can read more about that [here](configuration.md#pages). - -## Startpage - -![](images/startpage-preview.png) - -
-View config (requires Glance v0.6.0 or higher) - -```yaml -- name: Startpage - width: slim - hide-desktop-navigation: true - center-vertically: true - columns: - - size: full - widgets: - - type: search - autofocus: true - - - type: monitor - cache: 1m - title: Services - sites: - - title: Jellyfin - url: https://yourdomain.com/ - icon: si:jellyfin - - title: Gitea - url: https://yourdomain.com/ - icon: si:gitea - - title: qBittorrent # only for Linux ISOs, of course - url: https://yourdomain.com/ - icon: si:qbittorrent - - title: Immich - url: https://yourdomain.com/ - icon: si:immich - - title: AdGuard Home - url: https://yourdomain.com/ - icon: si:adguard - - title: Vaultwarden - url: https://yourdomain.com/ - icon: si:vaultwarden - - - type: bookmarks - groups: - - title: General - links: - - title: Gmail - url: https://mail.google.com/mail/u/0/ - - title: Amazon - url: https://www.amazon.com/ - - title: Github - url: https://github.com/ - - title: Entertainment - links: - - title: YouTube - url: https://www.youtube.com/ - - title: Prime Video - url: https://www.primevideo.com/ - - title: Disney+ - url: https://www.disneyplus.com/ - - title: Social - links: - - title: Reddit - url: https://www.reddit.com/ - - title: Twitter - url: https://twitter.com/ - - title: Instagram - url: https://www.instagram.com/ -``` -
- -## Markets - -![](images/markets-page-preview.png) - -
-View config (requires Glance v0.6.0 or higher) - -```yaml - - name: Markets - columns: - - size: small - widgets: - - type: markets - title: Indices - markets: - - symbol: SPY - name: S&P 500 - - symbol: DX-Y.NYB - name: Dollar Index - - - type: markets - title: Crypto - markets: - - symbol: BTC-USD - name: Bitcoin - - symbol: ETH-USD - name: Ethereum - - - type: markets - title: Stocks - sort-by: absolute-change - markets: - - symbol: NVDA - name: NVIDIA - - symbol: AAPL - name: Apple - - symbol: MSFT - name: Microsoft - - symbol: GOOGL - name: Google - - symbol: AMD - name: AMD - - symbol: RDDT - name: Reddit - - symbol: AMZN - name: Amazon - - symbol: TSLA - name: Tesla - - symbol: INTC - name: Intel - - symbol: META - name: Meta - - - size: full - widgets: - - type: rss - title: News - style: horizontal-cards - feeds: - - url: https://feeds.bloomberg.com/markets/news.rss - title: Bloomberg - - url: https://moxie.foxbusiness.com/google-publisher/markets.xml - title: Fox Business - - url: https://moxie.foxbusiness.com/google-publisher/technology.xml - title: Fox Business - - - type: group - widgets: - - type: reddit - show-thumbnails: true - subreddit: technology - - type: reddit - show-thumbnails: true - subreddit: wallstreetbets - - - type: videos - style: grid-cards - collapse-after-rows: 3 - channels: - - UCvSXMi2LebwJEM1s4bz5IBA # New Money - - UCV6KDgJskWaEckne5aPA0aQ # Graham Stephan - - UCAzhpt9DmG6PnHXjmJTvRGQ # Federal Reserve - - - size: small - widgets: - - type: rss - title: News - limit: 30 - collapse-after: 13 - feeds: - - url: https://www.ft.com/technology?format=rss - title: Financial Times - - url: https://feeds.a.dj.com/rss/RSSMarketsMain.xml - title: Wall Street Journal -``` -
- -## Gaming - -![](images/gaming-page-preview.png) - -
-View config (requires Glance v0.6.0 or higher) - -```yaml -- name: Gaming - columns: - - size: small - widgets: - - type: twitch-top-games - limit: 20 - collapse-after: 13 - exclude: - - just-chatting - - pools-hot-tubs-and-beaches - - music - - art - - asmr - - - size: full - widgets: - - type: group - widgets: - - type: reddit - show-thumbnails: true - subreddit: pcgaming - - type: reddit - subreddit: games - - - type: videos - style: grid-cards - collapse-after-rows: 3 - channels: - - UCNvzD7Z-g64bPXxGzaQaa4g # gameranx - - UCZ7AeeVbyslLM_8-nVy2B8Q # Skill Up - - UCHDxYLv8iovIbhrfl16CNyg # GameLinked - - UC9PBzalIcEQCsiIkq36PyUA # Digital Foundry - - - size: small - widgets: - - type: reddit - subreddit: gamingnews - limit: 7 - style: vertical-cards -``` -
diff --git a/docs/themes.md b/docs/themes.md index fdc10b2..a943f88 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -11,30 +11,8 @@ theme: contrast-multiplier: 1.1 ``` -### Catppuccin Frappe -![screenshot](images/themes/catppuccin-frappe.png) -```yaml -theme: - background-color: 229 19 23 - contrast-multiplier: 1.2 - primary-color: 222 74 74 - positive-color: 96 44 68 - negative-color: 359 68 71 -``` - -### Catppuccin Macchiato -![screenshot](images/themes/catppuccin-macchiato.png) -```yaml -theme: - background-color: 232 23 18 - contrast-multiplier: 1.2 - primary-color: 220 83 75 - positive-color: 105 48 72 - negative-color: 351 74 73 -``` - -### Catppuccin Mocha -![screenshot](images/themes/catppuccin-mocha.png) +### Catppuccin +![screenshot](images/themes/catppuccin.png) ```yaml theme: background-color: 240 21 15 @@ -53,26 +31,6 @@ theme: primary-color: 97 13 80 ``` -### Gruvbox Dark -![screenshot](images/themes/gruvbox.png) -```yaml -theme: - background-color: 0 0 16 - primary-color: 43 59 81 - positive-color: 61 66 44 - negative-color: 6 96 59 -``` - -### Kanagawa Dark -![screenshot](images/themes/kanagawa-dark.png) -```yaml -theme: - background-color: 240 13 14 - primary-color: 51 33 68 - negative-color: 358 100 68 - contrast-multiplier: 1.2 -``` - ### Tucan ![screenshot](images/themes/tucan.png) ```yaml @@ -82,31 +40,8 @@ theme: negative-color: 209 88 54 ``` -### Dracula -![screenshot](images/themes/dracula.png) -```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 -![screenshot](images/themes/catppuccin-latte.png) -```yaml -theme: - light: true - background-color: 220 23 95 - contrast-multiplier: 1.0 - primary-color: 220 91 54 - positive-color: 109 58 40 - negative-color: 347 87 44 -``` - ### Peachy ![screenshot](images/themes/peachy.png) ```yaml diff --git a/docs/v0.7.0-upgrade.md b/docs/v0.7.0-upgrade.md deleted file mode 100644 index 93fa6b8..0000000 --- a/docs/v0.7.0-upgrade.md +++ /dev/null @@ -1,57 +0,0 @@ -## Upgrading to v0.7.0 from previous versions - -In essence, the `glance.yml` file has been moved from the root of the project to a `config/` directory and you now need to mount that directory to `/app/config` in the container. - -### Before - -Versions before v0.7.0 used a `docker-compose.yml` that looked like the following: - -```yaml -services: - glance: - image: glanceapp/glance - volumes: - - ./glance.yml:/app/glance.yml - ports: - - 8080:8080 -``` - -And expected you to have the following directory structure: - -```plaintext -glance/ - docker-compose.yml - glance.yml -``` - -### After - -With the release of v0.7.0, the recommended `docker-compose.yml` looks like the following: - -```yaml -services: - glance: - container_name: glance - image: glanceapp/glance - volumes: - - ./config:/app/config - ports: - - 8080:8080 -``` - -And expects you to have the following directory structure: - -```plaintext -glance/ - docker-compose.yml - config/ - glance.yml -``` - -## Why this change was necessary - -1. Mounting a file rather than a directory is not common practice and leads to some issues, such as creating a directory if the file is not present, which has tripped up multiple people and caused unnecessary confusion -2. v0.7.0 added automatic reloads when the configuration file changes, which based on testing didn't work when mounting a single file -3. v0.7.0 added the ability to include config files, so you'd have to make this change anyways if you wanted to take advantage of that feature - -Taking all of these into account, it felt like the right time to implement the change. diff --git a/go.mod b/go.mod index 4c19477..b4a1e72 100644 --- a/go.mod +++ b/go.mod @@ -1,32 +1,19 @@ module github.com/glanceapp/glance -go 1.24.2 +go 1.22.0 require ( - github.com/fsnotify/fsnotify v1.9.0 github.com/mmcdole/gofeed v1.3.0 - github.com/shirou/gopsutil/v4 v4.25.3 - github.com/tidwall/gjson v1.18.0 - golang.org/x/text v0.24.0 + golang.org/x/text v0.14.0 gopkg.in/yaml.v3 v3.0.1 ) require ( - 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/PuerkitoBio/goquery v1.9.1 // indirect + github.com/andybalholm/cascadia v1.3.2 // indirect github.com/json-iterator/go v1.1.12 // 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.15 // indirect - github.com/tklauser/numcpus v0.10.0 // indirect - github.com/yusufpapurcu/wmi v1.2.4 // indirect - golang.org/x/net v0.39.0 // indirect - golang.org/x/sys v0.32.0 // indirect + golang.org/x/net v0.24.0 // indirect ) diff --git a/go.sum b/go.sum index 9a79559..54489e6 100644 --- a/go.sum +++ b/go.sum @@ -1,31 +1,13 @@ -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/PuerkitoBio/goquery v1.9.1 h1:mTL6XjbJTZdpfL+Gwl5U2h1l9yEkJjhmlTeV9VPW7UI= +github.com/PuerkitoBio/goquery v1.9.1/go.mod h1:cW1n6TmIMDoORQU5IU/P1T3tGFunOeXEpGP2WHRwkbY= +github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss= +github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/ebitengine/purego v0.8.2 h1:jPPGWs2sZ1UgOSgD2bClL0MJIqu58nOmIcBuXr62z1I= -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= @@ -37,111 +19,47 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= -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= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= -github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -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/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 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= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= -golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= -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/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= 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= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -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/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= -golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -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= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/assets/files.go b/internal/assets/files.go new file mode 100644 index 0000000..bfb2b4c --- /dev/null +++ b/internal/assets/files.go @@ -0,0 +1,15 @@ +package assets + +import ( + "embed" + "io/fs" +) + +//go:embed static +var _publicFS embed.FS + +//go:embed templates +var _templateFS embed.FS + +var PublicFS, _ = fs.Sub(_publicFS, "static") +var TemplateFS, _ = fs.Sub(_templateFS, "templates") diff --git a/internal/glance/static/favicon.png b/internal/assets/static/favicon.png similarity index 100% rename from internal/glance/static/favicon.png rename to internal/assets/static/favicon.png diff --git a/internal/glance/static/fonts/JetBrainsMono-Regular.woff2 b/internal/assets/static/fonts/JetBrainsMono-Regular.woff2 similarity index 100% rename from internal/glance/static/fonts/JetBrainsMono-Regular.woff2 rename to internal/assets/static/fonts/JetBrainsMono-Regular.woff2 diff --git a/internal/assets/static/main.css b/internal/assets/static/main.css new file mode 100644 index 0000000..b77a60f --- /dev/null +++ b/internal/assets/static/main.css @@ -0,0 +1,1077 @@ +@font-face { + font-family: 'JetBrains Mono'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url('fonts/JetBrainsMono-Regular.woff2') format('woff2'); +} + +:root { + font-size: 10px; + + --scheme: ; + --bgh: 240; + --bgs: 8%; + --bgl: 9%; + --bghs: var(--bgh), var(--bgs); + --cm: 1; + --tsm: 1; + + --widget-gap: 25px; + --widget-content-vertical-padding: 15px; + --widget-content-horizontal-padding: 17px; + --widget-content-padding: var(--widget-content-vertical-padding) var(--widget-content-horizontal-padding); + --content-bounds-padding: 15px; + --border-radius: 5px; + --mobile-navigation-height: 50px; + + --color-primary: hsl(43, 50%, 70%); + --color-positive: var(--color-primary); + --color-negative: hsl(0, 70%, 70%); + --color-background: hsl(var(--bghs), var(--bgl)); + --color-widget-background-hsl-values: var(--bghs), calc(var(--bgl) + 1%); + --color-widget-background: hsl(var(--color-widget-background-hsl-values)); + --color-separator: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 4% * var(--cm)))); + --color-widget-content-border: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 4%))); + --color-widget-background-highlight: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 4%))); + + --ths: var(--bgh), calc(var(--bgs) * var(--tsm)); + --color-text-base: hsl(var(--ths), calc(var(--scheme) var(--cm) * 58%)); + --color-text-highlight: hsl(var(--ths), calc(var(--scheme) var(--cm) * 85%)); + --color-text-subdue: hsl(var(--ths), calc(var(--scheme) var(--cm) * 35%)); + + --font-size-h1: 1.7rem; + --font-size-h2: 1.6rem; + --font-size-h3: 1.5rem; + --font-size-h4: 1.4rem; + --font-size-base: 1.3rem; + --font-size-h5: 1.2rem; + --font-size-h6: 1.1rem; +} + +.light-scheme { + --scheme: 100% -; +} + +.size-title-dynamic { + font-size: var(--font-size-h4); +} + +.page-column-full .size-title-dynamic { + font-size: var(--font-size-h3); +} + +.color-primary-if-not-visited:not(:visited) { + color: var(--color-primary); +} + +.text-truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.text-truncate-3-lines { + overflow: hidden; + text-overflow: ellipsis; + -webkit-line-clamp: 3; + display: -webkit-box; + -webkit-box-orient: vertical; +} + +.visited-indicator:not(.text-truncate)::after, +.visited-indicator.text-truncate::before, +.bookmarks-link:not(.bookmarks-link-no-arrow)::after { + content: '↗'; + margin-left: 0.5em; + display: inline-block; + position: relative; + top: 0.15em; + color: var(--color-text-base); +} + +.visited-indicator.text-truncate { + direction: rtl; + text-align: left; +} + +.visited-indicator:not(:visited)::before, .visited-indicator:not(:visited)::after { + color: var(--color-primary); +} + +.list { --list-half-gap: 0rem; } +.list-gap-2 { --list-half-gap: 0.1rem; } +.list-gap-4 { --list-half-gap: 0.2rem; } +.list-gap-14 { --list-half-gap: 0.7rem; } +.list-gap-20 { --list-half-gap: 1rem; } +.list-gap-24 { --list-half-gap: 1.2rem; } + +.list > *:not(:first-child) { + margin-top: calc(var(--list-half-gap) * 2 + 1px); +} + +.list-with-separator > *:not(:first-child) { + margin-top: var(--list-half-gap); + border-top: 1px solid var(--color-separator); + padding-top: var(--list-half-gap); +} + +@keyframes listItemReveal { + from { + opacity: 0; + transform: translateY(10px); + } +} + +.list-collapsible-item { + display: none; + animation: listItemReveal 0.3s backwards; + animation-delay: var(--animation-delay); +} + +.list-collapsible-label { + display: flex; + align-items: center; + gap: 1rem; + padding: var(--widget-content-vertical-padding) 0; + background: var(--color-widget-background); +} + +.list-collapsible-label:has(.list-collapsible-input:checked) { + position: sticky; + bottom: 0; +} + +.list-collapsible:has(+ .list-collapsible-label > .list-collapsible-input:checked) .list-collapsible-item { + display: block; +} + +.list-collapsible-input { + display: none; +} + +.list-collapsible-label::before, .list-collapsible-label::after { + cursor: pointer; + display: block; +} + +.list-collapsible-label::before { + content: 'SHOW MORE'; + font-size: var(--font-size-h4); +} + +.list-collapsible-label:has(.list-collapsible-input:checked)::before { + content: 'SHOW LESS'; +} + +.list-collapsible-label::after { + content: ''; + font-size: 0.8rem; + transform: rotate(90deg); + line-height: 1; + transition: transform 0.3s; +} + +.list-collapsible-label:has(.list-collapsible-input:checked)::after { + transform: rotate(-90deg); +} + +.widget-content:has(.list-collapsible-label:last-child) { + padding-bottom: 0; +} + +::selection { + background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 20%))); + color: var(--color-text-highlight); +} + +::-webkit-scrollbar-thumb { + background: var(--color-text-subdue); + border-radius: var(--border-radius); +} + +::-webkit-scrollbar { + background: var(--color-background); + height: 5px; + width: 10px; +} + +*, *::before, *::after { + box-sizing: border-box; +} + +* { + padding: 0; + margin: 0; +} + +img, svg { + display: block; + max-width: 100%; +} + +html { + scrollbar-color: var(--color-text-subdue) transparent; + scroll-behavior: smooth; +} + +a { + text-decoration: none; + color: inherit; +} + +ul { + list-style: none; +} + +body { + font-size: 1.3rem; + font-family: 'JetBrains Mono', monospace; + font-variant-ligatures: none; + line-height: 1.6; + color: var(--color-text-base); + background-color: var(--color-background); + overflow-y: scroll; +} + +.page-column-small { + width: 300px; + flex-shrink: 0; +} + +.page-column-full { + width: 100%; + min-width: 0; +} + +.page-columns { + display: flex; + gap: var(--widget-gap); + margin: var(--widget-gap) 0; + animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; +} + +@keyframes pageColumnsEntrance { + from { + opacity: 0; + transform: translateY(10px); + } +} + +.page-loading-container { + margin: 50px auto; + width: fit-content; + animation: loadingContainerEntrance 200ms backwards; + animation-delay: 150ms; + font-size: 2rem; +} + +@keyframes loadingContainerEntrance { + from { + opacity: 0; + } +} + +.loading-icon { + min-width: 1.5em; + width: 1.5em; + height: 1.5em; + border: 0.25em solid hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 12%))); + border-top-color: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%))); + border-radius: 50%; + animation: loadingIconSpin 800ms infinite linear; +} + +@keyframes loadingIconSpin { + to { + transform: rotate(360deg); + } +} + +@keyframes loadingIconSpin { + to { + transform: rotate(360deg); + } +} + +.notice-icon { + width: 0.7rem; + height: 0.7rem; + border-radius: 50%; +} + +.notice-icon-major { + background: var(--color-negative); +} + +.notice-icon-minor { + border: 1px solid var(--color-negative); +} + +.content-bounds { + max-width: 1600px; + margin-inline: auto; + padding: 0 var(--content-bounds-padding); +} + +.cards-vertical { + flex-direction: column; +} + +.cards-horizontal { + --cards-per-row: 6.5; +} + +.cards-grid { + --cards-per-row: 6; +} + +.cards-horizontal, .cards-vertical, .cards-grid { + --cards-gap: calc(var(--widget-content-vertical-padding) * 0.7); + display: flex; + gap: var(--cards-gap); +} + +.cards-horizontal { + overflow-x: auto; + padding-bottom: 1rem; +} + +.cards-grid { + flex-wrap: wrap; +} + +@container widget (max-width: 1300px) { .cards-horizontal { --cards-per-row: 5.5; } } +@container widget (max-width: 1100px) { .cards-horizontal { --cards-per-row: 4.5; } } +@container widget (max-width: 850px) { .cards-horizontal { --cards-per-row: 3.5; } } +@container widget (max-width: 750px) { .cards-horizontal { --cards-per-row: 3.5; } } +@container widget (max-width: 650px) { .cards-horizontal { --cards-per-row: 2.2; } } + +@container widget (max-width: 1300px) { .cards-grid { --cards-per-row: 5; } } +@container widget (max-width: 1100px) { .cards-grid { --cards-per-row: 4; } } +@container widget (max-width: 850px) { .cards-grid { --cards-per-row: 3; } } +@container widget (max-width: 750px) { .cards-grid { --cards-per-row: 3; } } +@container widget (max-width: 650px) { .cards-grid { --cards-per-row: 2; } } + +.card { + flex-shrink: 0; + width: calc(100% / var(--cards-per-row) - var(--cards-gap) * (var(--cards-per-row) - 1) / var(--cards-per-row)); + display: flex; + flex-direction: column; +} + +.widget-error-header { + display: flex; + align-items: center; + justify-content: space-between; + position: relative; + margin-bottom: 1.8rem; +} + +.widget-error-header::before { + content: ''; + position: absolute; + inset: calc(0rem - (var(--widget-content-vertical-padding) / 2)) calc(0rem - (var(--widget-content-horizontal-padding) / 2)); + background: var(--color-negative); + opacity: 0.05; + border-radius: var(--border-radius); + z-index: -1; +} + +.widget-error-icon { + width: 2.4rem; + height: 2.4rem; + border: 0.2rem solid var(--color-negative); + border-radius: 50%; + text-align: center; + line-height: 2rem; + flex-shrink: 0; + opacity: 0.6; +} + +.widget-error-icon::before { + content: '!'; + color: var(--color-text-highlight); +} + +.widget-content { + container-type: inline-size; + container-name: widget; +} + +.widget-content:not(.widget-content-frameless) { + padding: var(--widget-content-padding); +} + +.widget-content:not(.widget-content-frameless), .widget-content-frame { + background: var(--color-widget-background); + border-radius: var(--border-radius); + border: 1px solid var(--color-widget-content-border); + box-shadow: 0px 3px 0px 0px hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl)) - 0.5%)); +} + +.padding-widget { + padding: var(--widget-content-padding); +} + +.margin-bottom-widget { + margin-bottom: var(--widget-content-vertical-padding); +} + +.padding-block-widget { + padding-block: var(--widget-content-vertical-padding); +} + +.padding-inline-widget { + padding-inline: var(--widget-content-horizontal-padding); +} + +.widget-header { + padding: 0 calc(var(--widget-content-horizontal-padding) + 1px); + font-size: var(--font-size-h4); + margin-bottom: 1rem; + display: flex; + align-items: center; + gap: 1rem; +} + +.widget + .widget { + margin-top: var(--widget-gap); +} + +.list-horizontal-text { + display: flex; + list-style: none; + flex-wrap: wrap; + align-items: center; +} + +.list-horizontal-text > *:not(:last-child)::after { + content: '•'; + color: var(--color-text-subdue); + margin: 0 0.5rem; + position: relative; + top: 0.1rem; +} + +.header-container { + margin-top: calc(var(--widget-gap) / 2); + --header-height: 45px; + --header-items-gap: 2.5rem; +} + +.header { + display: flex; + height: var(--header-height); + gap: var(--header-items-gap); +} + +.logo { + height: 100%; + line-height: var(--header-height); + font-size: 2rem; + color: var(--color-text-highlight); + border-right: 1px solid var(--color-widget-content-border); + padding-right: var(--widget-content-horizontal-padding); +} + +.nav { + height: 100%; + gap: var(--header-items-gap); +} + +.nav .nav-item { + line-height: var(--header-height); +} + +.footer { + margin-block: calc(var(--widget-gap) * 1.5); + animation: loadingContainerEntrance 200ms backwards; + animation-delay: 150ms; +} + +.mobile-navigation { + display: none; +} + +.nav-item { + display: block; + height: 100%; + border-bottom: 2px solid transparent; + transition: color .3s, border-color .3s; + font-size: var(--font-size-h3); +} + +.nav-item:not(.nav-item-current):hover { + border-bottom-color: var(--color-text-subdue); + color: var(--color-text-highlight); +} + +.nav-item.nav-item-current { + border-bottom-color: var(--color-primary); + color: var(--color-text-highlight); +} + +.stock-chart { + margin-left: auto; + width: 6.5rem; +} + +.stock-values { + min-width: 8rem; +} + +.carousel-container { + position: relative; +} + +.carousel-container::before, .carousel-container::after { + content: ''; + position: absolute; + width: 2rem; + top: 0; + bottom: 1rem; + z-index: 10; + opacity: 0; + pointer-events: none; + transition-duration: 0.2s; +} + +.carousel-container::before { + left: 0; + background: linear-gradient(to right, var(--color-background), transparent); +} + +.carousel-container::after { + right: 0; + background: linear-gradient(to left, var(--color-background), transparent); +} + +.carousel-container.show-left-cutoff::before, .carousel-container.show-right-cutoff::after { + opacity: 1; +} + +.video-thumbnail { + width: 100%; + aspect-ratio: 16 / 9; + object-fit: cover; + border-radius: var(--border-radius) var(--border-radius) 0 0; +} + +.video-title { + margin-bottom: auto; + overflow: hidden; + display: block; + text-overflow: ellipsis; + -webkit-line-clamp: 2; + display: -webkit-box; + -webkit-box-orient: vertical; +} + +.forum-post-list-item { + display: flex; + gap: 1.2rem; +} + +.forum-post-list-thumbnail { + flex-shrink: 0; + width: 6rem; + height: 4.1rem; + border-radius: var(--border-radius); + object-fit: cover; + border: 1px solid var(--color-separator); + margin-top: 0.1rem; +} + +.bookmarks-group { + --bookmarks-group-color: var(--color-primary); +} + +.bookmarks-group-title { + color: var(--bookmarks-group-color); +} + +.bookmarks-group .bookmarks-link::after { + color: var(--bookmarks-group-color); +} + +.bookmarks-icon-container { + margin-block: 0.1rem; + background-color: var(--color-widget-background-highlight); + border-radius: var(--border-radius); + padding: 0.5rem; +} + +.bookmarks-icon { + width: 20px; + height: 20px; + opacity: 0.8; +} + +.simple-icon { + opacity: 0.7; +} + +:root:not(.light-scheme) .simple-icon { + filter: invert(1); +} + +.calendar-day { + width: calc(100% / 7); + text-align: center; + padding: 0.6rem 0; +} + +.calendar-day-today { + border-radius: var(--border-radius); + background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) (var(--bgl)) + 6%))); + color: var(--color-text-highlight); +} + +.weather-column { + position: relative; + display: flex; + align-items: center; + justify-content: end; + flex-direction: column; + width: calc(100% / 12); + padding-top: 3px; + max-width: 3.5rem; +} + +.weather-column-value, .weather-columns:hover .weather-column-value { + font-size: 13px; + color: var(--color-text-highlight); + letter-spacing: -0.1rem; + margin-right: 0.1rem; + position: relative; + margin-bottom: 0.3rem; + opacity: 0; + transform: translateY(0.5rem); + transition: opacity .2s, transform .2s; + user-select: none; +} + +.weather-column-current .weather-column-value, .weather-column:hover .weather-column-value { + opacity: 1; + transform: translateY(0); +} + +.weather-column-value::after { + position: absolute; + content: '°'; + left: 100%; + color: var(--color-text-subdue); +} + +.weather-column-value.weather-column-value-negative::before { + position: absolute; + content: '-'; + right: 100%; +} + +.weather-bar, .weather-columns:hover .weather-bar { + height: calc(20px + var(--weather-bar-height) * 40px); + width: 6px; + background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 18%))); + border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 24%))); + border-bottom: 0; + border-radius: 6px 6px 0 0; + mask-image: linear-gradient(0deg, transparent 0, #000 10px); + -webkit-mask-image: linear-gradient(0deg, transparent 0, #000 10px); + transition: background-color .2s, border-color .2s, width .2s; +} + +.weather-column-current .weather-bar, .weather-column:hover .weather-bar { + width: 10px; + background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%))); + border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 50%))); +} + +.weather-column-rain { + position: absolute; + inset: 0; + bottom: 20%; + overflow: hidden; + mask-image: linear-gradient(0deg, transparent 40%, #000); + -webkit-mask-image: linear-gradient(0deg, transparent 40%, #000); + z-index: -1; +} + +.weather-column-rain::before { + content: ''; + position: absolute; + /* TODO: figure out a way to make it look continuous between columns, right now + depending on the width of the page the rain inside two columns next to each other + can overlap and look bad */ + background: radial-gradient(circle at 4px 4px, hsl(200, 90%, 70%, 0.4) 1px, transparent 0); + background-size: 8px 8px; + transform: rotate(45deg) translate(-50%, 25%); + height: 130%; + aspect-ratio: 1; + left: 55%; +} + +.weather-column:nth-child(3) .weather-column-time, +.weather-column:nth-child(7) .weather-column-time, +.weather-column:nth-child(11) .weather-column-time { + opacity: 1; + transform: translateY(0); +} + +.weather-column-time, .weather-columns:hover .weather-column-time { + margin-top: 0.3rem; + font-size: var(--font-size-h6); + opacity: 0; + transform: translateY(-0.5rem); + transition: opacity .2s, transform .2s; + user-select: none; +} + +.weather-column:hover .weather-column-time { + opacity: 1; + transform: translateY(0); +} + +.weather-column-daylight { + position: absolute; + inset: 0; + background: linear-gradient(0deg, transparent 30px, hsl(50, 50%, 30%, 0.2)); +} + +.weather-column-daylight-sunrise { + border-radius: 20px 0 0 0; +} + +.weather-column-daylight-sunset { + border-radius: 0 20px 0 0; +} + +.location-icon { + width: 0.8em; + height: 0.8em; + border-radius: 0 50% 50% 50%; + background-color: currentColor; + transform: rotate(225deg) translate(.1em, .1em); + position: relative; + flex-shrink: 0; +} + +.location-icon::after { + content: ''; + position: absolute; + z-index: 2; + width: .4em; + height: .4em; + border-radius: 50%; + background-color: var(--color-widget-background); + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} + +.monitor-site-icon { + display: block; + opacity: 0.8; + filter: grayscale(0.4); + object-fit: contain; + aspect-ratio: 1 / 1; + width: 3.2rem; + position: relative; + top: -0.1rem; + transition: filter 0.3s, opacity 0.3s; +} + +.monitor-site:hover .monitor-site-icon { + filter: grayscale(0); + opacity: 1; +} + +.monitor-site-status-icon { + margin-left: auto; + width: 2rem; + height: 2rem; +} + +.thumbnail { + filter: grayscale(0.2) contrast(0.9); + transition: all 0.2s; + opacity: 0.8; +} + +.thumbnail-container:hover .thumbnail { + opacity: 1; + filter: none; +} + +.rss-card-image { + height: 10rem; + object-fit: cover; + border-radius: var(--border-radius) var(--border-radius) 0 0; +} + +.twitch-category-thumbnail { + width: 5rem; + border-radius: var(--border-radius); +} + +.twitch-channel-avatar { + aspect-ratio: 1; + border-radius: 50%; +} + +.twitch-channel-avatar-container { + width: 4.4rem; + height: 4.4rem; + border: 2px solid var(--color-text-subdue); + padding: 2px; + border-radius: 50%; + position: relative; + flex-shrink: 0; +} + +.twitch-channel-live .twitch-channel-avatar-container { + border: 2px solid var(--color-positive); + margin-bottom: 1rem; +} + +.twitch-channel-live .twitch-channel-avatar-container::after { + content: 'LIVE'; + position: absolute; + background: var(--color-positive); + color: var(--color-widget-background); + font-size: var(--font-size-h6); + left: 50%; + bottom: -35%; + border-radius: var(--border-radius); + padding-inline: 0.3rem; + transform: translate(-50%); + border: 2px solid var(--color-widget-background); +} + +.reddit-card-thumbnail { + width: 100%; + height: 100%; + object-fit: cover; + object-position: 0% 20%; + opacity: 0.15; + filter: blur(1px); +} + +.reddit-card-thumbnail-container { + position: absolute; + inset: 0; + overflow: hidden; + border-radius: var(--border-radius); +} + +.reddit-card-thumbnail-container::after { + content: ''; + position: absolute; + inset: 0; + background: linear-gradient(0deg, var(--color-widget-background) 10%, transparent); +} + +@media (max-width: 1190px) { + .header-container { + display: none; + } + + .page-column-full .size-title-dynamic { + font-size: var(--font-size-h3); + } + + .page-column-small { + width: 100%; + flex-shrink: 1; + } + + .page-column { + display: none; + animation: columnEntrance 0s cubic-bezier(0.25, 1, 0.5, 1) backwards; + } + + .animate-element-transition .page-column { + animation-duration: .3s; + } + + @keyframes columnEntrance { + from { + opacity: 0; + transform: scaleX(0.95); + } + } + + body { + padding-bottom: calc(var(--mobile-navigation-height) + var(--content-bounds-padding)); + } + + .mobile-navigation { + display: block; + position: fixed; + bottom: 0; + transform: translateY(calc(100% - var(--mobile-navigation-height))); + left: var(--content-bounds-padding); + right: var(--content-bounds-padding); + z-index: 10; + background-color: var(--color-widget-background); + border: 1px solid var(--color-widget-content-border); + border-bottom: 0; + border-radius: var(--border-radius) var(--border-radius) 0 0; + transition: transform .3s; + } + + .mobile-navigation:has(.mobile-navigation-page-links-input:checked) .hamburger-icon { + --spacing: 7px; + color: var(--color-primary); + height: 2px; + } + + .mobile-navigation:has(.mobile-navigation-page-links-input:checked) { + transform: translateY(0); + } + + .mobile-navigation-page-links { + border-top: 1px solid var(--color-widget-content-border); + padding: 15px var(--content-bounds-padding); + display: flex; + align-items: center; + overflow-x: scroll; + gap: 2.5rem; + } + + .mobile-navigation-icons { + display: flex; + justify-content: space-around; + align-items: center; + } + + body:has(.mobile-navigation-input[value="0"]:checked) .page-columns > :nth-child(1), + body:has(.mobile-navigation-input[value="1"]:checked) .page-columns > :nth-child(2), + body:has(.mobile-navigation-input[value="2"]:checked) .page-columns > :nth-child(3) { + display: block; + } + + .mobile-navigation-label { + display: flex; + flex: 1; + max-width: 50px; + height: var(--mobile-navigation-height); + justify-content: center; + align-items: center; + cursor: pointer; + font-size: 15px; + line-height: var(--mobile-navigation-height); + } + + .mobile-navigation-pill { + display: block; + background: var(--color-text-base); + height: 10px; + width: 10px; + border-radius: 10px; + transition: width .3s, background-color .3s; + } + + .mobile-navigation-label:hover > .mobile-navigation-pill { + background-color: var(--color-text-highlight); + } + + .mobile-navigation-label:hover { + color: var(--color-text-highlight); + } + + .mobile-navigation-input:checked + .mobile-navigation-pill { + background: var(--color-primary); + width: 30px; + } + + .mobile-navigation-input, .mobile-navigation-page-links-input { + display: none; + } + + .hamburger-icon { + --spacing: 4px; + width: 1em; + height: 1px; + background-color: currentColor; + transition: color .3s, box-shadow .3s; + box-shadow: 0 calc(var(--spacing) * -1) 0 0 currentColor, 0 var(--spacing) 0 0 currentColor; + } + + .list-collapsible-label:has(.list-collapsible-input:checked) { + bottom: var(--mobile-navigation-height); + } +} + +@media (max-width: 550px) { + :root { + font-size: 9px; + --widget-gap: 15px; + --widget-content-vertical-padding: 10px; + --widget-content-horizontal-padding: 10px; + --content-bounds-padding: 10px; + } + + .forum-post-list-item { + flex-flow: row-reverse; + } + + .hide-on-mobile { + display: none + } +} + +.size-h1 { font-size: var(--font-size-h1); } +.size-h2 { font-size: var(--font-size-h2); } +.size-h3 { font-size: var(--font-size-h3); } +.size-h4 { font-size: var(--font-size-h4); } +.size-base { font-size: var(--font-size-base); } +.size-h5 { font-size: var(--font-size-h5); } +.size-h6 { font-size: var(--font-size-h6); } + +.color-highlight { color: var(--color-text-highlight); } +.color-base { color: var(--color-text-base); } +.color-subdue { color: var(--color-text-subdue); } +.color-negative { color: var(--color-negative); } +.color-positive { color: var(--color-positive); } +.color-primary { color: var(--color-primary); } + +.break-all { word-break: break-all; } +.text-left { text-align: left; } +.text-right { text-align: right; } +.text-center { text-align: center; } +.rtl { direction: rtl; } +.shrink { flex-shrink: 1; } +.shrink-0 { flex-shrink: 0; } +.min-width-0 { min-width: 0; } +.block { display: block; } +.overflow-hidden { overflow: hidden; } +.relative { position: relative; } +.flex { display: flex; } +.flex-wrap { flex-wrap: wrap; } +.flex-nowrap { flex-wrap: nowrap; } +.justify-between { justify-content: space-between; } +.justify-stretch { justify-content: stretch; } +.justify-center { justify-content: center; } +.justify-end { justify-content: end; } +.uppercase { text-transform: uppercase; } +.grow { flex-grow: 1; } +.flex-column { flex-direction: column; } +.items-center { align-items: center; } +.items-start { align-items: start; } +.gap-5 { gap: 0.5rem; } +.gap-7 { gap: 0.7rem; } +.gap-10 { gap: 1rem; } +.gap-15 { gap: 1.5rem; } +.margin-top-3 { margin-top: 0.3rem; } +.margin-top-5 { margin-top: 0.5rem; } +.margin-top-7 { margin-top: 0.7rem; } +.margin-top-10 { margin-top: 1rem; } +.margin-top-15 { margin-top: 1.5rem; } +.margin-bottom-3 { margin-bottom: 0.3rem; } +.margin-bottom-5 { margin-bottom: 0.5rem; } +.margin-bottom-7 { margin-bottom: 0.7rem; } +.margin-bottom-10 { margin-bottom: 1rem; } +.margin-bottom-15 { margin-bottom: 1.5rem; } +.margin-bottom-auto { margin-bottom: auto; } diff --git a/internal/assets/static/main.js b/internal/assets/static/main.js new file mode 100644 index 0000000..3a6ec0b --- /dev/null +++ b/internal/assets/static/main.js @@ -0,0 +1,163 @@ +function throttledDebounce(callback, maxDebounceTimes, debounceDelay) { + let debounceTimeout; + let timesDebounced = 0; + + return function () { + if (timesDebounced == maxDebounceTimes) { + clearTimeout(debounceTimeout); + timesDebounced = 0; + callback(); + return; + } + + clearTimeout(debounceTimeout); + timesDebounced++; + + debounceTimeout = setTimeout(() => { + timesDebounced = 0; + callback(); + }, debounceDelay); + }; +}; + + +async function fetchPageContents (pageSlug) { + // TODO: handle non 200 status codes/time outs + // TODO: add retries + const response = await fetch(`/api/pages/${pageSlug}/content/`); + const content = await response.text(); + + return content; +} + +function setupCarousels() { + const carouselElements = document.getElementsByClassName("carousel-container"); + + for (let i = 0; i < carouselElements.length; i++) { + const carousel = carouselElements[i]; + const itemsContainer = carousel.getElementsByClassName("carousel-items-container")[0]; + + const determineSideCutoffs = () => { + if (itemsContainer.scrollLeft != 0) { + carousel.classList.add("show-left-cutoff"); + } else { + carousel.classList.remove("show-left-cutoff"); + } + + if (Math.ceil(itemsContainer.scrollLeft) + itemsContainer.clientWidth < itemsContainer.scrollWidth) { + carousel.classList.add("show-right-cutoff"); + } else { + carousel.classList.remove("show-right-cutoff"); + } + } + + const determineSideCutoffsRateLimited = throttledDebounce(determineSideCutoffs, 20, 100); + + itemsContainer.addEventListener("scroll", determineSideCutoffsRateLimited); + document.addEventListener("resize", determineSideCutoffsRateLimited); + + determineSideCutoffs(); + } +} + +const minuteInSeconds = 60; +const hourInSeconds = minuteInSeconds * 60; +const dayInSeconds = hourInSeconds * 24; +const monthInSeconds = dayInSeconds * 30; +const yearInSeconds = monthInSeconds * 12; + +function relativeTimeSince(timestamp) { + const delta = Math.round((Date.now() / 1000) - timestamp); + + if (delta < minuteInSeconds) { + return "1m"; + } + if (delta < hourInSeconds) { + return Math.floor(delta / minuteInSeconds) + "m"; + } + if (delta < dayInSeconds) { + return Math.floor(delta / hourInSeconds) + "h"; + } + if (delta < monthInSeconds) { + return Math.floor(delta / dayInSeconds) + "d"; + } + if (delta < yearInSeconds) { + return Math.floor(delta / monthInSeconds) + "mo"; + } + + return Math.floor(delta / yearInSeconds) + "y"; +} + +function updateRelativeTimeForElements(elements) +{ + for (let i = 0; i < elements.length; i++) + { + const element = elements[i]; + const timestamp = element.dataset.dynamicRelativeTime; + + if (timestamp === undefined) + continue + + element.innerText = relativeTimeSince(timestamp); + } +} + +function setupDynamicRelativeTime() { + const elements = document.querySelectorAll("[data-dynamic-relative-time]"); + const updateInterval = 60 * 1000; + let lastUpdateTime = Date.now(); + + const updateElementsAndTimestamp = () => { + updateRelativeTimeForElements(elements); + lastUpdateTime = Date.now(); + }; + + const scheduleRepeatingUpdate = () => setInterval(updateElementsAndTimestamp, updateInterval); + + if (document.hidden === undefined) { + scheduleRepeatingUpdate(); + return; + } + + let timeout = scheduleRepeatingUpdate(); + + document.addEventListener("visibilitychange", () => { + if (document.hidden) { + clearTimeout(timeout); + return; + } + + const delta = Date.now() - lastUpdateTime; + + if (delta >= updateInterval) { + updateElementsAndTimestamp(); + timeout = scheduleRepeatingUpdate(); + return; + } + + timeout = setTimeout(() => { + updateElementsAndTimestamp(); + timeout = scheduleRepeatingUpdate(); + }, updateInterval - delta); + }); +} + +async function setupPage() { + const pageElement = document.getElementById("page"); + const pageContents = await fetchPageContents(pageData.slug); + + pageElement.innerHTML = pageContents; + + setTimeout(() => { + document.body.classList.add("animate-element-transition"); + }, 150); + + setupCarousels(); + setupDynamicRelativeTime(); +} + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", setupPage); +} else { + setupPage(); +} diff --git a/internal/assets/templates.go b/internal/assets/templates.go new file mode 100644 index 0000000..fe82ed5 --- /dev/null +++ b/internal/assets/templates.go @@ -0,0 +1,112 @@ +package assets + +import ( + "fmt" + "html/template" + "math" + "strconv" + "time" + + "golang.org/x/text/language" + "golang.org/x/text/message" +) + +var ( + PageTemplate = compileTemplate("page.html", "document.html", "page-style-overrides.gotmpl") + PageContentTemplate = compileTemplate("content.html") + CalendarTemplate = compileTemplate("calendar.html", "widget-base.html") + BookmarksTemplate = compileTemplate("bookmarks.html", "widget-base.html") + IFrameTemplate = compileTemplate("iframe.html", "widget-base.html") + WeatherTemplate = compileTemplate("weather.html", "widget-base.html") + ForumPostsTemplate = compileTemplate("forum-posts.html", "widget-base.html") + RedditCardsHorizontalTemplate = compileTemplate("reddit-horizontal-cards.html", "widget-base.html") + RedditCardsVerticalTemplate = compileTemplate("reddit-vertical-cards.html", "widget-base.html") + ReleasesTemplate = compileTemplate("releases.html", "widget-base.html") + VideosTemplate = compileTemplate("videos.html", "widget-base.html") + StocksTemplate = compileTemplate("stocks.html", "widget-base.html") + RSSListTemplate = compileTemplate("rss-list.html", "widget-base.html") + RSSCardsTemplate = compileTemplate("rss-cards.html", "widget-base.html") + MonitorTemplate = compileTemplate("monitor.html", "widget-base.html") + TwitchGamesListTemplate = compileTemplate("twitch-games-list.html", "widget-base.html") + TwitchChannelsTemplate = compileTemplate("twitch-channels.html", "widget-base.html") +) + +var globalTemplateFunctions = template.FuncMap{ + "relativeTime": relativeTimeSince, + "formatViewerCount": formatViewerCount, + "formatNumber": intl.Sprint, + "absInt": func(i int) int { + return int(math.Abs(float64(i))) + }, + "formatPrice": func(price float64) string { + return intl.Sprintf("%.2f", price) + }, + "formatTime": func(t time.Time) string { + return t.Format("2006-01-02 15:04:05") + }, + "shouldCollapse": func(i int, collapseAfter int) bool { + if collapseAfter < -1 { + return false + } + + return i >= collapseAfter + }, + "itemAnimationDelay": func(i int, collapseAfter int) string { + return fmt.Sprintf("%dms", (i-collapseAfter)*30) + }, + "dynamicRelativeTimeAttrs": func(t time.Time) template.HTMLAttr { + return template.HTMLAttr(fmt.Sprintf(`data-dynamic-relative-time="%d"`, t.Unix())) + }, +} + +func compileTemplate(primary string, dependencies ...string) *template.Template { + t, err := template.New(primary). + Funcs(globalTemplateFunctions). + ParseFS(TemplateFS, append([]string{primary}, dependencies...)...) + + if err != nil { + panic(err) + } + + return t +} + +var intl = message.NewPrinter(language.English) + +func formatViewerCount(count int) string { + if count < 1_000 { + return strconv.Itoa(count) + } + + if count < 10_000 { + return fmt.Sprintf("%.1fk", float64(count)/1_000) + } + + if count < 1_000_000 { + return fmt.Sprintf("%dk", count/1_000) + } + + return fmt.Sprintf("%.1fm", float64(count)/1_000_000) +} + +func relativeTimeSince(t time.Time) string { + delta := time.Since(t) + + if delta < time.Minute { + return "1m" + } + if delta < time.Hour { + return fmt.Sprintf("%dm", delta/time.Minute) + } + if delta < 24*time.Hour { + return fmt.Sprintf("%dh", delta/time.Hour) + } + if delta < 30*24*time.Hour { + return fmt.Sprintf("%dd", delta/(24*time.Hour)) + } + if delta < 12*30*24*time.Hour { + return fmt.Sprintf("%dmo", delta/(30*24*time.Hour)) + } + + return fmt.Sprintf("%dy", delta/(365*24*time.Hour)) +} diff --git a/internal/assets/templates/bookmarks.html b/internal/assets/templates/bookmarks.html new file mode 100644 index 0000000..068ab4d --- /dev/null +++ b/internal/assets/templates/bookmarks.html @@ -0,0 +1,23 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} + +{{ end }} diff --git a/internal/assets/templates/calendar.html b/internal/assets/templates/calendar.html new file mode 100644 index 0000000..68fda83 --- /dev/null +++ b/internal/assets/templates/calendar.html @@ -0,0 +1,27 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
+
{{ .Calendar.CurrentMonthName }}
+
    +
  • Week {{ .Calendar.CurrentWeekNumber }}
  • +
  • {{ .Calendar.CurrentYear }}
  • +
+
+ +
+
Mo
+
Tu
+
We
+
Th
+
Fr
+
Sa
+
Su
+
+ +
+ {{ range .Calendar.Days }} +
{{ . }}
+ {{ end }} +
+{{ end }} diff --git a/internal/glance/templates/page-content.html b/internal/assets/templates/content.html similarity index 66% rename from internal/glance/templates/page-content.html rename to internal/assets/templates/content.html index c59d6e1..845507f 100644 --- a/internal/glance/templates/page-content.html +++ b/internal/assets/templates/content.html @@ -1,7 +1,3 @@ -{{ if .Page.ShowMobileHeader }} -
{{ .Page.Title }}
-{{ end }} -
{{ range .Page.Columns }}
diff --git a/internal/assets/templates/document.html b/internal/assets/templates/document.html new file mode 100644 index 0000000..04984f8 --- /dev/null +++ b/internal/assets/templates/document.html @@ -0,0 +1,17 @@ + + + + {{ block "document-head-before" . }}{{ end }} + {{ block "document-title" . }}{{ end }} + + + + + + + {{ block "document-head-after" . }}{{ end }} + + +{{ template "document-body" . }} + + diff --git a/internal/assets/templates/forum-posts.html b/internal/assets/templates/forum-posts.html new file mode 100644 index 0000000..32f7076 --- /dev/null +++ b/internal/assets/templates/forum-posts.html @@ -0,0 +1,39 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $post := .Posts }} +
  • +
    + {{ if $.ShowThumbnails }} + {{ if ne $post.ThumbnailUrl "" }} + + {{ else if $post.HasTargetUrl }} + + + + {{ else }} + + + + {{ end }} + {{ end }} +
    + {{ .Title }} +
      +
    • {{ $post.TimePosted | relativeTime }}
    • +
    • {{ $post.Score | formatNumber }} points
    • +
    • {{ $post.CommentCount | formatNumber }} comments
    • + {{ if $post.HasTargetUrl }} +
    • {{ $post.TargetUrlDomain }}
    • + {{ end }} +
    +
    +
    +
  • + {{ end }} +
+{{ if gt (len .Posts) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/glance/templates/iframe.html b/internal/assets/templates/iframe.html similarity index 100% rename from internal/glance/templates/iframe.html rename to internal/assets/templates/iframe.html diff --git a/internal/assets/templates/monitor.html b/internal/assets/templates/monitor.html new file mode 100644 index 0000000..fa97302 --- /dev/null +++ b/internal/assets/templates/monitor.html @@ -0,0 +1,39 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range .Sites }} +
  • + {{ if .IconUrl }} + + {{ end }} +
    + {{ .Title }} +
      + {{ if not .Status.Error }} +
    • {{ .StatusText }}
    • +
    • {{ .Status.ResponseTime.Milliseconds | formatNumber }}ms
    • + {{ else if .Status.TimedOut }} +
    • Timed Out
    • + {{ else }} +
    • ERROR
    • + {{ end }} +
    +
    + {{ if eq .StatusStyle "good" }} +
    + + + +
    + {{ else }} +
    + + + +
    + {{ end }} +
  • + {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/page-style-overrides.gotmpl b/internal/assets/templates/page-style-overrides.gotmpl new file mode 100644 index 0000000..0bf2a99 --- /dev/null +++ b/internal/assets/templates/page-style-overrides.gotmpl @@ -0,0 +1,14 @@ + diff --git a/internal/assets/templates/page.html b/internal/assets/templates/page.html new file mode 100644 index 0000000..61fad9e --- /dev/null +++ b/internal/assets/templates/page.html @@ -0,0 +1,69 @@ +{{ template "document.html" . }} + +{{ define "document-title" }}{{ .Page.Title }} - Glance{{ end }} + +{{ define "document-head-before" }} + +{{ end }} + +{{ define "document-root-attrs" }}{{ if .App.Config.Theme.Light }}class="light-scheme"{{ end }}{{ end }} +{{ define "document-head-after" }} +{{ template "page-style-overrides.gotmpl" . }} +{{ if ne "" .App.Config.Theme.CustomCSSFile }} + +{{ end }} +{{ end }} + +{{ define "navigation-links" }} +{{ range .App.Config.Pages }} +{{ .Title }} +{{ end }} +{{ end }} + +{{ define "document-body" }} +
+
+ + + +
+
+ +
+
+ + {{ range $i, $column := .Page.Columns }} + + {{ end }} + +
+ +
+ +
+
+
+ +
+
+
+
+ + +{{ end }} diff --git a/internal/glance/templates/reddit-horizontal-cards.html b/internal/assets/templates/reddit-horizontal-cards.html similarity index 73% rename from internal/glance/templates/reddit-horizontal-cards.html rename to internal/assets/templates/reddit-horizontal-cards.html index 9ee31b3..4159bcc 100644 --- a/internal/glance/templates/reddit-horizontal-cards.html +++ b/internal/assets/templates/reddit-horizontal-cards.html @@ -18,10 +18,10 @@ {{ else }}
/r/{{ $.Subreddit }}
{{ end }} - {{ .Title }} + {{ .Title }}
    -
  • -
  • {{ .Score | formatApproxNumber }} points
  • +
  • {{ .TimePosted | relativeTime }}
  • +
  • {{ .Score | formatNumber }} points
diff --git a/internal/glance/templates/reddit-vertical-cards.html b/internal/assets/templates/reddit-vertical-cards.html similarity index 71% rename from internal/glance/templates/reddit-vertical-cards.html rename to internal/assets/templates/reddit-vertical-cards.html index 747cc7e..1ca0996 100644 --- a/internal/glance/templates/reddit-vertical-cards.html +++ b/internal/assets/templates/reddit-vertical-cards.html @@ -17,10 +17,10 @@ {{ else }}
/r/{{ $.Subreddit }}
{{ end }} - {{ .Title }} + {{ .Title }} diff --git a/internal/assets/templates/releases.html b/internal/assets/templates/releases.html new file mode 100644 index 0000000..2600dc2 --- /dev/null +++ b/internal/assets/templates/releases.html @@ -0,0 +1,21 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} + +{{ if gt (len .Releases) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/glance/templates/rss-horizontal-cards.html b/internal/assets/templates/rss-cards.html similarity index 63% rename from internal/glance/templates/rss-horizontal-cards.html rename to internal/assets/templates/rss-cards.html index d8eef92..75ffa5e 100644 --- a/internal/glance/templates/rss-horizontal-cards.html +++ b/internal/assets/templates/rss-cards.html @@ -3,11 +3,10 @@ {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} -{{ if gt (len .Items) 0 }} - -{{- end }} -{{- end }} diff --git a/internal/glance/templates/split-column.html b/internal/glance/templates/split-column.html deleted file mode 100644 index 63b4aea..0000000 --- a/internal/glance/templates/split-column.html +++ /dev/null @@ -1,11 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content-classes" }}widget-content-frameless{{ end }} - -{{ define "widget-content" }} -
-{{ range .Widgets }} - {{ .Render }} -{{ end }} -
-{{ end }} diff --git a/internal/glance/templates/theme-style.gotmpl b/internal/glance/templates/theme-style.gotmpl deleted file mode 100644 index 878ca0b..0000000 --- a/internal/glance/templates/theme-style.gotmpl +++ /dev/null @@ -1,14 +0,0 @@ - diff --git a/internal/glance/templates/twitch-channels.html b/internal/glance/templates/twitch-channels.html deleted file mode 100644 index 021a17a..0000000 --- a/internal/glance/templates/twitch-channels.html +++ /dev/null @@ -1,47 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content" }} - -{{ end }} diff --git a/internal/glance/templates/twitch-games-list.html b/internal/glance/templates/twitch-games-list.html deleted file mode 100644 index 94fc400..0000000 --- a/internal/glance/templates/twitch-games-list.html +++ /dev/null @@ -1,31 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content" }} - -{{ end }} diff --git a/internal/glance/templates/v0.7-update-notice-page.html b/internal/glance/templates/v0.7-update-notice-page.html deleted file mode 100644 index fa976fb..0000000 --- a/internal/glance/templates/v0.7-update-notice-page.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - Update notice - - - - -
-

UPDATE NOTICE

-
-

- The default location of glance.yml in the Docker image has - changed since v0.7.0, please see the migration guide - for instructions or visit the release notes - to find out more about why this change was necessary. Sorry for the inconvenience. -

- -

Migration should take around 5 minutes.

-
-
- - - diff --git a/internal/glance/templates/video-card-contents.html b/internal/glance/templates/video-card-contents.html deleted file mode 100644 index c6340c5..0000000 --- a/internal/glance/templates/video-card-contents.html +++ /dev/null @@ -1,12 +0,0 @@ -{{ define "video-card-contents" }} - -
- {{ .Title }} - -
-{{ end }} diff --git a/internal/glance/templates/videos-grid.html b/internal/glance/templates/videos-grid.html deleted file mode 100644 index 2819fe8..0000000 --- a/internal/glance/templates/videos-grid.html +++ /dev/null @@ -1,13 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content-classes" }}widget-content-frameless{{ end }} - -{{ define "widget-content" }} -
- {{ range .Videos }} -
- {{ template "video-card-contents" . }} -
- {{ end }} -
-{{ end }} diff --git a/internal/glance/templates/videos-vertical-list.html b/internal/glance/templates/videos-vertical-list.html deleted file mode 100644 index a735a74..0000000 --- a/internal/glance/templates/videos-vertical-list.html +++ /dev/null @@ -1,20 +0,0 @@ -{{ template "widget-base.html" . }} - -{{- define "widget-content" }} - -{{- end }} diff --git a/internal/glance/templates/videos.html b/internal/glance/templates/videos.html deleted file mode 100644 index 16e7261..0000000 --- a/internal/glance/templates/videos.html +++ /dev/null @@ -1,15 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content-classes" }}widget-content-frameless{{ end }} - -{{ define "widget-content" }} - -{{ end }} diff --git a/internal/glance/templates/weather.html b/internal/glance/templates/weather.html deleted file mode 100644 index f271b74..0000000 --- a/internal/glance/templates/weather.html +++ /dev/null @@ -1,31 +0,0 @@ -{{ template "widget-base.html" . }} - -{{ define "widget-content" }} -
-
{{ .Weather.WeatherCodeAsString }}
-
Feels like {{ .Weather.ApparentTemperature }}°{{ if eq .Units "metric" }}C{{ else }}F{{ end }}
- -
- {{ range $i, $column := .Weather.Columns }} -
- {{ if $column.HasPrecipitation }} -
- {{ end }} - {{ if and (ge $i $.Weather.SunriseColumn) (le $i $.Weather.SunsetColumn ) }} -
- {{ end }} -
{{ $column.Temperature | absInt }}
-
-
{{ index $.TimeLabels $i }}
-
- {{ end }} -
- - {{ if not .HideLocation }} -
-
-
{{ .Place.Name }},{{ if .ShowAreaName }} {{ .Place.Area }},{{ end }} {{ .Place.Country }}
-
- {{ end }} -
-{{ end }} diff --git a/internal/glance/templates/widget-base.html b/internal/glance/templates/widget-base.html deleted file mode 100644 index b6fd9bc..0000000 --- a/internal/glance/templates/widget-base.html +++ /dev/null @@ -1,41 +0,0 @@ -
- {{- if not .HideHeader}} -
- {{- if ne "" .TitleURL }} -

{{ .Title }}

- {{- else }} -

{{ .Title }}

- {{- end }} - {{- if .IsWIP }} -
-
-

WORK IN PROGRESS

-

This widget is still in development, certain features may not work as expected or may change drastically.

- Report issue -
- - - -
- {{- end }} - {{- if and .Error .ContentAvailable }} -
- {{- else if .Notice }} -
- {{- end }} -
- {{- end }} -
- {{- if .ContentAvailable }} - {{ block "widget-content" . }}{{ end }} - {{- else }} -
-
ERROR
- - - -
-

{{ if .Error }}{{ .Error }}{{ else }}No error information provided{{ end }}

- {{- end}} -
-
diff --git a/internal/glance/utils.go b/internal/glance/utils.go deleted file mode 100644 index a614bda..0000000 --- a/internal/glance/utils.go +++ /dev/null @@ -1,184 +0,0 @@ -package glance - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "net/url" - "os" - "regexp" - "slices" - "strings" - "time" -) - -var sequentialWhitespacePattern = regexp.MustCompile(`\s+`) - -func percentChange(current, previous float64) float64 { - return (current/previous - 1) * 100 -} - -func extractDomainFromUrl(u string) string { - if u == "" { - return "" - } - - parsed, err := url.Parse(u) - if err != nil { - return "" - } - - return strings.TrimPrefix(strings.ToLower(parsed.Host), "www.") -} - -func svgPolylineCoordsFromYValues(width float64, height float64, values []float64) string { - if len(values) < 2 { - return "" - } - - verticalPadding := height * 0.02 - height -= verticalPadding * 2 - coordinates := make([]string, len(values)) - distanceBetweenPoints := width / float64(len(values)-1) - min := slices.Min(values) - max := slices.Max(values) - - for i := range values { - coordinates[i] = fmt.Sprintf( - "%.2f,%.2f", - float64(i)*distanceBetweenPoints, - ((max-values[i])/(max-min))*height+verticalPadding, - ) - } - - return strings.Join(coordinates, " ") -} - -func maybeCopySliceWithoutZeroValues[T int | float64](values []T) []T { - if len(values) == 0 { - return values - } - - for i := range values { - if values[i] != 0 { - continue - } - - c := make([]T, 0, len(values)-1) - - for i := range values { - if values[i] != 0 { - c = append(c, values[i]) - } - } - - return c - } - - return values -} - -var urlSchemePattern = regexp.MustCompile(`^[a-z]+:\/\/`) - -func stripURLScheme(url string) string { - return urlSchemePattern.ReplaceAllString(url, "") -} - -func isRunningInsideDockerContainer() bool { - _, err := os.Stat("/.dockerenv") - return err == nil -} - -func prefixStringLines(prefix string, s string) string { - lines := strings.Split(s, "\n") - - for i, line := range lines { - lines[i] = prefix + line - } - - return strings.Join(lines, "\n") -} - -func limitStringLength(s string, max int) (string, bool) { - asRunes := []rune(s) - - if len(asRunes) > max { - return string(asRunes[:max]), true - } - - return s, false -} - -func parseRFC3339Time(t string) time.Time { - parsed, err := time.Parse(time.RFC3339, t) - if err != nil { - return time.Now() - } - - return parsed -} - -func normalizeVersionFormat(version string) string { - version = strings.ToLower(strings.TrimSpace(version)) - - if len(version) > 0 && version[0] != 'v' { - return "v" + version - } - - return version -} - -func titleToSlug(s string) string { - s = strings.ToLower(s) - s = sequentialWhitespacePattern.ReplaceAllString(s, "-") - s = strings.Trim(s, "-") - - return s -} - -func fileServerWithCache(fs http.FileSystem, cacheDuration time.Duration) http.Handler { - server := http.FileServer(fs) - cacheControlValue := fmt.Sprintf("public, max-age=%d", int(cacheDuration.Seconds())) - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // TODO: fix always setting cache control even if the file doesn't exist - w.Header().Set("Cache-Control", cacheControlValue) - server.ServeHTTP(w, r) - }) -} - -func executeTemplateToHTML(t *template.Template, data interface{}) (template.HTML, error) { - var b bytes.Buffer - - err := t.Execute(&b, data) - if err != nil { - return "", fmt.Errorf("executing template: %w", err) - } - - return template.HTML(b.String()), nil -} - -func stringToBool(s string) bool { - return s == "true" || s == "yes" -} - -func itemAtIndexOrDefault[T any](items []T, index int, def T) T { - if index >= len(items) { - return def - } - - return items[index] -} - -func ternary[T any](condition bool, a, b T) T { - if condition { - return a - } - - 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) {} diff --git a/internal/glance/widget-bookmarks.go b/internal/glance/widget-bookmarks.go deleted file mode 100644 index 4f3d26e..0000000 --- a/internal/glance/widget-bookmarks.go +++ /dev/null @@ -1,76 +0,0 @@ -package glance - -import ( - "html/template" -) - -var bookmarksWidgetTemplate = mustParseTemplate("bookmarks.html", "widget-base.html") - -type bookmarksWidget struct { - widgetBase `yaml:",inline"` - cachedHTML template.HTML `yaml:"-"` - Groups []struct { - Title string `yaml:"title"` - Color *hslColorField `yaml:"color"` - SameTab bool `yaml:"same-tab"` - HideArrow bool `yaml:"hide-arrow"` - Target string `yaml:"target"` - Links []struct { - Title string `yaml:"title"` - URL string `yaml:"url"` - Icon customIconField `yaml:"icon"` - // we need a pointer to bool to know whether a value was provided, - // however there's no way to dereference a pointer in a template so - // {{ if not .SameTab }} would return true for any non-nil pointer - // which leaves us with no way of checking if the value is true or - // false, hence the duplicated fields below - SameTabRaw *bool `yaml:"same-tab"` - SameTab bool `yaml:"-"` - HideArrowRaw *bool `yaml:"hide-arrow"` - HideArrow bool `yaml:"-"` - Target string `yaml:"target"` - } `yaml:"links"` - } `yaml:"groups"` -} - -func (widget *bookmarksWidget) initialize() error { - widget.withTitle("Bookmarks").withError(nil) - - for g := range widget.Groups { - group := &widget.Groups[g] - for l := range group.Links { - link := &group.Links[l] - if link.SameTabRaw == nil { - link.SameTab = group.SameTab - } else { - link.SameTab = *link.SameTabRaw - } - - if link.HideArrowRaw == nil { - link.HideArrow = group.HideArrow - } else { - link.HideArrow = *link.HideArrowRaw - } - - if link.Target == "" { - if group.Target != "" { - link.Target = group.Target - } else { - if link.SameTab { - link.Target = "" - } else { - link.Target = "_blank" - } - } - } - } - } - - widget.cachedHTML = widget.renderTemplate(widget, bookmarksWidgetTemplate) - - return nil -} - -func (widget *bookmarksWidget) Render() template.HTML { - return widget.cachedHTML -} diff --git a/internal/glance/widget-calendar.go b/internal/glance/widget-calendar.go deleted file mode 100644 index 9537e53..0000000 --- a/internal/glance/widget-calendar.go +++ /dev/null @@ -1,45 +0,0 @@ -package glance - -import ( - "errors" - "html/template" - "time" -) - -var calendarWidgetTemplate = mustParseTemplate("calendar.html", "widget-base.html") - -var calendarWeekdaysToInt = map[string]time.Weekday{ - "sunday": time.Sunday, - "monday": time.Monday, - "tuesday": time.Tuesday, - "wednesday": time.Wednesday, - "thursday": time.Thursday, - "friday": time.Friday, - "saturday": time.Saturday, -} - -type calendarWidget struct { - widgetBase `yaml:",inline"` - FirstDayOfWeek string `yaml:"first-day-of-week"` - FirstDay int `yaml:"-"` - cachedHTML template.HTML `yaml:"-"` -} - -func (widget *calendarWidget) initialize() error { - widget.withTitle("Calendar").withError(nil) - - if widget.FirstDayOfWeek == "" { - widget.FirstDayOfWeek = "monday" - } else if _, ok := calendarWeekdaysToInt[widget.FirstDayOfWeek]; !ok { - return errors.New("invalid first day of week") - } - - widget.FirstDay = int(calendarWeekdaysToInt[widget.FirstDayOfWeek]) - widget.cachedHTML = widget.renderTemplate(widget, calendarWidgetTemplate) - - return nil -} - -func (widget *calendarWidget) Render() template.HTML { - return widget.cachedHTML -} diff --git a/internal/glance/widget-changedetection.go b/internal/glance/widget-changedetection.go deleted file mode 100644 index 8ca8803..0000000 --- a/internal/glance/widget-changedetection.go +++ /dev/null @@ -1,197 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html/template" - "log/slog" - "net/http" - "sort" - "strings" - "time" -) - -var changeDetectionWidgetTemplate = mustParseTemplate("change-detection.html", "widget-base.html") - -type changeDetectionWidget struct { - widgetBase `yaml:",inline"` - ChangeDetections changeDetectionWatchList `yaml:"-"` - WatchUUIDs []string `yaml:"watches"` - InstanceURL string `yaml:"instance-url"` - Token string `yaml:"token"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` -} - -func (widget *changeDetectionWidget) initialize() error { - widget.withTitle("Change Detection").withCacheDuration(1 * time.Hour) - - if widget.Limit <= 0 { - widget.Limit = 10 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - if widget.InstanceURL == "" { - widget.InstanceURL = "https://www.changedetection.io" - } - - return nil -} - -func (widget *changeDetectionWidget) update(ctx context.Context) { - if len(widget.WatchUUIDs) == 0 { - uuids, err := fetchWatchUUIDsFromChangeDetection(widget.InstanceURL, string(widget.Token)) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - widget.WatchUUIDs = uuids - } - - watches, err := fetchWatchesFromChangeDetection(widget.InstanceURL, widget.WatchUUIDs, string(widget.Token)) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if len(watches) > widget.Limit { - watches = watches[:widget.Limit] - } - - widget.ChangeDetections = watches -} - -func (widget *changeDetectionWidget) Render() template.HTML { - return widget.renderTemplate(widget, changeDetectionWidgetTemplate) -} - -type changeDetectionWatch struct { - Title string - URL string - LastChanged time.Time - DiffURL string - PreviousHash string -} - -type changeDetectionWatchList []changeDetectionWatch - -func (r changeDetectionWatchList) sortByNewest() changeDetectionWatchList { - sort.Slice(r, func(i, j int) bool { - return r[i].LastChanged.After(r[j].LastChanged) - }) - - return r -} - -type changeDetectionResponseJson struct { - Title string `json:"title"` - URL string `json:"url"` - LastChanged int64 `json:"last_changed"` - DateCreated int64 `json:"date_created"` - PreviousHash string `json:"previous_md5"` -} - -func fetchWatchUUIDsFromChangeDetection(instanceURL string, token string) ([]string, error) { - request, _ := http.NewRequest("GET", fmt.Sprintf("%s/api/v1/watch", instanceURL), nil) - - if token != "" { - request.Header.Add("x-api-key", token) - } - - uuidsMap, err := decodeJsonFromRequest[map[string]struct{}](defaultHTTPClient, request) - if err != nil { - return nil, fmt.Errorf("could not fetch list of watch UUIDs: %v", err) - } - - uuids := make([]string, 0, len(uuidsMap)) - - for uuid := range uuidsMap { - uuids = append(uuids, uuid) - } - - return uuids, nil -} - -func fetchWatchesFromChangeDetection(instanceURL string, requestedWatchIDs []string, token string) (changeDetectionWatchList, error) { - watches := make(changeDetectionWatchList, 0, len(requestedWatchIDs)) - - if len(requestedWatchIDs) == 0 { - return watches, nil - } - - requests := make([]*http.Request, len(requestedWatchIDs)) - - for i, repository := range requestedWatchIDs { - request, _ := http.NewRequest("GET", fmt.Sprintf("%s/api/v1/watch/%s", instanceURL, repository), nil) - - if token != "" { - request.Header.Add("x-api-key", token) - } - - requests[i] = request - } - - task := decodeJsonFromRequestTask[changeDetectionResponseJson](defaultHTTPClient) - job := newJob(task, requests).withWorkers(15) - responses, errs, err := workerPoolDo(job) - if err != nil { - return nil, err - } - - var failed int - - for i := range responses { - if errs[i] != nil { - failed++ - slog.Error("Failed to fetch or parse change detection watch", "url", requests[i].URL, "error", errs[i]) - continue - } - - watchJson := responses[i] - - watch := changeDetectionWatch{ - URL: watchJson.URL, - DiffURL: fmt.Sprintf("%s/diff/%s?from_version=%d", instanceURL, requestedWatchIDs[i], watchJson.LastChanged-1), - } - - if watchJson.LastChanged == 0 { - watch.LastChanged = time.Unix(watchJson.DateCreated, 0) - } else { - watch.LastChanged = time.Unix(watchJson.LastChanged, 0) - } - - if watchJson.Title != "" { - watch.Title = watchJson.Title - } else { - watch.Title = strings.TrimPrefix(strings.Trim(stripURLScheme(watchJson.URL), "/"), "www.") - } - - if watchJson.PreviousHash != "" { - var hashLength = 8 - - if len(watchJson.PreviousHash) < hashLength { - hashLength = len(watchJson.PreviousHash) - } - - watch.PreviousHash = watchJson.PreviousHash[0:hashLength] - } - - watches = append(watches, watch) - } - - if len(watches) == 0 { - return nil, errNoContent - } - - watches.sortByNewest() - - if failed > 0 { - return watches, fmt.Errorf("%w: could not get %d watches", errPartialContent, failed) - } - - return watches, nil -} diff --git a/internal/glance/widget-clock.go b/internal/glance/widget-clock.go deleted file mode 100644 index c69fc95..0000000 --- a/internal/glance/widget-clock.go +++ /dev/null @@ -1,48 +0,0 @@ -package glance - -import ( - "errors" - "fmt" - "html/template" - "time" -) - -var clockWidgetTemplate = mustParseTemplate("clock.html", "widget-base.html") - -type clockWidget struct { - widgetBase `yaml:",inline"` - cachedHTML template.HTML `yaml:"-"` - HourFormat string `yaml:"hour-format"` - Timezones []struct { - Timezone string `yaml:"timezone"` - Label string `yaml:"label"` - } `yaml:"timezones"` -} - -func (widget *clockWidget) initialize() error { - widget.withTitle("Clock").withError(nil) - - if widget.HourFormat == "" { - widget.HourFormat = "24h" - } else if widget.HourFormat != "12h" && widget.HourFormat != "24h" { - return errors.New("hour-format must be either 12h or 24h") - } - - for t := range widget.Timezones { - if widget.Timezones[t].Timezone == "" { - return errors.New("missing timezone value") - } - - if _, err := time.LoadLocation(widget.Timezones[t].Timezone); err != nil { - return fmt.Errorf("invalid timezone '%s': %v", widget.Timezones[t].Timezone, err) - } - } - - widget.cachedHTML = widget.renderTemplate(widget, clockWidgetTemplate) - - return nil -} - -func (widget *clockWidget) Render() template.HTML { - return widget.cachedHTML -} diff --git a/internal/glance/widget-container.go b/internal/glance/widget-container.go deleted file mode 100644 index 4c9f33a..0000000 --- a/internal/glance/widget-container.go +++ /dev/null @@ -1,58 +0,0 @@ -package glance - -import ( - "context" - "sync" - "time" -) - -type containerWidgetBase struct { - Widgets widgets `yaml:"widgets"` -} - -func (widget *containerWidgetBase) _initializeWidgets() error { - for i := range widget.Widgets { - if err := widget.Widgets[i].initialize(); err != nil { - return formatWidgetInitError(err, widget.Widgets[i]) - } - } - - return nil -} - -func (widget *containerWidgetBase) _update(ctx context.Context) { - var wg sync.WaitGroup - now := time.Now() - - for w := range widget.Widgets { - widget := widget.Widgets[w] - - if !widget.requiresUpdate(&now) { - continue - } - - wg.Add(1) - go func() { - defer wg.Done() - widget.update(ctx) - }() - } - - wg.Wait() -} - -func (widget *containerWidgetBase) _setProviders(providers *widgetProviders) { - for i := range widget.Widgets { - widget.Widgets[i].setProviders(providers) - } -} - -func (widget *containerWidgetBase) _requiresUpdate(now *time.Time) bool { - for i := range widget.Widgets { - if widget.Widgets[i].requiresUpdate(now) { - return true - } - } - - return false -} diff --git a/internal/glance/widget-custom-api.go b/internal/glance/widget-custom-api.go deleted file mode 100644 index 93d51c0..0000000 --- a/internal/glance/widget-custom-api.go +++ /dev/null @@ -1,594 +0,0 @@ -package glance - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "html/template" - "io" - "log/slog" - "math" - "net/http" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "time" - - "github.com/tidwall/gjson" -) - -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"` - *CustomAPIRequest `yaml:",inline"` // the primary request - Subrequests map[string]*CustomAPIRequest `yaml:"subrequests"` - Template string `yaml:"template"` - Frameless bool `yaml:"frameless"` - compiledTemplate *template.Template `yaml:"-"` - CompiledHTML template.HTML `yaml:"-"` -} - -func (widget *customAPIWidget) initialize() error { - widget.withTitle("Custom API").withCacheDuration(1 * time.Hour) - - 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 == "" { - return errors.New("template is required") - } - - compiledTemplate, err := template.New("").Funcs(customAPITemplateFuncs).Parse(widget.Template) - if err != nil { - return fmt.Errorf("parsing template: %w", err) - } - - widget.compiledTemplate = compiledTemplate - - return nil -} - -func (widget *customAPIWidget) update(ctx context.Context) { - compiledHTML, err := fetchAndParseCustomAPI(widget.CustomAPIRequest, widget.Subrequests, widget.compiledTemplate) - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - widget.CompiledHTML = compiledHTML -} - -func (widget *customAPIWidget) Render() template.HTML { - return widget.renderTemplate(widget, customAPIWidgetTemplate) -} - -func (req *CustomAPIRequest) initialize() error { - if req.URL == "" { - return errors.New("URL is required") - } - - 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 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 nil, err - } - - body := strings.TrimSpace(string(bodyBytes)) - - if !req.SkipJSONValidation && body != "" && !gjson.Valid(body) { - truncatedBody, isTruncated := limitStringLength(body, 100) - if isTruncated { - truncatedBody += "... " - } - - slog.Error("Invalid response JSON in custom API widget", "url", req.httpRequest.URL.String(), "body", truncatedBody) - return nil, errors.New("invalid response JSON") - } - - 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 - } - - return template.HTML(templateBuffer.String()), nil -} - -type decoratedGJSONResult struct { - gjson.Result -} - -func gJsonResultArrayToDecoratedResultArray(results []gjson.Result) []decoratedGJSONResult { - decoratedResults := make([]decoratedGJSONResult, len(results)) - - for i, result := range results { - decoratedResults[i] = decoratedGJSONResult{result} - } - - return decoratedResults -} - -func (r *decoratedGJSONResult) Exists(key string) bool { - return r.Get(key).Exists() -} - -func (r *decoratedGJSONResult) Array(key string) []decoratedGJSONResult { - if key == "" { - return gJsonResultArrayToDecoratedResultArray(r.Result.Array()) - } - - return gJsonResultArrayToDecoratedResultArray(r.Get(key).Array()) -} - -func (r *decoratedGJSONResult) String(key string) string { - if key == "" { - return r.Result.String() - } - - return r.Get(key).String() -} - -func (r *decoratedGJSONResult) Int(key string) int { - if key == "" { - return int(r.Result.Int()) - } - - return int(r.Get(key).Int()) -} - -func (r *decoratedGJSONResult) Float(key string) float64 { - if key == "" { - return r.Result.Float() - } - - return r.Get(key).Float() -} - -func (r *decoratedGJSONResult) Bool(key string) bool { - if key == "" { - return r.Result.Bool() - } - - return r.Get(key).Bool() -} - -func customAPIDoMathOp[T int | float64](a, b T, op string) T { - switch op { - case "add": - return a + b - case "sub": - return a - b - case "mul": - return a * b - case "div": - if b == 0 { - 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 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 - }, - } - - for key, value := range globalTemplateFunctions { - if _, exists := funcs[key]; !exists { - funcs[key] = value - } - } - - 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 -} diff --git a/internal/glance/widget-dns-stats.go b/internal/glance/widget-dns-stats.go deleted file mode 100644 index eb42b5a..0000000 --- a/internal/glance/widget-dns-stats.go +++ /dev/null @@ -1,674 +0,0 @@ -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"` - HideTopDomains bool `yaml:"hide-top-domains"` - Service string `yaml:"service"` - AllowInsecure bool `yaml:"allow-insecure"` - URL string `yaml:"url"` - Token string `yaml:"token"` - Username string `yaml:"username"` - Password string `yaml:"password"` -} - -const ( - dnsServiceAdguard = "adguard" - dnsServicePihole = "pihole" - dnsServicePiholeV6 = "pihole-v6" -) - -func makeDNSWidgetTimeLabels(format string) [8]string { - now := time.Now() - var labels [dnsStatsBars]string - - for h := dnsStatsHoursSpan; h > 0; h -= dnsStatsHoursPerBar { - labels[7-(h/3-1)] = strings.ToLower(now.Add(-time.Duration(h) * time.Hour).Format(format)) - } - - return labels -} - -func (widget *dnsStatsWidget) initialize() error { - widget. - withTitle("DNS Stats"). - withTitleURL(string(widget.URL)). - withCacheDuration(10 * time.Minute) - - 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 -} - -func (widget *dnsStatsWidget) update(ctx context.Context) { - var stats *dnsStats - var err error - - switch widget.Service { - case dnsServiceAdguard: - stats, err = fetchAdguardStats(widget.URL, widget.AllowInsecure, widget.Username, widget.Password, 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) { - return - } - - if widget.HourFormat == "24h" { - widget.TimeLabels = makeDNSWidgetTimeLabels("15:00") - } else { - widget.TimeLabels = makeDNSWidgetTimeLabels("3PM") - } - - widget.Stats = stats -} - -func (widget *dnsStatsWidget) Render() template.HTML { - return widget.renderTemplate(widget, dnsStatsWidgetTemplate) -} - -type dnsStats struct { - TotalQueries int - BlockedQueries int // we don't actually use this anywhere in templates, maybe remove it later? - BlockedPercent int - ResponseTime int - DomainsBlocked int - Series [dnsStatsBars]dnsStatsSeries - TopBlockedDomains []dnsStatsBlockedDomain -} - -type dnsStatsSeries struct { - Queries int - Blocked int - PercentTotal int - PercentBlocked int -} - -type dnsStatsBlockedDomain struct { - Domain string - PercentBlocked int -} - -type adguardStatsResponse struct { - TotalQueries int `json:"num_dns_queries"` - QueriesSeries []int `json:"dns_queries"` - BlockedQueries int `json:"num_blocked_filtering"` - BlockedSeries []int `json:"blocked_filtering"` - ResponseTime float64 `json:"avg_processing_time"` - TopBlockedDomains []map[string]int `json:"top_blocked_domains"` -} - -func fetchAdguardStats(instanceURL string, allowInsecure bool, username, password string, noGraph bool) (*dnsStats, error) { - requestURL := strings.TrimRight(instanceURL, "/") + "/control/stats" - - request, err := http.NewRequest("GET", requestURL, nil) - if err != nil { - return nil, err - } - - request.SetBasicAuth(username, password) - - var client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient) - responseJson, err := decodeJsonFromRequest[adguardStatsResponse](client, request) - if err != nil { - return nil, err - } - - var topBlockedDomainsCount = min(len(responseJson.TopBlockedDomains), 5) - - stats := &dnsStats{ - TotalQueries: responseJson.TotalQueries, - BlockedQueries: responseJson.BlockedQueries, - ResponseTime: int(responseJson.ResponseTime * 1000), - TopBlockedDomains: make([]dnsStatsBlockedDomain, 0, topBlockedDomainsCount), - } - - if stats.TotalQueries <= 0 { - return stats, nil - } - - stats.BlockedPercent = int(float64(responseJson.BlockedQueries) / float64(responseJson.TotalQueries) * 100) - - for i := range topBlockedDomainsCount { - domain := responseJson.TopBlockedDomains[i] - var firstDomain string - - for k := range domain { - firstDomain = k - break - } - - if firstDomain == "" { - continue - } - - stats.TopBlockedDomains = append(stats.TopBlockedDomains, dnsStatsBlockedDomain{ - Domain: firstDomain, - }) - - if stats.BlockedQueries > 0 { - stats.TopBlockedDomains[i].PercentBlocked = int(float64(domain[firstDomain]) / float64(responseJson.BlockedQueries) * 100) - } - } - - if noGraph { - return stats, nil - } - - queriesSeries := responseJson.QueriesSeries - blockedSeries := responseJson.BlockedSeries - - 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) > dnsStatsHoursSpan { - blockedSeries = blockedSeries[len(blockedSeries)-dnsStatsHoursSpan:] - } else if len(blockedSeries) < dnsStatsHoursSpan { - blockedSeries = append(make([]int, dnsStatsHoursSpan-len(blockedSeries)), blockedSeries...) - } - - maxQueriesInSeries := 0 - - for i := range dnsStatsBars { - queries := 0 - blocked := 0 - - for j := range dnsStatsHoursPerBar { - queries += queriesSeries[i*dnsStatsHoursPerBar+j] - blocked += blockedSeries[i*dnsStatsHoursPerBar+j] - } - - stats.Series[i] = dnsStatsSeries{ - Queries: queries, - Blocked: blocked, - } - - if queries > 0 { - stats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100) - } - - if queries > maxQueriesInSeries { - maxQueriesInSeries = queries - } - } - - for i := range dnsStatsBars { - stats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100) - } - - return stats, nil -} - -// Legacy Pi-hole stats response (before v6) -type pihole5StatsResponse struct { - TotalQueries int `json:"dns_queries_today"` - 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 pihole5TopBlockedDomains `json:"top_ads"` - DomainsBlocked int `json:"domains_being_blocked"` -} - -// If the user has query logging disabled it's possible for domains_over_time to be returned as an -// 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 pihole5QueriesSeries map[int64]int - -func (p *pihole5QueriesSeries) UnmarshalJSON(data []byte) error { - temp := make(map[int64]int) - - err := json.Unmarshal(data, &temp) - if err != nil { - *p = make(pihole5QueriesSeries) - } else { - *p = temp - } - - return nil -} - -// 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 pihole5TopBlockedDomains map[string]int - -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(pihole5TopBlockedDomains) - } else { - *p = temp - } - - return nil -} - -func fetchPihole5Stats(instanceURL string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) { - if token == "" { - return nil, errors.New("missing API token") - } - - requestURL := strings.TrimRight(instanceURL, "/") + - "/admin/api.php?summaryRaw&topItems&overTimeData10mins&auth=" + token - - request, err := http.NewRequest("GET", requestURL, nil) - if err != nil { - return nil, err - } - - var client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient) - responseJson, err := decodeJsonFromRequest[pihole5StatsResponse](client, request) - if err != nil { - return nil, err - } - - stats := &dnsStats{ - TotalQueries: responseJson.TotalQueries, - BlockedQueries: responseJson.BlockedQueries, - BlockedPercent: int(responseJson.BlockedPercentage), - DomainsBlocked: responseJson.DomainsBlocked, - } - - if len(responseJson.TopBlockedDomains) > 0 { - domains := make([]dnsStatsBlockedDomain, 0, len(responseJson.TopBlockedDomains)) - - for domain, count := range responseJson.TopBlockedDomains { - domains = append(domains, dnsStatsBlockedDomain{ - Domain: domain, - PercentBlocked: int(float64(count) / float64(responseJson.BlockedQueries) * 100), - }) - } - - sort.Slice(domains, func(a, b int) bool { - return domains[a].PercentBlocked > domains[b].PercentBlocked - }) - - stats.TopBlockedDomains = domains[:min(len(domains), 5)] - } - - if noGraph { - return stats, nil - } - - // Pihole _should_ return data for the last 24 hours in a 10 minute interval, 6*24 = 144 - if len(responseJson.QueriesSeries) != 144 || len(responseJson.BlockedSeries) != 144 { - slog.Warn( - "DNS stats for pihole: did not get expected 144 data points", - "len(queries)", len(responseJson.QueriesSeries), - "len(blocked)", len(responseJson.BlockedSeries), - ) - return stats, nil - } - - var lowestTimestamp int64 = 0 - for timestamp := range responseJson.QueriesSeries { - if lowestTimestamp == 0 || timestamp < lowestTimestamp { - lowestTimestamp = timestamp - } - } - - maxQueriesInSeries := 0 - - for i := range dnsStatsBars { - queries := 0 - blocked := 0 - - for j := range 18 { - index := lowestTimestamp + int64(i*10800+j*600) - - queries += responseJson.QueriesSeries[index] - blocked += responseJson.BlockedSeries[index] - } - - 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) - } - - 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 -} diff --git a/internal/glance/widget-docker-containers.go b/internal/glance/widget-docker-containers.go deleted file mode 100644 index f38cdeb..0000000 --- a/internal/glance/widget-docker-containers.go +++ /dev/null @@ -1,273 +0,0 @@ -package glance - -import ( - "context" - "encoding/json" - "fmt" - "html/template" - "net" - "net/http" - "sort" - "strings" - "time" -) - -var dockerContainersWidgetTemplate = mustParseTemplate("docker-containers.html", "widget-base.html") - -type dockerContainersWidget struct { - widgetBase `yaml:",inline"` - HideByDefault bool `yaml:"hide-by-default"` - SockPath string `yaml:"sock-path"` - Containers dockerContainerList `yaml:"-"` -} - -func (widget *dockerContainersWidget) initialize() error { - widget.withTitle("Docker Containers").withCacheDuration(1 * time.Minute) - - if widget.SockPath == "" { - widget.SockPath = "/var/run/docker.sock" - } - - return nil -} - -func (widget *dockerContainersWidget) update(ctx context.Context) { - containers, err := fetchDockerContainers(widget.SockPath, widget.HideByDefault) - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - containers.sortByStateIconThenTitle() - widget.Containers = containers -} - -func (widget *dockerContainersWidget) Render() template.HTML { - return widget.renderTemplate(widget, dockerContainersWidgetTemplate) -} - -const ( - dockerContainerLabelHide = "glance.hide" - dockerContainerLabelName = "glance.name" - dockerContainerLabelURL = "glance.url" - dockerContainerLabelDescription = "glance.description" - dockerContainerLabelSameTab = "glance.same-tab" - dockerContainerLabelIcon = "glance.icon" - dockerContainerLabelID = "glance.id" - dockerContainerLabelParent = "glance.parent" -) - -const ( - dockerContainerStateIconOK = "ok" - dockerContainerStateIconPaused = "paused" - dockerContainerStateIconWarn = "warn" - dockerContainerStateIconOther = "other" -) - -var dockerContainerStateIconPriorities = map[string]int{ - dockerContainerStateIconWarn: 0, - dockerContainerStateIconOther: 1, - dockerContainerStateIconPaused: 2, - dockerContainerStateIconOK: 3, -} - -type dockerContainerJsonResponse struct { - Names []string `json:"Names"` - Image string `json:"Image"` - State string `json:"State"` - Status string `json:"Status"` - Labels dockerContainerLabels `json:"Labels"` -} - -type dockerContainerLabels map[string]string - -func (l *dockerContainerLabels) getOrDefault(label, def string) string { - if l == nil { - return def - } - - v, ok := (*l)[label] - if !ok { - return def - } - - if v == "" { - return def - } - - return v -} - -type dockerContainer struct { - Title string - URL string - SameTab bool - Image string - State string - StateText string - StateIcon string - Description string - Icon customIconField - Children dockerContainerList -} - -type dockerContainerList []dockerContainer - -func (containers dockerContainerList) sortByStateIconThenTitle() { - p := &dockerContainerStateIconPriorities - - sort.SliceStable(containers, func(a, b int) bool { - if containers[a].StateIcon != containers[b].StateIcon { - return (*p)[containers[a].StateIcon] < (*p)[containers[b].StateIcon] - } - - return strings.ToLower(containers[a].Title) < strings.ToLower(containers[b].Title) - }) -} - -func dockerContainerStateToStateIcon(state string) string { - switch state { - case "running": - return dockerContainerStateIconOK - case "paused": - return dockerContainerStateIconPaused - case "exited", "unhealthy", "dead": - return dockerContainerStateIconWarn - default: - return dockerContainerStateIconOther - } -} - -func fetchDockerContainers(socketPath string, hideByDefault bool) (dockerContainerList, error) { - containers, err := fetchAllDockerContainersFromSock(socketPath) - if err != nil { - return nil, fmt.Errorf("fetching containers: %w", err) - } - - containers, children := groupDockerContainerChildren(containers, hideByDefault) - dockerContainers := make(dockerContainerList, 0, len(containers)) - - for i := range containers { - container := &containers[i] - - dc := dockerContainer{ - Title: deriveDockerContainerTitle(container), - URL: container.Labels.getOrDefault(dockerContainerLabelURL, ""), - Description: container.Labels.getOrDefault(dockerContainerLabelDescription, ""), - SameTab: stringToBool(container.Labels.getOrDefault(dockerContainerLabelSameTab, "false")), - Image: container.Image, - State: strings.ToLower(container.State), - StateText: strings.ToLower(container.Status), - Icon: newCustomIconField(container.Labels.getOrDefault(dockerContainerLabelIcon, "si:docker")), - } - - if idValue := container.Labels.getOrDefault(dockerContainerLabelID, ""); idValue != "" { - if children, ok := children[idValue]; ok { - for i := range children { - child := &children[i] - dc.Children = append(dc.Children, dockerContainer{ - Title: deriveDockerContainerTitle(child), - StateText: child.Status, - StateIcon: dockerContainerStateToStateIcon(strings.ToLower(child.State)), - }) - } - } - } - - dc.Children.sortByStateIconThenTitle() - - stateIconSupersededByChild := false - for i := range dc.Children { - if dc.Children[i].StateIcon == dockerContainerStateIconWarn { - dc.StateIcon = dockerContainerStateIconWarn - stateIconSupersededByChild = true - break - } - } - if !stateIconSupersededByChild { - dc.StateIcon = dockerContainerStateToStateIcon(dc.State) - } - - dockerContainers = append(dockerContainers, dc) - } - - return dockerContainers, nil -} - -func deriveDockerContainerTitle(container *dockerContainerJsonResponse) string { - if v := container.Labels.getOrDefault(dockerContainerLabelName, ""); v != "" { - return v - } - - return strings.TrimLeft(itemAtIndexOrDefault(container.Names, 0, "n/a"), "/") -} - -func groupDockerContainerChildren( - containers []dockerContainerJsonResponse, - hideByDefault bool, -) ( - []dockerContainerJsonResponse, - map[string][]dockerContainerJsonResponse, -) { - parents := make([]dockerContainerJsonResponse, 0, len(containers)) - children := make(map[string][]dockerContainerJsonResponse) - - for i := range containers { - container := &containers[i] - - if isDockerContainerHidden(container, hideByDefault) { - continue - } - - isParent := container.Labels.getOrDefault(dockerContainerLabelID, "") != "" - parent := container.Labels.getOrDefault(dockerContainerLabelParent, "") - - if !isParent && parent != "" { - children[parent] = append(children[parent], *container) - } else { - parents = append(parents, *container) - } - } - - return parents, children -} - -func isDockerContainerHidden(container *dockerContainerJsonResponse, hideByDefault bool) bool { - if v := container.Labels.getOrDefault(dockerContainerLabelHide, ""); v != "" { - return stringToBool(v) - } - - return hideByDefault -} - -func fetchAllDockerContainersFromSock(socketPath string) ([]dockerContainerJsonResponse, error) { - client := &http.Client{ - Timeout: 5 * time.Second, - Transport: &http.Transport{ - DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { - return net.Dial("unix", socketPath) - }, - }, - } - - request, err := http.NewRequest("GET", "http://docker/containers/json?all=true", nil) - if err != nil { - return nil, fmt.Errorf("creating request: %w", err) - } - - response, err := client.Do(request) - if err != nil { - return nil, fmt.Errorf("sending request to socket: %w", err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - return nil, fmt.Errorf("non-200 response status: %s", response.Status) - } - - var containers []dockerContainerJsonResponse - if err := json.NewDecoder(response.Body).Decode(&containers); err != nil { - return nil, fmt.Errorf("decoding response: %w", err) - } - - return containers, nil -} diff --git a/internal/glance/widget-extension.go b/internal/glance/widget-extension.go deleted file mode 100644 index c2b11f5..0000000 --- a/internal/glance/widget-extension.go +++ /dev/null @@ -1,172 +0,0 @@ -package glance - -import ( - "context" - "errors" - "fmt" - "html" - "html/template" - "io" - "log/slog" - "net/http" - "net/url" - "time" -) - -var extensionWidgetTemplate = mustParseTemplate("extension.html", "widget-base.html") - -const extensionWidgetDefaultTitle = "Extension" - -type extensionWidget struct { - widgetBase `yaml:",inline"` - URL string `yaml:"url"` - FallbackContentType string `yaml:"fallback-content-type"` - Parameters queryParametersField `yaml:"parameters"` - Headers map[string]string `yaml:"headers"` - AllowHtml bool `yaml:"allow-potentially-dangerous-html"` - Extension extension `yaml:"-"` - cachedHTML template.HTML `yaml:"-"` -} - -func (widget *extensionWidget) initialize() error { - widget.withTitle(extensionWidgetDefaultTitle).withCacheDuration(time.Minute * 30) - - if widget.URL == "" { - return errors.New("URL is required") - } - - if _, err := url.Parse(widget.URL); err != nil { - return fmt.Errorf("parsing URL: %v", err) - } - - return nil -} - -func (widget *extensionWidget) update(ctx context.Context) { - extension, err := fetchExtension(extensionRequestOptions{ - URL: widget.URL, - FallbackContentType: widget.FallbackContentType, - Parameters: widget.Parameters, - Headers: widget.Headers, - AllowHtml: widget.AllowHtml, - }) - - widget.canContinueUpdateAfterHandlingErr(err) - - widget.Extension = extension - - if widget.Title == extensionWidgetDefaultTitle && extension.Title != "" { - widget.Title = extension.Title - } - - if widget.TitleURL == "" && extension.TitleURL != "" { - widget.TitleURL = extension.TitleURL - } - - widget.cachedHTML = widget.renderTemplate(widget, extensionWidgetTemplate) -} - -func (widget *extensionWidget) Render() template.HTML { - return widget.cachedHTML -} - -type extensionType int - -const ( - extensionContentHTML extensionType = iota - extensionContentUnknown -) - -var extensionStringToType = map[string]extensionType{ - "html": extensionContentHTML, -} - -const ( - extensionHeaderTitle = "Widget-Title" - extensionHeaderTitleURL = "Widget-Title-URL" - extensionHeaderContentType = "Widget-Content-Type" - extensionHeaderContentFrameless = "Widget-Content-Frameless" -) - -type extensionRequestOptions struct { - URL string `yaml:"url"` - FallbackContentType string `yaml:"fallback-content-type"` - 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 -} - -func convertExtensionContent(options extensionRequestOptions, content []byte, contentType extensionType) template.HTML { - switch contentType { - case extensionContentHTML: - if options.AllowHtml { - return template.HTML(content) - } - - fallthrough - default: - return template.HTML("
" + html.EscapeString(string(content)) + "
") - } -} - -func fetchExtension(options extensionRequestOptions) (extension, error) { - request, _ := http.NewRequest("GET", options.URL, nil) - if len(options.Parameters) > 0 { - request.URL.RawQuery = options.Parameters.toQueryString() - } - - for key, value := range options.Headers { - request.Header.Add(key, value) - } - - response, err := http.DefaultClient.Do(request) - if err != nil { - slog.Error("Failed fetching extension", "url", options.URL, "error", err) - return extension{}, fmt.Errorf("%w: request failed: %w", errNoContent, err) - } - - defer response.Body.Close() - - body, err := io.ReadAll(response.Body) - if err != nil { - slog.Error("Failed reading response body of extension", "url", options.URL, "error", err) - return extension{}, fmt.Errorf("%w: could not read body: %w", errNoContent, err) - } - - extension := extension{} - - if response.Header.Get(extensionHeaderTitle) == "" { - extension.Title = "Extension" - } else { - 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 { - contentType, ok = extensionStringToType[options.FallbackContentType] - - if !ok { - contentType = extensionContentUnknown - } - } - - if stringToBool(response.Header.Get(extensionHeaderContentFrameless)) { - extension.Frameless = true - } - - extension.Content = convertExtensionContent(options, body, contentType) - - return extension, nil -} diff --git a/internal/glance/widget-group.go b/internal/glance/widget-group.go deleted file mode 100644 index 2ea3813..0000000 --- a/internal/glance/widget-group.go +++ /dev/null @@ -1,52 +0,0 @@ -package glance - -import ( - "context" - "errors" - "html/template" - "time" -) - -var groupWidgetTemplate = mustParseTemplate("group.html", "widget-base.html") - -type groupWidget struct { - widgetBase `yaml:",inline"` - containerWidgetBase `yaml:",inline"` -} - -func (widget *groupWidget) initialize() error { - widget.withError(nil) - widget.HideHeader = true - - for i := range widget.Widgets { - widget.Widgets[i].setHideHeader(true) - - if widget.Widgets[i].GetType() == "group" { - return errors.New("nested groups are not supported") - } else if widget.Widgets[i].GetType() == "split-column" { - return errors.New("split columns inside of groups are not supported") - } - } - - if err := widget.containerWidgetBase._initializeWidgets(); err != nil { - return err - } - - return nil -} - -func (widget *groupWidget) update(ctx context.Context) { - widget.containerWidgetBase._update(ctx) -} - -func (widget *groupWidget) setProviders(providers *widgetProviders) { - widget.containerWidgetBase._setProviders(providers) -} - -func (widget *groupWidget) requiresUpdate(now *time.Time) bool { - return widget.containerWidgetBase._requiresUpdate(now) -} - -func (widget *groupWidget) Render() template.HTML { - return widget.renderTemplate(widget, groupWidgetTemplate) -} diff --git a/internal/glance/widget-hacker-news.go b/internal/glance/widget-hacker-news.go deleted file mode 100644 index ad00df0..0000000 --- a/internal/glance/widget-hacker-news.go +++ /dev/null @@ -1,152 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html/template" - "log/slog" - "net/http" - "strconv" - "strings" - "time" -) - -type hackerNewsWidget struct { - widgetBase `yaml:",inline"` - Posts forumPostList `yaml:"-"` - Limit int `yaml:"limit"` - SortBy string `yaml:"sort-by"` - ExtraSortBy string `yaml:"extra-sort-by"` - CollapseAfter int `yaml:"collapse-after"` - CommentsUrlTemplate string `yaml:"comments-url-template"` - ShowThumbnails bool `yaml:"-"` -} - -func (widget *hackerNewsWidget) initialize() error { - widget. - withTitle("Hacker News"). - withTitleURL("https://news.ycombinator.com/"). - withCacheDuration(30 * time.Minute) - - if widget.Limit <= 0 { - widget.Limit = 15 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - if widget.SortBy != "top" && widget.SortBy != "new" && widget.SortBy != "best" { - widget.SortBy = "top" - } - - return nil -} - -func (widget *hackerNewsWidget) update(ctx context.Context) { - posts, err := fetchHackerNewsPosts(widget.SortBy, 40, widget.CommentsUrlTemplate) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if widget.ExtraSortBy == "engagement" { - posts.calculateEngagement() - posts.sortByEngagement() - } - - if widget.Limit < len(posts) { - posts = posts[:widget.Limit] - } - - widget.Posts = posts -} - -func (widget *hackerNewsWidget) Render() template.HTML { - return widget.renderTemplate(widget, forumPostsTemplate) -} - -type hackerNewsPostResponseJson struct { - Id int `json:"id"` - Score int `json:"score"` - Title string `json:"title"` - TargetUrl string `json:"url,omitempty"` - CommentCount int `json:"descendants"` - TimePosted int64 `json:"time"` -} - -func fetchHackerNewsPostIds(sort string) ([]int, error) { - request, _ := http.NewRequest("GET", fmt.Sprintf("https://hacker-news.firebaseio.com/v0/%sstories.json", sort), nil) - response, err := decodeJsonFromRequest[[]int](defaultHTTPClient, request) - if err != nil { - return nil, fmt.Errorf("%w: could not fetch list of post IDs", errNoContent) - } - - return response, nil -} - -func fetchHackerNewsPostsFromIds(postIds []int, commentsUrlTemplate string) (forumPostList, error) { - requests := make([]*http.Request, len(postIds)) - - for i, id := range postIds { - request, _ := http.NewRequest("GET", fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json", id), nil) - requests[i] = request - } - - task := decodeJsonFromRequestTask[hackerNewsPostResponseJson](defaultHTTPClient) - job := newJob(task, requests).withWorkers(30) - results, errs, err := workerPoolDo(job) - if err != nil { - return nil, err - } - - posts := make(forumPostList, 0, len(postIds)) - - for i := range results { - if errs[i] != nil { - slog.Error("Failed to fetch or parse hacker news post", "error", errs[i], "url", requests[i].URL) - continue - } - - var commentsUrl string - - if commentsUrlTemplate == "" { - commentsUrl = "https://news.ycombinator.com/item?id=" + strconv.Itoa(results[i].Id) - } else { - commentsUrl = strings.ReplaceAll(commentsUrlTemplate, "{POST-ID}", strconv.Itoa(results[i].Id)) - } - - posts = append(posts, forumPost{ - Title: results[i].Title, - DiscussionUrl: commentsUrl, - TargetUrl: results[i].TargetUrl, - TargetUrlDomain: extractDomainFromUrl(results[i].TargetUrl), - CommentCount: results[i].CommentCount, - Score: results[i].Score, - TimePosted: time.Unix(results[i].TimePosted, 0), - }) - } - - if len(posts) == 0 { - return nil, errNoContent - } - - if len(posts) != len(postIds) { - return posts, fmt.Errorf("%w could not fetch some hacker news posts", errPartialContent) - } - - return posts, nil -} - -func fetchHackerNewsPosts(sort string, limit int, commentsUrlTemplate string) (forumPostList, error) { - postIds, err := fetchHackerNewsPostIds(sort) - if err != nil { - return nil, err - } - - if len(postIds) > limit { - postIds = postIds[:limit] - } - - return fetchHackerNewsPostsFromIds(postIds, commentsUrlTemplate) -} diff --git a/internal/glance/widget-html.go b/internal/glance/widget-html.go deleted file mode 100644 index 0e32a46..0000000 --- a/internal/glance/widget-html.go +++ /dev/null @@ -1,20 +0,0 @@ -package glance - -import ( - "html/template" -) - -type htmlWidget struct { - widgetBase `yaml:",inline"` - Source template.HTML `yaml:"source"` -} - -func (widget *htmlWidget) initialize() error { - widget.withTitle("").withError(nil) - - return nil -} - -func (widget *htmlWidget) Render() template.HTML { - return widget.Source -} diff --git a/internal/glance/widget-lobsters.go b/internal/glance/widget-lobsters.go deleted file mode 100644 index 786d1df..0000000 --- a/internal/glance/widget-lobsters.go +++ /dev/null @@ -1,144 +0,0 @@ -package glance - -import ( - "context" - "html/template" - "net/http" - "strings" - "time" -) - -type lobstersWidget struct { - widgetBase `yaml:",inline"` - Posts forumPostList `yaml:"-"` - InstanceURL string `yaml:"instance-url"` - CustomURL string `yaml:"custom-url"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` - SortBy string `yaml:"sort-by"` - Tags []string `yaml:"tags"` - ShowThumbnails bool `yaml:"-"` -} - -func (widget *lobstersWidget) initialize() error { - widget.withTitle("Lobsters").withCacheDuration(time.Hour) - - if widget.InstanceURL == "" { - widget.withTitleURL("https://lobste.rs") - } else { - widget.withTitleURL(widget.InstanceURL) - } - - if widget.SortBy == "" || (widget.SortBy != "hot" && widget.SortBy != "new") { - widget.SortBy = "hot" - } - - if widget.Limit <= 0 { - widget.Limit = 15 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - return nil -} - -func (widget *lobstersWidget) update(ctx context.Context) { - posts, err := fetchLobstersPosts(widget.CustomURL, widget.InstanceURL, widget.SortBy, widget.Tags) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if widget.Limit < len(posts) { - posts = posts[:widget.Limit] - } - - widget.Posts = posts -} - -func (widget *lobstersWidget) Render() template.HTML { - return widget.renderTemplate(widget, forumPostsTemplate) -} - -type lobstersPostResponseJson struct { - CreatedAt string `json:"created_at"` - Title string `json:"title"` - URL string `json:"url"` - Score int `json:"score"` - CommentCount int `json:"comment_count"` - CommentsURL string `json:"comments_url"` - Tags []string `json:"tags"` -} - -type lobstersFeedResponseJson []lobstersPostResponseJson - -func fetchLobstersPostsFromFeed(feedUrl string) (forumPostList, error) { - request, err := http.NewRequest("GET", feedUrl, nil) - if err != nil { - return nil, err - } - - feed, err := decodeJsonFromRequest[lobstersFeedResponseJson](defaultHTTPClient, request) - if err != nil { - return nil, err - } - - posts := make(forumPostList, 0, len(feed)) - - for i := range feed { - createdAt, _ := time.Parse(time.RFC3339, feed[i].CreatedAt) - - posts = append(posts, forumPost{ - Title: feed[i].Title, - DiscussionUrl: feed[i].CommentsURL, - TargetUrl: feed[i].URL, - TargetUrlDomain: extractDomainFromUrl(feed[i].URL), - CommentCount: feed[i].CommentCount, - Score: feed[i].Score, - TimePosted: createdAt, - Tags: feed[i].Tags, - }) - } - - if len(posts) == 0 { - return nil, errNoContent - } - - return posts, nil -} - -func fetchLobstersPosts(customURL string, instanceURL string, sortBy string, tags []string) (forumPostList, error) { - var feedUrl string - - if customURL != "" { - feedUrl = customURL - } else { - if instanceURL != "" { - instanceURL = strings.TrimRight(instanceURL, "/") + "/" - } else { - instanceURL = "https://lobste.rs/" - } - - if sortBy == "hot" { - sortBy = "hottest" - } else if sortBy == "new" { - sortBy = "newest" - } - - if len(tags) == 0 { - feedUrl = instanceURL + sortBy + ".json" - } else { - tags := strings.Join(tags, ",") - feedUrl = instanceURL + "t/" + tags + ".json" - } - } - - posts, err := fetchLobstersPostsFromFeed(feedUrl) - if err != nil { - return nil, err - } - - return posts, nil -} diff --git a/internal/glance/widget-markets.go b/internal/glance/widget-markets.go deleted file mode 100644 index b53b10a..0000000 --- a/internal/glance/widget-markets.go +++ /dev/null @@ -1,228 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html/template" - "log/slog" - "math" - "net/http" - "sort" - "strings" - "time" -) - -var marketsWidgetTemplate = mustParseTemplate("markets.html", "widget-base.html") - -type marketsWidget struct { - widgetBase `yaml:",inline"` - StocksRequests []marketRequest `yaml:"stocks"` - MarketRequests []marketRequest `yaml:"markets"` - ChartLinkTemplate string `yaml:"chart-link-template"` - SymbolLinkTemplate string `yaml:"symbol-link-template"` - Sort string `yaml:"sort-by"` - Markets marketList `yaml:"-"` -} - -func (widget *marketsWidget) initialize() error { - widget.withTitle("Markets").withCacheDuration(time.Hour) - - // legacy support, remove in v0.10.0 - if len(widget.MarketRequests) == 0 { - widget.MarketRequests = widget.StocksRequests - } - - for i := range widget.MarketRequests { - m := &widget.MarketRequests[i] - - if widget.ChartLinkTemplate != "" && m.ChartLink == "" { - m.ChartLink = strings.ReplaceAll(widget.ChartLinkTemplate, "{SYMBOL}", m.Symbol) - } - - if widget.SymbolLinkTemplate != "" && m.SymbolLink == "" { - m.SymbolLink = strings.ReplaceAll(widget.SymbolLinkTemplate, "{SYMBOL}", m.Symbol) - } - } - - return nil -} - -func (widget *marketsWidget) update(ctx context.Context) { - markets, err := fetchMarketsDataFromYahoo(widget.MarketRequests) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if widget.Sort == "absolute-change" { - markets.sortByAbsChange() - } else if widget.Sort == "change" { - markets.sortByChange() - } - - widget.Markets = markets -} - -func (widget *marketsWidget) Render() template.HTML { - return widget.renderTemplate(widget, marketsWidgetTemplate) -} - -type marketRequest struct { - CustomName string `yaml:"name"` - Symbol string `yaml:"symbol"` - ChartLink string `yaml:"chart-link"` - SymbolLink string `yaml:"symbol-link"` -} - -type market struct { - marketRequest - Name string - Currency string - Price float64 - PriceHint int - PercentChange float64 - SvgChartPoints string -} - -type marketList []market - -func (t marketList) sortByAbsChange() { - sort.Slice(t, func(i, j int) bool { - return math.Abs(t[i].PercentChange) > math.Abs(t[j].PercentChange) - }) -} - -func (t marketList) sortByChange() { - sort.Slice(t, func(i, j int) bool { - return t[i].PercentChange > t[j].PercentChange - }) -} - -type marketResponseJson struct { - Chart struct { - Result []struct { - Meta struct { - Currency string `json:"currency"` - Symbol string `json:"symbol"` - RegularMarketPrice float64 `json:"regularMarketPrice"` - ChartPreviousClose float64 `json:"chartPreviousClose"` - ShortName string `json:"shortName"` - PriceHint int `json:"priceHint"` - } `json:"meta"` - Indicators struct { - Quote []struct { - Close []float64 `json:"close,omitempty"` - } `json:"quote"` - } `json:"indicators"` - } `json:"result"` - } `json:"chart"` -} - -// TODO: allow changing chart time frame -const marketChartDays = 21 - -func fetchMarketsDataFromYahoo(marketRequests []marketRequest) (marketList, error) { - requests := make([]*http.Request, 0, len(marketRequests)) - - for i := range marketRequests { - request, _ := http.NewRequest("GET", fmt.Sprintf("https://query1.finance.yahoo.com/v8/finance/chart/%s?range=1mo&interval=1d", marketRequests[i].Symbol), nil) - setBrowserUserAgentHeader(request) - requests = append(requests, request) - } - - job := newJob(decodeJsonFromRequestTask[marketResponseJson](defaultHTTPClient), requests) - responses, errs, err := workerPoolDo(job) - if err != nil { - return nil, fmt.Errorf("%w: %v", errNoContent, err) - } - - markets := make(marketList, 0, len(responses)) - var failed int - - for i := range responses { - if errs[i] != nil { - failed++ - slog.Error("Failed to fetch market data", "symbol", marketRequests[i].Symbol, "error", errs[i]) - continue - } - - response := responses[i] - - if len(response.Chart.Result) == 0 { - failed++ - slog.Error("Market response contains no data", "symbol", marketRequests[i].Symbol) - continue - } - - result := &response.Chart.Result[0] - prices := result.Indicators.Quote[0].Close - - if len(prices) > marketChartDays { - prices = prices[len(prices)-marketChartDays:] - } - - previous := result.Meta.RegularMarketPrice - - if len(prices) >= 2 && prices[len(prices)-2] != 0 { - previous = prices[len(prices)-2] - } - - points := svgPolylineCoordsFromYValues(100, 50, maybeCopySliceWithoutZeroValues(prices)) - - currency, exists := currencyToSymbol[strings.ToUpper(result.Meta.Currency)] - if !exists { - currency = result.Meta.Currency - } - - markets = append(markets, market{ - marketRequest: marketRequests[i], - Price: result.Meta.RegularMarketPrice, - Currency: currency, - PriceHint: result.Meta.PriceHint, - Name: ternary(marketRequests[i].CustomName == "", - result.Meta.ShortName, - marketRequests[i].CustomName, - ), - PercentChange: percentChange( - result.Meta.RegularMarketPrice, - previous, - ), - SvgChartPoints: points, - }) - } - - if len(markets) == 0 { - return nil, errNoContent - } - - if failed > 0 { - return markets, fmt.Errorf("%w: could not fetch data for %d market(s)", errPartialContent, failed) - } - - return markets, nil -} - -var currencyToSymbol = map[string]string{ - "USD": "$", - "EUR": "€", - "JPY": "¥", - "CAD": "C$", - "AUD": "A$", - "GBP": "£", - "CHF": "Fr", - "NZD": "N$", - "INR": "₹", - "BRL": "R$", - "RUB": "₽", - "TRY": "₺", - "ZAR": "R", - "CNY": "¥", - "KRW": "₩", - "HKD": "HK$", - "SGD": "S$", - "SEK": "kr", - "NOK": "kr", - "DKK": "kr", - "PLN": "zł", - "PHP": "₱", -} diff --git a/internal/glance/widget-monitor.go b/internal/glance/widget-monitor.go deleted file mode 100644 index 76f0d45..0000000 --- a/internal/glance/widget-monitor.go +++ /dev/null @@ -1,182 +0,0 @@ -package glance - -import ( - "context" - "errors" - "html/template" - "net/http" - "slices" - "strconv" - "time" -) - -var ( - monitorWidgetTemplate = mustParseTemplate("monitor.html", "widget-base.html") - monitorWidgetCompactTemplate = mustParseTemplate("monitor-compact.html", "widget-base.html") -) - -type monitorWidget struct { - widgetBase `yaml:",inline"` - Sites []struct { - *SiteStatusRequest `yaml:",inline"` - Status *siteStatus `yaml:"-"` - URL string `yaml:"-"` - ErrorURL string `yaml:"error-url"` - Title string `yaml:"title"` - Icon customIconField `yaml:"icon"` - SameTab bool `yaml:"same-tab"` - StatusText string `yaml:"-"` - StatusStyle string `yaml:"-"` - AltStatusCodes []int `yaml:"alt-status-codes"` - } `yaml:"sites"` - Style string `yaml:"style"` - ShowFailingOnly bool `yaml:"show-failing-only"` - HasFailing bool `yaml:"-"` -} - -func (widget *monitorWidget) initialize() error { - widget.withTitle("Monitor").withCacheDuration(5 * time.Minute) - - return nil -} - -func (widget *monitorWidget) update(ctx context.Context) { - requests := make([]*SiteStatusRequest, len(widget.Sites)) - - for i := range widget.Sites { - requests[i] = widget.Sites[i].SiteStatusRequest - } - - statuses, err := fetchStatusForSites(requests) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - widget.HasFailing = false - - for i := range widget.Sites { - site := &widget.Sites[i] - status := &statuses[i] - site.Status = status - - if !slices.Contains(site.AltStatusCodes, status.Code) && (status.Code >= 400 || status.Error != nil) { - widget.HasFailing = true - } - - if status.Error != nil && site.ErrorURL != "" { - site.URL = site.ErrorURL - } else { - site.URL = site.DefaultURL - } - - site.StatusText = statusCodeToText(status.Code, site.AltStatusCodes) - site.StatusStyle = statusCodeToStyle(status.Code, site.AltStatusCodes) - } -} - -func (widget *monitorWidget) Render() template.HTML { - if widget.Style == "compact" { - return widget.renderTemplate(widget, monitorWidgetCompactTemplate) - } - - return widget.renderTemplate(widget, monitorWidgetTemplate) -} - -func statusCodeToText(status int, altStatusCodes []int) string { - if status == 200 || slices.Contains(altStatusCodes, status) { - return "OK" - } - if status == 404 { - return "Not Found" - } - if status == 403 { - return "Forbidden" - } - if status == 401 { - return "Unauthorized" - } - if status >= 500 { - return "Server Error" - } - if status >= 400 { - return "Client Error" - } - - return strconv.Itoa(status) -} - -func statusCodeToStyle(status int, altStatusCodes []int) string { - if status == 200 || slices.Contains(altStatusCodes, status) { - return "ok" - } - - return "error" -} - -type SiteStatusRequest struct { - DefaultURL string `yaml:"url"` - CheckURL string `yaml:"check-url"` - AllowInsecure bool `yaml:"allow-insecure"` -} - -type siteStatus struct { - Code int - TimedOut bool - ResponseTime time.Duration - Error error -} - -func fetchSiteStatusTask(statusRequest *SiteStatusRequest) (siteStatus, error) { - var url string - if statusRequest.CheckURL != "" { - url = statusRequest.CheckURL - } else { - url = statusRequest.DefaultURL - } - request, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return siteStatus{ - Error: err, - }, nil - } - - ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) - defer cancel() - request = request.WithContext(ctx) - requestSentAt := time.Now() - var response *http.Response - - if !statusRequest.AllowInsecure { - response, err = defaultHTTPClient.Do(request) - } else { - response, err = defaultInsecureHTTPClient.Do(request) - } - - status := siteStatus{ResponseTime: time.Since(requestSentAt)} - - if err != nil { - if errors.Is(err, context.DeadlineExceeded) { - status.TimedOut = true - } - - status.Error = err - return status, nil - } - - defer response.Body.Close() - - status.Code = response.StatusCode - - return status, nil -} - -func fetchStatusForSites(requests []*SiteStatusRequest) ([]siteStatus, error) { - job := newJob(fetchSiteStatusTask, requests).withWorkers(20) - results, _, err := workerPoolDo(job) - if err != nil { - return nil, err - } - - return results, nil -} diff --git a/internal/glance/widget-old-calendar.go b/internal/glance/widget-old-calendar.go deleted file mode 100644 index e4fbe74..0000000 --- a/internal/glance/widget-old-calendar.go +++ /dev/null @@ -1,86 +0,0 @@ -package glance - -import ( - "context" - "html/template" - "time" -) - -var oldCalendarWidgetTemplate = mustParseTemplate("old-calendar.html", "widget-base.html") - -type oldCalendarWidget struct { - widgetBase `yaml:",inline"` - Calendar *calendar - StartSunday bool `yaml:"start-sunday"` -} - -func (widget *oldCalendarWidget) initialize() error { - widget.withTitle("Calendar").withCacheOnTheHour() - - return nil -} - -func (widget *oldCalendarWidget) update(ctx context.Context) { - widget.Calendar = newCalendar(time.Now(), widget.StartSunday) - widget.withError(nil).scheduleNextUpdate() -} - -func (widget *oldCalendarWidget) Render() template.HTML { - return widget.renderTemplate(widget, oldCalendarWidgetTemplate) -} - -type calendar struct { - CurrentDay int - CurrentWeekNumber int - CurrentMonthName string - CurrentYear int - Days []int -} - -// TODO: very inflexible, refactor to allow more customizability -// TODO: allow changing between showing the previous and next week and the entire month -func newCalendar(now time.Time, startSunday bool) *calendar { - year, week := now.ISOWeek() - weekday := now.Weekday() - if !startSunday { - weekday = (weekday + 6) % 7 // Shift Monday to 0 - } - - currentMonthDays := daysInMonth(now.Month(), year) - - var previousMonthDays int - - if previousMonthNumber := now.Month() - 1; previousMonthNumber < 1 { - previousMonthDays = daysInMonth(12, year-1) - } else { - previousMonthDays = daysInMonth(previousMonthNumber, year) - } - - startDaysFrom := now.Day() - int(weekday) - 7 - - days := make([]int, 21) - - for i := 0; i < 21; i++ { - day := startDaysFrom + i - - if day < 1 { - day = previousMonthDays + day - } else if day > currentMonthDays { - day = day - currentMonthDays - } - - days[i] = day - } - - return &calendar{ - CurrentDay: now.Day(), - CurrentWeekNumber: week, - CurrentMonthName: now.Month().String(), - CurrentYear: year, - Days: days, - } -} - -func daysInMonth(m time.Month, year int) int { - return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day() -} diff --git a/internal/glance/widget-reddit.go b/internal/glance/widget-reddit.go deleted file mode 100644 index e7109fa..0000000 --- a/internal/glance/widget-reddit.go +++ /dev/null @@ -1,276 +0,0 @@ -package glance - -import ( - "context" - "errors" - "fmt" - "html" - "html/template" - "net/http" - "net/url" - "strings" - "time" -) - -var ( - redditWidgetHorizontalCardsTemplate = mustParseTemplate("reddit-horizontal-cards.html", "widget-base.html") - redditWidgetVerticalCardsTemplate = mustParseTemplate("reddit-vertical-cards.html", "widget-base.html") -) - -type redditWidget struct { - widgetBase `yaml:",inline"` - Posts forumPostList `yaml:"-"` - Subreddit string `yaml:"subreddit"` - Proxy proxyOptionsField `yaml:"proxy"` - Style string `yaml:"style"` - ShowThumbnails bool `yaml:"show-thumbnails"` - ShowFlairs bool `yaml:"show-flairs"` - SortBy string `yaml:"sort-by"` - TopPeriod string `yaml:"top-period"` - Search string `yaml:"search"` - ExtraSortBy string `yaml:"extra-sort-by"` - CommentsUrlTemplate string `yaml:"comments-url-template"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` - RequestUrlTemplate string `yaml:"request-url-template"` -} - -func (widget *redditWidget) initialize() error { - if widget.Subreddit == "" { - return errors.New("subreddit is required") - } - - if widget.Limit <= 0 { - widget.Limit = 15 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - if !isValidRedditSortType(widget.SortBy) { - widget.SortBy = "hot" - } - - if !isValidRedditTopPeriod(widget.TopPeriod) { - widget.TopPeriod = "day" - } - - if widget.RequestUrlTemplate != "" { - if !strings.Contains(widget.RequestUrlTemplate, "{REQUEST-URL}") { - return errors.New("no `{REQUEST-URL}` placeholder specified") - } - } - - widget. - withTitle("r/" + widget.Subreddit). - withTitleURL("https://www.reddit.com/r/" + widget.Subreddit + "/"). - withCacheDuration(30 * time.Minute) - - return nil -} - -func isValidRedditSortType(sortBy string) bool { - return sortBy == "hot" || - sortBy == "new" || - sortBy == "top" || - sortBy == "rising" -} - -func isValidRedditTopPeriod(period string) bool { - return period == "hour" || - period == "day" || - period == "week" || - period == "month" || - period == "year" || - period == "all" -} - -func (widget *redditWidget) update(ctx context.Context) { - // TODO: refactor, use a struct to pass all of these - posts, err := fetchSubredditPosts( - widget.Subreddit, - widget.SortBy, - widget.TopPeriod, - widget.Search, - widget.CommentsUrlTemplate, - widget.RequestUrlTemplate, - widget.Proxy.client, - widget.ShowFlairs, - ) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if len(posts) > widget.Limit { - posts = posts[:widget.Limit] - } - - if widget.ExtraSortBy == "engagement" { - posts.calculateEngagement() - posts.sortByEngagement() - } - - widget.Posts = posts -} - -func (widget *redditWidget) Render() template.HTML { - if widget.Style == "horizontal-cards" { - return widget.renderTemplate(widget, redditWidgetHorizontalCardsTemplate) - } - - if widget.Style == "vertical-cards" { - return widget.renderTemplate(widget, redditWidgetVerticalCardsTemplate) - } - - return widget.renderTemplate(widget, forumPostsTemplate) - -} - -type subredditResponseJson struct { - Data struct { - Children []struct { - Data struct { - Id string `json:"id"` - Title string `json:"title"` - Upvotes int `json:"ups"` - Url string `json:"url"` - Time float64 `json:"created"` - CommentsCount int `json:"num_comments"` - Domain string `json:"domain"` - Permalink string `json:"permalink"` - Stickied bool `json:"stickied"` - Pinned bool `json:"pinned"` - IsSelf bool `json:"is_self"` - Thumbnail string `json:"thumbnail"` - Flair string `json:"link_flair_text"` - ParentList []struct { - Id string `json:"id"` - Subreddit string `json:"subreddit"` - Permalink string `json:"permalink"` - } `json:"crosspost_parent_list"` - } `json:"data"` - } `json:"children"` - } `json:"data"` -} - -func templateRedditCommentsURL(template, subreddit, postId, postPath string) string { - template = strings.ReplaceAll(template, "{SUBREDDIT}", subreddit) - template = strings.ReplaceAll(template, "{POST-ID}", postId) - template = strings.ReplaceAll(template, "{POST-PATH}", strings.TrimLeft(postPath, "/")) - - return template -} - -func fetchSubredditPosts( - subreddit, - sort, - topPeriod, - search, - commentsUrlTemplate, - requestUrlTemplate string, - proxyClient *http.Client, - showFlairs bool, -) (forumPostList, error) { - query := url.Values{} - var requestUrl string - - if search != "" { - query.Set("q", search+" subreddit:"+subreddit) - query.Set("sort", sort) - } - - if sort == "top" { - query.Set("t", topPeriod) - } - - if search != "" { - requestUrl = fmt.Sprintf("https://www.reddit.com/search.json?%s", query.Encode()) - } else { - requestUrl = fmt.Sprintf("https://www.reddit.com/r/%s/%s.json?%s", subreddit, sort, query.Encode()) - } - - var client requestDoer = defaultHTTPClient - - if requestUrlTemplate != "" { - requestUrl = strings.ReplaceAll(requestUrlTemplate, "{REQUEST-URL}", requestUrl) - } else if proxyClient != nil { - client = proxyClient - } - - request, err := http.NewRequest("GET", requestUrl, nil) - if err != nil { - return nil, err - } - - // Required to increase rate limit, otherwise Reddit randomly returns 429 even after just 2 requests - setBrowserUserAgentHeader(request) - responseJson, err := decodeJsonFromRequest[subredditResponseJson](client, request) - if err != nil { - return nil, err - } - - if len(responseJson.Data.Children) == 0 { - return nil, fmt.Errorf("no posts found") - } - - posts := make(forumPostList, 0, len(responseJson.Data.Children)) - - for i := range responseJson.Data.Children { - post := &responseJson.Data.Children[i].Data - - if post.Stickied || post.Pinned { - continue - } - - var commentsUrl string - - if commentsUrlTemplate == "" { - commentsUrl = "https://www.reddit.com" + post.Permalink - } else { - commentsUrl = templateRedditCommentsURL(commentsUrlTemplate, subreddit, post.Id, post.Permalink) - } - - forumPost := forumPost{ - Title: html.UnescapeString(post.Title), - DiscussionUrl: commentsUrl, - TargetUrlDomain: post.Domain, - CommentCount: post.CommentsCount, - Score: post.Upvotes, - TimePosted: time.Unix(int64(post.Time), 0), - } - - if post.Thumbnail != "" && post.Thumbnail != "self" && post.Thumbnail != "default" && post.Thumbnail != "nsfw" { - forumPost.ThumbnailUrl = html.UnescapeString(post.Thumbnail) - } - - if !post.IsSelf { - forumPost.TargetUrl = post.Url - } - - if showFlairs && post.Flair != "" { - forumPost.Tags = append(forumPost.Tags, post.Flair) - } - - if len(post.ParentList) > 0 { - forumPost.IsCrosspost = true - forumPost.TargetUrlDomain = "r/" + post.ParentList[0].Subreddit - - if commentsUrlTemplate == "" { - forumPost.TargetUrl = "https://www.reddit.com" + post.ParentList[0].Permalink - } else { - forumPost.TargetUrl = templateRedditCommentsURL( - commentsUrlTemplate, - post.ParentList[0].Subreddit, - post.ParentList[0].Id, - post.ParentList[0].Permalink, - ) - } - } - - posts = append(posts, forumPost) - } - - return posts, nil -} diff --git a/internal/glance/widget-releases.go b/internal/glance/widget-releases.go deleted file mode 100644 index de56bc5..0000000 --- a/internal/glance/widget-releases.go +++ /dev/null @@ -1,421 +0,0 @@ -package glance - -import ( - "context" - "errors" - "fmt" - "html/template" - "log/slog" - "net/http" - "net/url" - "sort" - "strings" - "time" - - "gopkg.in/yaml.v3" -) - -var releasesWidgetTemplate = mustParseTemplate("releases.html", "widget-base.html") - -type releasesWidget struct { - widgetBase `yaml:",inline"` - Releases appReleaseList `yaml:"-"` - Repositories []*releaseRequest `yaml:"repositories"` - Token string `yaml:"token"` - GitLabToken string `yaml:"gitlab-token"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` - ShowSourceIcon bool `yaml:"show-source-icon"` -} - -func (widget *releasesWidget) initialize() error { - widget.withTitle("Releases").withCacheDuration(2 * time.Hour) - - if widget.Limit <= 0 { - widget.Limit = 10 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - for i := range widget.Repositories { - r := widget.Repositories[i] - - if r.source == releaseSourceGithub && widget.Token != "" { - r.token = &widget.Token - } else if r.source == releaseSourceGitlab && widget.GitLabToken != "" { - r.token = &widget.GitLabToken - } - } - - return nil -} - -func (widget *releasesWidget) update(ctx context.Context) { - releases, err := fetchLatestReleases(widget.Repositories) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if len(releases) > widget.Limit { - releases = releases[:widget.Limit] - } - - for i := range releases { - releases[i].SourceIconURL = widget.Providers.assetResolver("icons/" + string(releases[i].Source) + ".svg") - } - - widget.Releases = releases -} - -func (widget *releasesWidget) Render() template.HTML { - return widget.renderTemplate(widget, releasesWidgetTemplate) -} - -type releaseSource string - -const ( - releaseSourceCodeberg releaseSource = "codeberg" - releaseSourceGithub releaseSource = "github" - releaseSourceGitlab releaseSource = "gitlab" - releaseSourceDockerHub releaseSource = "dockerhub" -) - -type appRelease struct { - Source releaseSource - SourceIconURL string - Name string - Version string - NotesUrl string - TimeReleased time.Time - Downvotes int -} - -type appReleaseList []appRelease - -func (r appReleaseList) sortByNewest() appReleaseList { - sort.Slice(r, func(i, j int) bool { - return r[i].TimeReleased.After(r[j].TimeReleased) - }) - - return r -} - -type releaseRequest struct { - IncludePreleases bool `yaml:"include-prereleases"` - Repository string `yaml:"repository"` - - source releaseSource - token *string -} - -func (r *releaseRequest) UnmarshalYAML(node *yaml.Node) error { - type releaseRequestAlias releaseRequest - alias := (*releaseRequestAlias)(r) - var repository string - - if err := node.Decode(&repository); err != nil { - if err := node.Decode(alias); err != nil { - return fmt.Errorf("could not umarshal repository into string or struct: %v", err) - } - } - - if r.Repository == "" { - if repository == "" { - return errors.New("repository is required") - } else { - r.Repository = repository - } - } - - parts := strings.SplitN(repository, ":", 2) - if len(parts) == 1 { - r.source = releaseSourceGithub - } else if len(parts) == 2 { - r.Repository = parts[1] - - switch parts[0] { - case string(releaseSourceGithub): - r.source = releaseSourceGithub - case string(releaseSourceGitlab): - r.source = releaseSourceGitlab - case string(releaseSourceDockerHub): - r.source = releaseSourceDockerHub - case string(releaseSourceCodeberg): - r.source = releaseSourceCodeberg - default: - return errors.New("invalid source") - } - } - - return nil -} - -func fetchLatestReleases(requests []*releaseRequest) (appReleaseList, error) { - job := newJob(fetchLatestReleaseTask, requests).withWorkers(20) - results, errs, err := workerPoolDo(job) - if err != nil { - return nil, err - } - - var failed int - - releases := make(appReleaseList, 0, len(requests)) - - for i := range results { - if errs[i] != nil { - failed++ - slog.Error("Failed to fetch release", "source", requests[i].source, "repository", requests[i].Repository, "error", errs[i]) - continue - } - - releases = append(releases, *results[i]) - } - - if failed == len(requests) { - return nil, errNoContent - } - - releases.sortByNewest() - - if failed > 0 { - return releases, fmt.Errorf("%w: could not get %d releases", errPartialContent, failed) - } - - return releases, nil -} - -func fetchLatestReleaseTask(request *releaseRequest) (*appRelease, error) { - switch request.source { - case releaseSourceCodeberg: - return fetchLatestCodebergRelease(request) - case releaseSourceGithub: - return fetchLatestGithubRelease(request) - case releaseSourceGitlab: - return fetchLatestGitLabRelease(request) - case releaseSourceDockerHub: - return fetchLatestDockerHubRelease(request) - } - - return nil, errors.New("unsupported source") -} - -type githubReleaseResponseJson struct { - TagName string `json:"tag_name"` - PublishedAt string `json:"published_at"` - HtmlUrl string `json:"html_url"` - Reactions struct { - Downvotes int `json:"-1"` - } `json:"reactions"` -} - -func fetchLatestGithubRelease(request *releaseRequest) (*appRelease, error) { - var requestURL string - if !request.IncludePreleases { - requestURL = fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", request.Repository) - } else { - requestURL = fmt.Sprintf("https://api.github.com/repos/%s/releases", request.Repository) - } - - httpRequest, err := http.NewRequest("GET", requestURL, nil) - if err != nil { - return nil, err - } - - if request.token != nil { - httpRequest.Header.Add("Authorization", "Bearer "+(*request.token)) - } - - var response githubReleaseResponseJson - - if !request.IncludePreleases { - response, err = decodeJsonFromRequest[githubReleaseResponseJson](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - } else { - responses, err := decodeJsonFromRequest[[]githubReleaseResponseJson](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - - if len(responses) == 0 { - return nil, fmt.Errorf("no releases found for repository %s", request.Repository) - } - - response = responses[0] - } - - return &appRelease{ - Source: releaseSourceGithub, - Name: request.Repository, - Version: normalizeVersionFormat(response.TagName), - NotesUrl: response.HtmlUrl, - TimeReleased: parseRFC3339Time(response.PublishedAt), - Downvotes: response.Reactions.Downvotes, - }, nil -} - -type dockerHubRepositoryTagsResponse struct { - Results []dockerHubRepositoryTagResponse `json:"results"` -} - -type dockerHubRepositoryTagResponse struct { - Name string `json:"name"` - LastPushed string `json:"tag_last_pushed"` -} - -const dockerHubOfficialRepoTagURLFormat = "https://hub.docker.com/_/%s/tags?name=%s" -const dockerHubRepoTagURLFormat = "https://hub.docker.com/r/%s/tags?name=%s" -const dockerHubTagsURLFormat = "https://hub.docker.com/v2/namespaces/%s/repositories/%s/tags" -const dockerHubSpecificTagURLFormat = "https://hub.docker.com/v2/namespaces/%s/repositories/%s/tags/%s" - -func fetchLatestDockerHubRelease(request *releaseRequest) (*appRelease, error) { - nameParts := strings.Split(request.Repository, "/") - - if len(nameParts) > 2 { - return nil, fmt.Errorf("invalid repository name: %s", request.Repository) - } else if len(nameParts) == 1 { - nameParts = []string{"library", nameParts[0]} - } - - tagParts := strings.SplitN(nameParts[1], ":", 2) - var requestURL string - - if len(tagParts) == 2 { - requestURL = fmt.Sprintf(dockerHubSpecificTagURLFormat, nameParts[0], tagParts[0], tagParts[1]) - } else { - requestURL = fmt.Sprintf(dockerHubTagsURLFormat, nameParts[0], nameParts[1]) - } - - httpRequest, err := http.NewRequest("GET", requestURL, nil) - if err != nil { - return nil, err - } - - if request.token != nil { - httpRequest.Header.Add("Authorization", "Bearer "+(*request.token)) - } - - var tag *dockerHubRepositoryTagResponse - - if len(tagParts) == 1 { - response, err := decodeJsonFromRequest[dockerHubRepositoryTagsResponse](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - - if len(response.Results) == 0 { - return nil, fmt.Errorf("no tags found for repository: %s", request.Repository) - } - - tag = &response.Results[0] - } else { - response, err := decodeJsonFromRequest[dockerHubRepositoryTagResponse](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - - tag = &response - } - - var repo string - var displayName string - var notesURL string - - if len(tagParts) == 1 { - repo = nameParts[1] - } else { - repo = tagParts[0] - } - - if nameParts[0] == "library" { - displayName = repo - notesURL = fmt.Sprintf(dockerHubOfficialRepoTagURLFormat, repo, tag.Name) - } else { - displayName = nameParts[0] + "/" + repo - notesURL = fmt.Sprintf(dockerHubRepoTagURLFormat, displayName, tag.Name) - } - - return &appRelease{ - Source: releaseSourceDockerHub, - NotesUrl: notesURL, - Name: displayName, - Version: tag.Name, - TimeReleased: parseRFC3339Time(tag.LastPushed), - }, nil -} - -type gitlabReleaseResponseJson struct { - TagName string `json:"tag_name"` - ReleasedAt string `json:"released_at"` - Links struct { - Self string `json:"self"` - } `json:"_links"` -} - -func fetchLatestGitLabRelease(request *releaseRequest) (*appRelease, error) { - httpRequest, err := http.NewRequest( - "GET", - fmt.Sprintf( - "https://gitlab.com/api/v4/projects/%s/releases/permalink/latest", - url.QueryEscape(request.Repository), - ), - nil, - ) - if err != nil { - return nil, err - } - - if request.token != nil { - httpRequest.Header.Add("PRIVATE-TOKEN", *request.token) - } - - response, err := decodeJsonFromRequest[gitlabReleaseResponseJson](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - - return &appRelease{ - Source: releaseSourceGitlab, - Name: request.Repository, - Version: normalizeVersionFormat(response.TagName), - NotesUrl: response.Links.Self, - TimeReleased: parseRFC3339Time(response.ReleasedAt), - }, nil -} - -type codebergReleaseResponseJson struct { - TagName string `json:"tag_name"` - PublishedAt string `json:"published_at"` - HtmlUrl string `json:"html_url"` -} - -func fetchLatestCodebergRelease(request *releaseRequest) (*appRelease, error) { - httpRequest, err := http.NewRequest( - "GET", - fmt.Sprintf( - "https://codeberg.org/api/v1/repos/%s/releases/latest", - request.Repository, - ), - nil, - ) - if err != nil { - return nil, err - } - - response, err := decodeJsonFromRequest[codebergReleaseResponseJson](defaultHTTPClient, httpRequest) - if err != nil { - return nil, err - } - - return &appRelease{ - Source: releaseSourceCodeberg, - Name: request.Repository, - Version: normalizeVersionFormat(response.TagName), - NotesUrl: response.HtmlUrl, - TimeReleased: parseRFC3339Time(response.PublishedAt), - }, nil -} diff --git a/internal/glance/widget-repository.go b/internal/glance/widget-repository.go deleted file mode 100644 index 1eeb8b4..0000000 --- a/internal/glance/widget-repository.go +++ /dev/null @@ -1,238 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html/template" - "net/http" - "strings" - "sync" - "time" -) - -var repositoryWidgetTemplate = mustParseTemplate("repository.html", "widget-base.html") - -type repositoryWidget struct { - widgetBase `yaml:",inline"` - RequestedRepository string `yaml:"repository"` - Token string `yaml:"token"` - PullRequestsLimit int `yaml:"pull-requests-limit"` - IssuesLimit int `yaml:"issues-limit"` - CommitsLimit int `yaml:"commits-limit"` - Repository repository `yaml:"-"` -} - -func (widget *repositoryWidget) initialize() error { - widget.withTitle("Repository").withCacheDuration(1 * time.Hour) - - if widget.PullRequestsLimit == 0 || widget.PullRequestsLimit < -1 { - widget.PullRequestsLimit = 3 - } - - if widget.IssuesLimit == 0 || widget.IssuesLimit < -1 { - widget.IssuesLimit = 3 - } - - if widget.CommitsLimit == 0 || widget.CommitsLimit < -1 { - widget.CommitsLimit = -1 - } - - return nil -} - -func (widget *repositoryWidget) update(ctx context.Context) { - details, err := fetchRepositoryDetailsFromGithub( - widget.RequestedRepository, - string(widget.Token), - widget.PullRequestsLimit, - widget.IssuesLimit, - widget.CommitsLimit, - ) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - widget.Repository = details -} - -func (widget *repositoryWidget) Render() template.HTML { - return widget.renderTemplate(widget, repositoryWidgetTemplate) -} - -type repository struct { - Name string - Stars int - Forks int - OpenPullRequests int - PullRequests []githubTicket - OpenIssues int - Issues []githubTicket - LastCommits int - Commits []githubCommitDetails -} - -type githubTicket struct { - Number int - CreatedAt time.Time - Title string -} - -type githubCommitDetails struct { - Sha string - Author string - CreatedAt time.Time - Message string -} - -type githubRepositoryResponseJson struct { - Name string `json:"full_name"` - Stars int `json:"stargazers_count"` - Forks int `json:"forks_count"` -} - -type githubTicketResponseJson struct { - Count int `json:"total_count"` - Tickets []struct { - Number int `json:"number"` - CreatedAt string `json:"created_at"` - Title string `json:"title"` - } `json:"items"` -} - -type gitHubCommitResponseJson struct { - Sha string `json:"sha"` - Commit struct { - Author struct { - Name string `json:"name"` - Date string `json:"date"` - } `json:"author"` - Message string `json:"message"` - } `json:"commit"` -} - -func fetchRepositoryDetailsFromGithub(repo string, token string, maxPRs int, maxIssues int, maxCommits int) (repository, error) { - repositoryRequest, err := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s", repo), nil) - if err != nil { - return repository{}, fmt.Errorf("%w: could not create request with repository: %v", errNoContent, err) - } - - PRsRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/search/issues?q=is:pr+is:open+repo:%s&per_page=%d", repo, maxPRs), nil) - issuesRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/search/issues?q=is:issue+is:open+repo:%s&per_page=%d", repo, maxIssues), nil) - CommitsRequest, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s/commits?per_page=%d", repo, maxCommits), nil) - - if token != "" { - token = fmt.Sprintf("Bearer %s", token) - repositoryRequest.Header.Add("Authorization", token) - PRsRequest.Header.Add("Authorization", token) - issuesRequest.Header.Add("Authorization", token) - CommitsRequest.Header.Add("Authorization", token) - } - - var repositoryResponse githubRepositoryResponseJson - var detailsErr error - var PRsResponse githubTicketResponseJson - var PRsErr error - var issuesResponse githubTicketResponseJson - var issuesErr error - var commitsResponse []gitHubCommitResponseJson - var CommitsErr error - var wg sync.WaitGroup - - wg.Add(1) - go (func() { - defer wg.Done() - repositoryResponse, detailsErr = decodeJsonFromRequest[githubRepositoryResponseJson](defaultHTTPClient, repositoryRequest) - })() - - if maxPRs > 0 { - wg.Add(1) - go (func() { - defer wg.Done() - PRsResponse, PRsErr = decodeJsonFromRequest[githubTicketResponseJson](defaultHTTPClient, PRsRequest) - })() - } - - if maxIssues > 0 { - wg.Add(1) - go (func() { - defer wg.Done() - issuesResponse, issuesErr = decodeJsonFromRequest[githubTicketResponseJson](defaultHTTPClient, issuesRequest) - })() - } - - if maxCommits > 0 { - wg.Add(1) - go (func() { - defer wg.Done() - commitsResponse, CommitsErr = decodeJsonFromRequest[[]gitHubCommitResponseJson](defaultHTTPClient, CommitsRequest) - })() - } - - wg.Wait() - - if detailsErr != nil { - return repository{}, fmt.Errorf("%w: could not get repository details: %s", errNoContent, detailsErr) - } - - details := repository{ - Name: repositoryResponse.Name, - Stars: repositoryResponse.Stars, - Forks: repositoryResponse.Forks, - PullRequests: make([]githubTicket, 0, len(PRsResponse.Tickets)), - Issues: make([]githubTicket, 0, len(issuesResponse.Tickets)), - Commits: make([]githubCommitDetails, 0, len(commitsResponse)), - } - - err = nil - - if maxPRs > 0 { - if PRsErr != nil { - err = fmt.Errorf("%w: could not get PRs: %s", errPartialContent, PRsErr) - } else { - details.OpenPullRequests = PRsResponse.Count - - for i := range PRsResponse.Tickets { - details.PullRequests = append(details.PullRequests, githubTicket{ - Number: PRsResponse.Tickets[i].Number, - CreatedAt: parseRFC3339Time(PRsResponse.Tickets[i].CreatedAt), - Title: PRsResponse.Tickets[i].Title, - }) - } - } - } - - if maxIssues > 0 { - if issuesErr != nil { - // TODO: fix, overwriting the previous error - err = fmt.Errorf("%w: could not get issues: %s", errPartialContent, issuesErr) - } else { - details.OpenIssues = issuesResponse.Count - - for i := range issuesResponse.Tickets { - details.Issues = append(details.Issues, githubTicket{ - Number: issuesResponse.Tickets[i].Number, - CreatedAt: parseRFC3339Time(issuesResponse.Tickets[i].CreatedAt), - Title: issuesResponse.Tickets[i].Title, - }) - } - } - } - - if maxCommits > 0 { - if CommitsErr != nil { - err = fmt.Errorf("%w: could not get commits: %s", errPartialContent, CommitsErr) - } else { - for i := range commitsResponse { - details.Commits = append(details.Commits, githubCommitDetails{ - Sha: commitsResponse[i].Sha, - Author: commitsResponse[i].Commit.Author.Name, - CreatedAt: parseRFC3339Time(commitsResponse[i].Commit.Author.Date), - Message: strings.SplitN(commitsResponse[i].Commit.Message, "\n\n", 2)[0], - }) - } - } - } - - return details, err -} diff --git a/internal/glance/widget-rss.go b/internal/glance/widget-rss.go deleted file mode 100644 index 1598371..0000000 --- a/internal/glance/widget-rss.go +++ /dev/null @@ -1,361 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html" - "html/template" - "io" - "log/slog" - "net/http" - "net/url" - "regexp" - "sort" - "strings" - "time" - - "github.com/mmcdole/gofeed" - gofeedext "github.com/mmcdole/gofeed/extensions" -) - -var ( - rssWidgetTemplate = mustParseTemplate("rss-list.html", "widget-base.html") - rssWidgetDetailedListTemplate = mustParseTemplate("rss-detailed-list.html", "widget-base.html") - rssWidgetHorizontalCardsTemplate = mustParseTemplate("rss-horizontal-cards.html", "widget-base.html") - rssWidgetHorizontalCards2Template = mustParseTemplate("rss-horizontal-cards-2.html", "widget-base.html") -) - -type rssWidget struct { - widgetBase `yaml:",inline"` - FeedRequests []rssFeedRequest `yaml:"feeds"` - Style string `yaml:"style"` - ThumbnailHeight float64 `yaml:"thumbnail-height"` - CardHeight float64 `yaml:"card-height"` - Items rssFeedItemList `yaml:"-"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` - SingleLineTitles bool `yaml:"single-line-titles"` - PreserveOrder bool `yaml:"preserve-order"` - NoItemsMessage string `yaml:"-"` -} - -func (widget *rssWidget) initialize() error { - widget.withTitle("RSS Feed").withCacheDuration(1 * time.Hour) - - if widget.Limit <= 0 { - widget.Limit = 25 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - if widget.ThumbnailHeight < 0 { - widget.ThumbnailHeight = 0 - } - - if widget.CardHeight < 0 { - widget.CardHeight = 0 - } - - if widget.Style == "detailed-list" { - for i := range widget.FeedRequests { - widget.FeedRequests[i].IsDetailed = true - } - } - - widget.NoItemsMessage = "No items were returned from the feeds." - - return nil -} - -func (widget *rssWidget) update(ctx context.Context) { - items, err := fetchItemsFromRSSFeeds(widget.FeedRequests) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if !widget.PreserveOrder { - items.sortByNewest() - } - - if len(items) > widget.Limit { - items = items[:widget.Limit] - } - - widget.Items = items -} - -func (widget *rssWidget) Render() template.HTML { - if widget.Style == "horizontal-cards" { - return widget.renderTemplate(widget, rssWidgetHorizontalCardsTemplate) - } - - if widget.Style == "horizontal-cards-2" { - return widget.renderTemplate(widget, rssWidgetHorizontalCards2Template) - } - - if widget.Style == "detailed-list" { - return widget.renderTemplate(widget, rssWidgetDetailedListTemplate) - } - - return widget.renderTemplate(widget, rssWidgetTemplate) -} - -type rssFeedItem struct { - ChannelName string - ChannelURL string - Title string - Link string - ImageURL string - Categories []string - Description string - PublishedAt time.Time -} - -// doesn't cover all cases but works the vast majority of the time -var htmlTagsWithAttributesPattern = regexp.MustCompile(`<\/?[a-zA-Z0-9-]+ *(?:[a-zA-Z-]+=(?:"|').*?(?:"|') ?)* *\/?>`) - -func sanitizeFeedDescription(description string) string { - if description == "" { - return "" - } - - description = strings.ReplaceAll(description, "\n", " ") - description = htmlTagsWithAttributesPattern.ReplaceAllString(description, "") - description = sequentialWhitespacePattern.ReplaceAllString(description, " ") - description = strings.TrimSpace(description) - description = html.UnescapeString(description) - - return description -} - -func shortenFeedDescriptionLen(description string, maxLen int) string { - description, _ = limitStringLength(description, 1000) - description = sanitizeFeedDescription(description) - description, limited := limitStringLength(description, maxLen) - - if limited { - description += "…" - } - - return description -} - -type rssFeedRequest struct { - URL string `yaml:"url"` - Title string `yaml:"title"` - HideCategories bool `yaml:"hide-categories"` - HideDescription bool `yaml:"hide-description"` - Limit int `yaml:"limit"` - ItemLinkPrefix string `yaml:"item-link-prefix"` - Headers map[string]string `yaml:"headers"` - IsDetailed bool `yaml:"-"` -} - -type rssFeedItemList []rssFeedItem - -func (f rssFeedItemList) sortByNewest() rssFeedItemList { - sort.Slice(f, func(i, j int) bool { - return f[i].PublishedAt.After(f[j].PublishedAt) - }) - - return f -} - -var feedParser = gofeed.NewParser() - -func fetchItemsFromRSSFeedTask(request rssFeedRequest) ([]rssFeedItem, error) { - req, err := http.NewRequest("GET", request.URL, nil) - if err != nil { - return nil, err - } - - for key, value := range request.Headers { - req.Header.Add(key, value) - } - - resp, err := defaultHTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("unexpected status code %d from %s", resp.StatusCode, request.URL) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - feed, err := feedParser.ParseString(string(body)) - if err != nil { - return nil, err - } - - if request.Limit > 0 && len(feed.Items) > request.Limit { - feed.Items = feed.Items[:request.Limit] - } - - items := make(rssFeedItemList, 0, len(feed.Items)) - - for i := range feed.Items { - item := feed.Items[i] - - rssItem := rssFeedItem{ - ChannelURL: feed.Link, - } - - if request.ItemLinkPrefix != "" { - rssItem.Link = request.ItemLinkPrefix + item.Link - } else if strings.HasPrefix(item.Link, "http://") || strings.HasPrefix(item.Link, "https://") { - rssItem.Link = item.Link - } else { - parsedUrl, err := url.Parse(feed.Link) - if err != nil { - parsedUrl, err = url.Parse(request.URL) - } - - if err == nil { - var link string - - if len(item.Link) > 0 && item.Link[0] == '/' { - link = item.Link - } else { - link = "/" + item.Link - } - - rssItem.Link = parsedUrl.Scheme + "://" + parsedUrl.Host + link - } - } - - if item.Title != "" { - rssItem.Title = html.UnescapeString(item.Title) - } else { - rssItem.Title = shortenFeedDescriptionLen(item.Description, 100) - } - - if request.IsDetailed { - if !request.HideDescription && item.Description != "" && item.Title != "" { - rssItem.Description = shortenFeedDescriptionLen(item.Description, 200) - } - - if !request.HideCategories { - var categories = make([]string, 0, 6) - - for _, category := range item.Categories { - if len(categories) == 6 { - break - } - - if len(category) == 0 || len(category) > 30 { - continue - } - - categories = append(categories, category) - } - - rssItem.Categories = categories - } - } - - if request.Title != "" { - rssItem.ChannelName = request.Title - } else { - rssItem.ChannelName = feed.Title - } - - if item.Image != nil { - rssItem.ImageURL = item.Image.URL - } else if url := findThumbnailInItemExtensions(item); url != "" { - rssItem.ImageURL = url - } else if feed.Image != nil { - if len(feed.Image.URL) > 0 && feed.Image.URL[0] == '/' { - rssItem.ImageURL = strings.TrimRight(feed.Link, "/") + feed.Image.URL - } else { - rssItem.ImageURL = feed.Image.URL - } - } - - if item.PublishedParsed != nil { - rssItem.PublishedAt = *item.PublishedParsed - } else { - rssItem.PublishedAt = time.Now() - } - - items = append(items, rssItem) - } - - return items, nil -} - -func recursiveFindThumbnailInExtensions(extensions map[string][]gofeedext.Extension) string { - for _, exts := range extensions { - for _, ext := range exts { - if ext.Name == "thumbnail" || ext.Name == "image" { - if url, ok := ext.Attrs["url"]; ok { - return url - } - } - - if ext.Children != nil { - if url := recursiveFindThumbnailInExtensions(ext.Children); url != "" { - return url - } - } - } - } - - return "" -} - -func findThumbnailInItemExtensions(item *gofeed.Item) string { - media, ok := item.Extensions["media"] - - if !ok { - return "" - } - - return recursiveFindThumbnailInExtensions(media) -} - -func fetchItemsFromRSSFeeds(requests []rssFeedRequest) (rssFeedItemList, error) { - job := newJob(fetchItemsFromRSSFeedTask, requests).withWorkers(30) - feeds, errs, err := workerPoolDo(job) - if err != nil { - return nil, fmt.Errorf("%w: %v", errNoContent, err) - } - - failed := 0 - entries := make(rssFeedItemList, 0, len(feeds)*10) - seen := make(map[string]struct{}) - - for i := range feeds { - if errs[i] != nil { - failed++ - slog.Error("Failed to get RSS feed", "url", requests[i].URL, "error", errs[i]) - continue - } - - for _, item := range feeds[i] { - if _, exists := seen[item.Link]; exists { - continue - } - entries = append(entries, item) - seen[item.Link] = struct{}{} - } - } - - if failed == len(requests) { - return nil, errNoContent - } - - if failed > 0 { - return entries, fmt.Errorf("%w: missing %d RSS feeds", errPartialContent, failed) - } - - return entries, nil -} diff --git a/internal/glance/widget-search.go b/internal/glance/widget-search.go deleted file mode 100644 index 9d2b600..0000000 --- a/internal/glance/widget-search.go +++ /dev/null @@ -1,73 +0,0 @@ -package glance - -import ( - "fmt" - "html/template" - "strings" -) - -var searchWidgetTemplate = mustParseTemplate("search.html", "widget-base.html") - -type SearchBang struct { - Title string - Shortcut string - URL string -} - -type searchWidget struct { - widgetBase `yaml:",inline"` - cachedHTML template.HTML `yaml:"-"` - SearchEngine string `yaml:"search-engine"` - Bangs []SearchBang `yaml:"bangs"` - NewTab bool `yaml:"new-tab"` - Autofocus bool `yaml:"autofocus"` - Placeholder string `yaml:"placeholder"` -} - -func convertSearchUrl(url string) string { - // Go's template is being stubborn and continues to escape the curlies in the - // URL regardless of what the type of the variable is so this is my way around it - return strings.ReplaceAll(url, "{QUERY}", "!QUERY!") -} - -var searchEngines = map[string]string{ - "duckduckgo": "https://duckduckgo.com/?q={QUERY}", - "google": "https://www.google.com/search?q={QUERY}", -} - -func (widget *searchWidget) initialize() error { - widget.withTitle("Search").withError(nil) - - if widget.SearchEngine == "" { - widget.SearchEngine = "duckduckgo" - } - - if widget.Placeholder == "" { - widget.Placeholder = "Type here to search…" - } - - if url, ok := searchEngines[widget.SearchEngine]; ok { - widget.SearchEngine = url - } - - widget.SearchEngine = convertSearchUrl(widget.SearchEngine) - - for i := range widget.Bangs { - if widget.Bangs[i].Shortcut == "" { - return fmt.Errorf("search bang #%d has no shortcut", i+1) - } - - if widget.Bangs[i].URL == "" { - return fmt.Errorf("search bang #%d has no URL", i+1) - } - - widget.Bangs[i].URL = convertSearchUrl(widget.Bangs[i].URL) - } - - widget.cachedHTML = widget.renderTemplate(widget, searchWidgetTemplate) - return nil -} - -func (widget *searchWidget) Render() template.HTML { - return widget.cachedHTML -} diff --git a/internal/glance/widget-server-stats.go b/internal/glance/widget-server-stats.go deleted file mode 100644 index 90bf8db..0000000 --- a/internal/glance/widget-server-stats.go +++ /dev/null @@ -1,117 +0,0 @@ -package glance - -import ( - "context" - "html/template" - "log/slog" - "net/http" - "strconv" - "strings" - "sync" - "time" - - "github.com/glanceapp/glance/pkg/sysinfo" -) - -var serverStatsWidgetTemplate = mustParseTemplate("server-stats.html", "widget-base.html") - -type serverStatsWidget struct { - widgetBase `yaml:",inline"` - Servers []serverStatsRequest `yaml:"servers"` -} - -func (widget *serverStatsWidget) initialize() error { - widget.withTitle("Server Stats").withCacheDuration(15 * time.Second) - widget.widgetBase.WIP = true - - if len(widget.Servers) == 0 { - widget.Servers = []serverStatsRequest{{Type: "local"}} - } - - for i := range widget.Servers { - widget.Servers[i].URL = strings.TrimRight(widget.Servers[i].URL, "/") - - if widget.Servers[i].Timeout == 0 { - widget.Servers[i].Timeout = durationField(3 * time.Second) - } - } - - return nil -} - -func (widget *serverStatsWidget) update(context.Context) { - // Refactor later, most of it may change depending on feedback - var wg sync.WaitGroup - - for i := range widget.Servers { - serv := &widget.Servers[i] - - if serv.Type == "local" { - info, errs := sysinfo.Collect(serv.SystemInfoRequest) - - if len(errs) > 0 { - for i := range errs { - slog.Warn("Getting system info: " + errs[i].Error()) - } - } - - serv.IsReachable = true - serv.Info = info - } else { - wg.Add(1) - go func() { - defer wg.Done() - info, err := fetchRemoteServerInfo(serv) - if err != nil { - slog.Warn("Getting remote system info: " + err.Error()) - serv.IsReachable = false - serv.Info = &sysinfo.SystemInfo{ - Hostname: "Unnamed server #" + strconv.Itoa(i+1), - } - } else { - serv.IsReachable = true - serv.Info = info - } - }() - } - } - - wg.Wait() - widget.withError(nil).scheduleNextUpdate() -} - -func (widget *serverStatsWidget) Render() template.HTML { - return widget.renderTemplate(widget, serverStatsWidgetTemplate) -} - -type serverStatsRequest struct { - *sysinfo.SystemInfoRequest `yaml:",inline"` - Info *sysinfo.SystemInfo `yaml:"-"` - IsReachable bool `yaml:"-"` - StatusText string `yaml:"-"` - Name string `yaml:"name"` - HideSwap bool `yaml:"hide-swap"` - Type string `yaml:"type"` - URL string `yaml:"url"` - Token string `yaml:"token"` - Timeout durationField `yaml:"timeout"` - // Support for other agents - // Provider string `yaml:"provider"` -} - -func fetchRemoteServerInfo(infoReq *serverStatsRequest) (*sysinfo.SystemInfo, error) { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(infoReq.Timeout)) - defer cancel() - - request, _ := http.NewRequestWithContext(ctx, "GET", infoReq.URL+"/api/sysinfo/all", nil) - if infoReq.Token != "" { - request.Header.Set("Authorization", "Bearer "+infoReq.Token) - } - - info, err := decodeJsonFromRequest[*sysinfo.SystemInfo](defaultHTTPClient, request) - if err != nil { - return nil, err - } - - return info, nil -} diff --git a/internal/glance/widget-shared.go b/internal/glance/widget-shared.go deleted file mode 100644 index 45144ac..0000000 --- a/internal/glance/widget-shared.go +++ /dev/null @@ -1,64 +0,0 @@ -package glance - -import ( - "math" - "sort" - "time" -) - -const twitchGqlEndpoint = "https://gql.twitch.tv/gql" -const twitchGqlClientId = "kimne78kx3ncx6brgo4mv6wki5h1ko" - -var forumPostsTemplate = mustParseTemplate("forum-posts.html", "widget-base.html") - -type forumPost struct { - Title string - DiscussionUrl string - TargetUrl string - TargetUrlDomain string - ThumbnailUrl string - CommentCount int - Score int - Engagement float64 - TimePosted time.Time - Tags []string - IsCrosspost bool -} - -type forumPostList []forumPost - -const depreciatePostsOlderThanHours = 7 -const maxDepreciation = 0.9 -const maxDepreciationAfterHours = 24 - -func (p forumPostList) calculateEngagement() { - var totalComments int - var totalScore int - - for i := range p { - totalComments += p[i].CommentCount - totalScore += p[i].Score - } - - numberOfPosts := float64(len(p)) - averageComments := float64(totalComments) / numberOfPosts - averageScore := float64(totalScore) / numberOfPosts - - for i := range p { - p[i].Engagement = (float64(p[i].CommentCount)/averageComments + float64(p[i].Score)/averageScore) / 2 - - elapsed := time.Since(p[i].TimePosted) - - if elapsed < time.Hour*depreciatePostsOlderThanHours { - continue - } - - p[i].Engagement *= 1.0 - (math.Max(elapsed.Hours()-depreciatePostsOlderThanHours, maxDepreciationAfterHours)/maxDepreciationAfterHours)*maxDepreciation - } -} - -func (p forumPostList) sortByEngagement() { - sort.Slice(p, func(i, j int) bool { - return p[i].Engagement > p[j].Engagement - }) -} diff --git a/internal/glance/widget-split-column.go b/internal/glance/widget-split-column.go deleted file mode 100644 index 71747c9..0000000 --- a/internal/glance/widget-split-column.go +++ /dev/null @@ -1,45 +0,0 @@ -package glance - -import ( - "context" - "html/template" - "time" -) - -var splitColumnWidgetTemplate = mustParseTemplate("split-column.html", "widget-base.html") - -type splitColumnWidget struct { - widgetBase `yaml:",inline"` - containerWidgetBase `yaml:",inline"` - MaxColumns int `yaml:"max-columns"` -} - -func (widget *splitColumnWidget) initialize() error { - widget.withError(nil).withTitle("Split Column").setHideHeader(true) - - if err := widget.containerWidgetBase._initializeWidgets(); err != nil { - return err - } - - if widget.MaxColumns < 2 { - widget.MaxColumns = 2 - } - - return nil -} - -func (widget *splitColumnWidget) update(ctx context.Context) { - widget.containerWidgetBase._update(ctx) -} - -func (widget *splitColumnWidget) setProviders(providers *widgetProviders) { - widget.containerWidgetBase._setProviders(providers) -} - -func (widget *splitColumnWidget) requiresUpdate(now *time.Time) bool { - return widget.containerWidgetBase._requiresUpdate(now) -} - -func (widget *splitColumnWidget) Render() template.HTML { - return widget.renderTemplate(widget, splitColumnWidgetTemplate) -} diff --git a/internal/glance/widget-twitch-channels.go b/internal/glance/widget-twitch-channels.go deleted file mode 100644 index 1290a26..0000000 --- a/internal/glance/widget-twitch-channels.go +++ /dev/null @@ -1,238 +0,0 @@ -package glance - -import ( - "context" - "encoding/json" - "fmt" - "html/template" - "log/slog" - "net/http" - "sort" - "strings" - "time" -) - -var twitchChannelsWidgetTemplate = mustParseTemplate("twitch-channels.html", "widget-base.html") - -type twitchChannelsWidget struct { - widgetBase `yaml:",inline"` - ChannelsRequest []string `yaml:"channels"` - Channels []twitchChannel `yaml:"-"` - CollapseAfter int `yaml:"collapse-after"` - SortBy string `yaml:"sort-by"` -} - -func (widget *twitchChannelsWidget) initialize() error { - widget. - withTitle("Twitch Channels"). - withTitleURL("https://www.twitch.tv/directory/following"). - withCacheDuration(time.Minute * 10) - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - if widget.SortBy != "viewers" && widget.SortBy != "live" { - widget.SortBy = "viewers" - } - - return nil -} - -func (widget *twitchChannelsWidget) update(ctx context.Context) { - channels, err := fetchChannelsFromTwitch(widget.ChannelsRequest) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if widget.SortBy == "viewers" { - channels.sortByViewers() - } else if widget.SortBy == "live" { - channels.sortByLive() - } - - widget.Channels = channels -} - -func (widget *twitchChannelsWidget) Render() template.HTML { - return widget.renderTemplate(widget, twitchChannelsWidgetTemplate) -} - -type twitchChannel struct { - Login string - Exists bool - Name string - StreamTitle string - AvatarUrl string - IsLive bool - LiveSince time.Time - Category string - CategorySlug string - ViewersCount int -} - -type twitchChannelList []twitchChannel - -func (channels twitchChannelList) sortByViewers() { - sort.Slice(channels, func(i, j int) bool { - return channels[i].ViewersCount > channels[j].ViewersCount - }) -} - -func (channels twitchChannelList) sortByLive() { - sort.SliceStable(channels, func(i, j int) bool { - return channels[i].IsLive && !channels[j].IsLive - }) -} - -type twitchOperationResponse struct { - Data json.RawMessage - Extensions struct { - OperationName string `json:"operationName"` - } -} - -type twitchChannelShellOperationResponse struct { - UserOrError struct { - Type string `json:"__typename"` - DisplayName string `json:"displayName"` - ProfileImageUrl string `json:"profileImageURL"` - Stream *struct { - ViewersCount int `json:"viewersCount"` - } - } `json:"userOrError"` -} - -type twitchStreamMetadataOperationResponse struct { - UserOrNull *struct { - Stream *struct { - StartedAt string `json:"createdAt"` - Game *struct { - Slug string `json:"slug"` - Name string `json:"name"` - } `json:"game"` - } `json:"stream"` - LastBroadcast *struct { - Title string `json:"title"` - } - } `json:"user"` -} - -const twitchChannelStatusOperationRequestBody = `[ -{"operationName":"ChannelShell","variables":{"login":"%s"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe"}}}, -{"operationName":"StreamMetadata","variables":{"channelLogin":"%s"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"676ee2f834ede42eb4514cdb432b3134fefc12590080c9a2c9bb44a2a4a63266"}}} -]` - -// TODO: rework -// The operations for multiple channels can all be sent in a single request -// rather than sending a separate request for each channel. Need to figure out -// what the limit is for max operations per request and batch operations in -// multiple requests if number of channels exceeds allowed limit. - -func fetchChannelFromTwitchTask(channel string) (twitchChannel, error) { - result := twitchChannel{ - Login: strings.ToLower(channel), - } - - reader := strings.NewReader(fmt.Sprintf(twitchChannelStatusOperationRequestBody, channel, channel)) - request, _ := http.NewRequest("POST", twitchGqlEndpoint, reader) - request.Header.Add("Client-ID", twitchGqlClientId) - - response, err := decodeJsonFromRequest[[]twitchOperationResponse](defaultHTTPClient, request) - if err != nil { - return result, err - } - - if len(response) != 2 { - return result, fmt.Errorf("expected 2 operation responses, got %d", len(response)) - } - - var channelShell twitchChannelShellOperationResponse - var streamMetadata twitchStreamMetadataOperationResponse - - for i := range response { - switch response[i].Extensions.OperationName { - case "ChannelShell": - if err = json.Unmarshal(response[i].Data, &channelShell); err != nil { - return result, fmt.Errorf("unmarshalling channel shell: %w", err) - } - case "StreamMetadata": - if err = json.Unmarshal(response[i].Data, &streamMetadata); err != nil { - return result, fmt.Errorf("unmarshalling stream metadata: %w", err) - } - default: - return result, fmt.Errorf("unknown operation name: %s", response[i].Extensions.OperationName) - } - } - - if channelShell.UserOrError.Type != "User" { - result.Name = result.Login - return result, nil - } - - result.Exists = true - result.Name = channelShell.UserOrError.DisplayName - result.AvatarUrl = channelShell.UserOrError.ProfileImageUrl - - if channelShell.UserOrError.Stream != nil { - result.IsLive = true - result.ViewersCount = channelShell.UserOrError.Stream.ViewersCount - - if streamMetadata.UserOrNull != nil && streamMetadata.UserOrNull.Stream != nil { - if streamMetadata.UserOrNull.LastBroadcast != nil { - result.StreamTitle = streamMetadata.UserOrNull.LastBroadcast.Title - } - - if streamMetadata.UserOrNull.Stream.Game != nil { - result.Category = streamMetadata.UserOrNull.Stream.Game.Name - result.CategorySlug = streamMetadata.UserOrNull.Stream.Game.Slug - } - startedAt, err := time.Parse("2006-01-02T15:04:05Z", streamMetadata.UserOrNull.Stream.StartedAt) - - if err == nil { - result.LiveSince = startedAt - } else { - 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 -} - -func fetchChannelsFromTwitch(channelLogins []string) (twitchChannelList, error) { - result := make(twitchChannelList, 0, len(channelLogins)) - - job := newJob(fetchChannelFromTwitchTask, channelLogins).withWorkers(10) - channels, errs, err := workerPoolDo(job) - if err != nil { - return result, err - } - - var failed int - - for i := range channels { - if errs[i] != nil { - failed++ - slog.Error("Failed to fetch Twitch channel", "channel", channelLogins[i], "error", errs[i]) - continue - } - - result = append(result, channels[i]) - } - - if failed == len(channelLogins) { - return result, errNoContent - } - - if failed > 0 { - return result, fmt.Errorf("%w: failed to fetch %d channels", errPartialContent, failed) - } - - return result, nil -} diff --git a/internal/glance/widget-twitch-top-games.go b/internal/glance/widget-twitch-top-games.go deleted file mode 100644 index 4235bc9..0000000 --- a/internal/glance/widget-twitch-top-games.go +++ /dev/null @@ -1,125 +0,0 @@ -package glance - -import ( - "context" - "errors" - "fmt" - "html/template" - "net/http" - "slices" - "strings" - "time" -) - -var twitchGamesWidgetTemplate = mustParseTemplate("twitch-games-list.html", "widget-base.html") - -type twitchGamesWidget struct { - widgetBase `yaml:",inline"` - Categories []twitchCategory `yaml:"-"` - Exclude []string `yaml:"exclude"` - Limit int `yaml:"limit"` - CollapseAfter int `yaml:"collapse-after"` -} - -func (widget *twitchGamesWidget) initialize() error { - widget. - withTitle("Top games on Twitch"). - withTitleURL("https://www.twitch.tv/directory?sort=VIEWER_COUNT"). - withCacheDuration(time.Minute * 10) - - if widget.Limit <= 0 { - widget.Limit = 10 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 5 - } - - return nil -} - -func (widget *twitchGamesWidget) update(ctx context.Context) { - categories, err := fetchTopGamesFromTwitch(widget.Exclude, widget.Limit) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - widget.Categories = categories -} - -func (widget *twitchGamesWidget) Render() template.HTML { - return widget.renderTemplate(widget, twitchGamesWidgetTemplate) -} - -type twitchCategory struct { - Slug string `json:"slug"` - Name string `json:"name"` - AvatarUrl string `json:"avatarURL"` - ViewersCount int `json:"viewersCount"` - Tags []struct { - Name string `json:"tagName"` - } `json:"tags"` - GameReleaseDate string `json:"originalReleaseDate"` - IsNew bool `json:"-"` -} - -type twitchDirectoriesOperationResponse struct { - Data struct { - DirectoriesWithTags struct { - Edges []struct { - Node twitchCategory `json:"node"` - } `json:"edges"` - } `json:"directoriesWithTags"` - } `json:"data"` -} - -const twitchDirectoriesOperationRequestBody = `[ -{"operationName": "BrowsePage_AllDirectories","variables": {"limit": %d,"options": {"sort": "VIEWER_COUNT","tags": []}},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "2f67f71ba89f3c0ed26a141ec00da1defecb2303595f5cda4298169549783d9e"}}} -]` - -func fetchTopGamesFromTwitch(exclude []string, limit int) ([]twitchCategory, error) { - reader := strings.NewReader(fmt.Sprintf(twitchDirectoriesOperationRequestBody, len(exclude)+limit)) - request, _ := http.NewRequest("POST", twitchGqlEndpoint, reader) - request.Header.Add("Client-ID", twitchGqlClientId) - response, err := decodeJsonFromRequest[[]twitchDirectoriesOperationResponse](defaultHTTPClient, request) - if err != nil { - return nil, err - } - - if len(response) == 0 { - return nil, errors.New("no categories could be retrieved") - } - - edges := (response)[0].Data.DirectoriesWithTags.Edges - categories := make([]twitchCategory, 0, len(edges)) - - for i := range edges { - if slices.Contains(exclude, edges[i].Node.Slug) { - continue - } - - category := &edges[i].Node - category.AvatarUrl = strings.Replace(category.AvatarUrl, "285x380", "144x192", 1) - - if len(category.Tags) > 2 { - category.Tags = category.Tags[:2] - } - - gameReleasedDate, err := time.Parse("2006-01-02T15:04:05Z", category.GameReleaseDate) - - if err == nil { - if time.Since(gameReleasedDate) < 14*24*time.Hour { - category.IsNew = true - } - } - - categories = append(categories, *category) - } - - if len(categories) > limit { - categories = categories[:limit] - } - - return categories, nil -} diff --git a/internal/glance/widget-videos.go b/internal/glance/widget-videos.go deleted file mode 100644 index ff79864..0000000 --- a/internal/glance/widget-videos.go +++ /dev/null @@ -1,216 +0,0 @@ -package glance - -import ( - "context" - "fmt" - "html/template" - "log/slog" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -const videosWidgetPlaylistPrefix = "playlist:" - -var ( - videosWidgetTemplate = mustParseTemplate("videos.html", "widget-base.html", "video-card-contents.html") - videosWidgetGridTemplate = mustParseTemplate("videos-grid.html", "widget-base.html", "video-card-contents.html") - videosWidgetVerticalListTemplate = mustParseTemplate("videos-vertical-list.html", "widget-base.html") -) - -type videosWidget struct { - widgetBase `yaml:",inline"` - Videos videoList `yaml:"-"` - VideoUrlTemplate string `yaml:"video-url-template"` - Style string `yaml:"style"` - CollapseAfter int `yaml:"collapse-after"` - CollapseAfterRows int `yaml:"collapse-after-rows"` - Channels []string `yaml:"channels"` - Playlists []string `yaml:"playlists"` - Limit int `yaml:"limit"` - IncludeShorts bool `yaml:"include-shorts"` -} - -func (widget *videosWidget) initialize() error { - widget.withTitle("Videos").withCacheDuration(time.Hour) - - if widget.Limit <= 0 { - widget.Limit = 25 - } - - if widget.CollapseAfterRows == 0 || widget.CollapseAfterRows < -1 { - widget.CollapseAfterRows = 4 - } - - if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { - widget.CollapseAfter = 7 - } - - // A bit cheeky, but from a user's perspective it makes more sense when channels and - // playlists are separate things rather than specifying a list of channels and some of - // them awkwardly have a "playlist:" prefix - if len(widget.Playlists) > 0 { - initialLen := len(widget.Channels) - widget.Channels = append(widget.Channels, make([]string, len(widget.Playlists))...) - - for i := range widget.Playlists { - widget.Channels[initialLen+i] = videosWidgetPlaylistPrefix + widget.Playlists[i] - } - } - - return nil -} - -func (widget *videosWidget) update(ctx context.Context) { - videos, err := fetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate, widget.IncludeShorts) - - if !widget.canContinueUpdateAfterHandlingErr(err) { - return - } - - if len(videos) > widget.Limit { - videos = videos[:widget.Limit] - } - - widget.Videos = videos -} - -func (widget *videosWidget) Render() template.HTML { - var template *template.Template - - switch widget.Style { - case "grid-cards": - template = videosWidgetGridTemplate - case "vertical-list": - template = videosWidgetVerticalListTemplate - default: - template = videosWidgetTemplate - } - - return widget.renderTemplate(widget, template) -} - -type youtubeFeedResponseXml struct { - Channel string `xml:"author>name"` - ChannelLink string `xml:"author>uri"` - Videos []struct { - Title string `xml:"title"` - Published string `xml:"published"` - Link struct { - Href string `xml:"href,attr"` - } `xml:"link"` - - Group struct { - Thumbnail struct { - Url string `xml:"url,attr"` - } `xml:"http://search.yahoo.com/mrss/ thumbnail"` - } `xml:"http://search.yahoo.com/mrss/ group"` - } `xml:"entry"` -} - -func parseYoutubeFeedTime(t string) time.Time { - parsedTime, err := time.Parse("2006-01-02T15:04:05-07:00", t) - if err != nil { - return time.Now() - } - - return parsedTime -} - -type video struct { - ThumbnailUrl string - Title string - Url string - Author string - AuthorUrl string - TimePosted time.Time -} - -type videoList []video - -func (v videoList) sortByNewest() videoList { - sort.Slice(v, func(i, j int) bool { - return v[i].TimePosted.After(v[j].TimePosted) - }) - - return v -} - -func fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplate string, includeShorts bool) (videoList, error) { - requests := make([]*http.Request, 0, len(channelOrPlaylistIDs)) - - for i := range channelOrPlaylistIDs { - var feedUrl string - if strings.HasPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix) { - feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" + - strings.TrimPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix) - } else if !includeShorts && strings.HasPrefix(channelOrPlaylistIDs[i], "UC") { - playlistId := strings.Replace(channelOrPlaylistIDs[i], "UC", "UULF", 1) - feedUrl = "https://www.youtube.com/feeds/videos.xml?playlist_id=" + playlistId - } else { - feedUrl = "https://www.youtube.com/feeds/videos.xml?channel_id=" + channelOrPlaylistIDs[i] - } - - request, _ := http.NewRequest("GET", feedUrl, nil) - requests = append(requests, request) - } - - job := newJob(decodeXmlFromRequestTask[youtubeFeedResponseXml](defaultHTTPClient), requests).withWorkers(30) - responses, errs, err := workerPoolDo(job) - if err != nil { - return nil, fmt.Errorf("%w: %v", errNoContent, err) - } - - videos := make(videoList, 0, len(channelOrPlaylistIDs)*15) - var failed int - - for i := range responses { - if errs[i] != nil { - failed++ - slog.Error("Failed to fetch youtube feed", "channel", channelOrPlaylistIDs[i], "error", errs[i]) - continue - } - - response := responses[i] - - for j := range response.Videos { - v := &response.Videos[j] - var videoUrl string - - if videoUrlTemplate == "" { - videoUrl = v.Link.Href - } else { - parsedUrl, err := url.Parse(v.Link.Href) - - if err == nil { - videoUrl = strings.ReplaceAll(videoUrlTemplate, "{VIDEO-ID}", parsedUrl.Query().Get("v")) - } else { - videoUrl = "#" - } - } - - videos = append(videos, video{ - ThumbnailUrl: v.Group.Thumbnail.Url, - Title: v.Title, - Url: videoUrl, - Author: response.Channel, - AuthorUrl: response.ChannelLink + "/videos", - TimePosted: parseYoutubeFeedTime(v.Published), - }) - } - } - - if len(videos) == 0 { - return nil, errNoContent - } - - videos.sortByNewest() - - if failed > 0 { - return videos, fmt.Errorf("%w: missing videos from %d channels", errPartialContent, failed) - } - - return videos, nil -} diff --git a/internal/widget/bookmarks.go b/internal/widget/bookmarks.go new file mode 100644 index 0000000..afa8a05 --- /dev/null +++ b/internal/widget/bookmarks.go @@ -0,0 +1,51 @@ +package widget + +import ( + "html/template" + "strings" + + "github.com/glanceapp/glance/internal/assets" +) + +type Bookmarks struct { + widgetBase `yaml:",inline"` + cachedHTML template.HTML `yaml:"-"` + Groups []struct { + Title string `yaml:"title"` + Color *HSLColorField `yaml:"color"` + Links []struct { + Title string `yaml:"title"` + URL string `yaml:"url"` + Icon string `yaml:"icon"` + IsSimpleIcon bool `yaml:"-"` + SameTab bool `yaml:"same-tab"` + HideArrow bool `yaml:"hide-arrow"` + } `yaml:"links"` + } `yaml:"groups"` +} + +func (widget *Bookmarks) Initialize() error { + widget.withTitle("Bookmarks").withError(nil) + + for g := range widget.Groups { + for l := range widget.Groups[g].Links { + if widget.Groups[g].Links[l].Icon == "" { + continue + } + + if strings.HasPrefix(widget.Groups[g].Links[l].Icon, "si:") { + icon := strings.TrimPrefix(widget.Groups[g].Links[l].Icon, "si:") + widget.Groups[g].Links[l].IsSimpleIcon = true + widget.Groups[g].Links[l].Icon = "https://cdnjs.cloudflare.com/ajax/libs/simple-icons/11.14.0/" + icon + ".svg" + } + } + } + + widget.cachedHTML = widget.render(widget, assets.BookmarksTemplate) + + return nil +} + +func (widget *Bookmarks) Render() template.HTML { + return widget.cachedHTML +} diff --git a/internal/widget/calendar.go b/internal/widget/calendar.go new file mode 100644 index 0000000..a126353 --- /dev/null +++ b/internal/widget/calendar.go @@ -0,0 +1,30 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Calendar struct { + widgetBase `yaml:",inline"` + Calendar *feed.Calendar +} + +func (widget *Calendar) Initialize() error { + widget.withTitle("Calendar").withCacheOnTheHour() + + return nil +} + +func (widget *Calendar) Update(ctx context.Context) { + widget.Calendar = feed.NewCalendar(time.Now()) + widget.withError(nil).scheduleNextUpdate() +} + +func (widget *Calendar) Render() template.HTML { + return widget.render(widget, assets.CalendarTemplate) +} diff --git a/internal/widget/fields.go b/internal/widget/fields.go new file mode 100644 index 0000000..eecb916 --- /dev/null +++ b/internal/widget/fields.go @@ -0,0 +1,152 @@ +package widget + +import ( + "fmt" + "html/template" + "os" + "regexp" + "strconv" + "time" + + "gopkg.in/yaml.v3" +) + +var HSLColorPattern = regexp.MustCompile(`^(?:hsla?\()?(\d{1,3})(?: |,)+(\d{1,3})%?(?: |,)+(\d{1,3})%?\)?$`) +var EnvFieldPattern = regexp.MustCompile(`^\${([A-Z_]+)}$`) + +const ( + HSLHueMax = 360 + HSLSaturationMax = 100 + HSLLightnessMax = 100 +) + +type HSLColorField struct { + Hue uint16 + Saturation uint8 + Lightness uint8 +} + +func (c *HSLColorField) String() string { + return fmt.Sprintf("hsl(%d, %d%%, %d%%)", c.Hue, c.Saturation, c.Lightness) +} + +func (c *HSLColorField) AsCSSValue() template.CSS { + return template.CSS(c.String()) +} + +func (c *HSLColorField) UnmarshalYAML(node *yaml.Node) error { + var value string + + if err := node.Decode(&value); err != nil { + return err + } + + matches := HSLColorPattern.FindStringSubmatch(value) + + if len(matches) != 4 { + return fmt.Errorf("invalid HSL color format: %s", value) + } + + hue, err := strconv.ParseUint(matches[1], 10, 16) + + if err != nil { + return err + } + + if hue > HSLHueMax { + return fmt.Errorf("HSL hue must be between 0 and %d", HSLHueMax) + } + + saturation, err := strconv.ParseUint(matches[2], 10, 8) + + if err != nil { + return err + } + + if saturation > HSLSaturationMax { + return fmt.Errorf("HSL saturation must be between 0 and %d", HSLSaturationMax) + } + + lightness, err := strconv.ParseUint(matches[3], 10, 8) + + if err != nil { + return err + } + + if lightness > HSLLightnessMax { + return fmt.Errorf("HSL lightness must be between 0 and %d", HSLLightnessMax) + } + + c.Hue = uint16(hue) + c.Saturation = uint8(saturation) + c.Lightness = uint8(lightness) + + return nil +} + +var DurationPattern = regexp.MustCompile(`^(\d+)(s|m|h|d)$`) + +type DurationField time.Duration + +func (d *DurationField) UnmarshalYAML(node *yaml.Node) error { + var value string + + if err := node.Decode(&value); err != nil { + return err + } + + matches := DurationPattern.FindStringSubmatch(value) + + if len(matches) != 3 { + return fmt.Errorf("invalid duration format: %s", value) + } + + duration, err := strconv.Atoi(matches[1]) + + if err != nil { + return err + } + + switch matches[2] { + case "s": + *d = DurationField(time.Duration(duration) * time.Second) + case "m": + *d = DurationField(time.Duration(duration) * time.Minute) + case "h": + *d = DurationField(time.Duration(duration) * time.Hour) + case "d": + *d = DurationField(time.Duration(duration) * 24 * time.Hour) + } + + return nil +} + +type OptionalEnvString string + +func (f *OptionalEnvString) UnmarshalYAML(node *yaml.Node) error { + var value string + + err := node.Decode(&value) + + if err != nil { + return err + } + + matches := EnvFieldPattern.FindStringSubmatch(value) + + if len(matches) != 2 { + *f = OptionalEnvString(value) + + return nil + } + + value, found := os.LookupEnv(matches[1]) + + if !found { + return fmt.Errorf("environment variable %s not found", matches[1]) + } + + *f = OptionalEnvString(value) + + return nil +} diff --git a/internal/widget/hacker-news.go b/internal/widget/hacker-news.go new file mode 100644 index 0000000..ff9ece0 --- /dev/null +++ b/internal/widget/hacker-news.go @@ -0,0 +1,54 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type HackerNews struct { + widgetBase `yaml:",inline"` + Posts feed.ForumPosts `yaml:"-"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` + CommentsUrlTemplate string `yaml:"comments-url-template"` + ShowThumbnails bool `yaml:"-"` +} + +func (widget *HackerNews) Initialize() error { + widget.withTitle("Hacker News").withCacheDuration(30 * time.Minute) + + if widget.Limit <= 0 { + widget.Limit = 15 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *HackerNews) Update(ctx context.Context) { + posts, err := feed.FetchHackerNewsTopPosts(40, widget.CommentsUrlTemplate) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + posts.CalculateEngagement() + posts.SortByEngagement() + + if widget.Limit < len(posts) { + posts = posts[:widget.Limit] + } + + widget.Posts = posts +} + +func (widget *HackerNews) Render() template.HTML { + return widget.render(widget, assets.ForumPostsTemplate) +} diff --git a/internal/glance/widget-iframe.go b/internal/widget/iframe.go similarity index 50% rename from internal/glance/widget-iframe.go rename to internal/widget/iframe.go index 830b383..44d0822 100644 --- a/internal/glance/widget-iframe.go +++ b/internal/widget/iframe.go @@ -1,30 +1,32 @@ -package glance +package widget import ( "errors" "fmt" "html/template" "net/url" + + "github.com/glanceapp/glance/internal/assets" ) -var iframeWidgetTemplate = mustParseTemplate("iframe.html", "widget-base.html") - -type iframeWidget struct { +type IFrame struct { widgetBase `yaml:",inline"` cachedHTML template.HTML `yaml:"-"` Source string `yaml:"source"` Height int `yaml:"height"` } -func (widget *iframeWidget) initialize() error { +func (widget *IFrame) Initialize() error { widget.withTitle("IFrame").withError(nil) if widget.Source == "" { - return errors.New("source is required") + return errors.New("missing source for iframe") } - if _, err := url.Parse(widget.Source); err != nil { - return fmt.Errorf("parsing URL: %v", err) + _, err := url.Parse(widget.Source) + + if err != nil { + return fmt.Errorf("invalid source for iframe: %v", err) } if widget.Height == 50 { @@ -33,11 +35,11 @@ func (widget *iframeWidget) initialize() error { widget.Height = 50 } - widget.cachedHTML = widget.renderTemplate(widget, iframeWidgetTemplate) + widget.cachedHTML = widget.render(widget, assets.IFrameTemplate) return nil } -func (widget *iframeWidget) Render() template.HTML { +func (widget *IFrame) Render() template.HTML { return widget.cachedHTML } diff --git a/internal/widget/monitor.go b/internal/widget/monitor.go new file mode 100644 index 0000000..3375ae5 --- /dev/null +++ b/internal/widget/monitor.go @@ -0,0 +1,101 @@ +package widget + +import ( + "context" + "fmt" + "html/template" + "net/http" + "strconv" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +func statusCodeToText(status int) string { + if status == 200 { + return "OK" + } + if status == 404 { + return "Not Found" + } + if status == 403 { + return "Forbidden" + } + if status == 401 { + return "Unauthorized" + } + if status >= 400 { + return "Client Error" + } + if status >= 500 { + return "Server Error" + } + + return strconv.Itoa(status) +} + +func statusCodeToStyle(status int) string { + if status == 200 { + return "good" + } + + return "bad" +} + +type Monitor struct { + widgetBase `yaml:",inline"` + Sites []struct { + Title string `yaml:"title"` + Url string `yaml:"url"` + IconUrl string `yaml:"icon"` + SameTab bool `yaml:"same-tab"` + Status *feed.SiteStatus `yaml:"-"` + StatusText string `yaml:"-"` + StatusStyle string `yaml:"-"` + } `yaml:"sites"` +} + +func (widget *Monitor) Initialize() error { + widget.withTitle("Monitor").withCacheDuration(5 * time.Minute) + + return nil +} + +func (widget *Monitor) Update(ctx context.Context) { + requests := make([]*http.Request, len(widget.Sites)) + + for i := range widget.Sites { + request, err := http.NewRequest("GET", widget.Sites[i].Url, nil) + + if err != nil { + message := fmt.Errorf("failed to create http request for %s: %s", widget.Sites[i].Url, err) + widget.withNotice(message) + continue + } + + requests[i] = request + } + + statuses, err := feed.FetchStatusesForRequests(requests) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + for i := range widget.Sites { + site := &widget.Sites[i] + status := &statuses[i] + + site.Status = status + + if !status.TimedOut { + site.StatusText = statusCodeToText(status.Code) + site.StatusStyle = statusCodeToStyle(status.Code) + } + } +} + +func (widget *Monitor) Render() template.HTML { + return widget.render(widget, assets.MonitorTemplate) +} diff --git a/internal/widget/reddit.go b/internal/widget/reddit.go new file mode 100644 index 0000000..42ee264 --- /dev/null +++ b/internal/widget/reddit.go @@ -0,0 +1,76 @@ +package widget + +import ( + "context" + "errors" + "html/template" + "strings" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Reddit struct { + widgetBase `yaml:",inline"` + Posts feed.ForumPosts `yaml:"-"` + Subreddit string `yaml:"subreddit"` + Style string `yaml:"style"` + ShowThumbnails bool `yaml:"show-thumbnails"` + CommentsUrlTemplate string `yaml:"comments-url-template"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` + RequestUrlTemplate string `yaml:"request-url-template"` +} + +func (widget *Reddit) Initialize() error { + if widget.Subreddit == "" { + return errors.New("no subreddit specified") + } + + if widget.Limit <= 0 { + widget.Limit = 15 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + if widget.RequestUrlTemplate != "" { + if !strings.Contains(widget.RequestUrlTemplate, "{REQUEST-URL}") { + return errors.New("no `{REQUEST-URL}` placeholder specified") + } + } + + widget.withTitle("/r/" + widget.Subreddit).withCacheDuration(30 * time.Minute) + + return nil +} + +func (widget *Reddit) Update(ctx context.Context) { + posts, err := feed.FetchSubredditPosts(widget.Subreddit, widget.CommentsUrlTemplate, widget.RequestUrlTemplate) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(posts) > widget.Limit { + posts = posts[:widget.Limit] + } + + posts.SortByEngagement() + widget.Posts = posts +} + +func (widget *Reddit) Render() template.HTML { + if widget.Style == "horizontal-cards" { + return widget.render(widget, assets.RedditCardsHorizontalTemplate) + } + + if widget.Style == "vertical-cards" { + return widget.render(widget, assets.RedditCardsVerticalTemplate) + } + + return widget.render(widget, assets.ForumPostsTemplate) + +} diff --git a/internal/widget/releases.go b/internal/widget/releases.go new file mode 100644 index 0000000..77fe103 --- /dev/null +++ b/internal/widget/releases.go @@ -0,0 +1,51 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Releases struct { + widgetBase `yaml:",inline"` + Releases feed.AppReleases `yaml:"-"` + Repositories []string `yaml:"repositories"` + Token OptionalEnvString `yaml:"token"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *Releases) Initialize() error { + widget.withTitle("Releases").withCacheDuration(2 * time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 10 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *Releases) Update(ctx context.Context) { + releases, err := feed.FetchLatestReleasesFromGithub(widget.Repositories, string(widget.Token)) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(releases) > widget.Limit { + releases = releases[:widget.Limit] + } + + widget.Releases = releases +} + +func (widget *Releases) Render() template.HTML { + return widget.render(widget, assets.ReleasesTemplate) +} diff --git a/internal/widget/rss.go b/internal/widget/rss.go new file mode 100644 index 0000000..81bd3ae --- /dev/null +++ b/internal/widget/rss.go @@ -0,0 +1,55 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type RSS struct { + widgetBase `yaml:",inline"` + FeedRequests []feed.RSSFeedRequest `yaml:"feeds"` + Style string `yaml:"style"` + Items feed.RSSFeedItems `yaml:"-"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *RSS) Initialize() error { + widget.withTitle("RSS Feed").withCacheDuration(1 * time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 25 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *RSS) Update(ctx context.Context) { + items, err := feed.GetItemsFromRSSFeeds(widget.FeedRequests) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(items) > widget.Limit { + items = items[:widget.Limit] + } + + widget.Items = items +} + +func (widget *RSS) Render() template.HTML { + if widget.Style == "horizontal-cards" { + return widget.render(widget, assets.RSSCardsTemplate) + } + + return widget.render(widget, assets.RSSListTemplate) +} diff --git a/internal/widget/stocks.go b/internal/widget/stocks.go new file mode 100644 index 0000000..1863875 --- /dev/null +++ b/internal/widget/stocks.go @@ -0,0 +1,41 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Stocks struct { + widgetBase `yaml:",inline"` + Stocks feed.Stocks `yaml:"-"` + Sort string `yaml:"sort-by"` + Tickers []feed.StockRequest `yaml:"stocks"` +} + +func (widget *Stocks) Initialize() error { + widget.withTitle("Stocks").withCacheDuration(time.Hour) + + return nil +} + +func (widget *Stocks) Update(ctx context.Context) { + stocks, err := feed.FetchStocksDataFromYahoo(widget.Tickers) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if widget.Sort == "absolute-change" { + stocks.SortByAbsChange() + } + + widget.Stocks = stocks +} + +func (widget *Stocks) Render() template.HTML { + return widget.render(widget, assets.StocksTemplate) +} diff --git a/internal/widget/twitch-channels.go b/internal/widget/twitch-channels.go new file mode 100644 index 0000000..3f36669 --- /dev/null +++ b/internal/widget/twitch-channels.go @@ -0,0 +1,42 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type TwitchChannels struct { + widgetBase `yaml:",inline"` + ChannelsRequest []string `yaml:"channels"` + Channels []feed.TwitchChannel `yaml:"-"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *TwitchChannels) Initialize() error { + widget.withTitle("Twitch Channels").withCacheDuration(time.Minute * 10) + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *TwitchChannels) Update(ctx context.Context) { + channels, err := feed.FetchChannelsFromTwitch(widget.ChannelsRequest) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + channels.SortByViewers() + widget.Channels = channels +} + +func (widget *TwitchChannels) Render() template.HTML { + return widget.render(widget, assets.TwitchChannelsTemplate) +} diff --git a/internal/widget/twitch-top-games.go b/internal/widget/twitch-top-games.go new file mode 100644 index 0000000..812c3c6 --- /dev/null +++ b/internal/widget/twitch-top-games.go @@ -0,0 +1,46 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type TwitchGames struct { + widgetBase `yaml:",inline"` + Categories []feed.TwitchCategory `yaml:"-"` + Exclude []string `yaml:"exclude"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *TwitchGames) Initialize() error { + widget.withTitle("Top games on Twitch").withCacheDuration(time.Minute * 10) + + if widget.Limit <= 0 { + widget.Limit = 10 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *TwitchGames) Update(ctx context.Context) { + categories, err := feed.FetchTopGamesFromTwitch(widget.Exclude, widget.Limit) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + widget.Categories = categories +} + +func (widget *TwitchGames) Render() template.HTML { + return widget.render(widget, assets.TwitchGamesListTemplate) +} diff --git a/internal/widget/videos.go b/internal/widget/videos.go new file mode 100644 index 0000000..a472f0e --- /dev/null +++ b/internal/widget/videos.go @@ -0,0 +1,46 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Videos struct { + widgetBase `yaml:",inline"` + Videos feed.Videos `yaml:"-"` + VideoUrlTemplate string `yaml:"video-url-template"` + Channels []string `yaml:"channels"` + Limit int `yaml:"limit"` +} + +func (widget *Videos) Initialize() error { + widget.withTitle("Videos").withCacheDuration(time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 25 + } + + return nil +} + +func (widget *Videos) Update(ctx context.Context) { + videos, err := feed.FetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(videos) > widget.Limit { + videos = videos[:widget.Limit] + } + + widget.Videos = videos +} + +func (widget *Videos) Render() template.HTML { + return widget.render(widget, assets.VideosTemplate) +} diff --git a/internal/widget/weather.go b/internal/widget/weather.go new file mode 100644 index 0000000..9d90e03 --- /dev/null +++ b/internal/widget/weather.go @@ -0,0 +1,58 @@ +package widget + +import ( + "context" + "fmt" + "html/template" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Weather struct { + widgetBase `yaml:",inline"` + Location string `yaml:"location"` + ShowAreaName bool `yaml:"show-area-name"` + HideLocation bool `yaml:"hide-location"` + Units string `yaml:"units"` + Place *feed.PlaceJson `yaml:"-"` + Weather *feed.Weather `yaml:"-"` + TimeLabels [12]string `yaml:"-"` +} + +var timeLabels = [12]string{"2am", "4am", "6am", "8am", "10am", "12pm", "2pm", "4pm", "6pm", "8pm", "10pm", "12am"} + +func (widget *Weather) Initialize() error { + widget.withTitle("Weather").withCacheOnTheHour() + widget.TimeLabels = timeLabels + + if widget.Units == "" { + widget.Units = "metric" + } else if widget.Units != "metric" && widget.Units != "imperial" { + return fmt.Errorf("invalid units '%s' for weather, must be either metric or imperial", widget.Units) + } + + place, err := feed.FetchPlaceFromName(widget.Location) + + if err != nil { + return fmt.Errorf("failed fetching data for %s: %v", widget.Location, err) + } + + widget.Place = place + + return nil +} + +func (widget *Weather) Update(ctx context.Context) { + weather, err := feed.FetchWeatherForPlace(widget.Place, widget.Units) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + widget.Weather = weather +} + +func (widget *Weather) Render() template.HTML { + return widget.render(widget, assets.WeatherTemplate) +} diff --git a/internal/glance/widget.go b/internal/widget/widget.go similarity index 57% rename from internal/glance/widget.go rename to internal/widget/widget.go index ab41c79..367d822 100644 --- a/internal/glance/widget.go +++ b/internal/widget/widget.go @@ -1,4 +1,4 @@ -package glance +package widget import ( "bytes" @@ -8,85 +8,49 @@ import ( "html/template" "log/slog" "math" - "net/http" - "sync/atomic" "time" + "github.com/glanceapp/glance/internal/feed" + "gopkg.in/yaml.v3" ) -var widgetIDCounter atomic.Uint64 - -func newWidget(widgetType string) (widget, error) { - var w widget - +func New(widgetType string) (Widget, error) { switch widgetType { case "calendar": - w = &calendarWidget{} - case "calendar-legacy": - w = &oldCalendarWidget{} - case "clock": - w = &clockWidget{} + return &Calendar{}, nil case "weather": - w = &weatherWidget{} + return &Weather{}, nil case "bookmarks": - w = &bookmarksWidget{} + return &Bookmarks{}, nil case "iframe": - w = &iframeWidget{} - case "html": - w = &htmlWidget{} + return &IFrame{}, nil case "hacker-news": - w = &hackerNewsWidget{} + return &HackerNews{}, nil case "releases": - w = &releasesWidget{} + return &Releases{}, nil case "videos": - w = &videosWidget{} - case "markets", "stocks": - w = &marketsWidget{} + return &Videos{}, nil + case "stocks": + return &Stocks{}, nil case "reddit": - w = &redditWidget{} + return &Reddit{}, nil case "rss": - w = &rssWidget{} + return &RSS{}, nil case "monitor": - w = &monitorWidget{} + return &Monitor{}, nil case "twitch-top-games": - w = &twitchGamesWidget{} + return &TwitchGames{}, nil case "twitch-channels": - w = &twitchChannelsWidget{} - case "lobsters": - w = &lobstersWidget{} - case "change-detection": - w = &changeDetectionWidget{} - case "repository": - w = &repositoryWidget{} - case "search": - w = &searchWidget{} - case "extension": - w = &extensionWidget{} - case "group": - w = &groupWidget{} - case "dns-stats": - w = &dnsStatsWidget{} - case "split-column": - w = &splitColumnWidget{} - case "custom-api": - w = &customAPIWidget{} - case "docker-containers": - w = &dockerContainersWidget{} - case "server-stats": - w = &serverStatsWidget{} + return &TwitchChannels{}, nil default: return nil, fmt.Errorf("unknown widget type: %s", widgetType) } - - w.setID(widgetIDCounter.Add(1)) - - return w, nil } -type widgets []widget +type Widgets []Widget -func (w *widgets) UnmarshalYAML(node *yaml.Node) error { +func (w *Widgets) UnmarshalYAML(node *yaml.Node) error { var nodes []yaml.Node if err := node.Decode(&nodes); err != nil { @@ -102,7 +66,8 @@ func (w *widgets) UnmarshalYAML(node *yaml.Node) error { return err } - widget, err := newWidget(meta.Type) + widget, err := New(meta.Type) + if err != nil { return err } @@ -111,25 +76,22 @@ func (w *widgets) UnmarshalYAML(node *yaml.Node) error { return err } + if err = widget.Initialize(); err != nil { + return err + } + *w = append(*w, widget) } return nil } -type widget interface { - // These need to be exported because they get called in templates +type Widget interface { + Initialize() error + RequiresUpdate(*time.Time) bool + Update(context.Context) Render() template.HTML GetType() string - GetID() uint64 - - initialize() error - requiresUpdate(*time.Time) bool - setProviders(*widgetProviders) - update(context.Context) - setID(uint64) - handleRequest(w http.ResponseWriter, r *http.Request) - setHideHeader(bool) } type cacheType int @@ -141,30 +103,20 @@ const ( ) type widgetBase struct { - ID uint64 `yaml:"-"` - Providers *widgetProviders `yaml:"-"` - Type string `yaml:"type"` - Title string `yaml:"title"` - TitleURL string `yaml:"title-url"` - CSSClass string `yaml:"css-class"` - CustomCacheDuration durationField `yaml:"cache"` - ContentAvailable bool `yaml:"-"` - WIP bool `yaml:"-"` - Error error `yaml:"-"` - Notice error `yaml:"-"` - templateBuffer bytes.Buffer `yaml:"-"` - cacheDuration time.Duration `yaml:"-"` - cacheType cacheType `yaml:"-"` - nextUpdate time.Time `yaml:"-"` - updateRetriedTimes int `yaml:"-"` - HideHeader bool `yaml:"-"` + Type string `yaml:"type"` + Title string `yaml:"title"` + CustomCacheDuration DurationField `yaml:"cache"` + ContentAvailable bool `yaml:"-"` + Error error `yaml:"-"` + Notice error `yaml:"-"` + templateBuffer bytes.Buffer `yaml:"-"` + cacheDuration time.Duration `yaml:"-"` + cacheType cacheType `yaml:"-"` + nextUpdate time.Time `yaml:"-"` + updateRetriedTimes int `yaml:"-"` } -type widgetProviders struct { - assetResolver func(string) string -} - -func (w *widgetBase) requiresUpdate(now *time.Time) bool { +func (w *widgetBase) RequiresUpdate(now *time.Time) bool { if w.cacheType == cacheTypeInfinite { return false } @@ -176,46 +128,23 @@ func (w *widgetBase) requiresUpdate(now *time.Time) bool { return now.After(w.nextUpdate) } -func (w *widgetBase) IsWIP() bool { - return w.WIP -} +func (w *widgetBase) Update(ctx context.Context) { -func (w *widgetBase) update(ctx context.Context) { - -} - -func (w *widgetBase) GetID() uint64 { - return w.ID -} - -func (w *widgetBase) setID(id uint64) { - w.ID = id -} - -func (w *widgetBase) setHideHeader(value bool) { - w.HideHeader = value -} - -func (widget *widgetBase) handleRequest(w http.ResponseWriter, r *http.Request) { - http.Error(w, "not implemented", http.StatusNotImplemented) } func (w *widgetBase) GetType() string { return w.Type } -func (w *widgetBase) setProviders(providers *widgetProviders) { - w.Providers = providers -} - -func (w *widgetBase) renderTemplate(data any, t *template.Template) template.HTML { +func (w *widgetBase) render(data any, t *template.Template) template.HTML { w.templateBuffer.Reset() err := t.Execute(&w.templateBuffer, data) + if err != nil { w.ContentAvailable = false w.Error = err - slog.Error("Failed to render template", "error", err) + slog.Error("failed to render template", "error", err) // need to immediately re-render with the error, // otherwise risk breaking the page since the widget @@ -224,7 +153,7 @@ func (w *widgetBase) renderTemplate(data any, t *template.Template) template.HTM err2 := t.Execute(&w.templateBuffer, data) if err2 != nil { - slog.Error("Failed to render error within widget", "error", err2, "initial_error", err) + slog.Error("failed to render error within widget", "error", err2, "initial_error", err) w.templateBuffer.Reset() // TODO: add some kind of a generic widget error template when the widget // failed to render, and we also failed to re-render the widget with the error @@ -242,14 +171,6 @@ func (w *widgetBase) withTitle(title string) *widgetBase { return w } -func (w *widgetBase) withTitleURL(titleURL string) *widgetBase { - if w.TitleURL == "" { - w.TitleURL = titleURL - } - - return w -} - func (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase { w.cacheType = cacheTypeDuration @@ -301,7 +222,7 @@ func (w *widgetBase) canContinueUpdateAfterHandlingErr(err error) bool { if err != nil { w.scheduleEarlyUpdate() - if !errors.Is(err, errPartialContent) { + if !errors.Is(err, feed.ErrPartialContent) { w.withError(err) w.withNotice(nil) return false diff --git a/pkg/sysinfo/sysinfo.go b/pkg/sysinfo/sysinfo.go deleted file mode 100644 index 1ed8c75..0000000 --- a/pkg/sysinfo/sysinfo.go +++ /dev/null @@ -1,297 +0,0 @@ -package sysinfo - -import ( - "fmt" - "math" - "os" - "runtime" - "sort" - "strconv" - "time" - - "github.com/shirou/gopsutil/v4/cpu" - "github.com/shirou/gopsutil/v4/disk" - "github.com/shirou/gopsutil/v4/host" - "github.com/shirou/gopsutil/v4/load" - "github.com/shirou/gopsutil/v4/mem" - "github.com/shirou/gopsutil/v4/sensors" -) - -type timestampJSON struct { - time.Time -} - -func (t timestampJSON) MarshalJSON() ([]byte, error) { - return []byte(strconv.FormatInt(t.Unix(), 10)), nil -} - -func (t *timestampJSON) UnmarshalJSON(data []byte) error { - i, err := strconv.ParseInt(string(data), 10, 64) - if err != nil { - return err - } - - t.Time = time.Unix(i, 0) - return nil -} - -type SystemInfo struct { - HostInfoIsAvailable bool `json:"host_info_is_available"` - BootTime timestampJSON `json:"boot_time"` - Hostname string `json:"hostname"` - Platform string `json:"platform"` - - CPU struct { - LoadIsAvailable bool `json:"load_is_available"` - Load1Percent uint8 `json:"load1_percent"` - Load15Percent uint8 `json:"load15_percent"` - - TemperatureIsAvailable bool `json:"temperature_is_available"` - TemperatureC uint8 `json:"temperature_c"` - } `json:"cpu"` - - Memory struct { - IsAvailable bool `json:"memory_is_available"` - TotalMB uint64 `json:"total_mb"` - UsedMB uint64 `json:"used_mb"` - UsedPercent uint8 `json:"used_percent"` - - SwapIsAvailable bool `json:"swap_is_available"` - SwapTotalMB uint64 `json:"swap_total_mb"` - SwapUsedMB uint64 `json:"swap_used_mb"` - SwapUsedPercent uint8 `json:"swap_used_percent"` - } `json:"memory"` - - Mountpoints []MountpointInfo `json:"mountpoints"` -} - -type MountpointInfo struct { - Path string `json:"path"` - Name string `json:"name"` - TotalMB uint64 `json:"total_mb"` - UsedMB uint64 `json:"used_mb"` - UsedPercent uint8 `json:"used_percent"` -} - -type SystemInfoRequest struct { - CPUTempSensor string `yaml:"cpu-temp-sensor"` - HideMountpointsByDefault bool `yaml:"hide-mountpoints-by-default"` - Mountpoints map[string]MointpointRequest `yaml:"mountpoints"` -} - -type MointpointRequest struct { - Name string `yaml:"name"` - Hide *bool `yaml:"hide"` -} - -// Currently caches hostname indefinitely which isn't ideal -// Potential issue with caching boot time as it may not initially get reported correctly: -// https://github.com/shirou/gopsutil/issues/842#issuecomment-1908972344 -type cacheableHostInfo struct { - available bool - hostname string - platform string - bootTime timestampJSON -} - -var cachedHostInfo cacheableHostInfo - -func getHostInfo() (cacheableHostInfo, error) { - var err error - info := cacheableHostInfo{} - - info.hostname, err = os.Hostname() - if err != nil { - return info, err - } - - info.platform, _, _, err = host.PlatformInformation() - if err != nil { - return info, err - } - - bootTime, err := host.BootTime() - if err != nil { - return info, err - } - - info.bootTime = timestampJSON{time.Unix(int64(bootTime), 0)} - info.available = true - - return info, nil -} - -func Collect(req *SystemInfoRequest) (*SystemInfo, []error) { - if req == nil { - req = &SystemInfoRequest{} - } - - var errs []error - - addErr := func(err error) { - errs = append(errs, err) - } - - info := &SystemInfo{ - Mountpoints: []MountpointInfo{}, - } - - applyCachedHostInfo := func() { - info.HostInfoIsAvailable = true - info.BootTime = cachedHostInfo.bootTime - info.Hostname = cachedHostInfo.hostname - info.Platform = cachedHostInfo.platform - } - - if cachedHostInfo.available { - applyCachedHostInfo() - } else { - hostInfo, err := getHostInfo() - if err == nil { - cachedHostInfo = hostInfo - applyCachedHostInfo() - } else { - addErr(fmt.Errorf("getting host info: %v", err)) - } - } - - coreCount, err := cpu.Counts(true) - if err == nil { - loadAvg, err := load.Avg() - if err == nil { - info.CPU.LoadIsAvailable = true - if runtime.GOOS == "windows" { - // The numbers returned here seem unreliable on Windows. Even with the CPU pegged - // at close to 50% for multiple minutes, load1 is sometimes way under or way over - // with no clear pattern. Dividing by core count gives numbers that are way too - // low so that's likely not necessary as it is with unix. - info.CPU.Load1Percent = uint8(math.Min(loadAvg.Load1*100, 100)) - info.CPU.Load15Percent = uint8(math.Min(loadAvg.Load15*100, 100)) - } else { - info.CPU.Load1Percent = uint8(math.Min((loadAvg.Load1/float64(coreCount))*100, 100)) - info.CPU.Load15Percent = uint8(math.Min((loadAvg.Load15/float64(coreCount))*100, 100)) - } - } else { - addErr(fmt.Errorf("getting load avg: %v", err)) - } - } else { - addErr(fmt.Errorf("getting core count: %v", err)) - } - - memory, err := mem.VirtualMemory() - if err == nil { - info.Memory.IsAvailable = true - info.Memory.TotalMB = memory.Total / 1024 / 1024 - info.Memory.UsedMB = memory.Used / 1024 / 1024 - info.Memory.UsedPercent = uint8(math.Min(memory.UsedPercent, 100)) - } else { - addErr(fmt.Errorf("getting memory info: %v", err)) - } - - swapMemory, err := mem.SwapMemory() - if err == nil { - info.Memory.SwapIsAvailable = true - info.Memory.SwapTotalMB = swapMemory.Total / 1024 / 1024 - info.Memory.SwapUsedMB = swapMemory.Used / 1024 / 1024 - info.Memory.SwapUsedPercent = uint8(math.Min(swapMemory.UsedPercent, 100)) - } else { - addErr(fmt.Errorf("getting swap memory info: %v", err)) - } - - // currently disabled on Windows because it requires elevated privilidges, otherwise - // keeps returning a single sensor with key "ACPI\\ThermalZone\\TZ00_0" which - // doesn't seem to be the CPU sensor or correspond to anything useful when - // compared against the temperatures Libre Hardware Monitor reports - // also disabled on openbsd because it's not implemented by go-psutil - if runtime.GOOS != "windows" && runtime.GOOS != "openbsd" { - sensorReadings, err := sensors.SensorsTemperatures() - if err == nil { - if req.CPUTempSensor != "" { - for i := range sensorReadings { - if sensorReadings[i].SensorKey == req.CPUTempSensor { - info.CPU.TemperatureIsAvailable = true - info.CPU.TemperatureC = uint8(sensorReadings[i].Temperature) - break - } - } - - if !info.CPU.TemperatureIsAvailable { - addErr(fmt.Errorf("CPU temperature sensor %s not found", req.CPUTempSensor)) - } - } else if cpuTempSensor := inferCPUTempSensor(sensorReadings); cpuTempSensor != nil { - info.CPU.TemperatureIsAvailable = true - info.CPU.TemperatureC = uint8(cpuTempSensor.Temperature) - } - } else { - addErr(fmt.Errorf("getting sensor readings: %v", err)) - } - } - - addedMountpoints := map[string]struct{}{} - addMountpointInfo := func(requestedPath string, mpReq MointpointRequest) { - if _, exists := addedMountpoints[requestedPath]; exists { - return - } - - isHidden := req.HideMountpointsByDefault - if mpReq.Hide != nil { - isHidden = *mpReq.Hide - } - if isHidden { - return - } - - usage, err := disk.Usage(requestedPath) - if err == nil { - mpInfo := MountpointInfo{ - Path: requestedPath, - Name: mpReq.Name, - TotalMB: usage.Total / 1024 / 1024, - UsedMB: usage.Used / 1024 / 1024, - UsedPercent: uint8(math.Min(usage.UsedPercent, 100)), - } - - info.Mountpoints = append(info.Mountpoints, mpInfo) - addedMountpoints[requestedPath] = struct{}{} - } else { - 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 - }) - - return info, errs -} - -func inferCPUTempSensor(sensors []sensors.TemperatureStat) *sensors.TemperatureStat { - for i := range sensors { - switch sensors[i].SensorKey { - case - "coretemp_package_id_0", // intel / linux - "coretemp", // intel / linux - "k10temp", // amd / linux - "zenpower", // amd / linux - "cpu_thermal": // raspberry pi / linux - return &sensors[i] - } - } - - return nil -} diff --git a/scripts/build-and-ship/main.go b/scripts/build-and-ship/main.go new file mode 100644 index 0000000..2349947 --- /dev/null +++ b/scripts/build-and-ship/main.go @@ -0,0 +1,237 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "path" + "strings" +) + +// bunch of spaget but it does the job for now +// TODO: tidy up and add a proper build system with CI + +const buildPath = "./build" +const archivesPath = "./build/archives" +const executableName = "glance" +const ownerAndRepo = "glanceapp/glance" +const moduleName = "github.com/" + ownerAndRepo + +type archiveType int + +const ( + archiveTypeTarGz archiveType = iota + archiveTypeZip +) + +type buildInfo struct { + version string +} + +type buildTarget struct { + os string + arch string + armV int + extension string + archive archiveType +} + +var buildTargets = []buildTarget{ + { + os: "windows", + arch: "amd64", + extension: ".exe", + archive: archiveTypeZip, + }, + { + os: "windows", + arch: "arm64", + extension: ".exe", + archive: archiveTypeZip, + }, + { + os: "linux", + arch: "amd64", + }, + { + os: "linux", + arch: "arm64", + }, + { + os: "linux", + arch: "arm", + armV: 6, + }, + { + os: "linux", + arch: "arm", + armV: 7, + }, +} + +func main() { + cwd, err := os.Getwd() + + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + _, err = os.Stat(buildPath) + + if err == nil { + fmt.Println("Cleaning up build path") + os.RemoveAll(buildPath) + } + + os.Mkdir(buildPath, 0755) + os.Mkdir(archivesPath, 0755) + + version, err := getVersionFromGit() + + if err != nil { + fmt.Println(version, err) + os.Exit(1) + } + + info := buildInfo{ + version: version, + } + + for _, target := range buildTargets { + fmt.Printf("Building for %s/%s\n", target.os, target.arch) + if err := build(cwd, info, target); err != nil { + fmt.Println(err) + os.Exit(1) + } + } + + versionTag := fmt.Sprintf("%s:%s", ownerAndRepo, version) + latestTag := fmt.Sprintf("%s:latest", ownerAndRepo) + + fmt.Println("Building docker image") + + output, err := exec.Command( + "sudo", "docker", "build", + "--platform=linux/arm64,linux/amd64", + "-t", versionTag, + "-t", latestTag, + ".", + ).CombinedOutput() + + if err != nil { + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } + + var input string + fmt.Print("Push docker image? [y/n]: ") + fmt.Scanln(&input) + + if input != "y" { + os.Exit(0) + } + + output, err = exec.Command( + "sudo", "docker", "push", versionTag, + ).CombinedOutput() + + if err != nil { + fmt.Printf("Failed pushing %s:\n", versionTag) + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } + + output, err = exec.Command( + "sudo", "docker", "push", latestTag, + ).CombinedOutput() + + if err != nil { + fmt.Printf("Failed pushing %s:\n", latestTag) + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } +} + +func getVersionFromGit() (string, error) { + output, err := exec.Command("git", "describe", "--tags", "--abbrev=0").CombinedOutput() + + if err == nil { + return strings.TrimSpace(string(output)), err + } + + return string(output), err +} + +func archiveFile(name string, target string, t archiveType) error { + var output []byte + var err error + + if t == archiveTypeZip { + output, err = exec.Command("zip", "-j", path.Join(archivesPath, name+".zip"), target).CombinedOutput() + } else if t == archiveTypeTarGz { + output, err = exec.Command("tar", "-C", buildPath, "-czf", path.Join(archivesPath, name+".tar.gz"), name).CombinedOutput() + } + + if err != nil { + fmt.Println(string(output)) + return err + } + + return nil +} + +func build(workingDir string, info buildInfo, target buildTarget) error { + var name string + + if target.arch != "arm" { + name = fmt.Sprintf("%s-%s-%s%s", executableName, target.os, target.arch, target.extension) + } else { + name = fmt.Sprintf("%s-%s-%sv%d", executableName, target.os, target.arch, target.armV) + } + + binaryPath := path.Join(buildPath, name) + + glancePackage := moduleName + "/internal/glance" + + flags := "-s -w" + flags += fmt.Sprintf(" -X %s.buildVersion=%s", glancePackage, info.version) + + cmd := exec.Command( + "go", + "build", + "--trimpath", + "--ldflags", + flags, + "-o", + binaryPath, + ) + + cmd.Dir = workingDir + env := append(os.Environ(), "GOOS="+target.os, "GOARCH="+target.arch, "CGO_ENABLED=0") + + if target.arch == "arm" { + env = append(env, fmt.Sprintf("GOARM=%d", target.armV)) + } + + cmd.Env = env + output, err := cmd.CombinedOutput() + + if err != nil { + fmt.Println(err) + fmt.Println(string(output)) + return err + } + + os.Chmod(binaryPath, 0755) + + fmt.Println("Creating archive") + if err := archiveFile(name, binaryPath, target.archive); err != nil { + return err + } + + return nil +}