Repository: glanceapp/glance Branch: main Commit: 6c5b7a3f4cc4 Files: 148 Total size: 647.6 KB Directory structure: gitextract_g8m113ra/ ├── .dockerignore ├── .github/ │ ├── CODE_OF_CONDUCT.md │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yml │ │ ├── config.yml │ │ └── feature_request.yml │ ├── PULL_REQUEST_TEMPLATE.md │ ├── SECURITY.md │ └── workflows/ │ └── release.yaml ├── .gitignore ├── .goreleaser.yaml ├── Dockerfile ├── Dockerfile.goreleaser ├── LICENSE ├── README.md ├── docs/ │ ├── configuration.md │ ├── custom-api.md │ ├── extensions.md │ ├── glance.yml │ ├── preconfigured-pages.md │ ├── themes.md │ └── v0.7.0-upgrade.md ├── go.mod ├── go.sum ├── internal/ │ └── glance/ │ ├── auth.go │ ├── auth_test.go │ ├── cli.go │ ├── config-fields.go │ ├── config.go │ ├── diagnose.go │ ├── embed.go │ ├── glance.go │ ├── main.go │ ├── static/ │ │ ├── css/ │ │ │ ├── forum-posts.css │ │ │ ├── login.css │ │ │ ├── main.css │ │ │ ├── mobile.css │ │ │ ├── popover.css │ │ │ ├── site.css │ │ │ ├── utils.css │ │ │ ├── widget-bookmarks.css │ │ │ ├── widget-calendar.css │ │ │ ├── widget-clock.css │ │ │ ├── widget-dns-stats.css │ │ │ ├── widget-docker-containers.css │ │ │ ├── widget-group.css │ │ │ ├── widget-markets.css │ │ │ ├── widget-monitor.css │ │ │ ├── widget-reddit.css │ │ │ ├── widget-releases.css │ │ │ ├── widget-rss.css │ │ │ ├── widget-search.css │ │ │ ├── widget-server-stats.css │ │ │ ├── widget-todo.css │ │ │ ├── widget-twitch.css │ │ │ ├── widget-videos.css │ │ │ ├── widget-weather.css │ │ │ └── widgets.css │ │ └── js/ │ │ ├── animations.js │ │ ├── calendar.js │ │ ├── login.js │ │ ├── masonry.js │ │ ├── page.js │ │ ├── popover.js │ │ ├── templating.js │ │ ├── todo.js │ │ └── utils.js │ ├── templates/ │ │ ├── bookmarks.html │ │ ├── calendar.html │ │ ├── change-detection.html │ │ ├── clock.html │ │ ├── custom-api.html │ │ ├── dns-stats.html │ │ ├── docker-containers.html │ │ ├── document.html │ │ ├── extension.html │ │ ├── footer.html │ │ ├── forum-posts.html │ │ ├── group.html │ │ ├── iframe.html │ │ ├── login.html │ │ ├── manifest.json │ │ ├── markets.html │ │ ├── monitor-compact.html │ │ ├── monitor.html │ │ ├── old-calendar.html │ │ ├── page-content.html │ │ ├── page.html │ │ ├── reddit-horizontal-cards.html │ │ ├── reddit-vertical-cards.html │ │ ├── releases.html │ │ ├── repository.html │ │ ├── rss-detailed-list.html │ │ ├── rss-horizontal-cards-2.html │ │ ├── rss-horizontal-cards.html │ │ ├── rss-list.html │ │ ├── search.html │ │ ├── server-stats.html │ │ ├── split-column.html │ │ ├── theme-preset-preview.html │ │ ├── theme-style.gotmpl │ │ ├── todo.html │ │ ├── twitch-channels.html │ │ ├── twitch-games-list.html │ │ ├── v0.7-update-notice-page.html │ │ ├── video-card-contents.html │ │ ├── videos-grid.html │ │ ├── videos-vertical-list.html │ │ ├── videos.html │ │ ├── weather.html │ │ └── widget-base.html │ ├── templates.go │ ├── theme.go │ ├── utils.go │ ├── widget-bookmarks.go │ ├── widget-calendar.go │ ├── widget-changedetection.go │ ├── widget-clock.go │ ├── widget-container.go │ ├── widget-custom-api.go │ ├── widget-dns-stats.go │ ├── widget-docker-containers.go │ ├── widget-extension.go │ ├── widget-group.go │ ├── widget-hacker-news.go │ ├── widget-html.go │ ├── widget-iframe.go │ ├── widget-lobsters.go │ ├── widget-markets.go │ ├── widget-monitor.go │ ├── widget-old-calendar.go │ ├── widget-reddit.go │ ├── widget-releases.go │ ├── widget-repository.go │ ├── widget-rss.go │ ├── widget-search.go │ ├── widget-server-stats.go │ ├── widget-shared.go │ ├── widget-split-column.go │ ├── widget-todo.go │ ├── widget-twitch-channels.go │ ├── widget-twitch-top-games.go │ ├── widget-utils.go │ ├── widget-videos.go │ ├── widget-weather.go │ └── widget.go ├── main.go └── pkg/ └── sysinfo/ └── sysinfo.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ # 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 ================================================ FILE: .github/CODE_OF_CONDUCT.md ================================================ # 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. ================================================ FILE: .github/FUNDING.yml ================================================ github: [glanceapp] patreon: glanceapp ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yml ================================================ 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. ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ 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 ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yml ================================================ 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. ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ ================================================ FILE: .github/SECURITY.md ================================================ # 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. ================================================ FILE: .github/workflows/release.yaml ================================================ 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 ================================================ FILE: .gitignore ================================================ /assets /build /playground /.idea /glance*.yml ================================================ FILE: .goreleaser.yaml ================================================ 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 ================================================ FILE: Dockerfile ================================================ FROM golang:1.24.3-alpine3.21 AS builder WORKDIR /app COPY . /app RUN CGO_ENABLED=0 go build . FROM alpine:3.21 WORKDIR /app COPY --from=builder /app/glance . EXPOSE 8080/tcp ENTRYPOINT ["/app/glance", "--config", "/app/config/glance.yml"] ================================================ FILE: Dockerfile.goreleaser ================================================ FROM alpine:3.21 WORKDIR /app COPY glance . EXPOSE 8080/tcp ENTRYPOINT ["/app/glance", "--config", "/app/config/glance.yml"] ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================

Glance

InstallConfigurationDiscordSponsor

Community widgetsPreconfigured pagesThemes

A lightweight, highly customizable dashboard that displays
your feeds in a beautiful, streamlined interface

![](docs/images/readme-main-image.png) ## 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#configuring-glance) ### 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) ### 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 Because you'll want to take it with you on the go. ![](docs/images/mobile-preview.png) ### Themeable Easily create your own theme by tweaking a few numbers or choose from one of the [already available themes](docs/themes.md). ![](docs/images/themes-example.png)
## 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#configuring-glance).
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 ``` *[click here to view the files that will be created](https://github.com/glanceapp/docker-compose-template/tree/main/root)* 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 ``` 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: ```yaml services: glance: container_name: glance image: glanceapp/glance restart: unless-stopped volumes: - ./config:/app/config ports: - 8080:8080 ``` 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: ```bash mkdir config && wget -O config/glance.yml https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml ``` Feel free to edit the `glance.yml` file to your liking, and when ready 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. ================================================ FILE: docs/configuration.md ================================================ # Configuring Glance - [Preconfigured page](#preconfigured-page) - [The config file](#the-config-file) - [Auto reload](#auto-reload) - [Environment variables](#environment-variables) - [Other ways of providing tokens/passwords/secrets](#other-ways-of-providing-tokenspasswordssecrets) - [Including other config files](#including-other-config-files) - [Icons](#icons) - [Config schema](#config-schema) - [Authentication](#authentication) - [Server](#server) - [Document](#document) - [Branding](#branding) - [Theme](#theme) - [Available themes](#available-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) - [Todo](#todo) - [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) - [Twitch Channels](#twitch-channels) - [Twitch Top Games](#twitch-top-games) - [iframe](#iframe) - [HTML](#html) ## 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} ``` #### Other ways of providing tokens/passwords/secrets You can use [Docker secrets](https://docs.docker.com/compose/how-tos/use-secrets/) with the following syntax: ```yaml # This will be replaced with the contents of the file /run/secrets/github_token # so long as the secret `github_token` is provided to the container token: ${secret:github_token} ``` Alternatively, you can load the contents of a file who's path is provided by an environment variable: `docker-compose.yml` ```yaml services: glance: image: glanceapp/glance environment: - TOKEN_FILE=/home/user/token volumes: - /home/user/token:/home/user/token ``` `glance.yml` ```yaml token: ${readFileFromEnv:TOKEN_FILE} ``` > [!NOTE] > > The contents of the file will be stripped of any leading/trailing whitespace before being used. ### 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` ```yaml pages: - name: Home columns: - size: full widgets: - $include: rss.yml - name: News columns: - size: full widgets: - type: group widgets: - $include: rss.yml - type: reddit subreddit: news ``` `rss.yml` ```yaml - type: rss title: News feeds: - url: ${RSS_URL} ``` 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`. ## Icons For widgets which provide you with the ability to specify icons such as the monitor, bookmarks, docker containers, etc, you can use the `icon` property to specify a URL to an image or use icon names from multiple libraries via prefixes: ```yml icon: si:immich # si for Simple icons https://simpleicons.org/ icon: sh:immich # sh for selfh.st icons https://selfh.st/icons/ icon: di:immich # di for Dashboard icons https://github.com/homarr-labs/dashboard-icons icon: mdi:camera # mdi for Material Design icons https://pictogrammers.com/library/mdi/ ``` > [!NOTE] > > The 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. Icons from the Simple icons library as well as Material Design icons will automatically invert their color to match your light or dark theme, however you may want to enable this manually for other icons. To do this, you can use the `auto-invert` prefix: ```yaml icon: auto-invert https://example.com/path/to/icon.png # with a URL icon: auto-invert sh:glance-dark # with a selfh.st icon ``` This expects the icon to be black and will automatically invert it to white when using a dark theme. ## Config schema For property descriptions, validation and autocompletion of the config within your IDE, @not-first has kindly created a [schema](https://github.com/not-first/glance-schema). Massive thanks to them for this, go check it out and give them a star! ## Authentication To make sure that only you and the people you want to share your dashboard with have access to it, you can set up authentication via username and password. This is done through a top level `auth` property. Example: ```yaml auth: secret-key: # this must be set to a random value generated using the secret:make CLI command users: admin: password: 123456 svilen: password: 123456 ``` To generate a secret key, run the following command: ```sh ./glance secret:make ``` Or with Docker: ```sh docker run --rm glanceapp/glance secret:make ``` ### Using hashed passwords If you do not want to store plain passwords in your config file or in environment variables, you can hash your password and provide its hash instead: ```sh ./glance password:hash mysecretpassword ``` Or with Docker: ```sh docker run --rm glanceapp/glance password:hash mysecretpassword ``` Then, in your config file use the `password-hash` property instead of `password`: ```yaml auth: secret-key: # this must be set to a random value generated using the secret:make CLI command users: admin: password-hash: $2a$10$o6SXqiccI3DDP2dN4ADumuOeIHET6Q4bUMYZD6rT2Aqt6XQ3DyO.6 ``` ### Preventing brute-force attacks Glance will automatically block IP addresses of users who fail to authenticate 5 times in a row in the span of 5 minutes. In order for this feature to work correctly, Glance must know the real IP address of requests. If you're using a reverse proxy such as nginx, Traefik, NPM, etc, you must set the `proxied` property in the `server` configuration to `true`: ```yaml server: proxied: true ``` When set to `true`, Glance will use the `X-Forwarded-For` header to determine the original IP address of the request, so make sure that your reverse proxy is correctly configured to send that header. ## Server Server configuration is done through a top level `server` property. Example: ```yaml server: port: 8080 assets-path: /home/user/glance-assets ``` ### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | host | string | no | | | port | number | no | 8080 | | proxied | boolean | no | false | | base-url | string | no | | | assets-path | string | no | | #### `host` The address which the server will listen on. Setting it to `localhost` means that only the machine that the server is running on will be able to access the dashboard. By default it will listen on all interfaces. #### `port` A number between 1 and 65,535, so long as that port isn't already used by anything else. #### `proxied` Set to `true` if you're using a reverse proxy in front of Glance. This will make Glance use the `X-Forwarded-*` headers to determine the original request details. #### `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. > [!IMPORTANT] > > When installing through docker the path will point to the files inside the container. Don't forget to mount your assets path to the same path inside the container. > Example: > > If your assets are in: > ``` > /home/user/glance-assets > ``` > > You should mount: > ``` > /home/user/glance-assets:/app/assets > ``` > > And your config should contain: > ``` > assets-path: /app/assets > ``` ##### Examples Say you have a directory `glance-assets` with a file `gitea-icon.png` in it and you specify your assets path like: ```yaml assets-path: /home/user/glance-assets ``` To be able to point to an asset from your assets path, use 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 app-name: "My Dashboard" app-icon-url: "/assets/app-icon.png" app-background-color: "#151519" ``` ### 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 | | | app-name | string | no | Glance | | app-icon-url | string | no | Glance's default icon | | app-background-color | string | no | Glance's default background color | #### `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. #### `app-name` Specify the name of the web app shown in browser tab and PWA. #### `app-icon-url` Specify URL for PWA and browser tab icon (512x512 PNG). #### `app-background-color` Specify background color for PWA. Must be a valid CSS color. ## 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. Example: ```yaml theme: # This will be the default theme background-color: 100 20 10 primary-color: 40 90 40 contrast-multiplier: 1.1 disable-picker: false presets: gruvbox-dark: background-color: 0 0 16 primary-color: 43 59 81 positive-color: 61 66 44 negative-color: 6 96 59 zebra: light: true background-color: 0 0 95 primary-color: 0 0 10 negative-color: 0 90 50 ``` ### Available themes If you don't want to spend time configuring your own theme, there are [several available themes](themes.md) which you can simply copy the values for. ### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | light | boolean | no | false | | background-color | HSL | no | 240 8 9 | | primary-color | HSL | no | 43 50 70 | | positive-color | HSL | no | same as `primary-color` | | negative-color | HSL | no | 0 70 70 | | contrast-multiplier | number | no | 1 | | text-saturation-multiplier | number | no | 1 | | custom-css-file | string | no | | | disable-picker | bool | false | | | presets | object | no | | #### `light` Whether the scheme is light or dark. This does not change the background color, it inverts the text colors so that they look appropriately on a light background. #### `background-color` Color of the page and widgets. #### `primary-color` Color used across the page, largely to indicate unvisited links. #### `positive-color` Used to indicate that something is positive, such as stock price being up, twitch channel being live or a monitored site being online. If not set, the value of `primary-color` will be used. #### `negative-color` Oppposite of `positive-color`. #### `contrast-multiplier` Used to increase or decrease the contrast (in other words visibility) of the text. A value of `1.3` means that the text will be 30% lighter/darker depending on the scheme. Use this if you think that some of the text on the page is too dark and hard to read. Example: ![difference between 1 and 1.3 contrast](images/contrast-multiplier-example.png) #### `text-saturation-multiplier` Used to increase or decrease the saturation of text, useful when using a custom background color with a high amount of saturation and needing the text to have a more neutral color. `0.5` means that the saturation will be 50% lower and `1.5` means that it'll be 50% higher. #### `custom-css-file` Path to a custom CSS file, either external or one from within the server configured assets path. Example: ```yaml theme: custom-css-file: /assets/my-style.css ``` > [!TIP] > > Because Glance uses a lot of utility classes it might be difficult to target some elements. To make it easier to style specific widgets, each widget has a `widget-type-{name}` class, so for example if you wanted to make the links inside just the RSS widget bigger you could use the following selector: > > ```css > .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. #### `disable-picker` When set to `true` hides the theme picker and disables the abiltity to switch between themes. All users who previously picked a non-default theme will be switched over to the default theme. #### `presets` Define additional theme presets that can be selected from the theme picker on the page. For each preset, you can specify the same properties as for the default theme, such as `background-color`, `primary-color`, `positive-color`, `negative-color`, `contrast-multiplier`, etc., except for the `custom-css-file` property. Example: ```yaml theme: presets: my-custom-dark-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 my-custom-light-theme: light: true background-color: 220 23 95 contrast-multiplier: 1.1 primary-color: 220 91 54 positive-color: 109 58 40 negative-color: 347 87 44 ``` To override the default dark and light themes, use the key names `default-dark` and `default-light`. ## Pages & Columns ![illustration of pages and columns](images/pages-and-columns-illustration.png) Using pages and columns is how widgets are organized. Each page contains up to 3 columns and each column can have any number of widgets. ### Pages Pages are defined through a top level `pages` property. The page defined first becomes the home page and all pages get automatically added to the navigation bar in the order that they were defined. Example: ```yaml pages: - name: Home columns: ... - name: Videos columns: ... - name: Homelab columns: ... ``` ### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | name | string | yes | | | slug | string | no | | | width | string | no | | | desktop-navigation-width | string | no | | | center-vertically | boolean | no | false | | hide-desktop-navigation | boolean | no | false | | show-mobile-header | boolean | no | false | | head-widgets | array | no | | | columns | array | yes | | #### `name` 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 `default`, `slim` and `wide`. #### `desktop-navigation-width` The maximum width of the desktop navigation. Useful if you have a few pages that use a different width than the rest and don't want the navigation to jump abruptly when going to and away from those pages. Possible values are `default`, `slim` and `wide`. Here are the pixel equivalents for each value: * default: `1600px` * 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. #### `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) #### `head-widgets` Head widgets will be shown at the top of the page, above the columns, and take up the combined width of all columns. You can specify any widget, though some will look better than others, such as the markets, RSS feed with `horizontal-cards` style, and videos widgets. Example: ![](images/head-widgets-preview.png) ```yaml pages: - name: Home head-widgets: - type: markets hide-header: true markets: - symbol: SPY name: S&P 500 - symbol: BTC-USD name: Bitcoin - symbol: NVDA name: NVIDIA - symbol: AAPL name: Apple - symbol: MSFT name: Microsoft columns: - size: small widgets: - type: calendar - size: full widgets: - type: hacker-news - size: small widgets: - type: weather location: London, United Kingdom ``` ### 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: ```yaml pages: - name: Home columns: - size: small widgets: ... - size: full widgets: ... - size: small widgets: ... ``` ### Properties | Name | Type | Required | | ---- | ---- | -------- | | size | string | yes | | widgets | array | no | Here are some of the possible column configurations: ![column configuration small-full-small](images/column-configuration-1.png) ```yaml columns: - size: small widgets: ... - size: full widgets: ... - size: small widgets: ... ``` ![column configuration small-full-small](images/column-configuration-2.png) ```yaml columns: - size: full widgets: ... - size: small widgets: ... ``` ![column configuration small-full-small](images/column-configuration-3.png) ```yaml columns: - size: full widgets: ... - size: full widgets: ... ``` ## Widgets Widgets are defined for each column using a `widgets` property. Example: ```yaml pages: - name: Home columns: - size: small widgets: - type: weather location: London, United Kingdom ``` > [!NOTE] > > Currently not all widgets are designed to fit every column size, however some widgets offer different "styles" that help alleviate this limitation. ### Shared Properties | Name | Type | Required | | ---- | ---- | -------- | | type | string | yes | | title | string | no | | title-url | string | no | | hide-header | boolean | no | false | | cache | string | no | | css-class | string | no | #### `type` 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). #### `hide-header` When set to `true`, the header (title) of the widget will be hidden. You cannot hide the header of the group widget. > [!NOTE] > > If a widget fails to update, a red dot or circle is shown next to the title of that widget indicating that the it is not working. You will not be able to see this if you hide the header. #### `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: ```yaml cache: 30s # 30 seconds cache: 5m # 5 minutes cache: 2h # 2 hours cache: 1d # 1 day ``` > [!NOTE] > > 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. Example: ```yaml - 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 ``` #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | 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 | ##### `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. Example: ```yaml - type: videos channels: - UCXuqSBlHAE6Xw-yeJA0Tunw - UCBJycsmduvYEL83R_U4JriQ - UCHnyfMqiRRG1u-2MsSQLbXA ``` Preview: ![](images/videos-widget-preview.png) #### Properties | 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: ![](images/videos-channel-description-example.png) 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 ``` The playlist ID can be found in its link which is in the form of ``` https://www.youtube.com...&list={ID}&... ``` ##### `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: ```yaml video-url-template: https://invidious.your-domain.com/watch?v={VIDEO-ID} ``` Placeholders: `{VIDEO-ID}` - the ID of the video ### Hacker News Display a list of posts from [Hacker News](https://news.ycombinator.com/). Example: ```yaml - type: hacker-news limit: 15 collapse-after: 5 ``` Preview: ![](images/hacker-news-widget-preview.png) #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | 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: ```yaml comments-url-template: https://www.hckrnws.com/stories/{POST-ID} ``` 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 either [register an app on Reddit](https://ssl.reddit.com/prefs/apps/) and use the > generated ID and secret in the widget configuration to authenticate your requests (see `app-auth` property), use a proxy > (see `proxy` property) or route the traffic from Glance through a VPN. Example: ```yaml - type: reddit subreddit: technology ``` #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | 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 | | | app-auth | object | no | | ##### `subreddit` The subreddit for which to fetch the posts from. ##### `style` Used to change the appearance of the widget. Possible values are `vertical-list`, `horizontal-cards` and `vertical-cards`. The first two were designed for full columns and the last for small columns. `vertical-list` ![](images/reddit-widget-preview.png) `horizontal-cards` ![](images/reddit-widget-horizontal-cards-preview.png) `vertical-cards` ![](images/reddit-widget-vertical-cards-preview.png) ##### `show-thumbnails` Shows or hides thumbnails next to the post. This only works if the `style` is `vertical-list`. Preview: ![](images/reddit-widget-vertical-list-thumbnails.png) > [!NOTE] > > 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. ##### `collapse-after` How many posts are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. Not available when using the `vertical-cards` and `horizontal-cards` styles. ##### `comments-url-template` Used to replace the default link for post comments. Useful if you want to use the old Reddit design or any other 3rd party front-end. Example: ```yaml comments-url-template: https://old.reddit.com/{POST-PATH} ``` Placeholders: `{POST-PATH}` - the full path to the post, such as: ``` r/selfhosted/comments/bsp01i/welcome_to_rselfhosted_please_read_this_first/ ``` `{POST-ID}` - the ID that comes after `/comments/` `{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. Placeholders: `{REQUEST-URL}` - will be templated and replaced with the expanded request URL (i.e. https://www.reddit.com/r/selfhosted/hot.json). Example: ``` 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. ##### `app-auth` ```yaml widgets: - type: reddit subreddit: technology app-auth: name: ${REDDIT_APP_NAME} id: ${REDDIT_APP_CLIENT_ID} secret: ${REDDIT_APP_SECRET} ``` To register an app on Reddit, go to [this page](https://ssl.reddit.com/prefs/apps/). ### 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 | | target | string | no | _blank | | 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}` | | bing | `https://www.bing.com/search?q={QUERY}` | | perplexity | `https://www.perplexity.ai/search?q={QUERY}` | | kagi | `https://kagi.com/search?q={QUERY}` | | startpage | `https://www.startpage.com/search?q={QUERY}` | ##### `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. ##### `target` The target to use when opening the search results in a new tab. Possible values are `_blank`, `_self`, `_parent` and `_top`. ##### `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: |
    {{ range .JSON.Array "specials.items" }}
  • {{ .String "name" }}
    • {{ div (.Int "final_price" | toFloat) 100 | printf "$%.2f" }}
    • {{ $discount := .Int "discount_percent" }} {{ $discount }}% off
  • {{ end }}
```
#### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | url | string | no | | | 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 | | | options | map | no | | | 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). ##### `options` A map of options that will be passed to the template and can be used to modify the behavior of the widget.
View examples
Instead of defining options within the template and having to modify the template itself like such: ```yaml - type: custom-api template: | {{ /* User configurable options */ }} {{ $collapseAfter := 5 }} {{ $showThumbnails := true }} {{ $showFlairs := false }}
    {{ if $showThumbnails }}
  • thumbnail
  • {{ end }} {{ if $showFlairs }}
  • {{ .JSON.String "flair" }}
  • {{ end }}
``` You can use the `options` property to retrieve and define default values for these variables: ```yaml - type: custom-api template: |
    {{ if (.Options.BoolOr "show-thumbnails" true) }}
  • thumbnail
  • {{ end }} {{ if (.Options.BoolOr "show-flairs" false) }}
  • {{ .JSON.String "flair" }}
  • {{ end }}
``` This way, you can optionally specify the `collapse-after`, `show-thumbnails` and `show-flairs` properties in the widget configuration: ```yaml - type: custom-api options: collapse-after: 5 show-thumbnails: true show-flairs: false ``` Which means you can reuse the same template for multiple widgets with different options: ```yaml # Note that `custom-widgets` isn't a special property, it's just used to define the reusable "anchor", see https://support.atlassian.com/bitbucket-cloud/docs/yaml-anchors/ custom-widgets: - &example-widget type: custom-api template: | {{ .Options.StringOr "custom-option" "not defined" }} pages: - name: Home columns: - size: full widgets: - <<: *example-widget options: custom-option: "Value 1" - <<: *example-widget options: custom-option: "Value 2" ``` Currently, the available methods on the `.Options` object are: `StringOr`, `IntOr`, `BoolOr` and `FloatOr`.
##### `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/. 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: > > * Greenville, North Carolina, United States > * Greenville, South Carolina, United States > * Greenville, Mississippi, United States Preview: ![](images/weather-widget-preview.png) Each bar represents a 2 hour interval. The yellow background represents sunrise and sunset. The blue dots represent the times of the day where there is a high chance for precipitation. You can hover over the bars to view the exact temperature for that time. #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | location | string | yes | | | units | string | no | metric | | hour-format | string | no | 12h | | hide-location | boolean | no | false | | show-area-name | boolean | no | false | ##### `location` The name of the city and country to fetch weather information for. Attempting to launch the applcation with an invalid location will result in an error. You can use the [gecoding API page](https://open-meteo.com/en/docs/geocoding-api) to search for your specific location. Glance will use the first result from the list if there are multiple. ##### `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. ##### `show-area-name` Whether to display the state/administrative area in the location name. If set to `true` the location will be displayed as: ``` Greenville, North Carolina, United States ``` Otherwise, if set to `false` (which is the default) it'll be displayed as: ``` Greenville, United States ``` ### Todo A simple to-do list that allows you to add, edit and delete tasks. The tasks are stored in the browser's local storage. Example: ```yaml - type: to-do ``` Preview: ![](images/todo-widget-preview.png) To reorder tasks, drag and drop them by grabbing the top side of the task: ![](images/reorder-todo-tasks-prevew.gif) To delete a task, hover over it and click on the trash icon. #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | id | string | no | | ##### `id` The ID of the todo list. If you want to have multiple todo lists, you must specify a different ID for each one. The ID is used to store the tasks in the browser's local storage. This means that if you have multiple todo lists with the same ID, they will share the same tasks. #### Keyboard shortcuts | Keys | Action | Condition | | ---- | ------ | --------- | | Enter | Add a task to the bottom of the list | When the "Add a task" field is focused | | Ctrl + Enter | Add a task to the top of the list | When the "Add a task" field is focused | | Down Arrow | Focus the last task that was added | When the "Add a task" field is focused | | Escape | Focus the "Add a task" field | When a task is focused | ### 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. Example: ```yaml - type: monitor cache: 1m title: Services sites: - title: Jellyfin url: https://jellyfin.yourdomain.com icon: /assets/jellyfin-logo.png - title: Gitea url: https://gitea.yourdomain.com icon: /assets/gitea-logo.png - title: Immich url: https://immich.yourdomain.com icon: /assets/immich-logo.png - title: AdGuard Home url: https://adguard.yourdomain.com icon: /assets/adguard-logo.png - title: Vaultwarden url: https://vault.yourdomain.com icon: /assets/vaultwarden-logo.png ``` Preview: ![](images/monitor-widget-preview.png) 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) ##### `sites` Properties for each site: | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | title | string | yes | | | url | string | yes | | | check-url | string | no | | | error-url | string | no | | | icon | string | no | | | timeout | string | no | 3s | | allow-insecure | boolean | no | false | | same-tab | boolean | no | false | | alt-status-codes | array | no | | | basic-auth | object | no | | `title` The title used to indicate the site. `url` The URL of the monitored service, which must be reachable by Glance, and will be used as the link to go to when clicking on the title. 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. `icon` See [Icons](#icons) for more information on how to specify icons. `timeout` How long to wait for a response from the server before considering it unreachable. The value is a string and must be a number followed by one of s, m, h, d. Example: `5s` for 5 seconds, `1m` for 1 minute, etc. `allow-insecure` Whether to ignore invalid/self-signed certificates. `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 ``` `basic-auth` HTTP Basic Authentication credentials for protected sites. ```yaml basic-auth: username: your-username password: your-password ``` ### Releases Display a list of latest releases for specific repositories on Github, GitLab, Codeberg or Docker Hub. Example: ```yaml - type: releases show-source-icon: true repositories: - go-gitea/gitea - jellyfin/jellyfin - glanceapp/glance - codeberg:redict/redict - gitlab:fdroid/fdroidclient - dockerhub:gotify/server ``` Preview: ![](images/releases-widget-preview.png) #### Properties | 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`. ##### `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. You can also specify the value for this token through an ENV variable using the syntax `${GITHUB_TOKEN}` where `GITHUB_TOKEN` is the name of the variable that holds the token. If you've installed Glance through docker you can specify the token in your docker-compose: ```yaml services: glance: image: glanceapp/glance environment: - GITHUB_TOKEN= ``` and then use it in your `glance.yml` like this: ```yaml - type: releases token: ${GITHUB_TOKEN} repositories: ... ``` 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 ``` Alternatively, you can also define the values within your `glance.yml` via the `containers` property, where the key is the container name and each value is the same as the labels but without the "glance." prefix: ```yaml - type: docker-containers containers: container_name_1: name: Container Name description: Description of the container url: https://container.domain.com icon: si:container-icon hide: false ``` 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 | | format-container-names | boolean | no | false | | sock-path | string | no | /var/run/docker.sock | | category | string | no | | | running-only | boolean | no | false | ##### `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. ##### `format-container-names` When set to `true`, automatically converts container names such as `container_name_1` into `Container Name 1`. ##### `sock-path` The path to the Docker socket. This can also be a [remote socket](https://docs.docker.com/engine/daemon/remote-access/) or proxied socket using something like [docker-socket-proxy](https://github.com/Tecnativa/docker-socket-proxy). ###### `category` Filter to only the containers which have this category specified via the `glance.category` label. Useful if you want to have multiple containers widgets, each showing a different set of containers.
View example
```yaml services: jellyfin: image: jellyfin/jellyfin:latest labels: glance.name: Jellyfin glance.icon: si:jellyfin glance.url: https://jellyfin.domain.com glance.category: media gitea: image: gitea/gitea:latest labels: glance.name: Gitea glance.icon: si:gitea glance.url: https://gitea.domain.com glance.category: dev-tools vaultwarden: image: vaultwarden/server:latest labels: glance.name: Vaultwarden glance.icon: si:vaultwarden glance.url: https://vaultwarden.domain.com glance.category: dev-tools ``` Then you can use the `category` property to filter the containers: ```yaml - type: docker-containers title: Dev tool containers category: dev-tools - type: docker-containers title: Media containers category: media ```
##### `running-only` Whether to only show running containers. If set to `true` only containers that are currently running will be displayed. If set to `false` all containers will be displayed regardless of their state. #### Labels | Name | Description | | ---- | ----------- | | glance.name | The name displayed in the UI. If not specified, the name of the container will be used. | | glance.icon | See [Icons](#icons) for more information on how to specify icons | | 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. | | glance.category | The category of the container. Used to filter containers by category. | ### DNS Stats Display statistics from a self-hosted ad-blocking DNS resolver such as AdGuard Home, Pi-hole, or Technitium. 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 or Technitium 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`, `technitium`, 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 required when using Pi-hole major version 6 and above, where the password is the one used to log into the admin dashboard or the application password, which can be found in `Settings -> Web Interface / API -> Configure app password`. ##### `token` Required when using Pi-hole major version 5 or earlier. The API token which can be found in `Settings -> API -> Show API token`. Also required when using Technitium, an API token can be generated at `Administration -> Sessions -> Create 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. Example: ```yaml - type: bookmarks groups: - 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: Wikipedia url: https://en.wikipedia.org/ - title: Entertainment color: 10 70 50 links: - title: Netflix url: https://www.netflix.com/ - title: Disney+ url: https://www.disneyplus.com/ - title: YouTube url: https://www.youtube.com/ - title: Prime Video url: https://www.primevideo.com/ - title: Social color: 200 50 50 links: - title: Reddit url: https://www.reddit.com/ - title: Twitter url: https://twitter.com/ - title: Instagram url: https://www.instagram.com/ ``` Preview: ![](images/bookmarks-widget-preview.png) #### Properties | Name | Type | Required | | ---- | ---- | -------- | | groups | array | yes | ##### `groups` An array of groups which can optionally have a title and a custom color. ###### Properties for each group | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | 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 | | ---- | ---- | -------- | ------- | | title | string | yes | | | url | string | yes | | | description | string | no | | | icon | string | no | | | same-tab | boolean | no | false | | hide-arrow | boolean | no | false | | target | string | no | | `icon` See [Icons](#icons) for more information on how to specify icons. `same-tab` Whether to open the link in the same tab or a new one. `hide-arrow` 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. Example: ```yaml - type: calendar first-day-of-week: monday ``` Preview: ![](images/calendar-widget-preview.png) #### Properties | 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. 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: - 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 ``` Preview: ![](images/markets-widget-preview.png) #### Properties | Name | Type | Required | | ---- | ---- | -------- | | markets | 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. ##### `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 | Name | Type | Required | | ---- | ---- | -------- | | symbol | string | yes | | name | string | no | | symbol-link | string | no | | chart-link | string | no | `symbol` The symbol, as seen in Yahoo Finance. `name` 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. ### Twitch Channels Display a list of channels from Twitch. Example: ```yaml - type: twitch-channels channels: - jembawls - giantwaffle - asmongold - cohhcarnage - j_blow - xQc ``` Preview: ![](images/twitch-channels-widget-preview.png) #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | channels | array | yes | | | collapse-after | integer | no | 5 | | sort-by | string | no | viewers | ##### `channels` 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. Example: ```yaml - type: twitch-top-games exclude: - just-chatting - pools-hot-tubs-and-beaches - music - art - asmr ``` Preview: ![](images/twitch-top-games-widget-preview.png) #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | exclude | array | no | | | limit | integer | no | 10 | | collapse-after | integer | no | 5 | ##### `exclude` A list of categories that will never be shown. You must provide the slug found by clicking on the category and looking at the URL: ``` https://www.twitch.tv/directory/category/grand-theft-auto-v ^^^^^^^^^^^^^^^^^^ ``` ##### `limit` The maximum number of games to show. ##### `collapse-after` How many games are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. ### iframe Embed an iframe as a widget. Example: ```yaml - type: iframe source: height: 400 ``` #### Properties | Name | Type | Required | Default | | ---- | ---- | -------- | ------- | | source | string | yes | | | height | integer | no | 300 | ##### `source` 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. ================================================ FILE: docs/custom-api.md ================================================ [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`, `div` and `mod`.
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

```
In some instances, you may need to make two consecutive API calls, where you use the result of the first call in the second call. To achieve this, you can make additional HTTP requests from within the template itself using the following syntax: ```yaml - type: custom-api url: https://api.example.com/get-id-of-something template: | {{ $theID := .JSON.String "id" }} {{ $something := newRequest (concat "https://api.example.com/something/" $theID) | withParameter "key" "value" | withHeader "Authorization" "Bearer token" | getResponse }} {{ $something.JSON.String "title" }} ``` Here, `$theID` gets retrieved from the result of the first API call and used in the second API call. The `newRequest` function creates a new request, and the `getResponse` function executes it. You can also use `withParameter` and `withHeader` to optionally add parameters and headers to the request. If you need to make a request to a URL that requires dynamic parameters, you can omit the `url` property in the YAML and run the request entirely from within the template itself: ```yaml - type: custom-api title: Events from the last 24h template: | {{ $events := newRequest "https://api.example.com/events" | withParameter "after" (offsetNow "-24h" | formatTime "rfc3339") | getResponse }} {{ if eq $events.Response.StatusCode 200 }} {{ range $events.JSON.Array "events" }}
{{ .String "title" }}
{{ end }} {{ else }}

Failed to fetch data: {{ $events.Response.Status }}

{{ end }} ``` *Note that you need to manually check for the correct status code.* ## 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 functions are available on the `Options` object: - `StringOr(key string, default string) string`: Returns the value of the key as a string, or the default value if the key does not exist. - `IntOr(key string, default int) int`: Returns the value of the key as an integer, or the default value if the key does not exist. - `FloatOr(key string, default float) float`: Returns the value of the key as a float, or the default value if the key does not exist. - `BoolOr(key string, default bool) bool`: Returns the value of the key as a boolean, or the default value if the key does not exist. - `JSON(key string) JSON`: Returns the value of the key as a stringified `JSON` object, or throws an error if the key does not exist. 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". - `formatTime(layout string, s string) time.Time`: Formats a `time.Time` into a string. The layout uses the same format as `parseTime`. - `parseLocalTime(layout string, s string) time.Time`: Same as the above, except in the absence of a timezone, it will use the local timezone instead of UTC. - `parseRelativeTime(layout string, s string) time.Time`: A shorthand for `{{ .String "date" | parseTime "rfc3339" | toRelativeTime }}`. - `add(a, b float) float`: Adds two numbers. - `sub(a, b float) float`: Subtracts two numbers. - `mul(a, b float) float`: Multiplies two numbers. - `div(a, b float) float`: Divides two numbers. - `mod(a, b int) int`: Remainder after dividing a by b (a % b). - `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. - `percentChange(current float, previous float) float`: Calculates the percentage change between two numbers. - `startOfDay(t time.Time) time.Time`: Returns the start of the day for a given time. - `endOfDay(t time.Time) time.Time`: Returns the end of the day for a given time. 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. - `le(a, b any) bool`: Compares two values for less than or equal to. - `gt(a, b any) bool`: Compares two values for greater than. - `ge(a, b any) bool`: Compares two values for greater than or equal to. - `and(args ...bool) bool`: Returns true if **all** arguments are true; accepts two or more boolean values. - `or(args ...bool) bool`: Returns true if **any** argument is true; accepts two or more boolean values. - `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. ================================================ FILE: docs/extensions.md ================================================ # 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


  • horizontal
  • list
  • with
  • multiple
  • text
  • items

  • list
  • with
  • gap
  • and
  • horizontal
  • lines

  • collapsible
  • list
  • with
  • many
  • items
  • that
  • will
  • appear
  • when
  • you
  • click
  • the
  • button
  • below

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.** ================================================ FILE: docs/glance.yml ================================================ 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 - giantwaffle - 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 ================================================ FILE: docs/preconfigured-pages.md ================================================ # 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 ```
================================================ FILE: docs/themes.md ================================================ # Themes ## Dark ### Teal City ![screenshot](images/themes/teal-city.png) ```yaml theme: background-color: 225 14 15 primary-color: 157 47 65 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) ```yaml theme: background-color: 240 21 15 contrast-multiplier: 1.2 primary-color: 217 92 83 positive-color: 115 54 76 negative-color: 347 70 65 ``` ### Camouflage ![screenshot](images/themes/camouflage.png) ```yaml theme: background-color: 186 21 20 contrast-multiplier: 1.2 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 theme: background-color: 50 1 6 primary-color: 24 97 58 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 ``` ### Shades of Purple ![screenshot](images/themes/shades-of-purple.png) ```yaml theme: background-color: 243 33 25 contrast-multiplier: 1.2 primary-color: 50 100 49 positive-color: 98 82 71 negative-color: 12 77 52 ``` ### Neon Pink ![screenshot](images/themes/neon-pink.png) ```yaml theme: background-color: 240 27 11 contrast-multiplier: 1.5 primary-color: 321 100 71 positive-color: 165 78 51 negative-color: 360 100 71 ``` ## 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 theme: light: true background-color: 28 40 77 primary-color: 155 100 20 negative-color: 0 100 60 contrast-multiplier: 1.1 text-saturation-multiplier: 0.5 ``` ### Zebra ![screenshot](images/themes/zebra.png) ```yaml theme: light: true background-color: 0 0 95 primary-color: 0 0 10 negative-color: 0 90 50 ``` ================================================ FILE: docs/v0.7.0-upgrade.md ================================================ ## 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. ================================================ FILE: go.mod ================================================ module github.com/glanceapp/glance go 1.24.3 require ( github.com/fsnotify/fsnotify v1.9.0 github.com/mmcdole/gofeed v1.3.0 github.com/shirou/gopsutil/v4 v4.25.4 github.com/tidwall/gjson v1.18.0 golang.org/x/crypto v0.38.0 golang.org/x/text v0.25.0 gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/PuerkitoBio/goquery v1.10.3 // indirect github.com/andybalholm/cascadia v1.3.3 // indirect github.com/ebitengine/purego v0.8.4 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/lufia/plan9stats v0.0.0-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.40.0 // indirect golang.org/x/sys v0.33.0 // indirect ) ================================================ FILE: go.sum ================================================ github.com/PuerkitoBio/goquery v1.10.3 h1:pFYcNSqHxBD06Fpj/KsbStFRsgRATgnf3LeXiUkhzPo= github.com/PuerkitoBio/goquery v1.10.3/go.mod h1:tMUX0zDMHXYlAQk6p35XxQMqMweEKB7iK7iLNd4RH4Y= github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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.4 h1:CF7LEKg5FFOsASUj0+QwaXf8Ht6TlFxg09+S9wz0omw= github.com/ebitengine/purego v0.8.4/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= 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/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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-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= github.com/mmcdole/goxpp v1.1.1/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 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.4 h1:cdtFO363VEOOFrUCjZRh4XVJkb548lyF0q0uTeMqYPw= github.com/shirou/gopsutil/v4 v4.25.4/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.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4= github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4= github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso= github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= 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/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= 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.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY= golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= 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.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 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/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/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.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= 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= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: internal/glance/auth.go ================================================ package glance import ( "bytes" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/binary" "encoding/json" "fmt" "io" "log" mathrand "math/rand/v2" "net/http" "strconv" "strings" "time" "golang.org/x/crypto/bcrypt" ) const AUTH_SESSION_COOKIE_NAME = "session_token" const AUTH_RATE_LIMIT_WINDOW = 5 * time.Minute const AUTH_RATE_LIMIT_MAX_ATTEMPTS = 5 const AUTH_TOKEN_SECRET_LENGTH = 32 const AUTH_USERNAME_HASH_LENGTH = 32 const AUTH_SECRET_KEY_LENGTH = AUTH_TOKEN_SECRET_LENGTH + AUTH_USERNAME_HASH_LENGTH const AUTH_TIMESTAMP_LENGTH = 4 // uint32 const AUTH_TOKEN_DATA_LENGTH = AUTH_USERNAME_HASH_LENGTH + AUTH_TIMESTAMP_LENGTH // How long the token will be valid for const AUTH_TOKEN_VALID_PERIOD = 14 * 24 * time.Hour // 14 days // How long the token has left before it should be regenerated const AUTH_TOKEN_REGEN_BEFORE = 7 * 24 * time.Hour // 7 days var loginPageTemplate = mustParseTemplate("login.html", "document.html", "footer.html") type doWhenUnauthorized int const ( redirectToLogin doWhenUnauthorized = iota showUnauthorizedJSON ) type failedAuthAttempt struct { attempts int first time.Time } func generateSessionToken(username string, secret []byte, now time.Time) (string, error) { if len(secret) != AUTH_SECRET_KEY_LENGTH { return "", fmt.Errorf("secret key length is not %d bytes", AUTH_SECRET_KEY_LENGTH) } usernameHash, err := computeUsernameHash(username, secret) if err != nil { return "", err } data := make([]byte, AUTH_TOKEN_DATA_LENGTH) copy(data, usernameHash) expires := now.Add(AUTH_TOKEN_VALID_PERIOD).Unix() binary.LittleEndian.PutUint32(data[AUTH_USERNAME_HASH_LENGTH:], uint32(expires)) h := hmac.New(sha256.New, secret[0:AUTH_TOKEN_SECRET_LENGTH]) h.Write(data) signature := h.Sum(nil) encodedToken := base64.StdEncoding.EncodeToString(append(data, signature...)) // encodedToken ends up being (hashed username + expiration timestamp + signature) encoded as base64 return encodedToken, nil } func computeUsernameHash(username string, secret []byte) ([]byte, error) { if len(secret) != AUTH_SECRET_KEY_LENGTH { return nil, fmt.Errorf("secret key length is not %d bytes", AUTH_SECRET_KEY_LENGTH) } h := hmac.New(sha256.New, secret[AUTH_TOKEN_SECRET_LENGTH:]) h.Write([]byte(username)) return h.Sum(nil), nil } func verifySessionToken(token string, secretBytes []byte, now time.Time) ([]byte, bool, error) { tokenBytes, err := base64.StdEncoding.DecodeString(token) if err != nil { return nil, false, err } if len(tokenBytes) != AUTH_TOKEN_DATA_LENGTH+32 { return nil, false, fmt.Errorf("token length is invalid") } if len(secretBytes) != AUTH_SECRET_KEY_LENGTH { return nil, false, fmt.Errorf("secret key length is not %d bytes", AUTH_SECRET_KEY_LENGTH) } usernameHashBytes := tokenBytes[0:AUTH_USERNAME_HASH_LENGTH] timestampBytes := tokenBytes[AUTH_USERNAME_HASH_LENGTH : AUTH_USERNAME_HASH_LENGTH+AUTH_TIMESTAMP_LENGTH] providedSignatureBytes := tokenBytes[AUTH_TOKEN_DATA_LENGTH:] h := hmac.New(sha256.New, secretBytes[0:32]) h.Write(tokenBytes[0:AUTH_TOKEN_DATA_LENGTH]) expectedSignatureBytes := h.Sum(nil) if !hmac.Equal(expectedSignatureBytes, providedSignatureBytes) { return nil, false, fmt.Errorf("signature does not match") } expiresTimestamp := int64(binary.LittleEndian.Uint32(timestampBytes)) if now.Unix() > expiresTimestamp { return nil, false, fmt.Errorf("token has expired") } return usernameHashBytes, // True if the token should be regenerated time.Unix(expiresTimestamp, 0).Add(-AUTH_TOKEN_REGEN_BEFORE).Before(now), nil } func makeAuthSecretKey(length int) (string, error) { key := make([]byte, length) _, err := rand.Read(key) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(key), nil } func (a *application) handleAuthenticationAttempt(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { w.WriteHeader(http.StatusBadRequest) return } waitOnFailure := 1*time.Second - time.Duration(mathrand.IntN(500))*time.Millisecond ip := a.addressOfRequest(r) a.authAttemptsMu.Lock() exceededRateLimit, retryAfter := func() (bool, int) { attempt, exists := a.failedAuthAttempts[ip] if !exists { a.failedAuthAttempts[ip] = &failedAuthAttempt{ attempts: 1, first: time.Now(), } return false, 0 } elapsed := time.Since(attempt.first) if elapsed < AUTH_RATE_LIMIT_WINDOW && attempt.attempts >= AUTH_RATE_LIMIT_MAX_ATTEMPTS { return true, max(1, int(AUTH_RATE_LIMIT_WINDOW.Seconds()-elapsed.Seconds())) } attempt.attempts++ return false, 0 }() if exceededRateLimit { a.authAttemptsMu.Unlock() time.Sleep(waitOnFailure) w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) w.WriteHeader(http.StatusTooManyRequests) return } else { // Clean up old failed attempts for ipOfAttempt := range a.failedAuthAttempts { if time.Since(a.failedAuthAttempts[ipOfAttempt].first) > AUTH_RATE_LIMIT_WINDOW { delete(a.failedAuthAttempts, ipOfAttempt) } } a.authAttemptsMu.Unlock() } body, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return } var creds struct { Username string `json:"username"` Password string `json:"password"` } err = json.Unmarshal(body, &creds) if err != nil { w.WriteHeader(http.StatusBadRequest) return } logAuthFailure := func() { log.Printf( "Failed login attempt for user '%s' from %s", creds.Username, ip, ) } if len(creds.Username) == 0 || len(creds.Password) == 0 { time.Sleep(waitOnFailure) w.WriteHeader(http.StatusUnauthorized) return } if len(creds.Username) > 50 || len(creds.Password) > 100 { logAuthFailure() time.Sleep(waitOnFailure) w.WriteHeader(http.StatusUnauthorized) return } u, exists := a.Config.Auth.Users[creds.Username] if !exists { logAuthFailure() time.Sleep(waitOnFailure) w.WriteHeader(http.StatusUnauthorized) return } if err := bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(creds.Password)); err != nil { logAuthFailure() time.Sleep(waitOnFailure) w.WriteHeader(http.StatusUnauthorized) return } token, err := generateSessionToken(creds.Username, a.authSecretKey, time.Now()) if err != nil { log.Printf("Could not compute session token during login attempt: %v", err) time.Sleep(waitOnFailure) w.WriteHeader(http.StatusUnauthorized) return } a.setAuthSessionCookie(w, r, token, time.Now().Add(AUTH_TOKEN_VALID_PERIOD)) a.authAttemptsMu.Lock() delete(a.failedAuthAttempts, ip) a.authAttemptsMu.Unlock() w.WriteHeader(http.StatusOK) } func (a *application) isAuthorized(w http.ResponseWriter, r *http.Request) bool { if !a.RequiresAuth { return true } token, err := r.Cookie(AUTH_SESSION_COOKIE_NAME) if err != nil || token.Value == "" { return false } usernameHash, shouldRegenerate, err := verifySessionToken(token.Value, a.authSecretKey, time.Now()) if err != nil { return false } username, exists := a.usernameHashToUsername[string(usernameHash)] if !exists { return false } _, exists = a.Config.Auth.Users[username] if !exists { return false } if shouldRegenerate { newToken, err := generateSessionToken(username, a.authSecretKey, time.Now()) if err != nil { log.Printf("Could not compute session token during regeneration: %v", err) return false } a.setAuthSessionCookie(w, r, newToken, time.Now().Add(AUTH_TOKEN_VALID_PERIOD)) } return true } // Handles sending the appropriate response for an unauthorized request and returns true if the request was unauthorized func (a *application) handleUnauthorizedResponse(w http.ResponseWriter, r *http.Request, fallback doWhenUnauthorized) bool { if a.isAuthorized(w, r) { return false } switch fallback { case redirectToLogin: http.Redirect(w, r, a.Config.Server.BaseURL+"/login", http.StatusSeeOther) case showUnauthorizedJSON: w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(`{"error": "Unauthorized"}`)) } return true } // Maybe this should be a POST request instead? func (a *application) handleLogoutRequest(w http.ResponseWriter, r *http.Request) { a.setAuthSessionCookie(w, r, "", time.Now().Add(-1*time.Hour)) http.Redirect(w, r, a.Config.Server.BaseURL+"/login", http.StatusSeeOther) } func (a *application) setAuthSessionCookie(w http.ResponseWriter, r *http.Request, token string, expires time.Time) { http.SetCookie(w, &http.Cookie{ Name: AUTH_SESSION_COOKIE_NAME, Value: token, Expires: expires, Secure: strings.ToLower(r.Header.Get("X-Forwarded-Proto")) == "https", Path: a.Config.Server.BaseURL + "/", SameSite: http.SameSiteLaxMode, HttpOnly: true, }) } func (a *application) handleLoginPageRequest(w http.ResponseWriter, r *http.Request) { if a.isAuthorized(w, r) { http.Redirect(w, r, a.Config.Server.BaseURL+"/", http.StatusSeeOther) return } data := &templateData{ App: a, } a.populateTemplateRequestData(&data.Request, r) var responseBytes bytes.Buffer err := loginPageTemplate.Execute(&responseBytes, data) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } w.Write(responseBytes.Bytes()) } ================================================ FILE: internal/glance/auth_test.go ================================================ package glance import ( "bytes" "encoding/base64" "testing" "time" ) func TestAuthTokenGenerationAndVerification(t *testing.T) { secret, err := makeAuthSecretKey(AUTH_SECRET_KEY_LENGTH) if err != nil { t.Fatalf("Failed to generate secret key: %v", err) } secretBytes, err := base64.StdEncoding.DecodeString(secret) if err != nil { t.Fatalf("Failed to decode secret key: %v", err) } if len(secretBytes) != AUTH_SECRET_KEY_LENGTH { t.Fatalf("Secret key length is not %d bytes", AUTH_SECRET_KEY_LENGTH) } now := time.Now() username := "admin" token, err := generateSessionToken(username, secretBytes, now) if err != nil { t.Fatalf("Failed to generate session token: %v", err) } usernameHashBytes, shouldRegen, err := verifySessionToken(token, secretBytes, now) if err != nil { t.Fatalf("Failed to verify session token: %v", err) } if shouldRegen { t.Fatal("Token should not need to be regenerated immediately after generation") } computedUsernameHash, err := computeUsernameHash(username, secretBytes) if err != nil { t.Fatalf("Failed to compute username hash: %v", err) } if !bytes.Equal(usernameHashBytes, computedUsernameHash) { t.Fatal("Username hash does not match the expected value") } // Test token regeneration timeRightAfterRegenPeriod := now.Add(AUTH_TOKEN_VALID_PERIOD - AUTH_TOKEN_REGEN_BEFORE + 2*time.Second) _, shouldRegen, err = verifySessionToken(token, secretBytes, timeRightAfterRegenPeriod) if err != nil { t.Fatalf("Token verification should not fail during regeneration period, err: %v", err) } if !shouldRegen { t.Fatal("Token should have been marked for regeneration") } // Test token expiration _, _, err = verifySessionToken(token, secretBytes, now.Add(AUTH_TOKEN_VALID_PERIOD+2*time.Second)) if err == nil { t.Fatal("Expected token verification to fail after token expiration") } // Test tampered token decodedToken, err := base64.StdEncoding.DecodeString(token) if err != nil { t.Fatalf("Failed to decode token: %v", err) } // If any of the bytes are off by 1, the token should be considered invalid for i := range len(decodedToken) { tampered := make([]byte, len(decodedToken)) copy(tampered, decodedToken) tampered[i] += 1 _, _, err = verifySessionToken(base64.StdEncoding.EncodeToString(tampered), secretBytes, now) if err == nil { t.Fatalf("Expected token verification to fail for tampered token at index %d", i) } } } ================================================ FILE: internal/glance/cli.go ================================================ package glance import ( "flag" "fmt" "os" "strings" "github.com/shirou/gopsutil/v4/disk" "github.com/shirou/gopsutil/v4/sensors" ) type cliIntent uint8 const ( cliIntentVersionPrint cliIntent = iota cliIntentServe cliIntentConfigValidate cliIntentConfigPrint cliIntentDiagnose cliIntentSensorsPrint cliIntentMountpointInfo cliIntentSecretMake cliIntentPasswordHash ) type cliOptions struct { intent cliIntent configPath string args []string } func parseCliOptions() (*cliOptions, error) { var args []string args = os.Args[1:] if len(args) == 1 && (args[0] == "--version" || args[0] == "-v" || args[0] == "version") { return &cliOptions{ intent: cliIntentVersionPrint, }, nil } flags := flag.NewFlagSet("", flag.ExitOnError) flags.Usage = func() { fmt.Println("Usage: glance [options] command") fmt.Println("\nOptions:") flags.PrintDefaults() fmt.Println("\nCommands:") fmt.Println(" config:validate Validate the config file") fmt.Println(" config:print Print the parsed config file with embedded includes") fmt.Println(" password:hash Hash a password") fmt.Println(" secret:make Generate a random secret key") fmt.Println(" sensors:print List all sensors") fmt.Println(" mountpoint:info Print information about a given mountpoint path") fmt.Println(" diagnose Run diagnostic checks") } configPath := flags.String("config", "glance.yml", "Set config path") err := flags.Parse(os.Args[1:]) if err != nil { return nil, err } var intent cliIntent args = flags.Args() unknownCommandErr := fmt.Errorf("unknown command: %s", strings.Join(args, " ")) if len(args) == 0 { intent = cliIntentServe } else if len(args) == 1 { if args[0] == "config:validate" { intent = cliIntentConfigValidate } else if args[0] == "config:print" { intent = cliIntentConfigPrint } else if args[0] == "sensors:print" { intent = cliIntentSensorsPrint } else if args[0] == "diagnose" { intent = cliIntentDiagnose } else if args[0] == "secret:make" { intent = cliIntentSecretMake } else { return nil, unknownCommandErr } } else if len(args) == 2 { if args[0] == "password:hash" { intent = cliIntentPasswordHash } else { return nil, unknownCommandErr } } else if len(args) == 2 { if args[0] == "mountpoint:info" { intent = cliIntentMountpointInfo } else { return nil, unknownCommandErr } } else { return nil, unknownCommandErr } return &cliOptions{ intent: intent, configPath: *configPath, args: args, }, nil } func cliSensorsPrint() int { tempSensors, err := sensors.SensorsTemperatures() if err != nil { if warns, ok := err.(*sensors.Warnings); ok { fmt.Printf("Could not retrieve information for some sensors (%v):\n", err) for _, w := range warns.List { fmt.Printf(" - %v\n", w) } fmt.Println() } else { fmt.Printf("Failed to retrieve sensor information: %v\n", err) return 1 } } if len(tempSensors) == 0 { fmt.Println("No sensors found") return 0 } fmt.Println("Sensors found:") for _, sensor := range tempSensors { fmt.Printf(" %s: %.1f°C\n", sensor.SensorKey, sensor.Temperature) } return 0 } func cliMountpointInfo(requestedPath string) int { usage, err := disk.Usage(requestedPath) if err != nil { fmt.Printf("Failed to retrieve info for path %s: %v\n", requestedPath, err) if warns, ok := err.(*disk.Warnings); ok { for _, w := range warns.List { fmt.Printf(" - %v\n", w) } } return 1 } fmt.Println("Path:", usage.Path) fmt.Println("FS type:", ternary(usage.Fstype == "", "unknown", usage.Fstype)) fmt.Printf("Used percent: %.1f%%\n", usage.UsedPercent) return 0 } ================================================ FILE: internal/glance/config-fields.go ================================================ package glance import ( "crypto/tls" "fmt" "html/template" "net/http" "net/url" "regexp" "strconv" "strings" "time" "gopkg.in/yaml.v3" ) var hslColorFieldPattern = regexp.MustCompile(`^(?:hsla?\()?([\d\.]+)(?: |,)+([\d\.]+)%?(?: |,)+([\d\.]+)%?\)?$`) const ( hslHueMax = 360 hslSaturationMax = 100 hslLightnessMax = 100 ) type hslColorField struct { H float64 S float64 L float64 } func (c *hslColorField) String() string { return fmt.Sprintf("hsl(%.1f, %.1f%%, %.1f%%)", c.H, c.S, c.L) } func (c *hslColorField) ToHex() string { return hslToHex(c.H, c.S, c.L) } func (c1 *hslColorField) SameAs(c2 *hslColorField) bool { if c1 == nil && c2 == nil { return true } if c1 == nil || c2 == nil { return false } return c1.H == c2.H && c1.S == c2.S && c1.L == c2.L } func (c *hslColorField) UnmarshalYAML(node *yaml.Node) error { var value string if err := node.Decode(&value); err != nil { return err } matches := hslColorFieldPattern.FindStringSubmatch(value) if len(matches) != 4 { return fmt.Errorf("invalid HSL color format: %s", value) } hue, err := strconv.ParseFloat(matches[1], 64) if err != nil { return err } if hue > hslHueMax { return fmt.Errorf("HSL hue must be between 0 and %d", hslHueMax) } saturation, err := strconv.ParseFloat(matches[2], 64) if err != nil { return err } if saturation > hslSaturationMax { return fmt.Errorf("HSL saturation must be between 0 and %d", hslSaturationMax) } lightness, err := strconv.ParseFloat(matches[3], 64) if err != nil { return err } if lightness > hslLightnessMax { return fmt.Errorf("HSL lightness must be between 0 and %d", hslLightnessMax) } c.H = hue c.S = saturation c.L = lightness return nil } var durationFieldPattern = 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 := durationFieldPattern.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 customIconField struct { URL template.URL AutoInvert bool } func newCustomIconField(value string) customIconField { const autoInvertPrefix = "auto-invert " field := customIconField{} if strings.HasPrefix(value, autoInvertPrefix) { field.AutoInvert = true value = strings.TrimPrefix(value, autoInvertPrefix) } prefix, icon, found := strings.Cut(value, ":") if !found { field.URL = template.URL(value) return field } basename, ext, found := strings.Cut(icon, ".") if !found { ext = "svg" basename = icon } if ext != "svg" && ext != "png" { ext = "svg" } switch prefix { case "si": field.AutoInvert = true field.URL = template.URL("https://cdn.jsdelivr.net/npm/simple-icons@latest/icons/" + basename + ".svg") case "di": field.URL = template.URL("https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/" + ext + "/" + basename + "." + ext) case "mdi": field.AutoInvert = true field.URL = template.URL("https://cdn.jsdelivr.net/npm/@mdi/svg@latest/svg/" + basename + ".svg") case "sh": field.URL = template.URL("https://cdn.jsdelivr.net/gh/selfhst/icons/" + ext + "/" + basename + "." + ext) default: field.URL = template.URL(value) } return field } func (i *customIconField) UnmarshalYAML(node *yaml.Node) error { var value string if err := node.Decode(&value); err != nil { return err } *i = newCustomIconField(value) return nil } type proxyOptionsField struct { URL string `yaml:"url"` AllowInsecure bool `yaml:"allow-insecure"` Timeout durationField `yaml:"timeout"` client *http.Client `yaml:"-"` } func (p *proxyOptionsField) UnmarshalYAML(node *yaml.Node) error { type proxyOptionsFieldAlias proxyOptionsField alias := (*proxyOptionsFieldAlias)(p) var proxyURL string if err := node.Decode(&proxyURL); err != nil { if err := node.Decode(alias); err != nil { return err } } if proxyURL == "" && p.URL == "" { return nil } if p.URL != "" { proxyURL = p.URL } parsedUrl, err := url.Parse(proxyURL) if err != nil { return fmt.Errorf("parsing proxy URL: %v", err) } var timeout = defaultClientTimeout if p.Timeout > 0 { timeout = time.Duration(p.Timeout) } p.client = &http.Client{ Timeout: timeout, Transport: &http.Transport{ Proxy: http.ProxyURL(parsedUrl), TLSClientConfig: &tls.Config{InsecureSkipVerify: p.AllowInsecure}, }, } return nil } type queryParametersField map[string][]string func (q *queryParametersField) UnmarshalYAML(node *yaml.Node) error { var decoded map[string]any if err := node.Decode(&decoded); err != nil { return err } *q = make(queryParametersField) // TODO: refactor the duplication in the switch cases if any more types get added for key, value := range decoded { switch v := value.(type) { case string: (*q)[key] = []string{v} case int, int8, int16, int32, int64, float32, float64: (*q)[key] = []string{fmt.Sprintf("%v", v)} case bool: (*q)[key] = []string{fmt.Sprintf("%t", v)} case []string: (*q)[key] = append((*q)[key], v...) case []any: for _, item := range v { switch item := item.(type) { case string: (*q)[key] = append((*q)[key], item) case int, int8, int16, int32, int64, float32, float64: (*q)[key] = append((*q)[key], fmt.Sprintf("%v", item)) case bool: (*q)[key] = append((*q)[key], fmt.Sprintf("%t", item)) default: return fmt.Errorf("invalid query parameter value type: %T", item) } } default: return fmt.Errorf("invalid query parameter value type: %T", value) } } return nil } func (q *queryParametersField) toQueryString() string { query := url.Values{} for key, values := range *q { for _, value := range values { query.Add(key, value) } } return query.Encode() } ================================================ FILE: internal/glance/config.go ================================================ package glance import ( "bytes" "errors" "fmt" "html/template" "iter" "log" "maps" "os" "path/filepath" "regexp" "strings" "sync" "time" "github.com/fsnotify/fsnotify" "gopkg.in/yaml.v3" ) const CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT = 20 const ( configVarTypeEnv = "env" configVarTypeSecret = "secret" configVarTypeFileFromEnv = "readFileFromEnv" ) type config struct { Server struct { Host string `yaml:"host"` Port uint16 `yaml:"port"` Proxied bool `yaml:"proxied"` AssetsPath string `yaml:"assets-path"` BaseURL string `yaml:"base-url"` } `yaml:"server"` Auth struct { SecretKey string `yaml:"secret-key"` Users map[string]*user `yaml:"users"` } `yaml:"auth"` Document struct { Head template.HTML `yaml:"head"` } `yaml:"document"` Theme struct { themeProperties `yaml:",inline"` CustomCSSFile string `yaml:"custom-css-file"` DisablePicker bool `yaml:"disable-picker"` Presets orderedYAMLMap[string, *themeProperties] `yaml:"presets"` } `yaml:"theme"` Branding struct { HideFooter bool `yaml:"hide-footer"` CustomFooter template.HTML `yaml:"custom-footer"` LogoText string `yaml:"logo-text"` LogoURL string `yaml:"logo-url"` FaviconURL string `yaml:"favicon-url"` FaviconType string `yaml:"-"` AppName string `yaml:"app-name"` AppIconURL string `yaml:"app-icon-url"` AppBackgroundColor string `yaml:"app-background-color"` } `yaml:"branding"` Pages []page `yaml:"pages"` } type user struct { Password string `yaml:"password"` PasswordHashString string `yaml:"password-hash"` PasswordHash []byte `yaml:"-"` } type page struct { Title string `yaml:"name"` Slug string `yaml:"slug"` Width string `yaml:"width"` DesktopNavigationWidth string `yaml:"desktop-navigation-width"` ShowMobileHeader bool `yaml:"show-mobile-header"` HideDesktopNavigation bool `yaml:"hide-desktop-navigation"` CenterVertically bool `yaml:"center-vertically"` HeadWidgets widgets `yaml:"head-widgets"` Columns []struct { Size string `yaml:"size"` Widgets widgets `yaml:"widgets"` } `yaml:"columns"` PrimaryColumnIndex int8 `yaml:"-"` mu sync.Mutex `yaml:"-"` } func newConfigFromYAML(contents []byte) (*config, error) { contents, err := parseConfigVariables(contents) if err != nil { return nil, err } config := &config{} config.Server.Port = 8080 err = yaml.Unmarshal(contents, config) if err != nil { return nil, err } if err = isConfigStateValid(config); err != nil { return nil, err } for p := range config.Pages { for w := range config.Pages[p].HeadWidgets { if err := config.Pages[p].HeadWidgets[w].initialize(); err != nil { return nil, formatWidgetInitError(err, config.Pages[p].HeadWidgets[w]) } } for c := range config.Pages[p].Columns { for w := range config.Pages[p].Columns[c].Widgets { if err := config.Pages[p].Columns[c].Widgets[w].initialize(); err != nil { return nil, formatWidgetInitError(err, config.Pages[p].Columns[c].Widgets[w]) } } } } return config, nil } var envVariableNamePattern = regexp.MustCompile(`^[A-Z0-9_]+$`) var configVariablePattern = regexp.MustCompile(`(^|.)\$\{(?:([a-zA-Z]+):)?([a-zA-Z0-9_-]+)\}`) // Parses variables defined in the config such as: // ${API_KEY} - gets replaced with the value of the API_KEY environment variable // \${API_KEY} - escaped, gets used as is without the \ in the config // ${secret:api_key} - value gets loaded from /run/secrets/api_key // ${readFileFromEnv:PATH_TO_SECRET} - value gets loaded from the file path specified in the environment variable PATH_TO_SECRET // // TODO: don't match against commented out sections, not sure exactly how since // variables can be placed anywhere and used to modify the YAML structure itself func parseConfigVariables(contents []byte) ([]byte, error) { var err error replaced := configVariablePattern.ReplaceAllFunc(contents, func(match []byte) []byte { if err != nil { return nil } groups := configVariablePattern.FindSubmatch(match) if len(groups) != 4 { // we can't handle this match, this shouldn't happen unless the number of groups // in the regex has been changed without updating the below code return match } prefix := string(groups[1]) if prefix == `\` { if len(match) >= 2 { return match[1:] } else { return nil } } typeAsString, variableName := string(groups[2]), string(groups[3]) variableType := ternary(typeAsString == "", configVarTypeEnv, typeAsString) parsedValue, returnOriginal, localErr := parseConfigVariableOfType(variableType, variableName) if localErr != nil { err = fmt.Errorf("parsing variable: %v", localErr) return nil } if returnOriginal { return match } return []byte(prefix + parsedValue) }) if err != nil { return nil, err } return replaced, nil } // When the bool return value is true, it indicates that the caller should use the original value func parseConfigVariableOfType(variableType, variableName string) (string, bool, error) { switch variableType { case configVarTypeEnv: if !envVariableNamePattern.MatchString(variableName) { return "", true, nil } v, found := os.LookupEnv(variableName) if !found { return "", false, fmt.Errorf("environment variable %s not found", variableName) } return v, false, nil case configVarTypeSecret: secretPath := filepath.Join("/run/secrets", variableName) secret, err := os.ReadFile(secretPath) if err != nil { return "", false, fmt.Errorf("reading secret file: %v", err) } return strings.TrimSpace(string(secret)), false, nil case configVarTypeFileFromEnv: if !envVariableNamePattern.MatchString(variableName) { return "", true, nil } filePath, found := os.LookupEnv(variableName) if !found { return "", false, fmt.Errorf("readFileFromEnv: environment variable %s not found", variableName) } if !filepath.IsAbs(filePath) { return "", false, fmt.Errorf("readFileFromEnv: file path %s is not absolute", filePath) } fileContents, err := os.ReadFile(filePath) if err != nil { return "", false, fmt.Errorf("readFileFromEnv: reading file from %s: %v", variableName, err) } return strings.TrimSpace(string(fileContents)), false, nil default: return "", true, nil } } func formatWidgetInitError(err error, w widget) error { return fmt.Errorf("%s widget: %v", w.GetType(), err) } var configIncludePattern = regexp.MustCompile(`(?m)^([ \t]*)(?:-[ \t]*)?(?:!|\$)include:[ \t]*(.+)$`) func parseYAMLIncludes(mainFilePath string) ([]byte, map[string]struct{}, error) { return recursiveParseYAMLIncludes(mainFilePath, nil, 0) } func recursiveParseYAMLIncludes(mainFilePath string, includes map[string]struct{}, depth int) ([]byte, map[string]struct{}, error) { if depth > CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT { return nil, nil, fmt.Errorf("recursion depth limit of %d reached", CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT) } mainFileContents, err := os.ReadFile(mainFilePath) if err != nil { return nil, nil, fmt.Errorf("reading %s: %w", mainFilePath, err) } mainFileAbsPath, err := filepath.Abs(mainFilePath) if err != nil { return nil, nil, fmt.Errorf("getting absolute path of %s: %w", mainFilePath, err) } mainFileDir := filepath.Dir(mainFileAbsPath) if includes == nil { includes = make(map[string]struct{}) } var includesLastErr error mainFileContents = configIncludePattern.ReplaceAllFunc(mainFileContents, func(match []byte) []byte { if includesLastErr != nil { return nil } matches := configIncludePattern.FindSubmatch(match) if len(matches) != 3 { includesLastErr = fmt.Errorf("invalid include match: %v", matches) return nil } indent := string(matches[1]) includeFilePath := strings.TrimSpace(string(matches[2])) if !filepath.IsAbs(includeFilePath) { includeFilePath = filepath.Join(mainFileDir, includeFilePath) } var fileContents []byte var err error includes[includeFilePath] = struct{}{} fileContents, includes, err = recursiveParseYAMLIncludes(includeFilePath, includes, depth+1) if err != nil { includesLastErr = err return nil } return []byte(prefixStringLines(indent, string(fileContents))) }) if includesLastErr != nil { return nil, nil, includesLastErr } return mainFileContents, includes, nil } func configFilesWatcher( mainFilePath string, lastContents []byte, lastIncludes map[string]struct{}, onChange func(newContents []byte), onErr func(error), ) (func() error, error) { mainFileAbsPath, err := filepath.Abs(mainFilePath) if err != nil { return nil, fmt.Errorf("getting absolute path of main file: %w", err) } // TODO: refactor, flaky lastIncludes[mainFileAbsPath] = struct{}{} watcher, err := fsnotify.NewWatcher() if err != nil { return nil, fmt.Errorf("creating watcher: %w", err) } updateWatchedFiles := func(previousWatched map[string]struct{}, newWatched map[string]struct{}) { for filePath := range previousWatched { if _, ok := newWatched[filePath]; !ok { watcher.Remove(filePath) } } for filePath := range newWatched { if _, ok := previousWatched[filePath]; !ok { if err := watcher.Add(filePath); err != nil { log.Printf( "Could not add file to watcher, changes to this file will not trigger a reload. path: %s, error: %v", filePath, err, ) } } } } updateWatchedFiles(nil, lastIncludes) // needed for lastContents and lastIncludes because they get updated in multiple goroutines mu := sync.Mutex{} parseAndCompareBeforeCallback := func() { currentContents, currentIncludes, err := parseYAMLIncludes(mainFilePath) if err != nil { onErr(fmt.Errorf("parsing main file contents for comparison: %w", err)) return } // TODO: refactor, flaky currentIncludes[mainFileAbsPath] = struct{}{} mu.Lock() defer mu.Unlock() if !maps.Equal(currentIncludes, lastIncludes) { updateWatchedFiles(lastIncludes, currentIncludes) lastIncludes = currentIncludes } if !bytes.Equal(lastContents, currentContents) { lastContents = currentContents onChange(currentContents) } } const debounceDuration = 500 * time.Millisecond var debounceTimer *time.Timer debouncedParseAndCompareBeforeCallback := func() { if debounceTimer != nil { debounceTimer.Stop() debounceTimer.Reset(debounceDuration) } else { debounceTimer = time.AfterFunc(debounceDuration, parseAndCompareBeforeCallback) } } deleteLastInclude := func(filePath string) { mu.Lock() defer mu.Unlock() fileAbsPath, _ := filepath.Abs(filePath) delete(lastIncludes, fileAbsPath) } go func() { for { select { case event, isOpen := <-watcher.Events: if !isOpen { return } if event.Has(fsnotify.Write) { debouncedParseAndCompareBeforeCallback() } else if event.Has(fsnotify.Rename) { // on linux the file will no longer be watched after a rename, on windows // it will continue to be watched with the new name but we have no access to // the new name in this event in order to stop watching it manually and match the // behavior in linux, may lead to weird unintended behaviors on windows as we're // only handling renames from linux's perspective // see https://github.com/fsnotify/fsnotify/issues/255 // remove the old file from our manually tracked includes, calling // debouncedParseAndCompareBeforeCallback will re-add it if it's still // required after it triggers deleteLastInclude(event.Name) // wait for file to maybe get created again // see https://github.com/glanceapp/glance/pull/358 for range 10 { if _, err := os.Stat(event.Name); err == nil { break } time.Sleep(200 * time.Millisecond) } debouncedParseAndCompareBeforeCallback() } else if event.Has(fsnotify.Remove) { deleteLastInclude(event.Name) debouncedParseAndCompareBeforeCallback() } case err, isOpen := <-watcher.Errors: if !isOpen { return } onErr(fmt.Errorf("watcher error: %w", err)) } } }() onChange(lastContents) return func() error { if debounceTimer != nil { debounceTimer.Stop() } return watcher.Close() }, nil } // TODO: Refactor, we currently validate in two different places, this being // one of them, which doesn't modify the data and only checks for logical errors // and then again when creating the application which does modify the data and do // further validation. Would be better if validation was done in a single place. func isConfigStateValid(config *config) error { if len(config.Pages) == 0 { return fmt.Errorf("no pages configured") } if len(config.Auth.Users) > 0 && config.Auth.SecretKey == "" { return fmt.Errorf("secret-key must be set when users are configured") } for username := range config.Auth.Users { if username == "" { return fmt.Errorf("user has no name") } if len(username) < 3 { return errors.New("usernames must be at least 3 characters") } user := config.Auth.Users[username] if user.Password == "" { if user.PasswordHashString == "" { return fmt.Errorf("user %s must have a password or a password-hash set", username) } } else if len(user.Password) < 6 { return fmt.Errorf("the password for %s must be at least 6 characters", username) } } if config.Server.AssetsPath != "" { if _, err := os.Stat(config.Server.AssetsPath); os.IsNotExist(err) { return fmt.Errorf("assets directory does not exist: %s", config.Server.AssetsPath) } } for i := range config.Pages { page := &config.Pages[i] if page.Title == "" { return fmt.Errorf("page %d has no name", i+1) } if page.Width != "" && (page.Width != "wide" && page.Width != "slim" && page.Width != "default") { return fmt.Errorf("page %d: width can only be either wide or slim", i+1) } if page.DesktopNavigationWidth != "" { if page.DesktopNavigationWidth != "wide" && page.DesktopNavigationWidth != "slim" && page.DesktopNavigationWidth != "default" { return fmt.Errorf("page %d: desktop-navigation-width can only be either wide or slim", i+1) } } if len(page.Columns) == 0 { return fmt.Errorf("page %d has no columns", i+1) } if page.Width == "slim" { if len(page.Columns) > 2 { return fmt.Errorf("page %d is slim and cannot have more than 2 columns", i+1) } } else { if len(page.Columns) > 3 { return fmt.Errorf("page %d has more than 3 columns", i+1) } } columnSizesCount := make(map[string]int) for j := range page.Columns { column := &page.Columns[j] if column.Size != "small" && column.Size != "full" { return fmt.Errorf("column %d of page %d: size can only be either small or full", j+1, i+1) } columnSizesCount[page.Columns[j].Size]++ } full := columnSizesCount["full"] if full > 2 || full == 0 { return fmt.Errorf("page %d must have either 1 or 2 full width columns", i+1) } } return nil } // Read-only way to store ordered maps from a YAML structure type orderedYAMLMap[K comparable, V any] struct { keys []K data map[K]V } func newOrderedYAMLMap[K comparable, V any](keys []K, values []V) (*orderedYAMLMap[K, V], error) { if len(keys) != len(values) { return nil, fmt.Errorf("keys and values must have the same length") } om := &orderedYAMLMap[K, V]{ keys: make([]K, len(keys)), data: make(map[K]V, len(keys)), } copy(om.keys, keys) for i := range keys { om.data[keys[i]] = values[i] } return om, nil } func (om *orderedYAMLMap[K, V]) Items() iter.Seq2[K, V] { return func(yield func(K, V) bool) { for _, key := range om.keys { value, ok := om.data[key] if !ok { continue } if !yield(key, value) { return } } } } func (om *orderedYAMLMap[K, V]) Get(key K) (V, bool) { value, ok := om.data[key] return value, ok } func (self *orderedYAMLMap[K, V]) Merge(other *orderedYAMLMap[K, V]) *orderedYAMLMap[K, V] { merged := &orderedYAMLMap[K, V]{ keys: make([]K, 0, len(self.keys)+len(other.keys)), data: make(map[K]V, len(self.data)+len(other.data)), } merged.keys = append(merged.keys, self.keys...) maps.Copy(merged.data, self.data) for _, key := range other.keys { if _, exists := self.data[key]; !exists { merged.keys = append(merged.keys, key) } } maps.Copy(merged.data, other.data) return merged } func (om *orderedYAMLMap[K, V]) UnmarshalYAML(node *yaml.Node) error { if node.Kind != yaml.MappingNode { return fmt.Errorf("orderedMap: expected mapping node, got %d", node.Kind) } if len(node.Content)%2 != 0 { return fmt.Errorf("orderedMap: expected even number of content items, got %d", len(node.Content)) } om.keys = make([]K, len(node.Content)/2) om.data = make(map[K]V, len(node.Content)/2) for i := 0; i < len(node.Content); i += 2 { keyNode := node.Content[i] valueNode := node.Content[i+1] var key K if err := keyNode.Decode(&key); err != nil { return fmt.Errorf("orderedMap: decoding key: %v", err) } if _, ok := om.data[key]; ok { return fmt.Errorf("orderedMap: duplicate key %v", key) } var value V if err := valueNode.Decode(&value); err != nil { return fmt.Errorf("orderedMap: decoding value: %v", err) } (*om).keys[i/2] = key (*om).data[key] = value } return nil } ================================================ FILE: internal/glance/diagnose.go ================================================ package glance import ( "context" "fmt" "io" "net" "net/http" "runtime" "strings" "sync" "time" ) const httpTestRequestTimeout = 15 * time.Second var diagnosticSteps = []diagnosticStep{ { name: "resolve cloudflare.com through Cloudflare DoH", fn: func() (string, error) { return testHttpRequestWithHeaders("GET", "https://1.1.1.1/dns-query?name=cloudflare.com", map[string]string{ "accept": "application/dns-json", }, 200) }, }, { name: "resolve cloudflare.com through Google DoH", fn: func() (string, error) { return testHttpRequest("GET", "https://8.8.8.8/resolve?name=cloudflare.com", 200) }, }, { name: "resolve github.com", fn: func() (string, error) { return testDNSResolution("github.com") }, }, { name: "resolve reddit.com", fn: func() (string, error) { return testDNSResolution("reddit.com") }, }, { name: "resolve twitch.tv", fn: func() (string, error) { return testDNSResolution("twitch.tv") }, }, { name: "fetch data from YouTube RSS feed", fn: func() (string, error) { return testHttpRequest("GET", "https://www.youtube.com/feeds/videos.xml?channel_id=UCZU9T1ceaOgwfLRq7OKFU4Q", 200) }, }, { name: "fetch data from Twitch.tv GQL", fn: func() (string, error) { // this should always return 0 bytes, we're mainly looking for a 200 status code return testHttpRequest("OPTIONS", "https://gql.twitch.tv/gql", 200) }, }, { name: "fetch data from GitHub API", fn: func() (string, error) { return testHttpRequest("GET", "https://api.github.com", 200) }, }, { name: "fetch data from Open-Meteo API", fn: func() (string, error) { return testHttpRequest("GET", "https://geocoding-api.open-meteo.com/v1/search?name=London", 200) }, }, { name: "fetch data from Reddit API", fn: func() (string, error) { return testHttpRequestWithHeaders("GET", "https://www.reddit.com/search.json", map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0", }, 200) }, }, { name: "fetch data from Yahoo finance API", fn: func() (string, error) { return testHttpRequestWithHeaders("GET", "https://query1.finance.yahoo.com/v8/finance/chart/NVDA", map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0", }, 200) }, }, { name: "fetch data from Hacker News Firebase API", fn: func() (string, error) { return testHttpRequest("GET", "https://hacker-news.firebaseio.com/v0/topstories.json", 200) }, }, { name: "fetch data from Docker Hub API", fn: func() (string, error) { return testHttpRequest("GET", "https://hub.docker.com/v2/namespaces/library/repositories/ubuntu/tags/latest", 200) }, }, } func runDiagnostic() { fmt.Println("```") fmt.Println("Glance version: " + buildVersion) fmt.Println("Go version: " + runtime.Version()) fmt.Printf("Platform: %s / %s / %d CPUs\n", runtime.GOOS, runtime.GOARCH, runtime.NumCPU()) fmt.Println("In Docker container: " + ternary(isRunningInsideDockerContainer(), "yes", "no")) fmt.Printf("\nChecking network connectivity, this may take up to %d seconds...\n\n", int(httpTestRequestTimeout.Seconds())) var wg sync.WaitGroup for i := range diagnosticSteps { step := &diagnosticSteps[i] wg.Add(1) go func() { defer wg.Done() start := time.Now() step.extraInfo, step.err = step.fn() step.elapsed = time.Since(start) }() } wg.Wait() for _, step := range diagnosticSteps { var extraInfo string if step.extraInfo != "" { extraInfo = "| " + step.extraInfo + " " } fmt.Printf( "%s %s %s| %dms\n", ternary(step.err == nil, "✓ Can", "✗ Can't"), step.name, extraInfo, step.elapsed.Milliseconds(), ) if step.err != nil { fmt.Printf("└╴ error: %v\n", step.err) } } fmt.Println("```") } type diagnosticStep struct { name string fn func() (string, error) extraInfo string err error elapsed time.Duration } func testHttpRequest(method, url string, expectedStatusCode int) (string, error) { return testHttpRequestWithHeaders(method, url, nil, expectedStatusCode) } func testHttpRequestWithHeaders(method, url string, headers map[string]string, expectedStatusCode int) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), httpTestRequestTimeout) defer cancel() request, _ := http.NewRequestWithContext(ctx, method, url, nil) for key, value := range headers { request.Header.Add(key, value) } response, err := defaultHTTPClient.Do(request) if err != nil { return "", err } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { return "", err } printableBody := strings.ReplaceAll(string(body), "\n", "") if len(printableBody) > 50 { printableBody = printableBody[:50] + "..." } if len(printableBody) > 0 { printableBody = ", " + printableBody } extraInfo := fmt.Sprintf("%d bytes%s", len(body), printableBody) if response.StatusCode != expectedStatusCode { return extraInfo, fmt.Errorf("expected status code %d, got %d", expectedStatusCode, response.StatusCode) } return extraInfo, nil } func testDNSResolution(domain string) (string, error) { ips, err := net.LookupIP(domain) var ipStrings []string if err == nil { for i := range ips { ipStrings = append(ipStrings, ips[i].String()) } } return strings.Join(ipStrings, ", "), err } ================================================ FILE: internal/glance/embed.go ================================================ package glance import ( "bytes" "crypto/md5" "embed" "encoding/hex" "errors" "fmt" "io" "io/fs" "log" "path/filepath" "regexp" "strconv" "strings" "time" ) //go:embed static var _staticFS embed.FS //go:embed templates var _templateFS embed.FS var staticFS, _ = fs.Sub(_staticFS, "static") var templateFS, _ = fs.Sub(_templateFS, "templates") func readAllFromStaticFS(path string) ([]byte, error) { // For some reason fs.FS only works with forward slashes, so in case we're // running on Windows or pass paths with backslashes we need to replace them. path = strings.ReplaceAll(path, "\\", "/") file, err := staticFS.Open(path) if err != nil { return nil, err } return io.ReadAll(file) } var staticFSHash = func() string { hash, err := computeFSHash(staticFS) if err != nil { log.Printf("Could not compute static assets cache key: %v", err) return strconv.FormatInt(time.Now().Unix(), 10) } return hash }() func computeFSHash(files fs.FS) (string, error) { hash := md5.New() err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { return nil } file, err := files.Open(path) if err != nil { return err } if _, err := io.Copy(hash, file); err != nil { return err } return nil }) if err != nil { return "", err } return hex.EncodeToString(hash.Sum(nil))[:10], nil } var cssImportPattern = regexp.MustCompile(`(?m)^@import "(.*?)";$`) var cssSingleLineCommentPattern = regexp.MustCompile(`(?m)^\s*\/\*.*?\*\/$`) // Yes, we bundle at runtime, give comptime pls var bundledCSSContents = func() []byte { const mainFilePath = "css/main.css" var recursiveParseImports func(path string, depth int) ([]byte, error) recursiveParseImports = func(path string, depth int) ([]byte, error) { if depth > 20 { return nil, errors.New("maximum import depth reached, is one of your imports circular?") } mainFileContents, err := readAllFromStaticFS(path) if err != nil { return nil, err } // Normalize line endings, otherwise the \r's make the regex not match mainFileContents = bytes.ReplaceAll(mainFileContents, []byte("\r\n"), []byte("\n")) mainFileDir := filepath.Dir(path) var importLastErr error parsed := cssImportPattern.ReplaceAllFunc(mainFileContents, func(match []byte) []byte { if importLastErr != nil { return nil } matches := cssImportPattern.FindSubmatch(match) if len(matches) != 2 { importLastErr = fmt.Errorf( "import didn't return expected number of capture groups: %s, expected 2, got %d", match, len(matches), ) return nil } importFilePath := filepath.Join(mainFileDir, string(matches[1])) importContents, err := recursiveParseImports(importFilePath, depth+1) if err != nil { importLastErr = err return nil } return importContents }) if importLastErr != nil { return nil, importLastErr } return parsed, nil } contents, err := recursiveParseImports(mainFilePath, 0) if err != nil { panic(fmt.Sprintf("building CSS bundle: %v", err)) } // We could strip a bunch more unnecessary characters, but the biggest // win comes from removing the whitespace at the beginning of lines // since that's at least 4 bytes per property, which yielded a ~20% reduction. contents = cssSingleLineCommentPattern.ReplaceAll(contents, nil) contents = whitespaceAtBeginningOfLinePattern.ReplaceAll(contents, nil) contents = bytes.ReplaceAll(contents, []byte("\n"), []byte("")) return contents }() ================================================ FILE: internal/glance/glance.go ================================================ package glance import ( "bytes" "context" "encoding/base64" "fmt" "log" "net/http" "path/filepath" "slices" "strconv" "strings" "sync" "time" "golang.org/x/crypto/bcrypt" ) var ( pageTemplate = mustParseTemplate("page.html", "document.html", "footer.html") pageContentTemplate = mustParseTemplate("page-content.html") manifestTemplate = mustParseTemplate("manifest.json") ) const STATIC_ASSETS_CACHE_DURATION = 24 * time.Hour var reservedPageSlugs = []string{"login", "logout"} type application struct { Version string CreatedAt time.Time Config config parsedManifest []byte slugToPage map[string]*page widgetByID map[uint64]widget RequiresAuth bool authSecretKey []byte usernameHashToUsername map[string]string authAttemptsMu sync.Mutex failedAuthAttempts map[string]*failedAuthAttempt } func newApplication(c *config) (*application, error) { app := &application{ Version: buildVersion, CreatedAt: time.Now(), Config: *c, slugToPage: make(map[string]*page), widgetByID: make(map[uint64]widget), } config := &app.Config // // Init auth // if len(config.Auth.Users) > 0 { secretBytes, err := base64.StdEncoding.DecodeString(config.Auth.SecretKey) if err != nil { return nil, fmt.Errorf("decoding secret-key: %v", err) } if len(secretBytes) != AUTH_SECRET_KEY_LENGTH { return nil, fmt.Errorf("secret-key must be exactly %d bytes", AUTH_SECRET_KEY_LENGTH) } app.usernameHashToUsername = make(map[string]string) app.failedAuthAttempts = make(map[string]*failedAuthAttempt) app.RequiresAuth = true for username := range config.Auth.Users { user := config.Auth.Users[username] usernameHash, err := computeUsernameHash(username, secretBytes) if err != nil { return nil, fmt.Errorf("computing username hash for user %s: %v", username, err) } app.usernameHashToUsername[string(usernameHash)] = username if user.PasswordHashString != "" { user.PasswordHash = []byte(user.PasswordHashString) user.PasswordHashString = "" } else { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) if err != nil { return nil, fmt.Errorf("hashing password for user %s: %v", username, err) } user.Password = "" user.PasswordHash = hashedPassword } } app.authSecretKey = secretBytes } // // Init themes // if !config.Theme.DisablePicker { themeKeys := make([]string, 0, 2) themeProps := make([]*themeProperties, 0, 2) defaultDarkTheme, ok := config.Theme.Presets.Get("default-dark") if ok && !config.Theme.SameAs(defaultDarkTheme) || !config.Theme.SameAs(&themeProperties{}) { themeKeys = append(themeKeys, "default-dark") themeProps = append(themeProps, &themeProperties{}) } themeKeys = append(themeKeys, "default-light") themeProps = append(themeProps, &themeProperties{ Light: true, BackgroundColor: &hslColorField{240, 13, 95}, PrimaryColor: &hslColorField{230, 100, 30}, NegativeColor: &hslColorField{0, 70, 50}, ContrastMultiplier: 1.3, TextSaturationMultiplier: 0.5, }) themePresets, err := newOrderedYAMLMap(themeKeys, themeProps) if err != nil { return nil, fmt.Errorf("creating theme presets: %v", err) } config.Theme.Presets = *themePresets.Merge(&config.Theme.Presets) for key, properties := range config.Theme.Presets.Items() { properties.Key = key if err := properties.init(); err != nil { return nil, fmt.Errorf("initializing preset theme %s: %v", key, err) } } } config.Theme.Key = "default" if err := config.Theme.init(); err != nil { return nil, fmt.Errorf("initializing default theme: %v", err) } // // Init pages // app.slugToPage[""] = &config.Pages[0] providers := &widgetProviders{ assetResolver: app.StaticAssetPath, } for p := range config.Pages { page := &config.Pages[p] page.PrimaryColumnIndex = -1 if page.Slug == "" { page.Slug = titleToSlug(page.Title) } if slices.Contains(reservedPageSlugs, page.Slug) { return nil, fmt.Errorf("page slug \"%s\" is reserved", page.Slug) } app.slugToPage[page.Slug] = page if page.Width == "default" { page.Width = "" } if page.DesktopNavigationWidth == "" && page.DesktopNavigationWidth != "default" { page.DesktopNavigationWidth = page.Width } for i := range page.HeadWidgets { widget := page.HeadWidgets[i] app.widgetByID[widget.GetID()] = widget widget.setProviders(providers) } for c := range page.Columns { column := &page.Columns[c] if page.PrimaryColumnIndex == -1 && column.Size == "full" { page.PrimaryColumnIndex = int8(c) } for w := range column.Widgets { widget := column.Widgets[w] app.widgetByID[widget.GetID()] = widget widget.setProviders(providers) } } } config.Server.BaseURL = strings.TrimRight(config.Server.BaseURL, "/") config.Theme.CustomCSSFile = app.resolveUserDefinedAssetPath(config.Theme.CustomCSSFile) config.Branding.LogoURL = app.resolveUserDefinedAssetPath(config.Branding.LogoURL) config.Branding.FaviconURL = ternary( config.Branding.FaviconURL == "", app.StaticAssetPath("favicon.svg"), app.resolveUserDefinedAssetPath(config.Branding.FaviconURL), ) config.Branding.FaviconType = ternary( strings.HasSuffix(config.Branding.FaviconURL, ".svg"), "image/svg+xml", "image/png", ) if config.Branding.AppName == "" { config.Branding.AppName = "Glance" } if config.Branding.AppIconURL == "" { config.Branding.AppIconURL = app.StaticAssetPath("app-icon.png") } if config.Branding.AppBackgroundColor == "" { config.Branding.AppBackgroundColor = config.Theme.BackgroundColorAsHex } manifest, err := executeTemplateToString(manifestTemplate, templateData{App: app}) if err != nil { return nil, fmt.Errorf("parsing manifest.json: %v", err) } app.parsedManifest = []byte(manifest) return app, nil } func (p *page) updateOutdatedWidgets() { now := time.Now() var wg sync.WaitGroup context := context.Background() for w := range p.HeadWidgets { widget := p.HeadWidgets[w] if !widget.requiresUpdate(&now) { continue } wg.Add(1) go func() { defer wg.Done() widget.update(context) }() } for c := range p.Columns { for w := range p.Columns[c].Widgets { widget := p.Columns[c].Widgets[w] if !widget.requiresUpdate(&now) { continue } wg.Add(1) go func() { defer wg.Done() widget.update(context) }() } } wg.Wait() } func (a *application) resolveUserDefinedAssetPath(path string) string { if strings.HasPrefix(path, "/assets/") { return a.Config.Server.BaseURL + path } return path } type templateRequestData struct { Theme *themeProperties } type templateData struct { App *application Page *page Request templateRequestData } func (a *application) populateTemplateRequestData(data *templateRequestData, r *http.Request) { theme := &a.Config.Theme.themeProperties if !a.Config.Theme.DisablePicker { selectedTheme, err := r.Cookie("theme") if err == nil { preset, exists := a.Config.Theme.Presets.Get(selectedTheme.Value) if exists { theme = preset } } } data.Theme = theme } func (a *application) handlePageRequest(w http.ResponseWriter, r *http.Request) { page, exists := a.slugToPage[r.PathValue("page")] if !exists { a.handleNotFound(w, r) return } if a.handleUnauthorizedResponse(w, r, redirectToLogin) { return } data := templateData{ Page: page, App: a, } a.populateTemplateRequestData(&data.Request, r) var responseBytes bytes.Buffer err := pageTemplate.Execute(&responseBytes, data) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } w.Write(responseBytes.Bytes()) } func (a *application) handlePageContentRequest(w http.ResponseWriter, r *http.Request) { page, exists := a.slugToPage[r.PathValue("page")] if !exists { a.handleNotFound(w, r) return } if a.handleUnauthorizedResponse(w, r, showUnauthorizedJSON) { return } pageData := templateData{ Page: page, } var err error var responseBytes bytes.Buffer func() { page.mu.Lock() defer page.mu.Unlock() page.updateOutdatedWidgets() err = pageContentTemplate.Execute(&responseBytes, pageData) }() if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } w.Write(responseBytes.Bytes()) } func (a *application) addressOfRequest(r *http.Request) string { remoteAddrWithoutPort := func() string { for i := len(r.RemoteAddr) - 1; i >= 0; i-- { if r.RemoteAddr[i] == ':' { return r.RemoteAddr[:i] } } return r.RemoteAddr } if !a.Config.Server.Proxied { return remoteAddrWithoutPort() } // This should probably be configurable or look for multiple headers, not just this one forwardedFor := r.Header.Get("X-Forwarded-For") if forwardedFor == "" { return remoteAddrWithoutPort() } ips := strings.Split(forwardedFor, ",") if len(ips) == 0 || ips[0] == "" { return remoteAddrWithoutPort() } return ips[0] } func (a *application) handleNotFound(w http.ResponseWriter, _ *http.Request) { // TODO: add proper not found page w.WriteHeader(http.StatusNotFound) w.Write([]byte("Page not found")) } func (a *application) handleWidgetRequest(w http.ResponseWriter, r *http.Request) { // TODO: this requires a rework of the widget update logic so that rather // than locking the entire page we lock individual widgets w.WriteHeader(http.StatusNotImplemented) // widgetValue := r.PathValue("widget") // widgetID, err := strconv.ParseUint(widgetValue, 10, 64) // if err != nil { // a.handleNotFound(w, r) // return // } // widget, exists := a.widgetByID[widgetID] // if !exists { // a.handleNotFound(w, r) // return // } // widget.handleRequest(w, r) } func (a *application) StaticAssetPath(asset string) string { return a.Config.Server.BaseURL + "/static/" + staticFSHash + "/" + asset } func (a *application) VersionedAssetPath(asset string) string { return a.Config.Server.BaseURL + asset + "?v=" + strconv.FormatInt(a.CreatedAt.Unix(), 10) } func (a *application) server() (func() error, func() error) { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", a.handlePageRequest) mux.HandleFunc("GET /{page}", a.handlePageRequest) mux.HandleFunc("GET /api/pages/{page}/content/{$}", a.handlePageContentRequest) if !a.Config.Theme.DisablePicker { mux.HandleFunc("POST /api/set-theme/{key}", a.handleThemeChangeRequest) } mux.HandleFunc("/api/widgets/{widget}/{path...}", a.handleWidgetRequest) mux.HandleFunc("GET /api/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) if a.RequiresAuth { mux.HandleFunc("GET /login", a.handleLoginPageRequest) mux.HandleFunc("GET /logout", a.handleLogoutRequest) mux.HandleFunc("POST /api/authenticate", a.handleAuthenticationAttempt) } mux.Handle( fmt.Sprintf("GET /static/%s/{path...}", staticFSHash), http.StripPrefix( "/static/"+staticFSHash, fileServerWithCache(http.FS(staticFS), STATIC_ASSETS_CACHE_DURATION), ), ) assetCacheControlValue := fmt.Sprintf( "public, max-age=%d", int(STATIC_ASSETS_CACHE_DURATION.Seconds()), ) mux.HandleFunc(fmt.Sprintf("GET /static/%s/css/bundle.css", staticFSHash), func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Cache-Control", assetCacheControlValue) w.Header().Add("Content-Type", "text/css; charset=utf-8") w.Write(bundledCSSContents) }) mux.HandleFunc("GET /manifest.json", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Cache-Control", assetCacheControlValue) w.Header().Add("Content-Type", "application/json") w.Write(a.parsedManifest) }) var absAssetsPath string if a.Config.Server.AssetsPath != "" { absAssetsPath, _ = filepath.Abs(a.Config.Server.AssetsPath) assetsFS := fileServerWithCache(http.Dir(a.Config.Server.AssetsPath), 2*time.Hour) mux.Handle("/assets/{path...}", http.StripPrefix("/assets/", assetsFS)) } server := http.Server{ Addr: fmt.Sprintf("%s:%d", a.Config.Server.Host, a.Config.Server.Port), Handler: mux, } start := func() error { log.Printf("Starting server on %s:%d (base-url: \"%s\", assets-path: \"%s\")\n", a.Config.Server.Host, a.Config.Server.Port, a.Config.Server.BaseURL, absAssetsPath, ) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { return err } return nil } stop := func() error { return server.Close() } return start, stop } ================================================ FILE: internal/glance/main.go ================================================ package glance import ( "fmt" "io" "log" "net/http" "os" "golang.org/x/crypto/bcrypt" ) var buildVersion = "dev" func Main() int { options, err := parseCliOptions() if err != nil { fmt.Println(err) return 1 } switch options.intent { case cliIntentVersionPrint: fmt.Println(buildVersion) case cliIntentServe: // remove in v0.10.0 if serveUpdateNoticeIfConfigLocationNotMigrated(options.configPath) { return 1 } if err := serveApp(options.configPath); err != nil { fmt.Println(err) return 1 } case cliIntentConfigValidate: contents, _, err := parseYAMLIncludes(options.configPath) if err != nil { fmt.Printf("Could not parse config file: %v\n", err) return 1 } if _, err := newConfigFromYAML(contents); err != nil { fmt.Printf("Config file is invalid: %v\n", err) return 1 } case cliIntentConfigPrint: contents, _, err := parseYAMLIncludes(options.configPath) if err != nil { fmt.Printf("Could not parse config file: %v\n", err) return 1 } fmt.Println(string(contents)) case cliIntentSensorsPrint: return cliSensorsPrint() case cliIntentMountpointInfo: return cliMountpointInfo(options.args[1]) case cliIntentDiagnose: runDiagnostic() case cliIntentSecretMake: key, err := makeAuthSecretKey(AUTH_SECRET_KEY_LENGTH) if err != nil { fmt.Printf("Failed to make secret key: %v\n", err) return 1 } fmt.Println(key) case cliIntentPasswordHash: password := options.args[1] if password == "" { fmt.Println("Password cannot be empty") return 1 } if len(password) < 6 { fmt.Println("Password must be at least 6 characters long") return 1 } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { fmt.Printf("Failed to hash password: %v\n", err) return 1 } fmt.Println(string(hashedPassword)) } return 0 } func serveApp(configPath string) error { // TODO: refactor if this gets any more complex, the current implementation is // difficult to reason about due to all of the callbacks and simultaneous operations, // use a single goroutine and a channel to initiate synchronous changes to the server exitChannel := make(chan struct{}) hadValidConfigOnStartup := false var stopServer func() error onChange := func(newContents []byte) { if stopServer != nil { log.Println("Config file changed, reloading...") } config, err := newConfigFromYAML(newContents) if err != nil { log.Printf("Config has errors: %v", err) if !hadValidConfigOnStartup { close(exitChannel) } return } app, err := newApplication(config) if err != nil { log.Printf("Failed to create application: %v", err) if !hadValidConfigOnStartup { close(exitChannel) } return } if !hadValidConfigOnStartup { hadValidConfigOnStartup = true } if stopServer != nil { if err := stopServer(); err != nil { log.Printf("Error while trying to stop server: %v", err) } } go func() { var startServer func() error startServer, stopServer = app.server() if err := startServer(); err != nil { log.Printf("Failed to start server: %v", err) } }() } onErr := func(err error) { log.Printf("Error watching config files: %v", err) } configContents, configIncludes, err := parseYAMLIncludes(configPath) if err != nil { return fmt.Errorf("parsing config: %w", err) } stopWatching, err := configFilesWatcher(configPath, configContents, configIncludes, onChange, onErr) if err == nil { defer stopWatching() } else { log.Printf("Error starting file watcher, config file changes will require a manual restart. (%v)", err) config, err := newConfigFromYAML(configContents) if err != nil { return fmt.Errorf("validating config file: %w", err) } app, err := newApplication(config) if err != nil { return fmt.Errorf("creating application: %w", err) } startServer, _ := app.server() if err := startServer(); err != nil { return fmt.Errorf("starting server: %w", err) } } <-exitChannel return nil } func serveUpdateNoticeIfConfigLocationNotMigrated(configPath string) bool { if !isRunningInsideDockerContainer() { return false } if _, err := os.Stat(configPath); err == nil { return false } // glance.yml wasn't mounted to begin with or was incorrectly mounted as a directory if stat, err := os.Stat("glance.yml"); err != nil || stat.IsDir() { return false } templateFile, _ := templateFS.Open("v0.7-update-notice-page.html") bodyContents, _ := io.ReadAll(templateFile) fmt.Println("!!! WARNING !!!") fmt.Println("The default location of glance.yml in the Docker image has changed starting from v0.7.0.") fmt.Println("Please see https://github.com/glanceapp/glance/blob/main/docs/v0.7.0-upgrade.md for more information.") mux := http.NewServeMux() mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) w.Header().Set("Content-Type", "text/html") w.Write([]byte(bodyContents)) }) server := http.Server{ Addr: ":8080", Handler: mux, } server.ListenAndServe() return true } ================================================ FILE: internal/glance/static/css/forum-posts.css ================================================ .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; } .forum-post-tags-container { transform: translateY(-0.15rem); } @container widget (max-width: 550px) { .forum-post-autohide { display: none; } } ================================================ FILE: internal/glance/static/css/login.css ================================================ .login-bounds { max-width: 500px; padding: 0 2rem; } .form-label { text-transform: uppercase; margin-bottom: 0.5rem; } .form-input { transition: border-color .2s; } .form-input input { border: 0; background: none; width: 100%; height: 5.2rem; font: inherit; outline: none; color: var(--color-text-highlight); } .form-input-icon { width: 2rem; height: 2rem; margin-top: -0.1rem; opacity: 0.5; } .form-input input[type="password"] { letter-spacing: 0.3rem; font-size: 0.9em; } .form-input input[type="password"]::placeholder { letter-spacing: 0; font-size: var(--font-size-base); } .form-input:hover { border-color: var(--color-progress-border); } .form-input:focus-within { border-color: var(--color-primary); transition-duration: .7s; } .login-button { width: 100%; display: block; padding: 1rem; background: none; border: 1px solid var(--color-text-subdue); border-radius: var(--border-radius); color: var(--color-text-paragraph); cursor: pointer; font: inherit; font-size: var(--font-size-h4); display: flex; gap: .5rem; align-items: center; justify-content: center; transition: all .3s, margin-top 0s; margin-top: 3rem; } .login-button:not(:disabled) { box-shadow: 0 0 10px 1px var(--color-separator); } .login-error-message:not(:empty) + .login-button { margin-top: 2rem; } .login-button:focus, .login-button:hover { outline: none; border-color: var(--color-primary); color: var(--color-primary); } .login-button:disabled { border-color: var(--color-separator); color: var(--color-text-subdue); cursor: not-allowed; } .login-button svg { width: 1.7rem; height: 1.7rem; transition: transform .2s; } .login-button:not(:disabled):hover svg, .login-button:not(:disabled):focus svg { transform: translateX(.5rem); } .animate-entrance { animation: fieldReveal 0.7s backwards; animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1); } .animate-entrance:nth-child(1) { animation-delay: .1s; } .animate-entrance:nth-child(2) { animation-delay: .2s; } .animate-entrance:nth-child(4) { animation-delay: .3s; } @keyframes fieldReveal { from { opacity: 0.0001; transform: translateY(4rem); } } .login-error-message { color: var(--color-negative); font-size: var(--font-size-base); padding: 1.3rem calc(var(--widget-content-horizontal-padding) + 1px); position: relative; margin-top: 2rem; animation: errorMessageEntrance 0.4s backwards cubic-bezier(0.34, 1.56, 0.64, 1); } @keyframes errorMessageEntrance { from { opacity: 0; transform: scale(1.1); } } .login-error-message:empty { display: none; } .login-error-message::before { content: ""; position: absolute; inset: 0; border-radius: var(--border-radius); background: var(--color-negative); opacity: 0.05; z-index: -1; } .footer { animation-delay: .4s; animation-duration: 1s; } .toggle-password-visibility { background: none; border: none; cursor: pointer; } ================================================ FILE: internal/glance/static/css/main.css ================================================ @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: 23px; --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%))); --color-popover-background: hsl(var(--bgh), calc(var(--bgs) + 3%), calc(var(--bgl) + 3%)); --color-popover-border: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 12%))); --color-progress-border: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 10% * var(--cm)))); --color-progress-value: hsl(var(--bgh), calc(var(--bgs) * var(--tsm)), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 26% * var(--cm)))); --color-vertical-progress-value: hsl(var(--bgh), calc(var(--bgs) * var(--tsm)), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 28% * var(--cm)))); --color-graph-gridlines: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 6% * var(--cm)))); --ths: var(--bgh), calc(var(--bgs) * var(--tsm)); --color-text-highlight: hsl(var(--ths), calc(var(--scheme) var(--cm) * 85%)); --color-text-paragraph: hsl(var(--ths), calc(var(--scheme) var(--cm) * 73%)); --color-text-base: hsl(var(--ths), calc(var(--scheme) var(--cm) * 58%)); --color-text-base-muted: hsl(var(--ths), calc(var(--scheme) var(--cm) * 52%)); --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; } /* Do not change the order of the below imports unless you know what you're doing */ @import "site.css"; @import "widgets.css"; @import "popover.css"; @import "utils.css"; @import "mobile.css"; ================================================ FILE: internal/glance/static/css/mobile.css ================================================ @media (max-width: 1190px) { .header-container { display: none; } .page-column-small .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; } .page-columns-transitioned .page-column { animation-duration: .3s; } @keyframes columnEntrance { from { opacity: 0; transform: scaleX(0.95); } } .mobile-navigation-offset { height: var(--mobile-navigation-height); flex-shrink: 0; } .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: 11; 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-actions > * { padding-block: 1.1rem; padding-inline: var(--content-bounds-padding); cursor: pointer; transition: background-color 50ms; } .mobile-navigation-actions > *:active { background-color: var(--color-widget-background-highlight); } .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); border-bottom: 1px solid var(--color-widget-content-border); padding: 20px var(--content-bounds-padding); display: flex; align-items: center; overflow-x: auto; scrollbar-width: thin; 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; } .expand-toggle-button.container-expanded { bottom: var(--mobile-navigation-height); } .cards-grid + .expand-toggle-button.container-expanded { /* hides content that peeks through the rounded borders of the mobile navigation */ box-shadow: 0 var(--border-radius) 0 0 var(--color-background); } .weather-column-rain::before { background-size: 7px 7px; } .ios .search-input { /* so that iOS Safari does not zoom the page when the input is focused */ font-size: 16px; } } @media (max-width: 1190px) and (display-mode: standalone) { :root { --safe-area-inset-bottom: env(safe-area-inset-bottom, 0); } .ios .body-content { height: 100dvh; } .expand-toggle-button.container-expanded { bottom: calc(var(--mobile-navigation-height) + var(--safe-area-inset-bottom)); } .mobile-navigation { transform: translateY(calc(100% - var(--mobile-navigation-height) - var(--safe-area-inset-bottom))); padding-bottom: var(--safe-area-inset-bottom); } .mobile-navigation-icons { padding-bottom: var(--safe-area-inset-bottom); transition: padding-bottom .3s; } .mobile-navigation-offset { height: calc(var(--mobile-navigation-height) + var(--safe-area-inset-bottom)); } .mobile-navigation-icons:has(.mobile-navigation-page-links-input:checked) { padding-bottom: 0; } } @media (display-mode: standalone) { body { padding-top: env(safe-area-inset-top, 0); } } @media (max-width: 550px) { :root { font-size: 9.4px; --widget-gap: 15px; --widget-content-vertical-padding: 10px; --widget-content-horizontal-padding: 10px; --content-bounds-padding: 10px; } .dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; } .row-reverse-on-mobile { flex-direction: row-reverse; } .hide-on-mobile, .thumbnail-container:has(> .hide-on-mobile) { display: none } .mobile-reachability-header { display: block; font-size: 3rem; padding: 10vh 1rem; text-align: center; color: var(--color-text-highlight); animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; } .rss-detailed-thumbnail > * { height: 6rem; } .rss-detailed-description { line-clamp: 3; -webkit-line-clamp: 3; } } ================================================ FILE: internal/glance/static/css/popover.css ================================================ .popover-container, [data-popover-html] { display: none; } .popover-container { --triangle-size: 10px; --triangle-offset: 50%; --triangle-margin: calc(var(--triangle-size) + 3px); --entrance-y-offset: 8px; --entrance-direction: calc(var(--entrance-y-offset) * -1); z-index: 20; position: absolute; padding-top: var(--triangle-margin); padding-inline: var(--content-bounds-padding); } .popover-container.position-above { --entrance-direction: var(--entrance-y-offset); padding-top: 0; padding-bottom: var(--triangle-margin); } .popover-frame { --shadow-properties: 0 15px 20px -10px; --shadow-color: hsla(var(--bghs), calc(var(--bgl) * 0.2), 0.5); position: relative; padding: 10px; background: var(--color-popover-background); border: 1px solid var(--color-popover-border); border-radius: 5px; animation: popoverFrameEntrance 0.3s backwards cubic-bezier(0.16, 1, 0.3, 1); box-shadow: var(--shadow-properties) var(--shadow-color); } .popover-frame::before { content: ''; position: absolute; width: var(--triangle-size); height: var(--triangle-size); transform: rotate(45deg); background-color: var(--color-popover-background); border-top-left-radius: 2px; border-left: 1px solid var(--color-popover-border); border-top: 1px solid var(--color-popover-border); left: calc(var(--triangle-offset) - (var(--triangle-size) / 2)); top: calc(var(--triangle-size) / 2 * -1 - 1px); } .popover-container.position-above .popover-frame::before { transform: rotate(-135deg); top: auto; bottom: calc(var(--triangle-size) / 2 * -1 - 1px); } .popover-container.position-above .popover-frame { --shadow-properties: 0 10px 20px -10px; } @keyframes popoverFrameEntrance { from { opacity: 0; transform: translateY(var(--entrance-direction)); } } ================================================ FILE: internal/glance/static/css/site.css ================================================ :root[data-scheme=light] { --scheme: 100% -; } .page { height: 100%; padding-block: var(--widget-gap); } .page-content, .page.content-ready .page-loading-container { display: none; } .page.content-ready > .page-content { display: block; animation: pageContentEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; } .page-column-small .size-title-dynamic { font-size: var(--font-size-h4); } .page-column-full .size-title-dynamic { font-size: var(--font-size-h3); } pre { font: inherit; } input[type="text"] { width: 100%; border: 0; background: none; font: inherit; color: inherit; } button { font: inherit; border: 0; cursor: pointer; background: none; color: inherit; } ::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; } *:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 0.1rem; border-radius: var(--border-radius); } *, *::before, *::after { box-sizing: border-box; } * { padding: 0; margin: 0; } hr { border: 0; height: 1px; background-color: var(--color-separator); } img, svg { display: block; max-width: 100%; } img[loading=lazy].loaded:not(.finished-transition) { transition: opacity .4s; } img[loading=lazy].cached:not(.finished-transition) { transition: none; } img[loading=lazy]:not(.loaded, .cached) { opacity: 0; } html { scrollbar-color: var(--color-text-subdue) transparent; scroll-behavior: smooth; } html, body, .body-content { height: 100%; } h1, h2, h3, h4, h5 { font: inherit; } a { text-decoration: none; color: inherit; overflow-wrap: break-word; } 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); } @keyframes pageContentEntrance { from { opacity: 0; transform: translateY(10px); } } .page-loading-container { height: 100%; display: flex; align-items: center; justify-content: center; animation: loadingContainerEntrance 200ms backwards; animation-delay: 150ms; font-size: 2rem; } .page-loading-container > .loading-icon { translate: 0 -250%; } @keyframes loadingContainerEntrance { from { /* Using 0.001 instead of 0 fixes a random 1s freeze on Chrome on page load when all */ /* elements have opacity 0 and are animated in. I don't want to be a web dev anymore. */ opacity: 0.001; } } .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); } } .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); } kbd { font: inherit; padding: 0.1rem 0.8rem; border-radius: var(--border-radius); border: 2px solid var(--color-widget-background-highlight); box-shadow: 0 2px 0 var(--color-widget-background-highlight); user-select: none; transition: transform .1s, box-shadow .1s; font-size: var(--font-size-h5); cursor: pointer; } kbd:active { transform: translateY(2px); box-shadow: 0 0 0 0 var(--color-widget-background-highlight); } .content-bounds { max-width: 1600px; width: 100%; margin-inline: auto; padding: 0 var(--content-bounds-padding); } .content-bounds-wide { max-width: 1920px; } .content-bounds-slim { max-width: 1100px; } .page.center-vertically { display: flex; justify-content: center; flex-direction: column; } .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%; flex-shrink: 0; 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); } .logo:has(img, svg) { display: flex; align-items: center; } .logo img { max-height: 2.7rem; } .nav { overflow-x: auto; min-width: 0; height: 100%; gap: var(--header-items-gap); } .nav .nav-item { line-height: var(--header-height); } .footer { padding-bottom: calc(var(--widget-gap) * 1.5); padding-top: calc(var(--widget-gap) / 2); animation: loadingContainerEntrance 200ms backwards; animation-delay: 150ms; } .mobile-navigation, .mobile-reachability-header { 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); flex-shrink: 0; } .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); } .logout-button { width: 2rem; height: 2rem; stroke: var(--color-text-subdue); transition: stroke .2s; } .logout-button:hover, .logout-button:focus { stroke: var(--color-text-highlight); } .theme-choices { --presets-per-row: 2; display: grid; grid-template-columns: repeat(var(--presets-per-row), 1fr); align-items: center; gap: 1.35rem; } .theme-choices:has(> :nth-child(3)) { --presets-per-row: 3; } .theme-preset { background-color: var(--color); display: flex; align-items: center; justify-content: center; gap: 0.5rem; height: 2rem; padding-inline: 0.5rem; border-radius: 0.3rem; border: none; cursor: pointer; position: relative; } .theme-choices .theme-preset::before { content: ''; position: absolute; inset: -.4rem; border-radius: .7rem; border: 2px solid transparent; transition: border-color .3s; } .theme-choices .theme-preset:hover::before { border-color: var(--color-text-subdue); } .theme-choices .theme-preset.current::before { border-color: var(--color-text-base); } .theme-preset-light { gap: 0.3rem; height: 1.8rem; } .theme-color { background-color: var(--color); width: 0.9rem; height: 0.9rem; border-radius: 0.2rem; } .theme-preset-light .theme-color { width: 1rem; height: 1rem; border-radius: 0.3rem; } .current-theme-preview { opacity: 0.4; transition: opacity .3s; } .theme-picker.popover-active .current-theme-preview, .theme-picker:hover { opacity: 1; } ================================================ FILE: internal/glance/static/css/utils.css ================================================ .masonry { display: flex; gap: var(--widget-gap); } .masonry-column { flex: 1; display: flex; flex-direction: column; } .widget-small-content-bounds { max-width: 350px; margin: 0 auto; } .visually-hidden { clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } .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.4rem; position: relative; top: 0.1rem; } .summary { width: 100%; cursor: pointer; word-spacing: -0.18em; user-select: none; list-style: none; position: relative; display: flex; z-index: 1; } .summary::-webkit-details-marker { display: none; } .details[open] .summary { margin-bottom: .8rem; } .summary::before { content: ""; position: absolute; inset: -.3rem -.8rem; border-radius: var(--border-radius); background-color: var(--color-widget-background-highlight); opacity: 0; transition: opacity 0.2s; z-index: -1; } .details[open] .summary::before, .summary:hover::before { opacity: 1; } .details:not([open]) .list-with-transition { display: none; } .summary::after { content: "◀" / ""; font-size: 1.2em; position: absolute; top: 0; bottom: 0; line-height: 1.3em; right: 0; transition: rotate .5s cubic-bezier(0.22, 1, 0.36, 1); } details[open] .summary::after { rotate: -90deg; } /* TODO: refactor, otherwise I hope I never have to change dynamic columns again */ .dynamic-columns { --list-half-gap: 0.5rem; gap: var(--widget-content-vertical-padding) var(--widget-content-horizontal-padding); display: grid; grid-template-columns: repeat(var(--columns-per-row), 1fr); } .dynamic-columns > * { padding-left: var(--widget-content-horizontal-padding); border-left: 1px solid var(--color-separator); min-width: 0; } .dynamic-columns > *:first-child { padding-top: 0; border-top: none; border-left: none; } .dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; } .dynamic-columns:has(> :nth-child(2)) { --columns-per-row: 2; } .dynamic-columns:has(> :nth-child(3)) { --columns-per-row: 3; } .dynamic-columns:has(> :nth-child(4)) { --columns-per-row: 4; } .dynamic-columns:has(> :nth-child(5)) { --columns-per-row: 5; } @container widget (max-width: 599px) { .dynamic-columns { gap: 0; } .dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; } .dynamic-columns > * { border-left: none; padding-left: 0; } .dynamic-columns > *:not(:first-child) { margin-top: calc(var(--list-half-gap) * 2); } .dynamic-columns.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); } } @container widget (min-width: 600px) and (max-width: 849px) { .dynamic-columns:has(> :nth-child(2)) { --columns-per-row: 2; } .dynamic-columns > :nth-child(2n-1) { border-left: none; padding-left: 0; } } @container widget (min-width: 850px) and (max-width: 1249px) { .dynamic-columns:has(> :nth-child(3)) { --columns-per-row: 3; } .dynamic-columns > :nth-child(3n+1) { border-left: none; padding-left: 0; } } @container widget (min-width: 1250px) and (max-width: 1499px) { .dynamic-columns:has(> :nth-child(4)) { --columns-per-row: 4; } .dynamic-columns > :nth-child(4n+1) { border-left: none; padding-left: 0; } } @container widget (min-width: 1500px) { .dynamic-columns:has(> :nth-child(5)) { --columns-per-row: 5; } .dynamic-columns > :nth-child(5n+1) { border-left: none; padding-left: 0; } } .cards-vertical { flex-direction: column; } .cards-horizontal { --cards-per-row: 6.5; } .cards-horizontal, .cards-vertical { --cards-gap: calc(var(--widget-content-vertical-padding) * 0.7); display: flex; gap: var(--cards-gap); } .card { display: flex; flex-direction: column; } .cards-horizontal .card { flex-shrink: 0; width: calc(100% / var(--cards-per-row) - var(--cards-gap) * (var(--cards-per-row) - 1) / var(--cards-per-row)); } .cards-grid .card { min-width: 0; } .cards-horizontal { overflow-x: auto; scrollbar-width: thin; padding-bottom: 1rem; } .cards-grid { --cards-per-row: 6; display: grid; grid-template-columns: repeat(var(--cards-per-row), 1fr); gap: calc(var(--widget-content-vertical-padding) * 0.7); } @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.5; } } @container widget (max-width: 450px) { .cards-horizontal { --cards-per-row: 2.3; } } @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; } } .text-truncate, .single-line-titles .title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .single-line-titles .title { display: block; } .text-truncate-2-lines, .text-truncate-3-lines { overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-box-orient: vertical; } .text-truncate-3-lines { line-clamp: 3; -webkit-line-clamp: 3; } .text-truncate-2-lines { line-clamp: 2; -webkit-line-clamp: 2; } .visited-indicator:not(.text-truncate)::after, .visited-indicator.text-truncate::before { 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); } .page-columns-transitioned .list-with-transition > * { animation: collapsibleItemReveal .25s backwards; } .list-with-transition > *:nth-child(2) { animation-delay: 30ms; } .list-with-transition > *:nth-child(3) { animation-delay: 60ms; } .list-with-transition > *:nth-child(4) { animation-delay: 90ms; } .list-with-transition > *:nth-child(5) { animation-delay: 120ms; } .list-with-transition > *:nth-child(6) { animation-delay: 150ms; } .list-with-transition > *:nth-child(7) { animation-delay: 180ms; } .list-with-transition > *:nth-child(8) { animation-delay: 210ms; } .list > *:not(:first-child) { margin-top: calc(var(--list-half-gap) * 2); } .list.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); } .collapsible-container:not(.container-expanded) > .collapsible-item { display: none; } .collapsible-item { animation: collapsibleItemReveal .25s backwards; } @keyframes collapsibleItemReveal { from { opacity: 0; transform: translateY(10px); } } .expand-toggle-button { font: inherit; border: 0; cursor: pointer; display: block; width: 100%; text-align: left; color: var(--color-text-base); text-transform: uppercase; font-size: var(--font-size-h4); padding: var(--widget-content-vertical-padding) 0; background: var(--color-widget-background); } .expand-toggle-button.container-expanded { position: sticky; /* -1px to hide 1px gap on chrome */ bottom: -1px; } .expand-toggle-button-icon { display: inline-block; margin-left: 1rem; position: relative; top: -.2rem; } .expand-toggle-button-icon::before { content: '' / ""; font-size: 0.8rem; transform: rotate(90deg); line-height: 1; display: inline-block; transition: transform 0.3s; } .expand-toggle-button.container-expanded .expand-toggle-button-icon::before { transform: rotate(-90deg); } .cards-grid.collapsible-container + .expand-toggle-button { text-align: center; margin-top: 0.5rem; background-color: var(--color-background); } .widget-content:has(.expand-toggle-button:last-child) { padding-bottom: 0; } .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 { 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; } .attachments { display: flex; flex-wrap: wrap; gap: 0.5rem; } :root:not([data-scheme=light]) .flat-icon { filter: invert(1); } .attachments > * { border-radius: var(--border-radius); padding: 0.1rem 0.5rem; font-size: var(--font-size-h6); background-color: var(--color-separator); } .progress-bar { border: 1px solid var(--color-progress-border); border-radius: var(--border-radius); display: flex; flex-direction: column; gap: 2px; padding: 2px; height: 1.5rem; /* naughty, but oh so beautiful */ margin-inline: -3px; } .progress-bar-combined { height: 3rem; } .popover-active > .progress-bar { transition: border-color .3s; border-color: var(--color-text-subdue); } .progress-value { --half-border-radius: calc(var(--border-radius) / 2); border-radius: 0 var(--half-border-radius) var(--half-border-radius) 0; background: var(--color-progress-value); width: calc(var(--percent) * 1%); min-width: 1px; flex: 1; } .progress-value:first-child { border-top-left-radius: var(--half-border-radius); } .progress-value:last-child { border-bottom-left-radius: var(--half-border-radius); } .progress-value-notice { background: linear-gradient(to right, var(--color-progress-value) 65%, var(--color-negative)); } .value-separator { min-width: 2rem; margin-inline: 0.8rem; flex: 1; height: calc(1em * 1.1); border-bottom: 1px dotted var(--color-text-subdue); } .thumbnail { filter: grayscale(0.2) contrast(0.9); opacity: 0.8; transition: filter 0.2s, opacity .2s; } .thumbnail-container { flex-shrink: 0; border: 1px solid var(--color-separator); border-radius: var(--border-radius); } .thumbnail-container > * { border-radius: var(--border-radius); object-fit: cover; } .thumbnail-parent:hover .thumbnail { opacity: 1; filter: none; } .hide-scrollbars { scrollbar-width: none; } /* Hide on Safari and Chrome */ .hide-scrollbars::-webkit-scrollbar { display: none; } .ui-icon { width: 2.3rem; height: 2.3rem; display: block; flex-shrink: 0; } .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-paragraph { color: var(--color-text-paragraph); } .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); } .color-primary-if-not-visited:not(:visited) { color: var(--color-primary); } .drag-and-drop-container { position: relative; } .drag-and-drop-decoy { outline: 1px dashed var(--color-primary); opacity: 0.25; border-radius: var(--border-radius); } .drag-and-drop-draggable { position: absolute; cursor: grabbing !important; } .drag-and-drop-draggable:empty { display: none; } .drag-and-drop-draggable * { cursor: grabbing !important; } .auto-scaling-textarea-container { position: relative; } .auto-scaling-textarea { position: absolute; inset: 0; background: none; border: none; font: inherit; resize: none; color: inherit; overflow: hidden; } .auto-scaling-textarea:focus { outline: none; } .auto-scaling-textarea-mimic { white-space: pre-wrap; min-height: 1lh; user-select: none; word-wrap: break-word; font: inherit; visibility: hidden; } .cursor-help { cursor: help; } .rounded { border-radius: var(--border-radius); } .break-all { word-break: break-all; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } .text-elevate { margin-top: -0.2em; } .text-compact { word-spacing: -0.18em; } .text-very-compact { word-spacing: -0.35em; } .rtl { direction: rtl; } .shrink { flex-shrink: 1; } .shrink-0 { flex-shrink: 0; } .min-width-0 { min-width: 0; } .max-width-100 { max-width: 100%; } .block { display: block; } .inline-block { display: inline-block; } .overflow-hidden { overflow: hidden; } .relative { position: relative; } .flex { display: flex; } .flex-1 { flex: 1; } .flex-wrap { flex-wrap: wrap; } .flex-nowrap { flex-wrap: nowrap; } .justify-between { justify-content: space-between; } .justify-stretch { justify-content: stretch; } .justify-evenly { justify-content: space-evenly; } .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; } .self-center { align-self: center; } .items-start { align-items: start; } .items-end { align-items: end; } .gap-5 { gap: 0.5rem; } .gap-7 { gap: 0.7rem; } .gap-10 { gap: 1rem; } .gap-12 { gap: 1.2rem; } .gap-15 { gap: 1.5rem; } .gap-20 { gap: 2rem; } .gap-25 { gap: 2.5rem; } .gap-35 { gap: 3.5rem; } .gap-45 { gap: 4.5rem; } .gap-55 { gap: 5.5rem; } .margin-left-auto { margin-left: auto; } .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-top-20 { margin-top: 2rem; } .margin-top-25 { margin-top: 2.5rem; } .margin-top-35 { margin-top: 3.5rem; } .margin-top-40 { margin-top: 4rem; } .margin-top-auto { margin-top: auto; } .margin-block-3 { margin-block: 0.3rem; } .margin-block-5 { margin-block: 0.5rem; } .margin-block-7 { margin-block: 0.7rem; } .margin-block-8 { margin-block: 0.8rem; } .margin-block-10 { margin-block: 1rem; } .margin-block-15 { margin-block: 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; } .margin-bottom-widget { margin-bottom: var(--widget-content-vertical-padding); } .padding-widget { padding: var(--widget-content-padding); } .padding-block-widget { padding-block: var(--widget-content-vertical-padding); } .padding-inline-widget { padding-inline: var(--widget-content-horizontal-padding); } .pointer-events-none { pointer-events: none; } .select-none { user-select: none; } .padding-block-5 { padding-block: 0.5rem; } .scale-half { transform: scale(0.5); } .list { --list-half-gap: 0rem; } .list-gap-2 { --list-half-gap: 0.1rem; } .list-gap-4 { --list-half-gap: 0.2rem; } .list-gap-8 { --list-half-gap: 0.4rem; } .list-gap-10 { --list-half-gap: 0.5rem; } .list-gap-14 { --list-half-gap: 0.7rem; } .list-gap-20 { --list-half-gap: 1rem; } .list-gap-24 { --list-half-gap: 1.2rem; } .list-gap-34 { --list-half-gap: 1.7rem; } @media (max-width: 1190px) { .size-base-on-mobile { font-size: var(--font-size-base); } } ================================================ FILE: internal/glance/static/css/widget-bookmarks.css ================================================ .bookmarks-group { --bookmarks-group-color: var(--color-primary); } .bookmarks-group-title { color: var(--bookmarks-group-color); } .bookmarks-link:not(.bookmarks-link-no-arrow)::after { content: '↗' / ""; margin-left: 0.5em; display: inline-block; position: relative; top: 0.15em; 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; opacity: 0.7; flex-shrink: 0; } .bookmarks-icon { width: 20px; height: 20px; opacity: 0.8; } ================================================ FILE: internal/glance/static/css/widget-calendar.css ================================================ .old-calendar-day { width: calc(100% / 7); text-align: center; padding: 0.6rem 0; } .old-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); } .calendar-dates { text-align: center; display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; } .calendar-date { padding: 0.4rem 0; color: var(--color-text-base); position: relative; border-radius: var(--border-radius); background: none; border: none; font: inherit; } .calendar-current-date { border-radius: var(--border-radius); background-color: var(--color-popover-border); color: var(--color-text-highlight); } .calendar-spillover-date { color: var(--color-text-subdue); } .calendar-header-button { position: relative; cursor: pointer; width: 2rem; height: 2rem; z-index: 1; background: none; border: none; } .calendar-header-button::before { content: ''; position: absolute; inset: -0.2rem; border-radius: var(--border-radius); background-color: var(--color-text-subdue); opacity: 0; transition: opacity 0.2s; z-index: -1; } .calendar-header-button:hover::before { opacity: 0.4; } .calendar-undo-button { display: inline-block; vertical-align: text-top; width: 2rem; height: 2rem; margin-left: 0.7rem; } ================================================ FILE: internal/glance/static/css/widget-clock.css ================================================ .clock-time { min-width: 8ch; } .clock-time span { color: var(--color-text-highlight); } ================================================ FILE: internal/glance/static/css/widget-dns-stats.css ================================================ .dns-stats-totals { transition: opacity .3s; transition-delay: 50ms; } .dns-stats:has(.dns-stats-graph .popover-active) .dns-stats-totals { opacity: 0.1; transition-delay: 0s; } .dns-stats-graph { --graph-height: 70px; height: var(--graph-height); position: relative; margin-bottom: 2.5rem; } .dns-stats-graph-gridlines-container { position: absolute; inset: 0; } .dns-stats-graph-gridlines { height: 100%; width: 100%; } .dns-stats-graph-columns { display: flex; height: 100%; } .dns-stats-graph-column { display: flex; justify-content: flex-end; align-items: center; flex-direction: column; width: calc(100% / 8); position: relative; } .dns-stats-graph-column::before { content: ''; position: absolute; inset: 1px 0; opacity: 0; background: var(--color-text-base); transition: opacity .2s; } .dns-stats-graph-column:hover::before { opacity: 0.05; } .dns-stats-graph-bar { width: 14px; height: calc((var(--bar-height) / 100) * var(--graph-height)); border: 1px solid var(--color-progress-border); border-radius: var(--border-radius) var(--border-radius) 0 0; display: flex; background: var(--color-widget-background); padding: 2px 2px 0 2px; flex-direction: column; gap: 2px; transition: border-color .2s; min-height: 10px; } .dns-stats-graph-column.popover-active .dns-stats-graph-bar { border-color: var(--color-text-subdue); border-bottom-color: var(--color-progress-border); } .dns-stats-graph-bar > * { border-radius: 2px; background: var(--color-vertical-progress-value); min-height: 1px; } .dns-stats-graph-bar > .queries { flex-grow: 1; } .dns-stats-graph-bar > *:last-child { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .dns-stats-graph-bar > .blocked { background-color: var(--color-negative); flex-basis: calc(var(--percent) - 1px); } .dns-stats-graph-column:nth-child(even) .dns-stats-graph-time { opacity: 1; transform: translateY(0); } .dns-stats-graph-time, .dns-stats-graph-columns:hover .dns-stats-graph-time { position: absolute; font-size: var(--font-size-h6); inset-inline: 0; text-align: center; height: 2.5rem; line-height: 2.5rem; top: 100%; user-select: none; opacity: 0; transform: translateY(-0.5rem); transition: opacity .2s, transform .2s; } .dns-stats-graph-column:hover .dns-stats-graph-time { opacity: 1; transform: translateY(0); } .dns-stats-graph-columns:hover .dns-stats-graph-column:not(:hover) .dns-stats-graph-time { opacity: 0; } ================================================ FILE: internal/glance/static/css/widget-docker-containers.css ================================================ .docker-container-icon { display: block; filter: grayscale(0.4); object-fit: contain; aspect-ratio: 1 / 1; width: 2.7rem; opacity: 0.8; transition: filter 0.3s, opacity 0.3s; } .docker-container-icon.flat-icon { opacity: 0.7; } .docker-container:hover .docker-container-icon { opacity: 1; } .docker-container:hover .docker-container-icon:not(.flat-icon) { filter: grayscale(0); } .docker-container-status-icon { width: 2rem; height: 2rem; } ================================================ FILE: internal/glance/static/css/widget-group.css ================================================ .widget-group-header { overflow-x: auto; scrollbar-width: thin; } .widget-group-title { background: none; font: inherit; border: none; text-transform: uppercase; border-bottom: 1px dotted transparent; cursor: pointer; flex-shrink: 0; transition: color .3s, border-color .3s; color: var(--color-text-subdue); line-height: calc(1.6em - 1px); } .widget-group-title:hover:not(.widget-group-title-current) { color: var(--color-text-base); } .widget-group-title-current { border-bottom-color: var(--color-text-base-muted); color: var(--color-text-base); } .widget-group-content { animation: widgetGroupContentEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; } .widget-group-content[data-direction="right"] { --direction: 5px; } .widget-group-content[data-direction="left"] { --direction: -5px; } @keyframes widgetGroupContentEntrance { from { opacity: 0; transform: translateX(var(--direction)); } } .widget-group-content:not(.widget-group-content-current) { display: none; } ================================================ FILE: internal/glance/static/css/widget-markets.css ================================================ .market-chart { margin-left: auto; width: 6.5rem; flex-shrink: 0; } .market-chart svg { width: 100%; } .market-values { min-width: 8rem; } ================================================ FILE: internal/glance/static/css/widget-monitor.css ================================================ .monitor-site-icon { display: block; opacity: 0.8; filter: grayscale(0.4); object-fit: contain; aspect-ratio: 1 / 1; width: 3.2rem; position: relative; top: -0.1rem; transition: filter 0.3s, opacity 0.3s; } .monitor-site-icon.flat-icon { opacity: 0.7; } .monitor-site:hover .monitor-site-icon { opacity: 1; } .monitor-site:hover .monitor-site-icon:not(.flat-icon) { filter: grayscale(0); } .monitor-site-status-icon { flex-shrink: 0; margin-left: auto; width: 2rem; height: 2rem; } .monitor-site-status-icon-compact { width: 1.8rem; height: 1.8rem; flex-shrink: 0; } ================================================ FILE: internal/glance/static/css/widget-reddit.css ================================================ .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); } ================================================ FILE: internal/glance/static/css/widget-releases.css ================================================ .release-source-icon { width: 16px; height: 16px; flex-shrink: 0; opacity: 0.4; } ================================================ FILE: internal/glance/static/css/widget-rss.css ================================================ .rss-card-image { height: var(--rss-thumbnail-height, 10rem); object-fit: cover; border-radius: var(--border-radius) var(--border-radius) 0 0; } .rss-card-2 { position: relative; height: var(--rss-card-height, 27rem); overflow: hidden; } .rss-card-2::before { content: ''; position: absolute; inset: 0; pointer-events: none; background-image: linear-gradient( 0deg, var(--color-widget-background), hsla(var(--color-widget-background-hsl-values), 0.8) 6rem, transparent 14rem ); z-index: 2; } .rss-card-2-image { position: absolute; width: 100%; height: 100%; object-fit: cover; /* +1px is required to fix some weird graphical bug where the image overflows on the bottom in firefox */ border-radius: calc(var(--border-radius) + 1px); opacity: 0.9; z-index: 1; } .rss-card-2-content { position: absolute; inset-inline: 0; bottom: var(--widget-content-vertical-padding); z-index: 3; } .rss-detailed-description { max-width: 55rem; color: var(--color-text-base-muted); } .rss-detailed-thumbnail { margin-top: 0.3rem; } .rss-detailed-thumbnail > * { aspect-ratio: 3 / 2; height: 8.7rem; } ================================================ FILE: internal/glance/static/css/widget-search.css ================================================ .search-icon { width: 2.3rem; } .search-icon-container { position: relative; flex-shrink: 0; } /* gives a wider hit area for the 3 people that will notice the animation : ) */ .search-icon-container::before { content: ''; position: absolute; inset: -1rem; } .search-icon-container:hover > .search-icon { animation: searchIconHover 2.9s forwards; } @keyframes searchIconHover { 0%, 39% { translate: 0 0; } 20% { scale: 1.3; } 40% { scale: 1; } 50% { translate: -30% 30%; } 70% { translate: 30% -30%; } 90% { translate: -30% -30%; } 100% { translate: 0 0; } } .search { transition: border-color .2s; position: relative; } .search:hover { border-color: var(--color-text-subdue); } .search:focus-within { border-color: var(--color-primary); } .search-input { border: 0; background: none; width: 100%; height: 6rem; font: inherit; outline: none; color: var(--color-text-highlight); } .search-input::placeholder { color: var(--color-text-base-muted); opacity: 1; } .search-bangs { display: none; } .search-bang { border-radius: calc(var(--border-radius) * 2); background: var(--color-widget-background-highlight); padding: 0.3rem 1rem; flex-shrink: 0; font-size: var(--font-size-h5); animation: searchBangsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; } @keyframes searchBangsEntrance { 0% { opacity: 0; transform: translateX(-10px); } } .search-bang:empty { display: none; } ================================================ FILE: internal/glance/static/css/widget-server-stats.css ================================================ .widget-type-server-info { position: relative; } .server + .server { margin-top: 3rem; } .server { gap: 1rem; display: flex; flex-direction: column; } .server-info { align-items: center; display: flex; justify-content: space-between; gap: 1.5rem; flex-shrink: 1; min-width: 0; } .server-details { min-width: 0; } .server-icon { height: 3rem; width: 3rem; } .server-spicy-cpu-icon { height: 1em; align-self: center; margin-left: 0.4em; margin-bottom: 0.2rem; } .server-stats { display: flex; gap: 1.5rem; margin-top: 0.5rem; } .server-stat-unavailable { opacity: 0.5; } @container widget (min-width: 650px) { .server { gap: 2rem; flex-direction: row; align-items: center; } .server + .server { margin-top: 1rem; } .server-info { flex-direction: row-reverse; justify-content: unset; margin-right: auto; z-index: 1; } .server-stats { flex-direction: row; justify-content: right; min-width: 450px; margin-top: 0; gap: 2rem; padding-bottom: 0.8rem; z-index: 1; } .server-stats > * { max-width: 200px; } } ================================================ FILE: internal/glance/static/css/widget-todo.css ================================================ .todo-widget { padding-top: 4rem; } .todo-plus-icon { --icon-color: var(--color-text-subdue); position: relative; width: 1.4rem; height: 1.4rem; } .todo-plus-icon::before, .todo-plus-icon::after { content: ""; position: absolute; background-color: var(--icon-color); transition: background-color .2s; } .todo-plus-icon::before { width: 2px; inset-block: 0.2rem; left: 50%; transform: translateX(-50%); } .todo-plus-icon::after { height: 2px; inset-inline: 0.2rem; top: 50%; transform: translateY(-50%); } .todo-input textarea::placeholder { color: var(--color-text-base-muted); } .todo-input { position: relative; color: var(--color-text-highlight); } .todo-input:focus-within .todo-plus-icon { --icon-color: var(--color-text-base); } .todo-item { transform-origin: center; padding: 0.5rem 0; } .todo-item-checkbox { -webkit-appearance: none; appearance: none; border: 2px solid var(--color-text-subdue); width: 1.4rem; height: 1.4rem; position: relative; cursor: pointer; border-radius: 0.3rem; transition: border-color .2s; } .todo-item-checkbox::before { content: ""; inset: -1rem; position: absolute; } .todo-item-checkbox::after { content: ''; position: absolute; inset: 0.3rem; border-radius: 0.1rem; opacity: 0; transition: opacity .2s; } .todo-item-checkbox:checked::after { background: var(--color-primary); opacity: 1; } .todo-item-checkbox:focus-visible { outline: none; border-color: var(--color-primary); } .todo-item-text { color: var(--color-text-base); transition: color .35s; } .todo-item-text:focus { color: var(--color-text-highlight); } .todo-item-drag-handle { position: absolute; top: -0.5rem; inset-inline: 0; height: 1rem; cursor: grab; } .todo-item.is-being-dragged .todo-item-drag-handle { height: 3rem; top: -1.5rem; } .todo-item:has(.todo-item-checkbox:checked) .todo-item-text { text-decoration: line-through; color: var(--color-text-subdue); } .todo-item-delete { width: 1.5rem; height: 1.5rem; opacity: 0; transition: opacity .2s; outline-offset: .5rem; } .todo-item:hover .todo-item-delete, .todo-item:focus-within .todo-item-delete { opacity: 1; } .todo-item.is-being-dragged .todo-item-delete { opacity: 0; } ================================================ FILE: internal/glance/static/css/widget-twitch.css ================================================ .twitch-category-thumbnail { width: 5rem; aspect-ratio: 3 / 4; 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); } .twitch-stream-preview { max-width: 100%; width: 400px; aspect-ratio: 16 / 9; border-radius: var(--border-radius); object-fit: cover; } ================================================ FILE: internal/glance/static/css/widget-videos.css ================================================ .video-thumbnail { width: 100%; aspect-ratio: 16 / 8.9; object-fit: cover; border-radius: var(--border-radius) var(--border-radius) 0 0; } .video-horizontal-list-thumbnail { height: 4rem; aspect-ratio: 16 / 8.9; object-fit: cover; border-radius: var(--border-radius); } ================================================ FILE: internal/glance/static/css/widget-weather.css ================================================ .weather-column { position: relative; display: flex; align-items: center; justify-content: end; flex-direction: column; width: calc(100% / 12); padding-top: 3px; } .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); } .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%); } ================================================ FILE: internal/glance/static/css/widgets.css ================================================ @import "widget-bookmarks.css"; @import "widget-calendar.css"; @import "widget-clock.css"; @import "widget-dns-stats.css"; @import "widget-docker-containers.css"; @import "widget-group.css"; @import "widget-markets.css"; @import "widget-monitor.css"; @import "widget-reddit.css"; @import "widget-releases.css"; @import "widget-rss.css"; @import "widget-search.css"; @import "widget-server-stats.css"; @import "widget-twitch.css"; @import "widget-videos.css"; @import "widget-weather.css"; @import "widget-todo.css"; @import "forum-posts.css"; .widget-error-header { display: flex; align-items: center; justify-content: space-between; position: relative; margin-bottom: 1.8rem; z-index: 1; } .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; flex-shrink: 0; stroke: var(--color-negative); opacity: 0.6; } .head-widgets { margin-bottom: var(--widget-gap); } .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%)); } .widget-header { padding: 0 calc(var(--widget-content-horizontal-padding) + 1px); font-size: var(--font-size-h4); margin-bottom: 0.9rem; display: flex; align-items: center; gap: 1rem; } .widget-beta-icon { width: 1.6rem; height: 1.6rem; flex-shrink: 0; transition: transform .45s, opacity .45s, stroke .45s; opacity: 0.7; } .widget-beta-icon:hover, .widget-header .popover-active > .widget-beta-icon { fill: var(--color-text-highlight); transform: translateY(-10%) scale(1.3); opacity: 1; } .widget + .widget { margin-top: var(--widget-gap); } ================================================ FILE: internal/glance/static/js/animations.js ================================================ export const easeOutQuint = 'cubic-bezier(0.22, 1, 0.36, 1)'; export function directions(anim, opt, ...dirs) { return dirs.map(dir => anim({ direction: dir, ...opt })); } export function slideFade({ direction = 'left', fill = 'backwards', duration = 200, distance = '1rem', easing = 'ease', offset = 0, }) { const axis = direction === 'left' || direction === 'right' ? 'X' : 'Y'; const negative = direction === 'left' || direction === 'up' ? '-' : ''; const amount = negative + distance; return { keyframes: [ { offset: offset, opacity: 0, transform: `translate${axis}(${amount})`, } ], options: { duration: duration, easing: easing, fill: fill, }, }; } export function animateReposition( element, onAnimEnd, animOptions = { duration: 400, easing: easeOutQuint } ) { const rectBefore = element.getBoundingClientRect(); return () => { const rectAfter = element.getBoundingClientRect(); const offsetY = rectBefore.y - rectAfter.y; const offsetX = rectBefore.x - rectAfter.x; element.animate({ keyframes: [ { transform: `translate(${offsetX}px, ${offsetY}px)` }, { transform: 'none' } ], options: animOptions }, onAnimEnd); return rectAfter; } } ================================================ FILE: internal/glance/static/js/calendar.js ================================================ import { directions, easeOutQuint, slideFade } from "./animations.js"; import { elem, repeat, text } from "./templating.js"; const FULL_MONTH_SLOTS = 7*6; const WEEKDAY_ABBRS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; const MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const leftArrowSvg = ` `; const rightArrowSvg = ` `; const undoArrowSvg = ` `; const [datesExitLeft, datesExitRight] = directions( slideFade, { distance: "2rem", duration: 120, offset: 1 }, "left", "right" ); const [datesEntranceLeft, datesEntranceRight] = directions( slideFade, { distance: "0.8rem", duration: 500, easing: easeOutQuint }, "left", "right" ); const undoEntrance = slideFade({ direction: "left", distance: "100%", duration: 300 }); export default function(element) { element.swapWith(Calendar( Number(element.dataset.firstDayOfWeek ?? 1) )); } // TODO: when viewing the previous/next month, display the current date if it's within the spill-over days function Calendar(firstDay) { let header, dates; let advanceTimeTicker; let now = new Date(); let activeDate; const update = (newDate) => { header.component.update(now, newDate); dates.component.update(now, newDate); activeDate = newDate; }; const autoAdvanceNow = () => { advanceTimeTicker = setTimeout(() => { // TODO: don't auto advance if looking at a different month update(now = new Date()); autoAdvanceNow(); }, msTillNextDay()); }; const adjacentMonth = (dir) => new Date(activeDate.getFullYear(), activeDate.getMonth() + dir, 1); const nextClicked = () => update(adjacentMonth(1)); const prevClicked = () => update(adjacentMonth(-1)); const undoClicked = () => update(now); const calendar = elem().classes("calendar").append( header = Header(nextClicked, prevClicked, undoClicked), dates = Dates(firstDay) ); update(now); autoAdvanceNow(); return calendar.component({ suspend: () => clearTimeout(advanceTimeTicker) }); } function Header(nextClicked, prevClicked, undoClicked) { let month, monthNumber, year, undo; const button = () => elem("button").classes("calendar-header-button"); const monthAndYear = elem().classes("size-h2", "color-highlight").append( month = text(), " ", year = elem("span").classes("size-h3"), undo = button() .hide() .classes("calendar-undo-button") .attr("title", "Back to current month") .on("click", undoClicked) .html(undoArrowSvg) ); const monthSwitcher = elem() .classes("flex", "gap-7", "items-center") .append( button() .attr("title", "Previous month") .on("click", prevClicked) .html(leftArrowSvg), monthNumber = elem() .classes("color-highlight") .styles({ marginTop: "0.1rem" }), button() .attr("title", "Next month") .on("click", nextClicked) .html(rightArrowSvg), ); return elem().classes("flex", "justify-between", "items-center").append( monthAndYear, monthSwitcher ).component({ update: function (now, newDate) { month.text(MONTH_NAMES[newDate.getMonth()]); year.text(newDate.getFullYear()); const m = newDate.getMonth() + 1; monthNumber.text((m < 10 ? "0" : "") + m); if (!datesWithinSameMonth(now, newDate)) { if (undo.isHidden()) undo.show().animate(undoEntrance); } else { undo.hide(); } return this; } }); } function Dates(firstDay) { let dates, lastRenderedDate; const updateFullMonth = function(now, newDate) { const firstWeekday = new Date(newDate.getFullYear(), newDate.getMonth(), 1).getDay(); const previousMonthSpilloverDays = (firstWeekday - firstDay + 7) % 7 || 7; const currentMonthDays = daysInMonth(newDate.getFullYear(), newDate.getMonth()); const nextMonthSpilloverDays = FULL_MONTH_SLOTS - (previousMonthSpilloverDays + currentMonthDays); const previousMonthDays = daysInMonth(newDate.getFullYear(), newDate.getMonth() - 1) const isCurrentMonth = datesWithinSameMonth(now, newDate); const currentDate = now.getDate(); let children = dates.children; let index = 0; for (let i = 0; i < FULL_MONTH_SLOTS; i++) { children[i].clearClasses("calendar-spillover-date", "calendar-current-date"); } for (let i = 0; i < previousMonthSpilloverDays; i++, index++) { children[index].classes("calendar-spillover-date").text( previousMonthDays - previousMonthSpilloverDays + i + 1 ) } for (let i = 1; i <= currentMonthDays; i++, index++) { children[index] .classesIf(isCurrentMonth && i === currentDate, "calendar-current-date") .text(i); } for (let i = 0; i < nextMonthSpilloverDays; i++, index++) { children[index].classes("calendar-spillover-date").text(i + 1); } lastRenderedDate = newDate; }; const update = function(now, newDate) { if (lastRenderedDate === undefined || datesWithinSameMonth(newDate, lastRenderedDate)) { updateFullMonth(now, newDate); return; } const next = newDate > lastRenderedDate; dates.animateUpdate( () => updateFullMonth(now, newDate), next ? datesExitLeft : datesExitRight, next ? datesEntranceRight : datesEntranceLeft, ); } return elem().append( elem().classes("calendar-dates", "margin-top-15").append( ...repeat(7, (i) => elem().classes("size-h6", "color-subdue").text( WEEKDAY_ABBRS[(firstDay + i) % 7] )) ), dates = elem().classes("calendar-dates", "margin-top-3").append( ...elem().classes("calendar-date").duplicate(FULL_MONTH_SLOTS) ) ).component({ update }); } function datesWithinSameMonth(d1, d2) { return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth(); } function daysInMonth(year, month) { return new Date(year, month + 1, 0).getDate(); } function msTillNextDay(now) { now = now || new Date(); return 86_400_000 - ( now.getMilliseconds() + now.getSeconds() * 1000 + now.getMinutes() * 60_000 + now.getHours() * 3_600_000 ); } ================================================ FILE: internal/glance/static/js/login.js ================================================ import { find } from "./templating.js"; const AUTH_ENDPOINT = pageData.baseURL + "/api/authenticate"; const showPasswordSVG = ` `; const hidePasswordSVG = ` `; const container = find("#login-container"); const usernameInput = find("#username"); const passwordInput = find("#password"); const errorMessage = find("#error-message"); const loginButton = find("#login-button"); const toggleVisibilityButton = find("#toggle-password-visibility"); const state = { lastUsername: "", lastPassword: "", isLoading: false, isRateLimited: false }; const lang = { showPassword: "Show password", hidePassword: "Hide password", incorrectCredentials: "Incorrect username or password", rateLimited: "Too many login attempts, try again in a few minutes", unknownError: "An error occurred, please try again", }; container.clearStyles("display"); setTimeout(() => usernameInput.focus(), 200); toggleVisibilityButton .html(showPasswordSVG) .attr("title", lang.showPassword) .on("click", function() { if (passwordInput.type === "password") { passwordInput.type = "text"; toggleVisibilityButton.html(hidePasswordSVG).attr("title", lang.hidePassword); return; } passwordInput.type = "password"; toggleVisibilityButton.html(showPasswordSVG).attr("title", lang.showPassword); }); function enableLoginButtonIfCriteriaMet() { const usernameValue = usernameInput.value.trim(); const passwordValue = passwordInput.value.trim(); const usernameValid = usernameValue.length >= 3; const passwordValid = passwordValue.length >= 6; const isUsingLastCredentials = usernameValue === state.lastUsername && passwordValue === state.lastPassword; loginButton.disabled = !( usernameValid && passwordValid && !isUsingLastCredentials && !state.isLoading && !state.isRateLimited ); } usernameInput.on("input", enableLoginButtonIfCriteriaMet); passwordInput.on("input", enableLoginButtonIfCriteriaMet); async function handleLoginAttempt() { state.lastUsername = usernameInput.value; state.lastPassword = passwordInput.value; errorMessage.text(""); loginButton.disable(); state.isLoading = true; const response = await fetch(AUTH_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: usernameInput.value, password: passwordInput.value }), }); state.isLoading = false; if (response.status === 200) { setTimeout(() => { window.location.href = pageData.baseURL + "/"; }, 300); container.animate({ keyframes: [{ offset: 1, transform: "scale(0.95)", opacity: 0 }], options: { duration: 300, easing: "ease", fill: "forwards" }} ); find("footer")?.animate({ keyframes: [{ offset: 1, opacity: 0 }], options: { duration: 300, easing: "ease", fill: "forwards", delay: 50 } }); } else if (response.status === 401) { errorMessage.text(lang.incorrectCredentials); passwordInput.focus(); } else if (response.status === 429) { errorMessage.text(lang.rateLimited); state.isRateLimited = true; const retryAfter = response.headers.get("Retry-After") || 30; setTimeout(() => { state.lastUsername = ""; state.lastPassword = ""; state.isRateLimited = false; enableLoginButtonIfCriteriaMet(); }, retryAfter * 1000); } else { errorMessage.text(lang.unknownError); passwordInput.focus(); } } loginButton.disable().on("click", handleLoginAttempt); ================================================ FILE: internal/glance/static/js/masonry.js ================================================ import { clamp } from "./utils.js"; export function setupMasonries() { const masonryContainers = document.getElementsByClassName("masonry"); for (let i = 0; i < masonryContainers.length; i++) { const container = masonryContainers[i]; const options = { minColumnWidth: container.dataset.minColumnWidth || 330, maxColumns: container.dataset.maxColumns || 6, }; const items = Array.from(container.children); let previousColumnsCount = 0; const render = function() { const columnsCount = clamp( Math.floor(container.offsetWidth / options.minColumnWidth), 1, Math.min(options.maxColumns, items.length) ); if (columnsCount === previousColumnsCount) { return; } else { container.textContent = ""; previousColumnsCount = columnsCount; } const columnsFragment = document.createDocumentFragment(); for (let i = 0; i < columnsCount; i++) { const column = document.createElement("div"); column.className = "masonry-column"; columnsFragment.append(column); } for (let i = 0; i < items.length; i++) { columnsFragment.children[i % columnsCount].appendChild(items[i]); } container.append(columnsFragment); }; const observer = new ResizeObserver(() => requestAnimationFrame(render)); observer.observe(container); } } ================================================ FILE: internal/glance/static/js/page.js ================================================ import { setupPopovers } from './popover.js'; import { setupMasonries } from './masonry.js'; import { throttledDebounce, isElementVisible, openURLInNewTab } from './utils.js'; import { elem, find, findAll } from './templating.js'; async function fetchPageContent(pageData) { // TODO: handle non 200 status codes/time outs // TODO: add retries const response = await fetch(`${pageData.baseURL}/api/pages/${pageData.slug}/content/`); const content = await response.text(); return content; } function setupCarousels() { const carouselElements = document.getElementsByClassName("carousel-container"); if (carouselElements.length == 0) { return; } for (let i = 0; i < carouselElements.length; i++) { const carousel = carouselElements[i]; carousel.classList.add("show-right-cutoff"); 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); window.addEventListener("resize", determineSideCutoffsRateLimited); afterContentReady(determineSideCutoffs); } } const minuteInSeconds = 60; const hourInSeconds = minuteInSeconds * 60; const dayInSeconds = hourInSeconds * 24; const monthInSeconds = dayInSeconds * 30.4; const yearInSeconds = dayInSeconds * 365; function timestampToRelativeTime(timestamp) { let delta = Math.round((Date.now() / 1000) - timestamp); let prefix = ""; if (delta < 0) { delta = -delta; prefix = "in "; } if (delta < minuteInSeconds) { return prefix + "1m"; } if (delta < hourInSeconds) { return prefix + Math.floor(delta / minuteInSeconds) + "m"; } if (delta < dayInSeconds) { return prefix + Math.floor(delta / hourInSeconds) + "h"; } if (delta < monthInSeconds) { return prefix + Math.floor(delta / dayInSeconds) + "d"; } if (delta < yearInSeconds) { return prefix + Math.floor(delta / monthInSeconds) + "mo"; } return prefix + 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.textContent = timestampToRelativeTime(timestamp); } } function setupSearchBoxes() { const searchWidgets = document.getElementsByClassName("search"); if (searchWidgets.length == 0) { return; } for (let i = 0; i < searchWidgets.length; i++) { const widget = searchWidgets[i]; const defaultSearchUrl = widget.dataset.defaultSearchUrl; const target = widget.dataset.target || "_blank"; const newTab = widget.dataset.newTab === "true"; const inputElement = widget.getElementsByClassName("search-input")[0]; const bangElement = widget.getElementsByClassName("search-bang")[0]; const bangs = widget.querySelectorAll(".search-bangs > input"); const bangsMap = {}; const kbdElement = widget.getElementsByTagName("kbd")[0]; let currentBang = null; let lastQuery = ""; for (let j = 0; j < bangs.length; j++) { const bang = bangs[j]; bangsMap[bang.dataset.shortcut] = bang; } const handleKeyDown = (event) => { if (event.key == "Escape") { inputElement.blur(); return; } if (event.key == "Enter") { const input = inputElement.value.trim(); let query; let searchUrlTemplate; if (currentBang != null) { query = input.slice(currentBang.dataset.shortcut.length + 1); searchUrlTemplate = currentBang.dataset.url; } else { query = input; searchUrlTemplate = defaultSearchUrl; } if (query.length == 0 && currentBang == null) { return; } const url = searchUrlTemplate.replace("!QUERY!", encodeURIComponent(query)); if (newTab && !event.ctrlKey || !newTab && event.ctrlKey) { window.open(url, target).focus(); } else { window.location.href = url; } lastQuery = query; inputElement.value = ""; return; } if (event.key == "ArrowUp" && lastQuery.length > 0) { inputElement.value = lastQuery; return; } }; const changeCurrentBang = (bang) => { currentBang = bang; bangElement.textContent = bang != null ? bang.dataset.title : ""; } const handleInput = (event) => { const value = event.target.value.trim(); if (value in bangsMap) { changeCurrentBang(bangsMap[value]); return; } const words = value.split(" "); if (words.length >= 2 && words[0] in bangsMap) { changeCurrentBang(bangsMap[words[0]]); return; } changeCurrentBang(null); }; inputElement.addEventListener("focus", () => { document.addEventListener("keydown", handleKeyDown); document.addEventListener("input", handleInput); }); inputElement.addEventListener("blur", () => { document.removeEventListener("keydown", handleKeyDown); document.removeEventListener("input", handleInput); }); document.addEventListener("keydown", (event) => { if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return; if (event.code != "KeyS") return; inputElement.focus(); event.preventDefault(); }); kbdElement.addEventListener("mousedown", () => { requestAnimationFrame(() => inputElement.focus()); }); } } function setupDynamicRelativeTime() { const elements = document.querySelectorAll("[data-dynamic-relative-time]"); const updateInterval = 60 * 1000; let lastUpdateTime = Date.now(); updateRelativeTimeForElements(elements); 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); }); } function setupGroups() { const groups = document.getElementsByClassName("widget-type-group"); if (groups.length == 0) { return; } for (let g = 0; g < groups.length; g++) { const group = groups[g]; const titles = group.getElementsByClassName("widget-header")[0].children; const tabs = group.getElementsByClassName("widget-group-contents")[0].children; let current = 0; for (let t = 0; t < titles.length; t++) { const title = titles[t]; if (title.dataset.titleUrl !== undefined) { title.addEventListener("mousedown", (event) => { if (event.button != 1) { return; } openURLInNewTab(title.dataset.titleUrl, false); event.preventDefault(); }); } title.addEventListener("click", () => { if (t == current) { if (title.dataset.titleUrl !== undefined) { openURLInNewTab(title.dataset.titleUrl); } return; } for (let i = 0; i < titles.length; i++) { titles[i].classList.remove("widget-group-title-current"); titles[i].setAttribute("aria-selected", "false"); tabs[i].classList.remove("widget-group-content-current"); tabs[i].setAttribute("aria-hidden", "true"); } if (current < t) { tabs[t].dataset.direction = "right"; } else { tabs[t].dataset.direction = "left"; } current = t; title.classList.add("widget-group-title-current"); title.setAttribute("aria-selected", "true"); tabs[t].classList.add("widget-group-content-current"); tabs[t].setAttribute("aria-hidden", "false"); }); } } } function setupLazyImages() { const images = document.querySelectorAll("img[loading=lazy]"); if (images.length == 0) { return; } function imageFinishedTransition(image) { image.classList.add("finished-transition"); } afterContentReady(() => { setTimeout(() => { for (let i = 0; i < images.length; i++) { const image = images[i]; if (image.complete) { image.classList.add("cached"); setTimeout(() => imageFinishedTransition(image), 1); } else { // TODO: also handle error event image.addEventListener("load", () => { image.classList.add("loaded"); setTimeout(() => imageFinishedTransition(image), 400); }); } } }, 1); }); } function attachExpandToggleButton(collapsibleContainer) { const showMoreText = "Show more"; const showLessText = "Show less"; let expanded = false; const button = document.createElement("button"); const icon = document.createElement("span"); icon.classList.add("expand-toggle-button-icon"); const textNode = document.createTextNode(showMoreText); button.classList.add("expand-toggle-button"); button.append(textNode, icon); button.addEventListener("click", () => { expanded = !expanded; if (expanded) { collapsibleContainer.classList.add("container-expanded"); button.classList.add("container-expanded"); textNode.nodeValue = showLessText; return; } const topBefore = button.getClientRects()[0].top; collapsibleContainer.classList.remove("container-expanded"); button.classList.remove("container-expanded"); textNode.nodeValue = showMoreText; const topAfter = button.getClientRects()[0].top; if (topAfter > 0) return; window.scrollBy({ top: topAfter - topBefore, behavior: "instant" }); }); collapsibleContainer.after(button); return button; }; function setupCollapsibleLists() { const collapsibleLists = document.querySelectorAll(".list.collapsible-container"); if (collapsibleLists.length == 0) { return; } for (let i = 0; i < collapsibleLists.length; i++) { const list = collapsibleLists[i]; if (list.dataset.collapseAfter === undefined) { continue; } const collapseAfter = parseInt(list.dataset.collapseAfter); if (collapseAfter == -1) { continue; } if (list.children.length <= collapseAfter) { continue; } attachExpandToggleButton(list); for (let c = collapseAfter; c < list.children.length; c++) { const child = list.children[c]; child.classList.add("collapsible-item"); child.style.animationDelay = ((c - collapseAfter) * 20).toString() + "ms"; } } } function setupCollapsibleGrids() { const collapsibleGridElements = document.querySelectorAll(".cards-grid.collapsible-container"); if (collapsibleGridElements.length == 0) { return; } for (let i = 0; i < collapsibleGridElements.length; i++) { const gridElement = collapsibleGridElements[i]; if (gridElement.dataset.collapseAfterRows === undefined) { continue; } const collapseAfterRows = parseInt(gridElement.dataset.collapseAfterRows); if (collapseAfterRows == -1) { continue; } const getCardsPerRow = () => { return parseInt(getComputedStyle(gridElement).getPropertyValue('--cards-per-row')); }; const button = attachExpandToggleButton(gridElement); let cardsPerRow; const resolveCollapsibleItems = () => requestAnimationFrame(() => { const hideItemsAfterIndex = cardsPerRow * collapseAfterRows; if (hideItemsAfterIndex >= gridElement.children.length) { button.style.display = "none"; } else { button.style.removeProperty("display"); } let row = 0; for (let i = 0; i < gridElement.children.length; i++) { const child = gridElement.children[i]; if (i >= hideItemsAfterIndex) { child.classList.add("collapsible-item"); child.style.animationDelay = (row * 40).toString() + "ms"; if (i % cardsPerRow + 1 == cardsPerRow) { row++; } } else { child.classList.remove("collapsible-item"); child.style.removeProperty("animation-delay"); } } }); const observer = new ResizeObserver(() => { if (!isElementVisible(gridElement)) { return; } const newCardsPerRow = getCardsPerRow(); if (cardsPerRow == newCardsPerRow) { return; } cardsPerRow = newCardsPerRow; resolveCollapsibleItems(); }); afterContentReady(() => observer.observe(gridElement)); } } const contentReadyCallbacks = []; function afterContentReady(callback) { contentReadyCallbacks.push(callback); } const weekDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; function makeSettableTimeElement(element, hourFormat) { const fragment = document.createDocumentFragment(); const hour = document.createElement('span'); const minute = document.createElement('span'); const amPm = document.createElement('span'); fragment.append(hour, document.createTextNode(':'), minute); if (hourFormat == '12h') { fragment.append(document.createTextNode(' '), amPm); } element.append(fragment); return (date) => { const hours = date.getHours(); if (hourFormat == '12h') { amPm.textContent = hours < 12 ? 'AM' : 'PM'; hour.textContent = hours % 12 || 12; } else { hour.textContent = hours < 10 ? '0' + hours : hours; } const minutes = date.getMinutes(); minute.textContent = minutes < 10 ? '0' + minutes : minutes; }; }; function timeInZone(now, zone) { let timeInZone; try { timeInZone = new Date(now.toLocaleString('en-US', { timeZone: zone })); } catch (e) { // TODO: indicate to the user that this is an invalid timezone console.error(e); timeInZone = now } const diffInMinutes = Math.round((timeInZone.getTime() - now.getTime()) / 1000 / 60); return { time: timeInZone, diffInMinutes: diffInMinutes }; } function zoneDiffText(diffInMinutes) { if (diffInMinutes == 0) { return ""; } const sign = diffInMinutes < 0 ? "-" : "+"; const signText = diffInMinutes < 0 ? "behind" : "ahead"; diffInMinutes = Math.abs(diffInMinutes); const hours = Math.floor(diffInMinutes / 60); const minutes = diffInMinutes % 60; const hourSuffix = hours == 1 ? "" : "s"; if (minutes == 0) { return { text: `${sign}${hours}h`, title: `${hours} hour${hourSuffix} ${signText}` }; } if (hours == 0) { return { text: `${sign}${minutes}m`, title: `${minutes} minutes ${signText}` }; } return { text: `${sign}${hours}h~`, title: `${hours} hour${hourSuffix} and ${minutes} minutes ${signText}` }; } function setupClocks() { const clocks = document.getElementsByClassName('clock'); if (clocks.length == 0) { return; } const updateCallbacks = []; for (var i = 0; i < clocks.length; i++) { const clock = clocks[i]; const hourFormat = clock.dataset.hourFormat; const localTimeContainer = clock.querySelector('[data-local-time]'); const localDateElement = localTimeContainer.querySelector('[data-date]'); const localWeekdayElement = localTimeContainer.querySelector('[data-weekday]'); const localYearElement = localTimeContainer.querySelector('[data-year]'); const timeZoneContainers = clock.querySelectorAll('[data-time-in-zone]'); const setLocalTime = makeSettableTimeElement( localTimeContainer.querySelector('[data-time]'), hourFormat ); updateCallbacks.push((now) => { setLocalTime(now); localDateElement.textContent = now.getDate() + ' ' + monthNames[now.getMonth()]; localWeekdayElement.textContent = weekDayNames[now.getDay()]; localYearElement.textContent = now.getFullYear(); }); for (var z = 0; z < timeZoneContainers.length; z++) { const timeZoneContainer = timeZoneContainers[z]; const diffElement = timeZoneContainer.querySelector('[data-time-diff]'); const setZoneTime = makeSettableTimeElement( timeZoneContainer.querySelector('[data-time]'), hourFormat ); updateCallbacks.push((now) => { const { time, diffInMinutes } = timeInZone(now, timeZoneContainer.dataset.timeInZone); setZoneTime(time); const { text, title } = zoneDiffText(diffInMinutes); diffElement.textContent = text; diffElement.title = title; }); } } const updateClocks = () => { const now = new Date(); for (var i = 0; i < updateCallbacks.length; i++) updateCallbacks[i](now); setTimeout(updateClocks, (60 - now.getSeconds()) * 1000); }; updateClocks(); } async function setupCalendars() { const elems = document.getElementsByClassName("calendar"); if (elems.length == 0) return; // TODO: implement prefetching, currently loads as a nasty waterfall of requests const calendar = await import ('./calendar.js'); for (let i = 0; i < elems.length; i++) calendar.default(elems[i]); } async function setupTodos() { const elems = Array.from(document.getElementsByClassName("todo")); if (elems.length == 0) return; const todo = await import ('./todo.js'); for (let i = 0; i < elems.length; i++){ todo.default(elems[i]); } } function setupTruncatedElementTitles() { const elements = document.querySelectorAll(".text-truncate, .single-line-titles .title, .text-truncate-2-lines, .text-truncate-3-lines"); if (elements.length == 0) { return; } for (let i = 0; i < elements.length; i++) { const element = elements[i]; if (element.getAttribute("title") === null) element.title = element.innerText.trim().replace(/\s+/g, " "); } } async function changeTheme(key, onChanged) { const themeStyleElem = find("#theme-style"); const response = await fetch(`${pageData.baseURL}/api/set-theme/${key}`, { method: "POST", }); if (response.status != 200) { alert("Failed to set theme: " + response.statusText); return; } const newThemeStyle = await response.text(); const tempStyle = elem("style") .html("* { transition: none !important; }") .appendTo(document.head); themeStyleElem.html(newThemeStyle); document.documentElement.setAttribute("data-theme", key); document.documentElement.setAttribute("data-scheme", response.headers.get("X-Scheme")); typeof onChanged == "function" && onChanged(); setTimeout(() => { tempStyle.remove(); }, 10); } function initThemePicker() { const themeChoicesInMobileNav = find(".mobile-navigation .theme-choices"); if (!themeChoicesInMobileNav) return; const themeChoicesInHeader = find(".header-container .theme-choices"); if (themeChoicesInHeader) { themeChoicesInHeader.replaceWith( themeChoicesInMobileNav.cloneNode(true) ); } const presetElems = findAll(".theme-choices .theme-preset"); let themePreviewElems = document.getElementsByClassName("current-theme-preview"); let isLoading = false; presetElems.forEach((presetElement) => { const themeKey = presetElement.dataset.key; if (themeKey === undefined) { return; } if (themeKey == pageData.theme) { presetElement.classList.add("current"); } presetElement.addEventListener("click", () => { if (themeKey == pageData.theme) return; if (isLoading) return; isLoading = true; changeTheme(themeKey, function() { isLoading = false; pageData.theme = themeKey; presetElems.forEach((e) => { e.classList.remove("current"); }); Array.from(themePreviewElems).forEach((preview) => { preview.querySelector(".theme-preset").replaceWith( presetElement.cloneNode(true) ); }) presetElems.forEach((e) => { if (e.dataset.key != themeKey) return; e.classList.add("current"); }); }); }); }) } async function setupPage() { initThemePicker(); const pageElement = document.getElementById("page"); const pageContentElement = document.getElementById("page-content"); const pageContent = await fetchPageContent(pageData); pageContentElement.innerHTML = pageContent; try { setupPopovers(); setupClocks() await setupCalendars(); await setupTodos(); setupCarousels(); setupSearchBoxes(); setupCollapsibleLists(); setupCollapsibleGrids(); setupGroups(); setupMasonries(); setupDynamicRelativeTime(); setupLazyImages(); } finally { pageElement.classList.add("content-ready"); pageElement.setAttribute("aria-busy", "false"); for (let i = 0; i < contentReadyCallbacks.length; i++) { contentReadyCallbacks[i](); } setTimeout(() => { setupTruncatedElementTitles(); }, 50); setTimeout(() => { document.body.classList.add("page-columns-transitioned"); }, 300); } } setupPage(); ================================================ FILE: internal/glance/static/js/popover.js ================================================ const defaultShowDelayMs = 200; const defaultHideDelayMs = 500; const defaultMaxWidth = "300px"; const defaultDistanceFromTarget = "0px" const htmlContentSelector = "[data-popover-html]"; let activeTarget = null; let pendingTarget = null; let cleanupOnHidePopover = null; let togglePopoverTimeout = null; const containerElement = document.createElement("div"); const containerComputedStyle = getComputedStyle(containerElement); containerElement.addEventListener("mouseenter", clearTogglePopoverTimeout); containerElement.addEventListener("mouseleave", handleMouseLeave); containerElement.classList.add("popover-container"); const frameElement = document.createElement("div"); frameElement.classList.add("popover-frame"); const contentElement = document.createElement("div"); contentElement.classList.add("popover-content"); frameElement.append(contentElement); containerElement.append(frameElement); document.body.append(containerElement); const queueRepositionContainer = () => requestAnimationFrame(repositionContainer); const observer = new ResizeObserver(queueRepositionContainer); function handleMouseEnter(event) { clearTogglePopoverTimeout(); const target = event.target; pendingTarget = target; const showDelay = target.dataset.popoverShowDelay || defaultShowDelayMs; if (activeTarget !== null) { if (activeTarget !== target) { hidePopover(); requestAnimationFrame(() => requestAnimationFrame(showPopover)); } else if (activeTarget.dataset.popoverTrigger === "click") { hidePopover(); } return; } togglePopoverTimeout = setTimeout(showPopover, showDelay); } function handleMouseLeave(event) { clearTogglePopoverTimeout(); const target = activeTarget || event.target; togglePopoverTimeout = setTimeout(hidePopover, target.dataset.popoverHideDelay || defaultHideDelayMs); } function clearTogglePopoverTimeout() { clearTimeout(togglePopoverTimeout); } function showPopover() { if (pendingTarget === null) return; activeTarget = pendingTarget; pendingTarget = null; const popoverType = activeTarget.dataset.popoverType; if (popoverType === "text") { const text = activeTarget.dataset.popoverText; if (text === undefined || text === "") return; contentElement.textContent = text; } else if (popoverType === "html") { const htmlContent = activeTarget.querySelector(htmlContentSelector); if (htmlContent === null) return; /** * The reason for all of the below shenanigans is that I want to preserve * all attached event listeners of the original HTML content. This is so I don't have to * re-setup events for things like lazy images, they'd just work as expected. */ const placeholder = document.createComment(""); htmlContent.replaceWith(placeholder); contentElement.replaceChildren(htmlContent); htmlContent.removeAttribute("data-popover-html"); cleanupOnHidePopover = () => { htmlContent.setAttribute("data-popover-html", ""); placeholder.replaceWith(htmlContent); placeholder.remove(); }; } else { return; } const contentMaxWidth = activeTarget.dataset.popoverMaxWidth || defaultMaxWidth; if (activeTarget.dataset.popoverTextAlign !== undefined) { contentElement.style.textAlign = activeTarget.dataset.popoverTextAlign; } else { contentElement.style.removeProperty("text-align"); } contentElement.style.maxWidth = contentMaxWidth; activeTarget.classList.add("popover-active"); document.addEventListener("keydown", handleHidePopoverOnEscape); window.addEventListener("scroll", queueRepositionContainer); window.addEventListener("resize", queueRepositionContainer); observer.observe(containerElement); } function repositionContainer() { if (activeTarget === null) return; containerElement.style.display = "block"; const targetBounds = activeTarget.dataset.popoverAnchor !== undefined ? activeTarget.querySelector(activeTarget.dataset.popoverAnchor).getBoundingClientRect() : activeTarget.getBoundingClientRect(); const containerBounds = containerElement.getBoundingClientRect(); const containerInlinePadding = parseInt(containerComputedStyle.getPropertyValue("padding-inline")); const targetBoundsWidthOffset = targetBounds.width * (activeTarget.dataset.popoverTargetOffset || 0.5); const position = activeTarget.dataset.popoverPosition || "below"; const popoverOffest = activeTarget.dataset.popoverOffset || 0.5; const left = Math.round(targetBounds.left + targetBoundsWidthOffset - (containerBounds.width * popoverOffest)); if (left < 0) { containerElement.style.left = 0; containerElement.style.removeProperty("right"); containerElement.style.setProperty("--triangle-offset", targetBounds.left - containerInlinePadding + targetBoundsWidthOffset + "px"); } else if (left + containerBounds.width > window.innerWidth) { containerElement.style.removeProperty("left"); containerElement.style.right = 0; containerElement.style.setProperty("--triangle-offset", containerBounds.width - containerInlinePadding - (document.documentElement.clientWidth - targetBounds.left - targetBoundsWidthOffset) + -1 + "px"); } else { containerElement.style.removeProperty("right"); containerElement.style.left = left + "px"; containerElement.style.setProperty("--triangle-offset", ((targetBounds.left + targetBoundsWidthOffset) - left - containerInlinePadding) + -1 + "px"); } const distanceFromTarget = activeTarget.dataset.popoverMargin || defaultDistanceFromTarget; const topWhenAbove = targetBounds.top + window.scrollY - containerBounds.height; const topWhenBelow = targetBounds.top + window.scrollY + targetBounds.height; if ( position === "above" && topWhenAbove > window.scrollY || (position === "below" && topWhenBelow + containerBounds.height > window.scrollY + window.innerHeight) ) { containerElement.classList.add("position-above"); frameElement.style.removeProperty("margin-top"); frameElement.style.marginBottom = distanceFromTarget; containerElement.style.top = topWhenAbove + "px"; } else { containerElement.classList.remove("position-above"); frameElement.style.removeProperty("margin-bottom"); frameElement.style.marginTop = distanceFromTarget; containerElement.style.top = topWhenBelow + "px"; } } function hidePopover() { if (activeTarget === null) return; activeTarget.classList.remove("popover-active"); containerElement.style.display = "none"; containerElement.style.removeProperty("top"); containerElement.style.removeProperty("left"); containerElement.style.removeProperty("right"); document.removeEventListener("keydown", handleHidePopoverOnEscape); window.removeEventListener("scroll", queueRepositionContainer); window.removeEventListener("resize", queueRepositionContainer); observer.unobserve(containerElement); if (cleanupOnHidePopover !== null) { cleanupOnHidePopover(); cleanupOnHidePopover = null; } activeTarget = null; } function handleHidePopoverOnEscape(event) { if (event.key === "Escape") { hidePopover(); } } export function setupPopovers() { const targets = document.querySelectorAll("[data-popover-type]"); for (let i = 0; i < targets.length; i++) { const target = targets[i]; if (target.dataset.popoverTrigger === "click") { target.addEventListener("click", handleMouseEnter); } else { target.addEventListener("mouseenter", handleMouseEnter); } target.addEventListener("mouseleave", handleMouseLeave); } } ================================================ FILE: internal/glance/static/js/templating.js ================================================ export function elem(tag = "div") { return document.createElement(tag); } export function fragment(...children) { const f = document.createDocumentFragment(); if (children) f.append(...children); return f; } export function text(str = "") { return document.createTextNode(str); } export function repeat(n, fn) { const elems = Array(n); for (let i = 0; i < n; i++) elems[i] = fn(i); return elems; } export function find(selector) { return document.querySelector(selector); } export function findAll(selector) { return document.querySelectorAll(selector); } HTMLCollection.prototype.map = function(fn) { return Array.from(this).map(fn); } HTMLCollection.prototype.indexOf = function(element) { return Array.prototype.indexOf.call(this, element); } const ep = HTMLElement.prototype; const fp = DocumentFragment.prototype; const tp = Text.prototype; ep.classes = function(...classes) { this.classList.add(...classes); return this; } ep.find = function(selector) { return this.querySelector(selector); } ep.findAll = function(selector) { return this.querySelectorAll(selector); } ep.classesIf = function(cond, ...classes) { cond ? this.classList.add(...classes) : this.classList.remove(...classes); return this; } ep.hide = function() { this.style.display = "none"; return this; } ep.show = function() { this.style.removeProperty("display"); return this; } ep.showIf = function(cond) { cond ? this.show() : this.hide(); return this; } ep.isHidden = function() { return this.style.display === "none"; } ep.clearClasses = function(...classes) { classes.length ? this.classList.remove(...classes) : this.className = ""; return this; } ep.hasClass = function(className) { return this.classList.contains(className); } ep.attr = function(name, value) { this.setAttribute(name, value); return this; } ep.attrs = function(attrs) { for (const [name, value] of Object.entries(attrs)) this.setAttribute(name, value); return this; } ep.tap = function(fn) { fn(this); return this; } ep.text = function(text) { this.innerText = text; return this; } ep.html = function(html) { this.innerHTML = html; return this; } ep.appendTo = function(parent) { parent.appendChild(this); return this; } ep.swapWith = function(element) { this.replaceWith(element); return element; } ep.on = function(event, callback, options) { if (typeof event === "string") { this.addEventListener(event, callback, options); return this; } for (let i = 0; i < event.length; i++) this.addEventListener(event[i], callback, options); return this; } const epAppend = ep.append; ep.append = function(...children) { epAppend.apply(this, children); return this; } ep.duplicate = function(n) { const elems = Array(n); for (let i = 0; i < n; i++) elems[i] = this.cloneNode(true); return elems; } ep.styles = function(s) { Object.assign(this.style, s); return this; } ep.clearStyles = function(...props) { for (let i = 0; i < props.length; i++) this.style.removeProperty(props[i]); return this; } ep.disable = function() { this.disabled = true; return this; } ep.enable = function() { this.disabled = false; return this; } const epAnimate = ep.animate; ep.animate = function(anim, callback) { const a = epAnimate.call(this, anim.keyframes, anim.options); if (callback) a.onfinish = () => callback(this, a); return this; } ep.animateUpdate = function(update, exit, entrance) { this.animate(exit, () => { update(this); this.animate(entrance); }); return this; } ep.styleVar = function(name, value) { this.style.setProperty(`--${name}`, value); return this; } ep.component = function (methods) { this.component = methods; return this; } const fpAppend = fp.append; fp.append = function(...children) { fpAppend.apply(this, children); return this; } fp.appendTo = function(parent) { parent.appendChild(this); return this; } tp.text = function(text) { this.nodeValue = text; return this; } ================================================ FILE: internal/glance/static/js/todo.js ================================================ import { elem, fragment } from "./templating.js"; import { animateReposition } from "./animations.js"; import { clamp, Vec2, toggleableEvents, throttledDebounce } from "./utils.js"; const trashIconSvg = ` `; export default function(element) { element.swapWith( Todo(element.dataset.todoId) ) } function itemAnim(height, entrance = true) { const visible = { height: height + "px", opacity: 1 }; const hidden = { height: "0", opacity: 0, padding: "0" }; return { keyframes: [ entrance ? hidden : visible, entrance ? visible : hidden ], options: { duration: 200, easing: "ease" } } } function inputMarginAnim(entrance = true) { const amount = "1.5rem"; return { keyframes: [ { marginBottom: entrance ? "0px" : amount }, { marginBottom: entrance ? amount : "0" } ], options: { duration: 200, easing: "ease", fill: "forwards" } } } function loadFromLocalStorage(id) { return JSON.parse(localStorage.getItem(`todo-${id}`) || "[]"); } function saveToLocalStorage(id, data) { localStorage.setItem(`todo-${id}`, JSON.stringify(data)); } function Item(unserialize = {}, onUpdate, onDelete, onEscape, onDragStart) { let item, input, inputArea; const serializeable = { text: unserialize.text || "", checked: unserialize.checked || false }; item = elem().classes("todo-item", "flex", "gap-10", "items-center").append( elem("input") .classes("todo-item-checkbox", "shrink-0") .styles({ marginTop: "-0.1rem" }) .attrs({ type: "checkbox" }) .on("change", (e) => { serializeable.checked = e.target.checked; onUpdate(); }) .tap(self => self.checked = serializeable.checked), input = autoScalingTextarea(textarea => inputArea = textarea .classes("todo-item-text") .attrs({ placeholder: "empty task", spellcheck: "false" }) .on("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); } else if (e.key === "Escape") { e.preventDefault(); onEscape(); } }) .on("input", () => { serializeable.text = inputArea.value; onUpdate(); }) ).classes("min-width-0", "grow").append( elem() .classes("todo-item-drag-handle") .on("mousedown", (e) => onDragStart(e, item)) ), elem("button") .classes("todo-item-delete", "shrink-0") .html(trashIconSvg) .on("click", () => onDelete(item)) ); input.component.setValue(serializeable.text); return item.component({ focusInput: () => inputArea.focus(), serialize: () => serializeable }); } function Todo(id) { let items, input, inputArea, inputContainer, lastAddedItem; let queuedForRemoval = 0; let reorderable; let isDragging = false; const onDragEnd = () => isDragging = false; const onDragStart = (event, element) => { isDragging = true; reorderable.component.onDragStart(event, element); }; const saveItems = () => { if (isDragging) return; saveToLocalStorage( id, items.children.map(item => item.component.serialize()) ); }; const onItemRepositioned = () => saveItems(); const debouncedOnItemUpdate = throttledDebounce(saveItems, 10, 1000); const onItemDelete = (item) => { if (lastAddedItem === item) lastAddedItem = null; const height = item.clientHeight; queuedForRemoval++; item.animate(itemAnim(height, false), () => { item.remove(); queuedForRemoval--; saveItems(); }); if (items.children.length - queuedForRemoval === 0) inputContainer.animate(inputMarginAnim(false)); }; const newItem = (data) => Item( data, debouncedOnItemUpdate, onItemDelete, () => inputArea.focus(), onDragStart ); const addNewItem = (itemText, prepend) => { const totalItemsBeforeAppending = items.children.length; const item = lastAddedItem = newItem({ text: itemText }); prepend ? items.prepend(item) : items.append(item); saveItems(); const height = item.clientHeight; item.animate(itemAnim(height)); if (totalItemsBeforeAppending === 0) inputContainer.animate(inputMarginAnim()); }; const handleInputKeyDown = (e) => { switch (e.key) { case "Enter": e.preventDefault(); const value = e.target.value.trim(); if (value === "") return; addNewItem(value, e.ctrlKey); input.component.setValue(""); break; case "Escape": e.target.blur(); break; case "ArrowDown": if (!lastAddedItem) return; e.preventDefault(); lastAddedItem.component.focusInput(); break; } }; items = elem() .classes("todo-items") .append( ...loadFromLocalStorage(id).map(data => newItem(data)) ); return fragment().append( inputContainer = elem() .classes("todo-input", "flex", "gap-10", "items-center") .classesIf(items.children.length > 0, "margin-bottom-15") .styles({ paddingRight: "2.5rem" }) .append( elem().classes("todo-plus-icon", "shrink-0"), input = autoScalingTextarea(textarea => inputArea = textarea .on("keydown", handleInputKeyDown) .attrs({ placeholder: "Add a task", spellcheck: "false" }) ).classes("grow", "min-width-0") ), reorderable = verticallyReorderable(items, onItemRepositioned, onDragEnd), ); } // See https://css-tricks.com/the-cleanest-trick-for-autogrowing-textareas/ export function autoScalingTextarea(yieldTextarea = null) { let textarea, mimic; const updateMimic = (newValue) => mimic.text(newValue + ' '); const container = elem().classes("auto-scaling-textarea-container").append( textarea = elem("textarea") .classes("auto-scaling-textarea") .on("input", () => updateMimic(textarea.value)), mimic = elem().classes("auto-scaling-textarea-mimic") ) if (typeof yieldTextarea === "function") yieldTextarea(textarea); return container.component({ setValue: (newValue) => { textarea.value = newValue; updateMimic(newValue); }}); } export function verticallyReorderable(itemsContainer, onItemRepositioned, onDragEnd) { const classToAddToDraggedItem = "is-being-dragged"; const currentlyBeingDragged = { element: null, initialIndex: null, clientOffset: Vec2.new(), }; const decoy = { element: null, currentIndex: null, }; const draggableContainer = { element: null, initialRect: null, }; const lastClientPos = Vec2.new(); let initialScrollY = null; let addDocumentEvents, removeDocumentEvents; const handleReposition = (event) => { if (currentlyBeingDragged.element == null) return; if (event.clientY !== undefined && event.clientX !== undefined) lastClientPos.setFromEvent(event); const client = lastClientPos; const container = draggableContainer; const item = currentlyBeingDragged; const scrollOffset = window.scrollY - initialScrollY; const offsetY = client.y - container.initialRect.y - item.clientOffset.y + scrollOffset; const offsetX = client.x - container.initialRect.x - item.clientOffset.x; const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth; const viewportWidth = window.innerWidth - scrollbarWidth; const confinedX = clamp( offsetX, -container.initialRect.x, viewportWidth - container.initialRect.x - container.initialRect.width ); container.element.styles({ transform: `translate(${confinedX}px, ${offsetY}px)`, }); const containerTop = client.y - item.clientOffset.y; const containerBottom = client.y + container.initialRect.height - item.clientOffset.y; let swapWithLast = true; let swapWithIndex = null; for (let i = 0; i < itemsContainer.children.length; i++) { const childRect = itemsContainer.children[i].getBoundingClientRect(); const topThreshold = childRect.top + childRect.height * .6; const bottomThreshold = childRect.top + childRect.height * .4; if (containerBottom > topThreshold) { if (containerTop < bottomThreshold && i != decoy.currentIndex) { swapWithIndex = i; swapWithLast = false; break; } continue; }; swapWithLast = false; if (i == decoy.currentIndex || i-1 == decoy.currentIndex) break; swapWithIndex = (i < decoy.currentIndex) ? i : i-1; break; } const lastItemIndex = itemsContainer.children.length - 1; if (swapWithLast && decoy.currentIndex != lastItemIndex) swapWithIndex = lastItemIndex; if (swapWithIndex === null) return; const diff = swapWithIndex - decoy.currentIndex; if (Math.abs(diff) > 1) { swapWithIndex = decoy.currentIndex + Math.sign(diff); } const siblingToSwapWith = itemsContainer.children[swapWithIndex]; if (siblingToSwapWith.isCurrentlyAnimating) return; const animateDecoy = animateReposition(decoy.element); const animateChild = animateReposition( siblingToSwapWith, () => { siblingToSwapWith.isCurrentlyAnimating = false; handleReposition({ clientX: client.x, clientY: client.y, }); } ); siblingToSwapWith.isCurrentlyAnimating = true; if (swapWithIndex > decoy.currentIndex) decoy.element.before(siblingToSwapWith); else decoy.element.after(siblingToSwapWith); decoy.currentIndex = itemsContainer.children.indexOf(decoy.element); animateDecoy(); animateChild(); } const handleRelease = (event) => { if (event.buttons != 0) return; removeDocumentEvents(); const item = currentlyBeingDragged; const element = item.element; element.styles({ pointerEvents: "none" }); const animate = animateReposition(element, () => { item.element = null; element .clearClasses(classToAddToDraggedItem) .clearStyles("pointer-events"); if (typeof onDragEnd === "function") onDragEnd(element); if (item.initialIndex != decoy.currentIndex && typeof onItemRepositioned === "function") onItemRepositioned(element, item.initialIndex, decoy.currentIndex); }); decoy.element.swapWith(element); draggableContainer.element.append(decoy.element); draggableContainer.element.clearStyles("transform", "width"); item.element = null; decoy.element.remove(); animate(); } const preventDefault = (event) => { event.preventDefault(); }; const handleGrab = (event, element) => { if (currentlyBeingDragged.element != null) return; event.preventDefault(); const item = currentlyBeingDragged; if (item.element != null) return; addDocumentEvents(); initialScrollY = window.scrollY; const client = lastClientPos.setFromEvent(event); const elementRect = element.getBoundingClientRect(); item.element = element; item.initialIndex = decoy.currentIndex = itemsContainer.children.indexOf(element); item.clientOffset.set(client.x - elementRect.x, client.y - elementRect.y); // We use getComputedStyle here to get width and height because .clientWidth and .clientHeight // return integers and not the real float values, which can cause the decoy to be off by a pixel const elementStyle = getComputedStyle(element); const initialWidth = elementStyle.width; decoy.element = elem().classes("drag-and-drop-decoy").styles({ height: elementStyle.height, width: initialWidth, }); const container = draggableContainer; element.swapWith(decoy.element); container.element.append(element); element.classes(classToAddToDraggedItem); decoy.element.animate({ keyframes: [{ transform: "scale(.9)", opacity: 0, offset: 0 }], options: { duration: 300, easing: "ease" } }) container.element.styles({ width: initialWidth, transform: "none" }); container.initialRect = container.element.getBoundingClientRect(); const offsetY = elementRect.y - container.initialRect.y; const offsetX = elementRect.x - container.initialRect.x; container.element.styles({ transform: `translate(${offsetX}px, ${offsetY}px)` }); } [addDocumentEvents, removeDocumentEvents] = toggleableEvents(document, { "mousemove": handleReposition, "scroll": handleReposition, "mousedown": preventDefault, "contextmenu": preventDefault, "mouseup": handleRelease, }); return elem().classes("drag-and-drop-container").append( itemsContainer, draggableContainer.element = elem().classes("drag-and-drop-draggable") ).component({ onDragStart: handleGrab }); } ================================================ FILE: internal/glance/static/js/utils.js ================================================ export 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); }; }; export function isElementVisible(element) { return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length); } export function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } // NOTE: inconsistent behavior between browsers when it comes to // whether the newly opened tab gets focused or not, potentially // depending on the event that this function is called from export function openURLInNewTab(url, focus = true) { const newWindow = window.open(url, '_blank', 'noopener,noreferrer'); if (focus && newWindow != null) newWindow.focus(); } export class Vec2 { constructor(x, y) { this.x = x; this.y = y; } static new(x = 0, y = 0) { return new Vec2(x, y); } static fromEvent(event) { return new Vec2(event.clientX, event.clientY); } setFromEvent(event) { this.x = event.clientX; this.y = event.clientY; return this; } set(x, y) { this.x = x; this.y = y; return this; } } export function toggleableEvents(element, eventToHandlerMap) { return [ () => { for (const [event, handler] of Object.entries(eventToHandlerMap)) { element.addEventListener(event, handler); } }, () => { for (const [event, handler] of Object.entries(eventToHandlerMap)) { element.removeEventListener(event, handler); } } ]; } ================================================ FILE: internal/glance/templates/bookmarks.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{- range .Groups }}
{{- if ne .Title "" }}
{{ .Title }}
{{- end }}
    {{- range .Links }}
  • {{- if ne "" .Icon.URL }}
    {{- end }} {{ .Title }}
    {{- if .Description }}
    {{ .Description }}
    {{- end }}
  • {{- end }}
{{- end }}
{{ end }} ================================================ FILE: internal/glance/templates/calendar.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ end }} ================================================ FILE: internal/glance/templates/change-detection.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/clock.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ if gt (len .Timezones) 0 }}
    {{ range .Timezones }}
  • {{ if ne .Label "" }}{{ .Label }}{{ else }}{{ .Timezone }}{{ end }}
  • {{ end }}
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/custom-api.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}{{ if .Frameless }}widget-content-frameless{{ end }}{{ end }} {{ define "widget-content" }} {{ .CompiledHTML }} {{ end }} ================================================ FILE: internal/glance/templates/dns-stats.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ .Stats.TotalQueries | formatNumber }}
QUERIES
{{ .Stats.BlockedPercent }}%
BLOCKED
{{ if gt .Stats.ResponseTime 0 }}
{{ .Stats.ResponseTime | formatNumber }}ms
LATENCY
{{ else }}
{{ .Stats.DomainsBlocked | formatApproxNumber }}
DOMAINS
{{ end }}
{{ $showGraph := not (or .HideGraph (eq (len .Stats.Series) 0)) }} {{ if $showGraph }}
{{ range $i, $column := .Stats.Series }}
{{ $column.Queries | formatNumber }}
QUERIES
{{ $column.PercentBlocked }}%
BLOCKED
{{ if gt $column.PercentTotal 0}}
{{ if ne $column.Queries $column.Blocked }}
{{ end }} {{ if gt $column.PercentBlocked 0 }}
{{ end }}
{{ end }}
{{ index $.TimeLabels $i }}
{{ end }}
{{ end }} {{ if and (not .HideTopDomains) .Stats.TopBlockedDomains }}
Top blocked domains
    {{ range .Stats.TopBlockedDomains }}
  • {{ .Domain }}
    {{ .PercentBlocked }}%
  • {{ end }}
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/docker-containers.html ================================================ {{ template "widget-base.html" . }} {{- define "widget-content" }}
    {{- range .Containers }}
  • {{- if .URL }} {{ .Name }} {{- else }}
    {{ .Name }}
    {{- end }} {{- if .Description }}
    {{ .Description }}
    {{- end }}
    {{ template "state-icon" .StateIcon }}
  • {{- else }}
    No containers available to show.
    {{- end }}
{{- end }} {{- define "state-icon" }} {{- if eq . "ok" }} {{- else if eq . "warn" }} {{- else if eq . "paused" }} {{- else }} {{- end }} {{- end }} ================================================ FILE: internal/glance/templates/document.html ================================================ {{ block "document-head-before" . }}{{ end }} {{ block "document-title" . }}{{ end }} {{ if .App.Config.Theme.CustomCSSFile }}{{ end }} {{ block "document-head-after" . }}{{ end }} {{ if .App.Config.Document.Head }}{{ .App.Config.Document.Head }}{{ end }} {{ template "document-body" . }} ================================================ FILE: internal/glance/templates/extension.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}{{ if .Extension.Frameless }}widget-content-frameless{{ end }}{{ end }} {{ define "widget-content" }} {{ .Extension.Content }} {{ end }} ================================================ FILE: internal/glance/templates/footer.html ================================================ {{ if not .App.Config.Branding.HideFooter }}
{{ if eq "" .App.Config.Branding.CustomFooter }}
Glance {{ if ne "dev" .App.Version }}{{ .App.Version }}{{ else }}({{ .App.Version }}){{ end }}
{{ else }} {{ .App.Config.Branding.CustomFooter }} {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/forum-posts.html ================================================ {{ template "widget-base.html" . }} {{- define "widget-content" }}
    {{- range .Posts }}
  • {{- if $.ShowThumbnails }} {{- if .IsCrosspost }} {{- else if .ThumbnailUrl }} {{- else if .TargetUrl }} {{- else }} {{- end }} {{- end }}
    {{ .Title }} {{- if .Tags }} {{- end }}
    • {{ .Score | formatApproxNumber }} points
    • {{ .CommentCount | formatApproxNumber }} comments
    • {{- if .TargetUrl }}
    • {{ .TargetUrlDomain }}
    • {{- end }}
  • {{- end }}
{{- end }} ================================================ FILE: internal/glance/templates/group.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }}
{{- range $i, $widget := .Widgets }} {{- end }}
{{- range $i, $widget := .Widgets }}
{{- .Render -}}
{{- end }}
{{ end }} ================================================ FILE: internal/glance/templates/iframe.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/login.html ================================================ {{- template "document.html" . }} {{- define "document-title" }}Login{{ end }} {{- define "document-head-before" }} {{- end }} {{- define "document-head-after" }} {{- end }} {{- define "document-body" }}

Login

{{ template "footer.html" . }}
{{- end }} ================================================ FILE: internal/glance/templates/manifest.json ================================================ { "name": "{{ .App.Config.Branding.AppName }}", "display": "standalone", "background_color": "{{ .App.Config.Branding.AppBackgroundColor }}", "theme_color": "{{ .App.Config.Branding.AppBackgroundColor }}", "scope": "/", "start_url": "/", "icons": [ { "src": "{{ .App.Config.Branding.AppIconURL }}", "type": "image/png", "sizes": "512x512" } ] } ================================================ FILE: internal/glance/templates/markets.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ range .Markets }}
{{ .Symbol }}
{{ .Name }}
{{ printf "%+.2f" .PercentChange }}%
{{ .Currency }}{{ .Price | formatPriceWithPrecision .PriceHint }}
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/monitor-compact.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }} {{ if not (and .ShowFailingOnly (not .HasFailing)) }}
    {{ range .Sites }} {{ if and $.ShowFailingOnly (eq .StatusStyle "ok" ) }}{{ continue }}{{ end }}
    {{ template "site" . }}
    {{ end }}
{{ else }}

All sites are online

{{ end }} {{ end }} {{ define "site" }} {{ .Title }} {{ if not .Status.TimedOut }}
{{ .Status.ResponseTime.Milliseconds | formatNumber }}ms
{{ end }} {{ if eq .StatusStyle "ok" }}
{{ else }}
{{ end }} {{ end }} ================================================ FILE: internal/glance/templates/monitor.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }} {{ if not (and .ShowFailingOnly (not .HasFailing)) }}
    {{ range .Sites }} {{ if and $.ShowFailingOnly (eq .StatusStyle "ok" ) }} {{ continue }} {{ end }}
    {{ template "site" . }}
    {{ end }}
{{ else }}

All sites are online

{{ end }} {{ end }} {{ define "site" }} {{ if .Icon.URL }} {{ end }}
{{ .Title }}
    {{ if not .Status.Error }}
  • {{ .StatusText }}
  • {{ .Status.ResponseTime.Milliseconds | formatNumber }}ms
  • {{ else if .Status.TimedOut }}
  • Timed Out
  • {{ else }}
  • ERROR
  • {{ end }}
{{ if eq .StatusStyle "ok" }}
{{ else }}
{{ end }} {{ end }} ================================================ FILE: internal/glance/templates/old-calendar.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ .Calendar.CurrentMonthName }}
  • Week {{ .Calendar.CurrentWeekNumber }}
  • {{ .Calendar.CurrentYear }}
{{ if .StartSunday }}
Su
{{ end }}
Mo
Tu
We
Th
Fr
Sa
{{ if not .StartSunday }}
Su
{{ end }}
{{ range .Calendar.Days }}
{{ . }}
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/page-content.html ================================================ {{ if .Page.ShowMobileHeader }}
{{ .Page.Title }}
{{ end }} {{ if .Page.HeadWidgets }}
{{- range .Page.HeadWidgets }} {{- .Render }} {{- end }}
{{ end }}
{{- range .Page.Columns }}
{{- range .Widgets }} {{- .Render }} {{- end }}
{{- end }}
================================================ FILE: internal/glance/templates/page.html ================================================ {{ template "document.html" . }} {{ define "document-title" }}{{ .Page.Title }}{{ end }} {{ define "document-head-after" }} {{ end }} {{ define "navigation-links" }} {{ range .App.Config.Pages }} {{ .Title }} {{ end }} {{ end }} {{ define "document-body" }}
{{ if not .Page.HideDesktopNavigation }}
{{ if not .App.Config.Theme.DisablePicker }}
{{ .Request.Theme.PreviewHTML }}
{{ end }} {{- if .App.RequiresAuth }} {{- end }}
{{ end }}
{{ range $i, $column := .Page.Columns }} {{ end }}
{{ if not .App.Config.Theme.DisablePicker }}
{{ .App.Config.Theme.PreviewHTML }} {{ range $_, $preset := .App.Config.Theme.Presets.Items }} {{ $preset.PreviewHTML }} {{ end }}
Change theme
{{ .Request.Theme.PreviewHTML }}
{{ end }} {{ if .App.RequiresAuth }}
Logout
{{ end }}

{{ .Page.Title }}

Loading
{{ template "footer.html" . }}
{{ end }} ================================================ FILE: internal/glance/templates/reddit-horizontal-cards.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/reddit-vertical-cards.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }}
{{ range .Posts }}
{{ if ne "" .ThumbnailUrl }}
{{ end }}
{{ if ne "" .TargetUrl }} {{ .TargetUrlDomain }} {{ else }}
/r/{{ $.Subreddit }}
{{ end }} {{ .Title }}
  • {{ .Score | formatApproxNumber }} points
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/releases.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
    {{ range .Releases }}
  • {{ .Name }} {{ if $.ShowSourceIcon }} {{ end }}
    • {{ .Version }}
    • {{ if gt .Downvotes 3 }}
    • {{ .Downvotes | formatNumber }} ⚠
    • {{ end }}
  • {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/repository.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }} {{ .Repository.Name }}
  • {{ .Repository.Stars | formatNumber }} stars
  • {{ .Repository.Forks | formatNumber }} forks
{{ if gt (len .Repository.Commits) 0 }}
Last {{ .CommitsLimit }} commits
    {{ range .Repository.Commits }}
  • {{ end }}
{{ end }} {{ if gt (len .Repository.PullRequests) 0 }}
Open pull requests ({{ .Repository.OpenPullRequests | formatNumber }} total)
    {{ range .Repository.PullRequests }}
  • {{ end }}
    {{ range .Repository.PullRequests }}
  • {{ .Title }}
  • {{ end }}
{{ end }} {{ if gt (len .Repository.Issues) 0 }}
Open issues ({{ .Repository.OpenIssues | formatNumber }} total)
    {{ range .Repository.Issues }}
  • {{ end }}
{{ end }} {{ end }} ================================================ FILE: internal/glance/templates/rss-detailed-list.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
    {{ range .Items }}
  • {{ if ne "" .ImageURL }} {{ else }} {{ end }}
    {{ .Title }} {{ if ne "" .Description }}

    {{ .Description }}

    {{ end }} {{ if gt (len .Categories) 0 }}
      {{ range .Categories }}
    • {{ . }}
    • {{ end }}
    {{ end }}
  • {{ else }}
  • {{ .NoItemsMessage }}
  • {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/rss-horizontal-cards-2.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ if gt (len .Items) 0 }} {{ else }}
{{ .NoItemsMessage }}
{{ end }} {{ end }} ================================================ FILE: internal/glance/templates/rss-horizontal-cards.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ if gt (len .Items) 0 }} {{ else }}
{{ .NoItemsMessage }}
{{ end }} {{ end }} ================================================ FILE: internal/glance/templates/rss-list.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/search.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/server-stats.html ================================================ {{ template "widget-base.html" . }} {{- define "widget-content" }} {{- range .Servers }}
{{ if .Name }}{{ .Name }}{{ else }}{{ .Info.Hostname }}{{ end }}
{{- if .IsReachable }} {{ if .Info.HostInfoIsAvailable }}{{ else }}unknown{{ end }} uptime {{- else }} unreachable {{- end }}
{{- if .IsReachable }}
PLATFORM
{{ if .Info.HostInfoIsAvailable }}{{ .Info.Platform }}{{ else }}Unknown{{ end }}
{{- end }}
CPU
{{- if and .Info.CPU.TemperatureIsAvailable (ge .Info.CPU.TemperatureC 80) }} {{- end }}
{{ if .Info.CPU.LoadIsAvailable }}{{ .Info.CPU.Load1Percent }} %{{ else }}n/a{{ end }}
{{- if .Info.CPU.LoadIsAvailable }}
1M AVG
{{ .Info.CPU.Load1Percent }} %
15M AVG
{{ .Info.CPU.Load15Percent }} %
{{- if .Info.CPU.TemperatureIsAvailable }}
TEMP C
{{ .Info.CPU.TemperatureC }} °
{{- end }}
{{- end }}
{{- if .Info.CPU.LoadIsAvailable }}
{{- end }}
RAM
{{ if .Info.Memory.IsAvailable }}{{ .Info.Memory.UsedPercent }} %{{ else }}n/a{{ end }}
{{- if .Info.Memory.IsAvailable }}
RAM
{{ .Info.Memory.UsedMB | formatServerMegabytes }} / {{ .Info.Memory.TotalMB | formatServerMegabytes }}
{{- if and (not .HideSwap) .Info.Memory.SwapIsAvailable }}
SWAP
{{ .Info.Memory.SwapUsedMB | formatServerMegabytes }} / {{ .Info.Memory.SwapTotalMB | formatServerMegabytes }}
{{- end }}
{{- end }}
{{- if .Info.Memory.IsAvailable }}
{{- if and (not .HideSwap) .Info.Memory.SwapIsAvailable }}
{{- end }} {{- end }}
DISK
{{ if .Info.Mountpoints }}{{ (index .Info.Mountpoints 0).UsedPercent }} %{{ else }}n/a{{ end }}
{{- if .Info.Mountpoints }}
    {{- range .Info.Mountpoints }}
  • {{ if .Name }}{{ .Name }}{{ else }}{{ .Path }}{{ end }}
    {{ .UsedMB | formatServerMegabytes }} / {{ .TotalMB | formatServerMegabytes }}
  • {{- end }}
{{- end }}
{{- if .Info.Mountpoints }}
{{- if ge (len .Info.Mountpoints) 2 }}
{{- end }} {{- end }}
{{- end }} {{- end }} ================================================ FILE: internal/glance/templates/split-column.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }}
{{ range .Widgets }} {{ .Render }} {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/theme-preset-preview.html ================================================ {{- $background := "hsl(240, 8%, 9%)" | safeCSS }} {{- $primary := "hsl(43, 50%, 70%)" | safeCSS }} {{- $positive := "hsl(43, 50%, 70%)" | safeCSS }} {{- $negative := "hsl(0, 70%, 70%)" | safeCSS }} {{- if .BackgroundColor }}{{ $background = .BackgroundColor.String | safeCSS }}{{ end }} {{- if .PrimaryColor }} {{- $primary = .PrimaryColor.String | safeCSS }} {{- if not .PositiveColor }} {{- $positive = $primary }} {{- else }} {{- $positive = .PositiveColor.String | safeCSS }} {{- end }} {{- end }} {{- if .NegativeColor }}{{ $negative = .NegativeColor.String | safeCSS }}{{ end }} ================================================ FILE: internal/glance/templates/theme-style.gotmpl ================================================ :root { {{ if .BackgroundColor }} --bgh: {{ .BackgroundColor.H }}; --bgs: {{ .BackgroundColor.S }}%; --bgl: {{ .BackgroundColor.L }}%; {{ end }} {{ if ne 0.0 .ContrastMultiplier }}--cm: {{ .ContrastMultiplier }};{{ end }} {{ if ne 0.0 .TextSaturationMultiplier }}--tsm: {{ .TextSaturationMultiplier }};{{ end }} {{ if .PrimaryColor }}--color-primary: {{ .PrimaryColor.String | safeCSS }};{{ end }} {{ if .PositiveColor }}--color-positive: {{ .PositiveColor.String | safeCSS }};{{ end }} {{ if .NegativeColor }}--color-negative: {{ .NegativeColor.String | safeCSS }};{{ end }} } ================================================ FILE: internal/glance/templates/todo.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
{{ end }} ================================================ FILE: internal/glance/templates/twitch-channels.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
    {{ range .Channels }}
  • {{ if .IsLive }}

    {{ .StreamTitle }}

    {{ end }} {{ if .Exists }} {{ else }} {{ end }}
    {{ .Name }} {{ if .Exists }} {{ if .IsLive }} {{ if .Category }} {{ .Category }} {{ end }}
    • {{ .ViewersCount | formatApproxNumber }} viewers
    {{ else }}
    Offline
    {{ end }} {{ else }}
    Not found
    {{ end }}
  • {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/twitch-games-list.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content" }}
    {{ range .Categories }}
  • {{ .Name }}
    • {{ .ViewersCount | formatApproxNumber }} viewers
    • {{ if .IsNew }}
    • NEW
    • {{ end }}
      {{ range $i, $tag := .Tags }} {{ if eq $i 0 }}
    • {{ $tag.Name }}
    • {{ else }}
    • {{ $tag.Name }}
    • {{ end }} {{ end }}
  • {{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/v0.7-update-notice-page.html ================================================ 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.

================================================ FILE: internal/glance/templates/video-card-contents.html ================================================ {{ define "video-card-contents" }} {{ end }} ================================================ FILE: internal/glance/templates/videos-grid.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }}
{{ range .Videos }}
{{ template "video-card-contents" . }}
{{ end }}
{{ end }} ================================================ FILE: internal/glance/templates/videos-vertical-list.html ================================================ {{ template "widget-base.html" . }} {{- define "widget-content" }} {{- end }} ================================================ FILE: internal/glance/templates/videos.html ================================================ {{ template "widget-base.html" . }} {{ define "widget-content-classes" }}widget-content-frameless{{ end }} {{ define "widget-content" }} {{ end }} ================================================ FILE: internal/glance/templates/weather.html ================================================ {{ 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 }} ================================================ FILE: internal/glance/templates/widget-base.html ================================================
{{- 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}}
================================================ FILE: internal/glance/templates.go ================================================ package glance import ( "fmt" "html/template" "math" "strconv" "golang.org/x/text/language" "golang.org/x/text/message" ) var intl = message.NewPrinter(language.English) var globalTemplateFunctions = template.FuncMap{ "formatApproxNumber": formatApproxNumber, "formatNumber": intl.Sprint, "safeCSS": func(str string) template.CSS { return template.CSS(str) }, "safeURL": func(str string) template.URL { return template.URL(str) }, "safeHTML": func(str string) template.HTML { return template.HTML(str) }, "absInt": func(i int) int { return int(math.Abs(float64(i))) }, "formatPrice": func(price float64) string { return intl.Sprintf("%.2f", price) }, "formatPriceWithPrecision": func(precision int, price float64) string { return intl.Sprintf("%."+strconv.Itoa(precision)+"f", price) }, "dynamicRelativeTimeAttrs": dynamicRelativeTimeAttrs, "formatServerMegabytes": func(mb uint64) template.HTML { var value string var label string if mb < 1_000 { value = strconv.FormatUint(mb, 10) label = "MB" } else if mb < 1_000_000 { if mb < 10_000 { value = fmt.Sprintf("%.1f", float64(mb)/1_000) } else { value = strconv.FormatUint(mb/1_000, 10) } label = "GB" } else { value = fmt.Sprintf("%.1f", float64(mb)/1_000_000) label = "TB" } return template.HTML(value + ` ` + label + ``) }, } func mustParseTemplate(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 } func formatApproxNumber(count int) string { if count < 1_000 { return strconv.Itoa(count) } if count < 10_000 { return strconv.FormatFloat(float64(count)/1_000, 'f', 1, 64) + "k" } if count < 1_000_000 { return strconv.Itoa(count/1_000) + "k" } return strconv.FormatFloat(float64(count)/1_000_000, 'f', 1, 64) + "m" } func dynamicRelativeTimeAttrs(t interface{ Unix() int64 }) template.HTMLAttr { return template.HTMLAttr(`data-dynamic-relative-time="` + strconv.FormatInt(t.Unix(), 10) + `"`) } ================================================ FILE: internal/glance/theme.go ================================================ package glance import ( "fmt" "html/template" "net/http" "time" ) var ( themeStyleTemplate = mustParseTemplate("theme-style.gotmpl") themePresetPreviewTemplate = mustParseTemplate("theme-preset-preview.html") ) func (a *application) handleThemeChangeRequest(w http.ResponseWriter, r *http.Request) { themeKey := r.PathValue("key") properties, exists := a.Config.Theme.Presets.Get(themeKey) if !exists && themeKey != "default" { w.WriteHeader(http.StatusNotFound) return } if themeKey == "default" { properties = &a.Config.Theme.themeProperties } http.SetCookie(w, &http.Cookie{ Name: "theme", Value: themeKey, Path: a.Config.Server.BaseURL + "/", SameSite: http.SameSiteLaxMode, Expires: time.Now().Add(2 * 365 * 24 * time.Hour), }) w.Header().Set("Content-Type", "text/css") w.Header().Set("X-Scheme", ternary(properties.Light, "light", "dark")) w.Write([]byte(properties.CSS)) } type themeProperties struct { BackgroundColor *hslColorField `yaml:"background-color"` PrimaryColor *hslColorField `yaml:"primary-color"` PositiveColor *hslColorField `yaml:"positive-color"` NegativeColor *hslColorField `yaml:"negative-color"` Light bool `yaml:"light"` ContrastMultiplier float32 `yaml:"contrast-multiplier"` TextSaturationMultiplier float32 `yaml:"text-saturation-multiplier"` Key string `yaml:"-"` CSS template.CSS `yaml:"-"` PreviewHTML template.HTML `yaml:"-"` BackgroundColorAsHex string `yaml:"-"` } func (t *themeProperties) init() error { css, err := executeTemplateToString(themeStyleTemplate, t) if err != nil { return fmt.Errorf("compiling theme style: %v", err) } t.CSS = template.CSS(whitespaceAtBeginningOfLinePattern.ReplaceAllString(css, "")) previewHTML, err := executeTemplateToString(themePresetPreviewTemplate, t) if err != nil { return fmt.Errorf("compiling theme preview: %v", err) } t.PreviewHTML = template.HTML(previewHTML) if t.BackgroundColor != nil { t.BackgroundColorAsHex = t.BackgroundColor.ToHex() } else { t.BackgroundColorAsHex = "#151519" } return nil } func (t1 *themeProperties) SameAs(t2 *themeProperties) bool { if t1 == nil && t2 == nil { return true } if t1 == nil || t2 == nil { return false } if t1.Light != t2.Light { return false } if t1.ContrastMultiplier != t2.ContrastMultiplier { return false } if t1.TextSaturationMultiplier != t2.TextSaturationMultiplier { return false } if !t1.BackgroundColor.SameAs(t2.BackgroundColor) { return false } if !t1.PrimaryColor.SameAs(t2.PrimaryColor) { return false } if !t1.PositiveColor.SameAs(t2.PositiveColor) { return false } if !t1.NegativeColor.SameAs(t2.NegativeColor) { return false } return true } ================================================ FILE: internal/glance/utils.go ================================================ package glance import ( "bytes" "fmt" "html/template" "math" "net/http" "net/url" "os" "regexp" "slices" "strings" "time" ) var sequentialWhitespacePattern = regexp.MustCompile(`\s+`) var whitespaceAtBeginningOfLinePattern = regexp.MustCompile(`(?m)^\s+`) func percentChange(current, previous float64) float64 { if previous == 0 { if current == 0 { return 0 // 0% change if both are 0 } return 100 // 100% increase if going from 0 to something } 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 executeTemplateToString(t *template.Template, data any) (string, error) { var b bytes.Buffer err := t.Execute(&b, data) if err != nil { return "", fmt.Errorf("executing template: %w", err) } return 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) {} func hslToHex(h, s, l float64) string { s /= 100.0 l /= 100.0 var r, g, b float64 if s == 0 { r, g, b = l, l, l } else { hueToRgb := func(p, q, t float64) float64 { if t < 0 { t += 1 } if t > 1 { t -= 1 } if t < 1.0/6.0 { return p + (q-p)*6.0*t } if t < 1.0/2.0 { return q } if t < 2.0/3.0 { return p + (q-p)*(2.0/3.0-t)*6.0 } return p } q := 0.0 if l < 0.5 { q = l * (1 + s) } else { q = l + s - l*s } p := 2*l - q h /= 360.0 r = hueToRgb(p, q, h+1.0/3.0) g = hueToRgb(p, q, h) b = hueToRgb(p, q, h-1.0/3.0) } ir := int(math.Round(r * 255.0)) ig := int(math.Round(g * 255.0)) ib := int(math.Round(b * 255.0)) ir = int(math.Max(0, math.Min(255, float64(ir)))) ig = int(math.Max(0, math.Min(255, float64(ig)))) ib = int(math.Max(0, math.Min(255, float64(ib)))) return fmt.Sprintf("#%02x%02x%02x", ir, ig, ib) } ================================================ FILE: internal/glance/widget-bookmarks.go ================================================ 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"` Description string `yaml:"description"` Icon customIconField `yaml:"icon"` // we need a pointer to bool to know whether a value was provided, // however there's no way to dereference a pointer in a template so // {{ if not .SameTab }} would return true for any non-nil pointer // which leaves us with no way of checking if the value is true or // false, hence the duplicated fields below SameTabRaw *bool `yaml:"same-tab"` SameTab bool `yaml:"-"` HideArrowRaw *bool `yaml:"hide-arrow"` HideArrow bool `yaml:"-"` Target string `yaml:"target"` } `yaml:"links"` } `yaml:"groups"` } func (widget *bookmarksWidget) initialize() error { widget.withTitle("Bookmarks").withError(nil) 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 } ================================================ FILE: internal/glance/widget-calendar.go ================================================ 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 } ================================================ FILE: internal/glance/widget-changedetection.go ================================================ 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 } ================================================ FILE: internal/glance/widget-clock.go ================================================ 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 } ================================================ FILE: internal/glance/widget-container.go ================================================ 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 } ================================================ FILE: internal/glance/widget-custom-api.go ================================================ 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"` Options customAPIOptions `yaml:"options"` 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 := fetchAndRenderCustomAPIRequest( widget.CustomAPIRequest, widget.Subrequests, widget.Options, widget.compiledTemplate, ) if !widget.canContinueUpdateAfterHandlingErr(err) { return } widget.CompiledHTML = compiledHTML } func (widget *customAPIWidget) Render() template.HTML { return widget.renderTemplate(widget, customAPIWidgetTemplate) } type customAPIOptions map[string]any func (o *customAPIOptions) StringOr(key, defaultValue string) string { return customAPIGetOptionOrDefault(*o, key, defaultValue) } func (o *customAPIOptions) IntOr(key string, defaultValue int) int { return customAPIGetOptionOrDefault(*o, key, defaultValue) } func (o *customAPIOptions) FloatOr(key string, defaultValue float64) float64 { return customAPIGetOptionOrDefault(*o, key, defaultValue) } func (o *customAPIOptions) BoolOr(key string, defaultValue bool) bool { return customAPIGetOptionOrDefault(*o, key, defaultValue) } func (o *customAPIOptions) JSON(key string) string { value, exists := (*o)[key] if !exists { panic(fmt.Sprintf("key %q does not exist in options", key)) } encoded, err := json.Marshal(value) if err != nil { panic(fmt.Sprintf("marshaling %s: %v", key, err)) } return string(encoded) } func customAPIGetOptionOrDefault[T any](o customAPIOptions, key string, defaultValue T) T { if value, exists := o[key]; exists { if typedValue, ok := value.(T); ok { return typedValue } } return defaultValue } func (req *CustomAPIRequest) initialize() error { if req == nil || req.URL == "" { return nil } 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 Options customAPIOptions } 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 fetchCustomAPIResponse(ctx context.Context, req *CustomAPIRequest) (*customAPIResponseData, error) { if req == nil || req.URL == "" { return &customAPIResponseData{ JSON: decoratedGJSONResult{gjson.Result{}}, Response: &http.Response{}, }, nil } 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) { if 200 <= resp.StatusCode && resp.StatusCode < 300 { 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") } return nil, fmt.Errorf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode)) } return &customAPIResponseData{ JSON: decoratedGJSONResult{gjson.Parse(body)}, Response: resp, }, nil } func fetchAndRenderCustomAPIRequest( primaryReq *CustomAPIRequest, subReqs map[string]*CustomAPIRequest, options customAPIOptions, 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 = fetchCustomAPIResponse(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 = fetchCustomAPIResponse(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 = fetchCustomAPIResponse(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, Options: options, } 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.Result.Get(key).Exists() } func (r *decoratedGJSONResult) Array(key string) []decoratedGJSONResult { if key == "" { return gJsonResultArrayToDecoratedResultArray(r.Result.Array()) } return gJsonResultArrayToDecoratedResultArray(r.Result.Get(key).Array()) } func (r *decoratedGJSONResult) String(key string) string { if key == "" { return r.Result.String() } return r.Result.Get(key).String() } func (r *decoratedGJSONResult) Int(key string) int { if key == "" { return int(r.Result.Int()) } return int(r.Result.Get(key).Int()) } func (r *decoratedGJSONResult) Float(key string) float64 { if key == "" { return r.Result.Float() } return r.Result.Get(key).Float() } func (r *decoratedGJSONResult) Bool(key string) bool { if key == "" { return r.Result.Bool() } return r.Result.Get(key).Bool() } func (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult { return &decoratedGJSONResult{r.Result.Get(key)} } 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") }, "mod": func(a, b int) int { if b == 0 { return 0 } return a % b }, "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": func(layout, value string) time.Time { return customAPIFuncParseTimeInLocation(layout, value, time.UTC) }, "formatTime": customAPIFuncFormatTime, "parseLocalTime": func(layout, value string) time.Time { return customAPIFuncParseTimeInLocation(layout, value, time.Local) }, "toRelativeTime": dynamicRelativeTimeAttrs, "parseRelativeTime": func(layout, value string) template.HTMLAttr { // Shorthand to do both of the above with a single function call return dynamicRelativeTimeAttrs(customAPIFuncParseTimeInLocation(layout, value, time.UTC)) }, "startOfDay": func(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) }, "endOfDay": func(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location()) }, // 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, "") }, "percentChange": percentChange, "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 := customAPIFuncParseTimeInLocation(layout, results[a].String(key), time.UTC) timeB := customAPIFuncParseTimeInLocation(layout, results[b].String(key), time.UTC) 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 }, "newRequest": func(url string) *CustomAPIRequest { return &CustomAPIRequest{ URL: url, } }, "withHeader": func(key, value string, req *CustomAPIRequest) *CustomAPIRequest { if req.Headers == nil { req.Headers = make(map[string]string) } req.Headers[key] = value return req }, "withParameter": func(key, value string, req *CustomAPIRequest) *CustomAPIRequest { if req.Parameters == nil { req.Parameters = make(queryParametersField) } req.Parameters[key] = append(req.Parameters[key], value) return req }, "withStringBody": func(body string, req *CustomAPIRequest) *CustomAPIRequest { req.Body = body req.BodyType = "string" return req }, "getResponse": func(req *CustomAPIRequest) *customAPIResponseData { err := req.initialize() if err != nil { panic(fmt.Sprintf("initializing request: %v", err)) } data, err := fetchCustomAPIResponse(context.Background(), req) if err != nil { slog.Error("Could not fetch response within custom API template", "error", err) return &customAPIResponseData{ JSON: decoratedGJSONResult{gjson.Result{}}, Response: &http.Response{ Status: err.Error(), }, } } return data }, } for key, value := range globalTemplateFunctions { if _, exists := funcs[key]; !exists { funcs[key] = value } } return funcs }() func customAPIFuncFormatTime(layout string, t time.Time) string { switch strings.ToLower(layout) { case "unix": return strconv.FormatInt(t.Unix(), 10) case "rfc3339": layout = time.RFC3339 case "rfc3339nano": layout = time.RFC3339Nano case "datetime": layout = time.DateTime case "dateonly": layout = time.DateOnly } return t.Format(layout) } func customAPIFuncParseTimeInLocation(layout, value string, loc *time.Location) 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.ParseInLocation(layout, value, loc) if err != nil { return time.Unix(0, 0) } return parsed } ================================================ FILE: internal/glance/widget-dns-stats.go ================================================ 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" dnsServiceTechnitium = "technitium" 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 { titleURL := strings.TrimRight(widget.URL, "/") switch widget.Service { case dnsServicePihole, dnsServicePiholeV6: titleURL = titleURL + "/admin" } widget. withTitle("DNS Stats"). withTitleURL(titleURL). withCacheDuration(10 * time.Minute) switch widget.Service { case dnsServiceAdguard: case dnsServicePiholeV6: case dnsServicePihole: case dnsServiceTechnitium: default: return fmt.Errorf("service must be one of: %s, %s, %s, %s", dnsServiceAdguard, dnsServicePihole, dnsServicePiholeV6, dnsServiceTechnitium) } 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 dnsServiceTechnitium: stats, err = fetchTechnitiumStats(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 } type technitiumStatsResponse struct { Response struct { Stats struct { TotalQueries int `json:"totalQueries"` BlockedQueries int `json:"totalBlocked"` BlockedZones int `json:"blockedZones"` BlockListZones int `json:"blockListZones"` } `json:"stats"` MainChartData struct { Datasets []struct { Label string `json:"label"` Data []int `json:"data"` } `json:"datasets"` } `json:"mainChartData"` TopBlockedDomains []struct { Domain string `json:"name"` Count int `json:"hits"` } } `json:"response"` } func fetchTechnitiumStats(instanceUrl string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) { if token == "" { return nil, errors.New("missing API token") } requestURL := strings.TrimRight(instanceUrl, "/") + "/api/dashboard/stats/get?token=" + token + "&type=LastDay" request, err := http.NewRequest("GET", requestURL, nil) if err != nil { return nil, err } var client requestDoer if !allowInsecure { client = defaultHTTPClient } else { client = defaultInsecureHTTPClient } responseJson, err := decodeJsonFromRequest[technitiumStatsResponse](client, request) if err != nil { return nil, err } var topBlockedDomainsCount = min(len(responseJson.Response.TopBlockedDomains), 5) stats := &dnsStats{ TotalQueries: responseJson.Response.Stats.TotalQueries, BlockedQueries: responseJson.Response.Stats.BlockedQueries, TopBlockedDomains: make([]dnsStatsBlockedDomain, 0, topBlockedDomainsCount), DomainsBlocked: responseJson.Response.Stats.BlockedZones + responseJson.Response.Stats.BlockListZones, } if stats.TotalQueries <= 0 { return stats, nil } stats.BlockedPercent = int(float64(responseJson.Response.Stats.BlockedQueries) / float64(responseJson.Response.Stats.TotalQueries) * 100) for i := 0; i < topBlockedDomainsCount; i++ { domain := responseJson.Response.TopBlockedDomains[i] firstDomain := domain.Domain if firstDomain == "" { continue } stats.TopBlockedDomains = append(stats.TopBlockedDomains, dnsStatsBlockedDomain{ Domain: firstDomain, }) if stats.BlockedQueries > 0 { stats.TopBlockedDomains[i].PercentBlocked = int(float64(domain.Count) / float64(responseJson.Response.Stats.BlockedQueries) * 100) } } if noGraph { return stats, nil } var queriesSeries, blockedSeries []int for _, label := range responseJson.Response.MainChartData.Datasets { switch label.Label { case "Total": queriesSeries = label.Data case "Blocked": blockedSeries = label.Data } } 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 := 0; i < dnsStatsBars; i++ { queries := 0 blocked := 0 for j := 0; j < dnsStatsHoursPerBar; j++ { 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 := 0; i < dnsStatsBars; i++ { stats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100) } return stats, nil } ================================================ FILE: internal/glance/widget-docker-containers.go ================================================ package glance import ( "context" "encoding/json" "fmt" "html/template" "net" "net/http" "net/url" "sort" "strings" "time" ) var dockerContainersWidgetTemplate = mustParseTemplate("docker-containers.html", "widget-base.html") type dockerContainersWidget struct { widgetBase `yaml:",inline"` HideByDefault bool `yaml:"hide-by-default"` RunningOnly bool `yaml:"running-only"` Category string `yaml:"category"` SockPath string `yaml:"sock-path"` FormatContainerNames bool `yaml:"format-container-names"` Containers dockerContainerList `yaml:"-"` LabelOverrides map[string]map[string]string `yaml:"containers"` } 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, widget.Category, widget.RunningOnly, widget.FormatContainerNames, widget.LabelOverrides, ) 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" dockerContainerLabelCategory = "glance.category" ) 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 { Name 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].Name) < strings.ToLower(containers[b].Name) }) } 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, category string, runningOnly bool, formatNames bool, labelOverrides map[string]map[string]string, ) (dockerContainerList, error) { containers, err := fetchDockerContainersFromSource(socketPath, category, runningOnly, labelOverrides) 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{ Name: deriveDockerContainerName(container, formatNames), 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{ Name: deriveDockerContainerName(child, formatNames), 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 deriveDockerContainerName(container *dockerContainerJsonResponse, formatNames bool) string { if v := container.Labels.getOrDefault(dockerContainerLabelName, ""); v != "" { return v } if len(container.Names) == 0 || container.Names[0] == "" { return "n/a" } name := strings.TrimLeft(container.Names[0], "/") if formatNames { name = strings.ReplaceAll(name, "_", " ") name = strings.ReplaceAll(name, "-", " ") words := strings.Split(name, " ") for i := range words { if len(words[i]) > 0 { words[i] = strings.ToUpper(words[i][:1]) + words[i][1:] } } name = strings.Join(words, " ") } return name } 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 fetchDockerContainersFromSource( source string, category string, runningOnly bool, labelOverrides map[string]map[string]string, ) ([]dockerContainerJsonResponse, error) { var hostname string var client *http.Client if strings.HasPrefix(source, "tcp://") || strings.HasPrefix(source, "http://") { client = &http.Client{} parsed, err := url.Parse(source) if err != nil { return nil, fmt.Errorf("parsing URL: %w", err) } port := parsed.Port() if port == "" { port = "80" } hostname = parsed.Hostname() + ":" + port } else { hostname = "docker" client = &http.Client{ Transport: &http.Transport{ DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { return net.Dial("unix", source) }, }, } } fetchAll := ternary(runningOnly, "false", "true") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() request, err := http.NewRequestWithContext(ctx, "GET", "http://"+hostname+"/containers/json?all="+fetchAll, 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) } for i := range containers { container := &containers[i] name := strings.TrimLeft(itemAtIndexOrDefault(container.Names, 0, ""), "/") if name == "" { continue } overrides, ok := labelOverrides[name] if !ok { continue } if container.Labels == nil { container.Labels = make(dockerContainerLabels) } for label, value := range overrides { container.Labels["glance."+label] = value } } // We have to filter here instead of using the `filters` parameter of Docker's API // because the user may define a category override within their config if category != "" { filtered := make([]dockerContainerJsonResponse, 0, len(containers)) for i := range containers { container := &containers[i] if container.Labels.getOrDefault(dockerContainerLabelCategory, "") == category { filtered = append(filtered, *container) } } containers = filtered } return containers, nil } ================================================ FILE: internal/glance/widget-extension.go ================================================ 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 } ================================================ FILE: internal/glance/widget-group.go ================================================ 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) } ================================================ FILE: internal/glance/widget-hacker-news.go ================================================ 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) } ================================================ FILE: internal/glance/widget-html.go ================================================ 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 } ================================================ FILE: internal/glance/widget-iframe.go ================================================ package glance import ( "errors" "fmt" "html/template" "net/url" ) var iframeWidgetTemplate = mustParseTemplate("iframe.html", "widget-base.html") type iframeWidget struct { widgetBase `yaml:",inline"` cachedHTML template.HTML `yaml:"-"` Source string `yaml:"source"` Height int `yaml:"height"` } func (widget *iframeWidget) initialize() error { widget.withTitle("IFrame").withError(nil) if widget.Source == "" { return errors.New("source is required") } if _, err := url.Parse(widget.Source); err != nil { return fmt.Errorf("parsing URL: %v", err) } if widget.Height == 50 { widget.Height = 300 } else if widget.Height < 50 { widget.Height = 50 } widget.cachedHTML = widget.renderTemplate(widget, iframeWidgetTemplate) return nil } func (widget *iframeWidget) Render() template.HTML { return widget.cachedHTML } ================================================ FILE: internal/glance/widget-lobsters.go ================================================ 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 } ================================================ FILE: internal/glance/widget-markets.go ================================================ 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": "₱", } ================================================ FILE: internal/glance/widget-monitor.go ================================================ 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"` Timeout durationField `yaml:"timeout"` BasicAuth struct { Username string `yaml:"username"` Password string `yaml:"password"` } `yaml:"basic-auth"` } 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 } timeout := ternary(statusRequest.Timeout > 0, time.Duration(statusRequest.Timeout), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return siteStatus{ Error: err, }, nil } if statusRequest.BasicAuth.Username != "" || statusRequest.BasicAuth.Password != "" { request.SetBasicAuth(statusRequest.BasicAuth.Username, statusRequest.BasicAuth.Password) } 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 } ================================================ FILE: internal/glance/widget-old-calendar.go ================================================ 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() } ================================================ FILE: internal/glance/widget-reddit.go ================================================ package glance import ( "context" "errors" "fmt" "html" "html/template" "net/http" "net/url" "strconv" "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"` AppAuth struct { Name string `yaml:"name"` ID string `yaml:"id"` Secret string `yaml:"secret"` enabled bool accessToken string tokenExpiresAt time.Time } `yaml:"app-auth"` } 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 } s := widget.SortBy if s != "hot" && s != "new" && s != "top" && s != "rising" { widget.SortBy = "hot" } p := widget.TopPeriod if p != "hour" && p != "day" && p != "week" && p != "month" && p != "year" && p != "all" { widget.TopPeriod = "day" } if widget.RequestURLTemplate != "" { if !strings.Contains(widget.RequestURLTemplate, "{REQUEST-URL}") { return errors.New("no `{REQUEST-URL}` placeholder specified") } } a := &widget.AppAuth if a.Name != "" || a.ID != "" || a.Secret != "" { if a.Name == "" || a.ID == "" || a.Secret == "" { return errors.New("application name, client ID and client secret are required") } a.enabled = true } widget. withTitle("r/" + widget.Subreddit). withTitleURL("https://www.reddit.com/r/" + widget.Subreddit + "/"). withCacheDuration(30 * time.Minute) return nil } func (widget *redditWidget) update(ctx context.Context) { posts, err := widget.fetchSubredditPosts() 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 (widget *redditWidget) parseCustomCommentsURL(subreddit, postId, postPath string) string { template := strings.ReplaceAll(widget.CommentsURLTemplate, "{SUBREDDIT}", subreddit) template = strings.ReplaceAll(template, "{POST-ID}", postId) template = strings.ReplaceAll(template, "{POST-PATH}", strings.TrimLeft(postPath, "/")) return template } func (widget *redditWidget) fetchSubredditPosts() (forumPostList, error) { var client requestDoer = defaultHTTPClient var baseURL string var requestURL string var headers http.Header query := url.Values{} app := &widget.AppAuth if !app.enabled { baseURL = "https://www.reddit.com" headers = http.Header{ "User-Agent": []string{getBrowserUserAgentHeader()}, } } else { baseURL = "https://oauth.reddit.com" if app.accessToken == "" || time.Now().Add(time.Minute).After(app.tokenExpiresAt) { if err := widget.fetchNewAppAccessToken(); err != nil { return nil, fmt.Errorf("fetching new app access token: %v", err) } } headers = http.Header{ "Authorization": []string{"Bearer " + app.accessToken}, "User-Agent": []string{app.Name + "/1.0"}, } } if widget.Limit > 25 { query.Set("limit", strconv.Itoa(widget.Limit)) } if widget.Search != "" { query.Set("q", widget.Search+" subreddit:"+widget.Subreddit) query.Set("sort", widget.SortBy) requestURL = fmt.Sprintf("%s/search.json?%s", baseURL, query.Encode()) } else { if widget.SortBy == "top" { query.Set("t", widget.TopPeriod) } requestURL = fmt.Sprintf("%s/r/%s/%s.json?%s", baseURL, widget.Subreddit, widget.SortBy, query.Encode()) } if widget.RequestURLTemplate != "" { requestURL = strings.ReplaceAll(widget.RequestURLTemplate, "{REQUEST-URL}", requestURL) } else if widget.Proxy.client != nil { client = widget.Proxy.client } request, err := http.NewRequest("GET", requestURL, nil) if err != nil { return nil, err } request.Header = headers 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 widget.CommentsURLTemplate == "" { commentsUrl = "https://www.reddit.com" + post.Permalink } else { commentsUrl = widget.parseCustomCommentsURL(widget.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 widget.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 widget.CommentsURLTemplate == "" { forumPost.TargetUrl = "https://www.reddit.com" + post.ParentList[0].Permalink } else { forumPost.TargetUrl = widget.parseCustomCommentsURL( post.ParentList[0].Subreddit, post.ParentList[0].Id, post.ParentList[0].Permalink, ) } } posts = append(posts, forumPost) } return posts, nil } func (widget *redditWidget) fetchNewAppAccessToken() error { body := strings.NewReader("grant_type=client_credentials") req, err := http.NewRequest("POST", "https://www.reddit.com/api/v1/access_token", body) if err != nil { return fmt.Errorf("creating request for app access token: %v", err) } app := &widget.AppAuth req.SetBasicAuth(app.ID, app.Secret) req.Header.Add("User-Agent", app.Name+"/1.0") req.Header.Add("Content-Type", "application/x-www-form-urlencoded") type tokenResponse struct { AccessToken string `json:"access_token"` ExpiresIn int `json:"expires_in"` } client := ternary(widget.Proxy.client != nil, widget.Proxy.client, defaultHTTPClient) response, err := decodeJsonFromRequest[tokenResponse](client, req) if err != nil { return err } app.accessToken = response.AccessToken app.tokenExpiresAt = time.Now().Add(time.Duration(response.ExpiresIn) * time.Second) return nil } ================================================ FILE: internal/glance/widget-releases.go ================================================ 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 } ================================================ FILE: internal/glance/widget-repository.go ================================================ 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 } ================================================ FILE: internal/glance/widget-rss.go ================================================ package glance import ( "context" "fmt" "html" "html/template" "io" "log/slog" "net/http" "net/url" "regexp" "sort" "strings" "sync" "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") ) var feedParser = gofeed.NewParser() type rssWidget struct { widgetBase `yaml:",inline"` FeedRequests []rssFeedRequest `yaml:"feeds"` Style string `yaml:"style"` ThumbnailHeight float64 `yaml:"thumbnail-height"` CardHeight float64 `yaml:"card-height"` Limit int `yaml:"limit"` CollapseAfter int `yaml:"collapse-after"` SingleLineTitles bool `yaml:"single-line-titles"` PreserveOrder bool `yaml:"preserve-order"` Items rssFeedItemList `yaml:"-"` NoItemsMessage string `yaml:"-"` cachedFeedsMutex sync.Mutex cachedFeeds map[string]*cachedRSSFeed `yaml:"-"` } func (widget *rssWidget) initialize() error { widget.withTitle("RSS Feed").withCacheDuration(2 * 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." widget.cachedFeeds = make(map[string]*cachedRSSFeed) return nil } func (widget *rssWidget) update(ctx context.Context) { items, err := widget.fetchItemsFromFeeds() 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 cachedRSSFeed struct { etag string lastModified string items []rssFeedItem } type rssFeedItem struct { ChannelName string ChannelURL string Title string Link string ImageURL string Categories []string Description string PublishedAt time.Time } 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 } func (widget *rssWidget) fetchItemsFromFeeds() (rssFeedItemList, error) { requests := widget.FeedRequests job := newJob(widget.fetchItemsFromFeedTask, 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 } func (widget *rssWidget) fetchItemsFromFeedTask(request rssFeedRequest) ([]rssFeedItem, error) { req, err := http.NewRequest("GET", request.URL, nil) if err != nil { return nil, err } req.Header.Add("User-Agent", glanceUserAgentString) widget.cachedFeedsMutex.Lock() cache, isCached := widget.cachedFeeds[request.URL] if isCached { if cache.etag != "" { req.Header.Add("If-None-Match", cache.etag) } if cache.lastModified != "" { req.Header.Add("If-Modified-Since", cache.lastModified) } } widget.cachedFeedsMutex.Unlock() for key, value := range request.Headers { req.Header.Set(key, value) } resp, err := defaultHTTPClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotModified && isCached { return cache.items, nil } 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) } if resp.Header.Get("ETag") != "" || resp.Header.Get("Last-Modified") != "" { widget.cachedFeedsMutex.Lock() widget.cachedFeeds[request.URL] = &cachedRSSFeed{ etag: resp.Header.Get("ETag"), lastModified: resp.Header.Get("Last-Modified"), items: items, } widget.cachedFeedsMutex.Unlock() } return items, nil } func findThumbnailInItemExtensions(item *gofeed.Item) string { media, ok := item.Extensions["media"] if !ok { return "" } return recursiveFindThumbnailInExtensions(media) } 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 "" } 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 } ================================================ FILE: internal/glance/widget-search.go ================================================ 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"` Target string `yaml:"target"` 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}", "bing": "https://www.bing.com/search?q={QUERY}", "perplexity": "https://www.perplexity.ai/search?q={QUERY}", "kagi": "https://kagi.com/search?q={QUERY}", "startpage": "https://www.startpage.com/search?q={QUERY}", } 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 } ================================================ FILE: internal/glance/widget-server-stats.go ================================================ 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 } ================================================ FILE: internal/glance/widget-shared.go ================================================ 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 }) } ================================================ FILE: internal/glance/widget-split-column.go ================================================ 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) } ================================================ FILE: internal/glance/widget-todo.go ================================================ package glance import ( "html/template" ) var todoWidgetTemplate = mustParseTemplate("todo.html", "widget-base.html") type todoWidget struct { widgetBase `yaml:",inline"` cachedHTML template.HTML `yaml:"-"` TodoID string `yaml:"id"` } func (widget *todoWidget) initialize() error { widget.withTitle("To-do").withError(nil) widget.cachedHTML = widget.renderTemplate(widget, todoWidgetTemplate) return nil } func (widget *todoWidget) Render() template.HTML { return widget.cachedHTML } ================================================ FILE: internal/glance/widget-twitch-channels.go ================================================ 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 } ================================================ FILE: internal/glance/widget-twitch-top-games.go ================================================ 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 } ================================================ FILE: internal/glance/widget-utils.go ================================================ package glance import ( "context" "crypto/tls" "encoding/json" "encoding/xml" "errors" "fmt" "io" "math/rand/v2" "net/http" "strconv" "sync" "sync/atomic" "time" ) var ( errNoContent = errors.New("failed to retrieve any content") errPartialContent = errors.New("failed to retrieve some of the content") ) const defaultClientTimeout = 5 * time.Second var defaultHTTPClient = &http.Client{ Transport: &http.Transport{ MaxIdleConnsPerHost: 10, Proxy: http.ProxyFromEnvironment, }, Timeout: defaultClientTimeout, } var defaultInsecureHTTPClient = &http.Client{ Timeout: defaultClientTimeout, Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, Proxy: http.ProxyFromEnvironment, }, } type requestDoer interface { Do(*http.Request) (*http.Response, error) } var glanceUserAgentString = "Glance/" + buildVersion + " +https://github.com/glanceapp/glance" var userAgentPersistentVersion atomic.Int32 func getBrowserUserAgentHeader() string { if rand.IntN(2000) == 0 { userAgentPersistentVersion.Store(rand.Int32N(5)) } version := strconv.Itoa(130 + int(userAgentPersistentVersion.Load())) return "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:" + version + ".0) Gecko/20100101 Firefox/" + version + ".0" } func setBrowserUserAgentHeader(request *http.Request) { request.Header.Set("User-Agent", getBrowserUserAgentHeader()) } func decodeJsonFromRequest[T any](client requestDoer, request *http.Request) (T, error) { var result T response, err := client.Do(request) if err != nil { return result, err } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { return result, err } if response.StatusCode != http.StatusOK { truncatedBody, _ := limitStringLength(string(body), 256) return result, fmt.Errorf( "unexpected status code %d from %s, response: %s", response.StatusCode, request.URL, truncatedBody, ) } err = json.Unmarshal(body, &result) if err != nil { return result, err } return result, nil } func decodeJsonFromRequestTask[T any](client requestDoer) func(*http.Request) (T, error) { return func(request *http.Request) (T, error) { return decodeJsonFromRequest[T](client, request) } } // TODO: tidy up, these are a copy of the above but with a line changed func decodeXmlFromRequest[T any](client requestDoer, request *http.Request) (T, error) { var result T response, err := client.Do(request) if err != nil { return result, err } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { return result, err } if response.StatusCode != http.StatusOK { truncatedBody, _ := limitStringLength(string(body), 256) return result, fmt.Errorf( "unexpected status code %d for %s, response: %s", response.StatusCode, request.URL, truncatedBody, ) } err = xml.Unmarshal(body, &result) if err != nil { return result, err } return result, nil } func decodeXmlFromRequestTask[T any](client requestDoer) func(*http.Request) (T, error) { return func(request *http.Request) (T, error) { return decodeXmlFromRequest[T](client, request) } } type workerPoolTask[I any, O any] struct { index int input I output O err error } type workerPoolJob[I any, O any] struct { data []I workers int task func(I) (O, error) ctx context.Context } const defaultNumWorkers = 10 func (job *workerPoolJob[I, O]) withWorkers(workers int) *workerPoolJob[I, O] { if workers == 0 { job.workers = defaultNumWorkers } else { job.workers = min(workers, len(job.data)) } return job } // func (job *workerPoolJob[I, O]) withContext(ctx context.Context) *workerPoolJob[I, O] { // if ctx != nil { // job.ctx = ctx // } // return job // } func newJob[I any, O any](task func(I) (O, error), data []I) *workerPoolJob[I, O] { return &workerPoolJob[I, O]{ workers: defaultNumWorkers, task: task, data: data, ctx: context.Background(), } } func workerPoolDo[I any, O any](job *workerPoolJob[I, O]) ([]O, []error, error) { results := make([]O, len(job.data)) errs := make([]error, len(job.data)) if len(job.data) == 0 { return results, errs, nil } if len(job.data) == 1 { results[0], errs[0] = job.task(job.data[0]) return results, errs, nil } tasksQueue := make(chan *workerPoolTask[I, O]) resultsQueue := make(chan *workerPoolTask[I, O]) var wg sync.WaitGroup for range job.workers { wg.Add(1) go func() { defer wg.Done() for t := range tasksQueue { t.output, t.err = job.task(t.input) resultsQueue <- t } }() } var err error go func() { loop: for i := range job.data { select { default: tasksQueue <- &workerPoolTask[I, O]{ index: i, input: job.data[i], } case <-job.ctx.Done(): err = job.ctx.Err() break loop } } close(tasksQueue) wg.Wait() close(resultsQueue) }() for task := range resultsQueue { errs[task.index] = task.err results[task.index] = task.output } return results, errs, err } ================================================ FILE: internal/glance/widget-videos.go ================================================ 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 } ================================================ FILE: internal/glance/widget-weather.go ================================================ package glance import ( "context" "errors" "fmt" "html/template" "math" "net/http" "net/url" "slices" "strings" "time" _ "time/tzdata" ) var weatherWidgetTemplate = mustParseTemplate("weather.html", "widget-base.html") type weatherWidget struct { widgetBase `yaml:",inline"` Location string `yaml:"location"` ShowAreaName bool `yaml:"show-area-name"` HideLocation bool `yaml:"hide-location"` HourFormat string `yaml:"hour-format"` Units string `yaml:"units"` Place *openMeteoPlaceResponseJson `yaml:"-"` Weather *weather `yaml:"-"` TimeLabels [12]string `yaml:"-"` } var timeLabels12h = [12]string{"2am", "4am", "6am", "8am", "10am", "12pm", "2pm", "4pm", "6pm", "8pm", "10pm", "12am"} var timeLabels24h = [12]string{"02:00", "04:00", "06:00", "08:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00", "00:00"} func (widget *weatherWidget) initialize() error { widget.withTitle("Weather").withCacheOnTheHour() if widget.Location == "" { return fmt.Errorf("location is required") } if widget.HourFormat == "" || widget.HourFormat == "12h" { widget.TimeLabels = timeLabels12h } else if widget.HourFormat == "24h" { widget.TimeLabels = timeLabels24h } else { return errors.New("hour-format must be either 12h or 24h") } if widget.Units == "" { widget.Units = "metric" } else if widget.Units != "metric" && widget.Units != "imperial" { return errors.New("units must be either metric or imperial") } return nil } func (widget *weatherWidget) update(ctx context.Context) { if widget.Place == nil { place, err := fetchOpenMeteoPlaceFromName(widget.Location) if err != nil { widget.withError(err).scheduleEarlyUpdate() return } widget.Place = place } weather, err := fetchWeatherForOpenMeteoPlace(widget.Place, widget.Units) if !widget.canContinueUpdateAfterHandlingErr(err) { return } widget.Weather = weather } func (widget *weatherWidget) Render() template.HTML { return widget.renderTemplate(widget, weatherWidgetTemplate) } type weather struct { Temperature int ApparentTemperature int WeatherCode int CurrentColumn int SunriseColumn int SunsetColumn int Columns []weatherColumn } func (w *weather) WeatherCodeAsString() string { if weatherCode, ok := weatherCodeTable[w.WeatherCode]; ok { return weatherCode } return "" } type openMeteoPlacesResponseJson struct { Results []openMeteoPlaceResponseJson } type openMeteoPlaceResponseJson struct { Name string Area string `json:"admin1"` Latitude float64 Longitude float64 Timezone string Country string location *time.Location } type openMeteoWeatherResponseJson struct { Daily struct { Sunrise []int64 `json:"sunrise"` Sunset []int64 `json:"sunset"` } `json:"daily"` Hourly struct { Temperature []float64 `json:"temperature_2m"` PrecipitationProbability []int `json:"precipitation_probability"` } `json:"hourly"` Current struct { Temperature float64 `json:"temperature_2m"` ApparentTemperature float64 `json:"apparent_temperature"` WeatherCode int `json:"weather_code"` } `json:"current"` } type weatherColumn struct { Temperature int Scale float64 HasPrecipitation bool } var commonCountryAbbreviations = map[string]string{ "US": "United States", "USA": "United States", "UK": "United Kingdom", } func expandCountryAbbreviations(name string) string { if expanded, ok := commonCountryAbbreviations[strings.TrimSpace(name)]; ok { return expanded } return name } // Separates the location that Open Meteo accepts from the administrative area // which can then be used to filter to the correct place after the list of places // has been retrieved. Also expands abbreviations since Open Meteo does not accept // country names like "US", "USA" and "UK" func parsePlaceName(name string) (string, string) { parts := strings.Split(name, ",") if len(parts) == 1 { return name, "" } if len(parts) == 2 { return parts[0] + ", " + expandCountryAbbreviations(parts[1]), "" } return parts[0] + ", " + expandCountryAbbreviations(parts[2]), strings.TrimSpace(parts[1]) } func fetchOpenMeteoPlaceFromName(location string) (*openMeteoPlaceResponseJson, error) { location, area := parsePlaceName(location) requestUrl := fmt.Sprintf("https://geocoding-api.open-meteo.com/v1/search?name=%s&count=20&language=en&format=json", url.QueryEscape(location)) request, _ := http.NewRequest("GET", requestUrl, nil) responseJson, err := decodeJsonFromRequest[openMeteoPlacesResponseJson](defaultHTTPClient, request) if err != nil { return nil, fmt.Errorf("fetching places data: %v", err) } if len(responseJson.Results) == 0 { return nil, fmt.Errorf("no places found for %s", location) } var place *openMeteoPlaceResponseJson if area != "" { area = strings.ToLower(area) for i := range responseJson.Results { if strings.ToLower(responseJson.Results[i].Area) == area { place = &responseJson.Results[i] break } } if place == nil { return nil, fmt.Errorf("no place found for %s in %s", location, area) } } else { place = &responseJson.Results[0] } loc, err := time.LoadLocation(place.Timezone) if err != nil { return nil, fmt.Errorf("loading location: %v", err) } place.location = loc return place, nil } func fetchWeatherForOpenMeteoPlace(place *openMeteoPlaceResponseJson, units string) (*weather, error) { query := url.Values{} var temperatureUnit string if units == "imperial" { temperatureUnit = "fahrenheit" } else { temperatureUnit = "celsius" } query.Add("latitude", fmt.Sprintf("%f", place.Latitude)) query.Add("longitude", fmt.Sprintf("%f", place.Longitude)) query.Add("timeformat", "unixtime") query.Add("timezone", place.Timezone) query.Add("forecast_days", "1") query.Add("current", "temperature_2m,apparent_temperature,weather_code") query.Add("hourly", "temperature_2m,precipitation_probability") query.Add("daily", "sunrise,sunset") query.Add("temperature_unit", temperatureUnit) requestUrl := "https://api.open-meteo.com/v1/forecast?" + query.Encode() request, _ := http.NewRequest("GET", requestUrl, nil) responseJson, err := decodeJsonFromRequest[openMeteoWeatherResponseJson](defaultHTTPClient, request) if err != nil { return nil, fmt.Errorf("%w: %v", errNoContent, err) } now := time.Now().In(place.location) bars := make([]weatherColumn, 0, 24) currentBar := now.Hour() / 2 sunriseBar := (time.Unix(int64(responseJson.Daily.Sunrise[0]), 0).In(place.location).Hour()) / 2 sunsetBar := (time.Unix(int64(responseJson.Daily.Sunset[0]), 0).In(place.location).Hour() - 1) / 2 if sunsetBar < 0 { sunsetBar = 0 } if len(responseJson.Hourly.Temperature) == 24 { temperatures := make([]int, 12) precipitations := make([]bool, 12) t := responseJson.Hourly.Temperature p := responseJson.Hourly.PrecipitationProbability for i := 0; i < 24; i += 2 { if i/2 == currentBar { temperatures[i/2] = int(responseJson.Current.Temperature) } else { temperatures[i/2] = int(math.Round((t[i] + t[i+1]) / 2)) } precipitations[i/2] = (p[i]+p[i+1])/2 > 75 } minT := slices.Min(temperatures) maxT := slices.Max(temperatures) temperaturesRange := float64(maxT - minT) for i := 0; i < 12; i++ { bars = append(bars, weatherColumn{ Temperature: temperatures[i], HasPrecipitation: precipitations[i], }) if temperaturesRange > 0 { bars[i].Scale = float64(temperatures[i]-minT) / temperaturesRange } else { bars[i].Scale = 1 } } } return &weather{ Temperature: int(responseJson.Current.Temperature), ApparentTemperature: int(responseJson.Current.ApparentTemperature), WeatherCode: responseJson.Current.WeatherCode, CurrentColumn: currentBar, SunriseColumn: sunriseBar, SunsetColumn: sunsetBar, Columns: bars, }, nil } var weatherCodeTable = map[int]string{ 0: "Clear Sky", 1: "Mainly Clear", 2: "Partly Cloudy", 3: "Overcast", 45: "Fog", 48: "Rime Fog", 51: "Drizzle", 53: "Drizzle", 55: "Drizzle", 56: "Drizzle", 57: "Drizzle", 61: "Rain", 63: "Moderate Rain", 65: "Heavy Rain", 66: "Freezing Rain", 67: "Freezing Rain", 71: "Snow", 73: "Moderate Snow", 75: "Heavy Snow", 77: "Snow Grains", 80: "Rain", 81: "Moderate Rain", 82: "Heavy Rain", 85: "Snow", 86: "Snow", 95: "Thunderstorm", 96: "Thunderstorm", 99: "Thunderstorm", } ================================================ FILE: internal/glance/widget.go ================================================ package glance import ( "bytes" "context" "errors" "fmt" "html/template" "log/slog" "math" "net/http" "sync/atomic" "time" "gopkg.in/yaml.v3" ) var widgetIDCounter atomic.Uint64 func newWidget(widgetType string) (widget, error) { if widgetType == "" { return nil, errors.New("widget 'type' property is empty or not specified") } var w widget switch widgetType { case "calendar": w = &calendarWidget{} case "calendar-legacy": w = &oldCalendarWidget{} case "clock": w = &clockWidget{} case "weather": w = &weatherWidget{} case "bookmarks": w = &bookmarksWidget{} case "iframe": w = &iframeWidget{} case "html": w = &htmlWidget{} case "hacker-news": w = &hackerNewsWidget{} case "releases": w = &releasesWidget{} case "videos": w = &videosWidget{} case "markets", "stocks": w = &marketsWidget{} case "reddit": w = &redditWidget{} case "rss": w = &rssWidget{} case "monitor": w = &monitorWidget{} case "twitch-top-games": w = &twitchGamesWidget{} 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{} case "to-do": w = &todoWidget{} default: return nil, fmt.Errorf("unknown widget type: %s", widgetType) } w.setID(widgetIDCounter.Add(1)) return w, nil } type widgets []widget func (w *widgets) UnmarshalYAML(node *yaml.Node) error { var nodes []yaml.Node if err := node.Decode(&nodes); err != nil { return err } for _, node := range nodes { meta := struct { Type string `yaml:"type"` }{} if err := node.Decode(&meta); err != nil { return err } widget, err := newWidget(meta.Type) if err != nil { return fmt.Errorf("line %d: %w", node.Line, err) } if err = node.Decode(widget); err != nil { return err } *w = append(*w, widget) } return nil } type widget interface { // These need to be exported because they get called in templates 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 const ( cacheTypeInfinite cacheType = iota cacheTypeDuration cacheTypeOnTheHour ) type widgetBase struct { ID uint64 `yaml:"-"` Providers *widgetProviders `yaml:"-"` Type string `yaml:"type"` Title string `yaml:"title"` TitleURL string `yaml:"title-url"` HideHeader bool `yaml:"hide-header"` 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:"-"` } type widgetProviders struct { assetResolver func(string) string } func (w *widgetBase) requiresUpdate(now *time.Time) bool { if w.cacheType == cacheTypeInfinite { return false } if w.nextUpdate.IsZero() { return true } return now.After(w.nextUpdate) } func (w *widgetBase) IsWIP() bool { return w.WIP } 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 { 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) // need to immediately re-render with the error, // otherwise risk breaking the page since the widget // will likely be partially rendered with tags not closed. w.templateBuffer.Reset() err2 := t.Execute(&w.templateBuffer, data) if err2 != nil { 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 } } return template.HTML(w.templateBuffer.String()) } func (w *widgetBase) withTitle(title string) *widgetBase { if w.Title == "" { w.Title = title } 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 if duration == -1 || w.CustomCacheDuration == 0 { w.cacheDuration = duration } else { w.cacheDuration = time.Duration(w.CustomCacheDuration) } return w } func (w *widgetBase) withCacheOnTheHour() *widgetBase { w.cacheType = cacheTypeOnTheHour return w } func (w *widgetBase) withNotice(err error) *widgetBase { w.Notice = err return w } func (w *widgetBase) withError(err error) *widgetBase { if err == nil && !w.ContentAvailable { w.ContentAvailable = true } w.Error = err return w } func (w *widgetBase) canContinueUpdateAfterHandlingErr(err error) bool { // TODO: needs covering more edge cases. // if there's partial content and we update early there's a chance // the early update returns even less content than the initial update. // need some kind of mechanism that tells us whether we should update early // or not depending on the number of things that failed during the initial // and subsequent update and how they failed - ie whether it was server // error (like gateway timeout, do retry early) or client error (like // hitting a rate limit, don't retry early). will require reworking a // good amount of code in the feed package and probably having a custom // error type that holds more information because screw wrapping errors. // alternatively have a resource cache and only refetch the failed resources, // then rebuild the widget. if err != nil { w.scheduleEarlyUpdate() if !errors.Is(err, errPartialContent) { w.withError(err) w.withNotice(nil) return false } w.withError(nil) w.withNotice(err) return true } w.withNotice(nil) w.withError(nil) w.scheduleNextUpdate() return true } func (w *widgetBase) getNextUpdateTime() time.Time { now := time.Now() if w.cacheType == cacheTypeDuration { return now.Add(w.cacheDuration) } if w.cacheType == cacheTypeOnTheHour { return now.Add(time.Duration( ((60-now.Minute())*60)-now.Second(), ) * time.Second) } return time.Time{} } func (w *widgetBase) scheduleNextUpdate() *widgetBase { w.nextUpdate = w.getNextUpdateTime() w.updateRetriedTimes = 0 return w } func (w *widgetBase) scheduleEarlyUpdate() *widgetBase { w.updateRetriedTimes++ if w.updateRetriedTimes > 5 { w.updateRetriedTimes = 5 } nextEarlyUpdate := time.Now().Add(time.Duration(math.Pow(float64(w.updateRetriedTimes), 2)) * time.Minute) nextUsualUpdate := w.getNextUpdateTime() if nextEarlyUpdate.After(nextUsualUpdate) { w.nextUpdate = nextUsualUpdate } else { w.nextUpdate = nextEarlyUpdate } return w } ================================================ FILE: main.go ================================================ package main import ( "os" "github.com/glanceapp/glance/internal/glance" ) func main() { os.Exit(glance.Main()) } ================================================ FILE: pkg/sysinfo/sysinfo.go ================================================ 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 the bsd's because it's not implemented by go-psutil for them if runtime.GOOS != "windows" && runtime.GOOS != "openbsd" && runtime.GOOS != "netbsd" && runtime.GOOS != "freebsd" { sensorReadings, err := sensors.SensorsTemperatures() _, errIsWarning := err.(*sensors.Warnings) if err == nil || errIsWarning { 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 }