[
  {
    "path": ".dockerignore",
    "content": "# https://docs.docker.com/build/building/context/#dockerignore-files\n# Ignore all files by default\n*\n\n# Only add necessary files to the Docker build context (Dockerfiles are always included implicitly)\n!/build/\n!/internal/\n!/pkg/\n!/go.mod\n!/go.sum\n!main.go\n"
  },
  {
    "path": ".github/CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\nglanceapp@duck.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [glanceapp]\npatreon: glanceapp\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yml",
    "content": "name: Bug report\ndescription: Let us know if something isn't working as expected\nlabels: [\"bug report\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        > [!NOTE]\n        >\n        > Do not prefix your title with \"[BUG]\", \"[Bug report]\", etc., a label will be added automatically.\n\n        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.\n\n        Please include only the information you think is relevant to the bug:\n\n        * How did you install Glance? (Docker container, manual binary install, etc)\n        * Which version of Glance are you using?\n        * Include the relevant parts of your `glance.yml` if applicable (widget, data source, properties used, etc)\n        * Include any relevant logs or screenshots if applicable\n        * Is the issue specific to a certain browser or OS?\n        * Steps to reliably reproduce the issue\n        * Are you hosting Glance on a VPS?\n        * Anything else you think might be relevant\n\n        **No need to copy the above list into your description, it's just a guide to help you provide the most useful information.**\n\n  - type: textarea\n    id: description\n    validations:\n      required: true\n    attributes:\n      label: Description\n\n  - type: markdown\n    attributes:\n      value: |\n        Thank you for taking the time to submit a bug report.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Discussions\n    url: https://github.com/glanceapp/glance/discussions\n    about: For help, feedback, guides, resources and more\n  - name: Discord\n    url: https://discord.com/invite/7KQ7Xa9kJd\n    about: Much like the discussions but more chatty\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yml",
    "content": "name: Feature request\ndescription: Share your ideas for new features or improvements\nlabels: [\"feature request\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        > [!NOTE]\n        >\n        > Do not prefix your title with \"[REQUEST]\", \"[Feature request]\", etc., a label will be added automatically.\n\n        Please provide a detailed description of what the feature would do and what it would look like:\n\n        * What problem would this feature solve?\n        * Are there any potential downsides to this feature?\n        * If applicable, what would the configuration for this feature look like?\n        * Are there any existing examples of this feature in other software?\n        * If applicable, include any external documentation required to implement this feature\n        * Anything else you think might be relevant\n\n        **No need to copy the above list into your description, it's just a guide to help you provide the most useful information.**\n\n  - type: textarea\n    id: description\n    validations:\n      required: true\n    attributes:\n      label: Description\n\n  - type: markdown\n    attributes:\n      value: |\n        Thank you for taking the time to submit your idea.\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!-- If your pull request adds new features, changes existing ones or fixes any bugs, please use the dev branch as the base, otherwise use the main branch -->\n"
  },
  {
    "path": ".github/SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\nSecurity updates will be applied to the latest as well as previous minor version release depending on severity and if applicable.\n\n## Reporting a Vulnerability\n\nPlease 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.\n"
  },
  {
    "path": ".github/workflows/release.yaml",
    "content": "name: Create release\n\npermissions:\n  contents: write\n\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout the target Git reference\n        uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n\n      - name: Log in to Docker Hub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n\n      - name: Set up Golang\n        uses: actions/setup-go@v5\n        with:\n          go-version-file: go.mod\n\n      - name: Set up Docker buildx\n        uses: docker/setup-buildx-action@v3\n\n      - name: Run GoReleaser\n        uses: goreleaser/goreleaser-action@v5\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          args: release\n"
  },
  {
    "path": ".gitignore",
    "content": "/assets\n/build\n/playground\n/.idea\n/glance*.yml\n"
  },
  {
    "path": ".goreleaser.yaml",
    "content": "project_name: glanceapp/glance\n\nchecksum:\n  disable: true\n\nbuilds:\n  - binary: glance\n    env:\n      - CGO_ENABLED=0\n    goos:\n      - linux\n      - openbsd\n      - freebsd\n      - windows\n      - darwin\n    goarch:\n      - amd64\n      - arm64\n      - arm\n      - 386\n    goarm:\n      - 7\n    ldflags:\n      - -s -w -X github.com/glanceapp/glance/internal/glance.buildVersion={{ .Tag }}\n\narchives:\n  -\n    name_template: \"glance-{{ .Os }}-{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}\"\n    files:\n      - nothing*\n    format_overrides:\n      - goos: windows\n        format: zip\n\ndockers:\n  - image_templates:\n      - &amd64_image \"{{ .ProjectName }}:{{ .Tag }}-amd64\"\n    build_flag_templates:\n      - --platform=linux/amd64\n    goarch: amd64\n    use: buildx\n    dockerfile: Dockerfile.goreleaser\n\n  - image_templates:\n      - &arm64v8_image \"{{ .ProjectName }}:{{ .Tag }}-arm64\"\n    build_flag_templates:\n      - --platform=linux/arm64\n    goarch: arm64\n    use: buildx\n    dockerfile: Dockerfile.goreleaser\n\n  - image_templates:\n      - &armv7_image \"{{ .ProjectName }}:{{ .Tag }}-armv7\"\n    build_flag_templates:\n      - --platform=linux/arm/v7\n    goarch: arm\n    goarm: 7\n    use: buildx\n    dockerfile: Dockerfile.goreleaser\n\ndocker_manifests:\n  - name_template: \"{{ .ProjectName }}:{{ .Tag }}\"\n    image_templates: &multiarch_images\n      - *amd64_image\n      - *arm64v8_image\n      - *armv7_image\n  - name_template: \"{{ .ProjectName }}:latest\"\n    skip_push: auto\n    image_templates: *multiarch_images\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM golang:1.24.3-alpine3.21 AS builder\n\nWORKDIR /app\nCOPY . /app\nRUN CGO_ENABLED=0 go build .\n\nFROM alpine:3.21\n\nWORKDIR /app\nCOPY --from=builder /app/glance .\n\nEXPOSE 8080/tcp\nENTRYPOINT [\"/app/glance\", \"--config\", \"/app/config/glance.yml\"]\n"
  },
  {
    "path": "Dockerfile.goreleaser",
    "content": "FROM alpine:3.21\n\nWORKDIR /app\nCOPY glance .\n\nEXPOSE 8080/tcp\nENTRYPOINT [\"/app/glance\", \"--config\", \"/app/config/glance.yml\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\"><img src=\"docs/logo.png\"></p>\n<h1 align=\"center\">Glance</h1>\n<p align=\"center\">\n  <a href=\"#installation\">Install</a> •\n  <a href=\"docs/configuration.md#configuring-glance\">Configuration</a> •\n  <a href=\"https://discord.com/invite/7KQ7Xa9kJd\">Discord</a> •\n  <a href=\"https://github.com/sponsors/glanceapp\">Sponsor</a>\n</p>\n<p align=\"center\">\n  <a href=\"https://github.com/glanceapp/community-widgets\">Community widgets</a> •\n  <a href=\"docs/preconfigured-pages.md\">Preconfigured pages</a> •\n  <a href=\"docs/themes.md\">Themes</a>\n</p>\n\n<p align=\"center\">A lightweight, highly customizable dashboard that displays<br> your feeds in a beautiful, streamlined interface</p>\n\n![](docs/images/readme-main-image.png)\n\n## Features\n### Various widgets\n* RSS feeds\n* Subreddit posts\n* Hacker News posts\n* Weather forecasts\n* YouTube channel uploads\n* Twitch channels\n* Market prices\n* Docker containers status\n* Server stats\n* Custom widgets\n* [and many more...](docs/configuration.md#configuring-glance)\n\n### Fast and lightweight\n* Low memory usage\n* Few dependencies\n* Minimal vanilla JS\n* Single <20mb binary available for multiple OSs & architectures and just as small Docker container\n* Uncached pages usually load within ~1s (depending on internet speed and number of widgets)\n\n### Tons of customizability\n* Different layouts\n* As many pages/tabs as you need\n* Numerous configuration options for each widget\n* Multiple styles for some widgets\n* Custom CSS\n\n### Optimized for mobile devices\nBecause you'll want to take it with you on the go.\n\n![](docs/images/mobile-preview.png)\n\n### Themeable\nEasily create your own theme by tweaking a few numbers or choose from one of the [already available themes](docs/themes.md).\n\n![](docs/images/themes-example.png)\n\n<br>\n\n## Configuration\nConfiguration 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).\n<details>\n<summary><strong>Preview example configuration file</strong></summary>\n<br>\n\n```yaml\npages:\n  - name: Home\n    columns:\n      - size: small\n        widgets:\n          - type: calendar\n            first-day-of-week: monday\n\n          - type: rss\n            limit: 10\n            collapse-after: 3\n            cache: 12h\n            feeds:\n              - url: https://selfh.st/rss/\n                title: selfh.st\n                limit: 4\n              - url: https://ciechanow.ski/atom.xml\n              - url: https://www.joshwcomeau.com/rss.xml\n                title: Josh Comeau\n              - url: https://samwho.dev/rss.xml\n              - url: https://ishadeed.com/feed.xml\n                title: Ahmad Shadeed\n\n          - type: twitch-channels\n            channels:\n              - theprimeagen\n              - j_blow\n              - piratesoftware\n              - cohhcarnage\n              - christitustech\n              - EJ_SA\n\n      - size: full\n        widgets:\n          - type: group\n            widgets:\n              - type: hacker-news\n              - type: lobsters\n\n          - type: videos\n            channels:\n              - UCXuqSBlHAE6Xw-yeJA0Tunw # Linus Tech Tips\n              - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling\n              - UCsBjURrPoezykLs9EqgamOA # Fireship\n              - UCBJycsmduvYEL83R_U4JriQ # Marques Brownlee\n              - UCHnyfMqiRRG1u-2MsSQLbXA # Veritasium\n\n          - type: group\n            widgets:\n              - type: reddit\n                subreddit: technology\n                show-thumbnails: true\n              - type: reddit\n                subreddit: selfhosted\n                show-thumbnails: true\n\n      - size: small\n        widgets:\n          - type: weather\n            location: London, United Kingdom\n            units: metric\n            hour-format: 12h\n\n          - type: markets\n            markets:\n              - symbol: SPY\n                name: S&P 500\n              - symbol: BTC-USD\n                name: Bitcoin\n              - symbol: NVDA\n                name: NVIDIA\n              - symbol: AAPL\n                name: Apple\n              - symbol: MSFT\n                name: Microsoft\n\n          - type: releases\n            cache: 1d\n            repositories:\n              - glanceapp/glance\n              - go-gitea/gitea\n              - immich-app/immich\n              - syncthing/syncthing\n```\n</details>\n\n<br>\n\n## Installation\n\nChoose one of the following methods:\n\n<details>\n<summary><strong>Docker compose using provided directory structure (recommended)</strong></summary>\n<br>\n\nCreate a new directory called `glance` as well as the template files within it by running:\n\n```bash\nmkdir glance && cd glance && curl -sL https://github.com/glanceapp/docker-compose-template/archive/refs/heads/main.tar.gz | tar -xzf - --strip-components 2\n```\n\n*[click here to view the files that will be created](https://github.com/glanceapp/docker-compose-template/tree/main/root)*\n\nThen, edit the following files as desired:\n* `docker-compose.yml` to configure the port, volumes and other containery things\n* `config/home.yml` to configure the widgets or layout of the home page\n* `config/glance.yml` if you want to change the theme or add more pages\n\n<details>\n<summary>Other files you may want to edit</summary>\n\n* `.env` to configure environment variables that will be available inside configuration files\n* `assets/user.css` to add custom CSS\n</details>\n\nWhen ready, run:\n\n```bash\ndocker compose up -d\n```\n\nIf you encounter any issues, you can check the logs by running:\n\n```bash\ndocker compose logs\n```\n\n<hr>\n</details>\n\n<details>\n<summary><strong>Docker compose manual</strong></summary>\n<br>\n\nCreate a `docker-compose.yml` file with the following contents:\n\n```yaml\nservices:\n  glance:\n    container_name: glance\n    image: glanceapp/glance\n    restart: unless-stopped\n    volumes:\n      - ./config:/app/config\n    ports:\n      - 8080:8080\n```\n\nThen, 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:\n\n```bash\nmkdir config && wget -O config/glance.yml https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml\n```\n\nFeel free to edit the `glance.yml` file to your liking, and when ready run:\n\n```bash\ndocker compose up -d\n```\n\nIf you encounter any issues, you can check the logs by running:\n\n```bash\ndocker logs glance\n```\n\n<hr>\n</details>\n\n<details>\n<summary><strong>Manual binary installation</strong></summary>\n<br>\n\nPrecompiled binaries are available for Linux, Windows and macOS (x86, x86_64, ARM and ARM64 architectures).\n\n### Linux\n\nVisit 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:\n\n```bash\n/opt/glance/glance --config /etc/glance.yml\n```\n\nTo grab a starting template for the config file, run:\n\n```bash\nwget https://raw.githubusercontent.com/glanceapp/glance/refs/heads/main/docs/glance.yml\n```\n\n### Windows\n\nDownload 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.\n\n\n\n<hr>\n</details>\n\n<details>\n<summary><strong>Other</strong></summary>\n<br>\n\nGlance can also be installed through the following 3rd party channels:\n* [Proxmox VE Helper Script](https://community-scripts.github.io/ProxmoxVE/scripts?id=glance)\n* [NixOS package](https://search.nixos.org/packages?channel=unstable&show=glance)\n* [Coolify.io](https://coolify.io/docs/services/glance/)\n\n<hr>\n</details>\n\n<br>\n\n## Common issues\n<details>\n<summary><strong>Requests timing out</strong></summary>\n\nThe 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.\n\nIf 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:\n```yaml\nnetworks:\n  podman:\n    external: true\n```\n</details>\n\n<details>\n<summary><strong>Broken layout for markets, bookmarks or other widgets</strong></summary>\n\nThis is almost always caused by the browser extension Dark Reader. To fix this, disable dark mode for the domain where Glance is hosted.\n</details>\n\n<details>\n<summary><strong>cannot unmarshal !!map into []glance.page</strong></summary>\n\nThe 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.\n\n</details>\n\n<br>\n\n## FAQ\n<details>\n<summary><strong>Does the information on the page update automatically?</strong></summary>\nNo, 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.\n</details>\n\n<details>\n<summary><strong>How frequently do widgets update?</strong></summary>\nNo 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.\n</details>\n\n<details>\n<summary><strong>Can I create my own widgets?</strong></summary>\n\nYes, there are multiple ways to create custom widgets:\n* `iframe` widget - allows you to embed things from other websites\n* `html` widget - allows you to insert your own static HTML\n* `extension` widget - fetch HTML from a URL\n* `custom-api` widget - fetch JSON from a URL and render it using custom HTML\n</details>\n\n<details>\n<summary><strong>Can I change the title of a widget?</strong></summary>\n\nYes, the title of all widgets can be changed by specifying the `title` property in the widget's configuration:\n\n```yaml\n- type: rss\n  title: My custom title\n\n- type: markets\n  title: My custom title\n\n- type: videos\n  title: My custom title\n\n# and so on for all widgets...\n```\n</details>\n\n<br>\n\n## Feature requests\n\nNew 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).\n\nFeature requests are tagged with one of the following:\n\n* [Roadmap](https://github.com/glanceapp/glance/labels/roadmap) - will be implemented in a future release\n* [Backlog](https://github.com/glanceapp/glance/labels/backlog) - may be implemented in the future but needs further feedback or interest from the community\n* [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\n\n<br>\n\n## Building from source\n\nChoose one of the following methods:\n\n<details>\n<summary><strong>Build binary with Go</strong></summary>\n<br>\n\nRequirements: [Go](https://go.dev/dl/) >= v1.23\n\nTo build the project for your current OS and architecture, run:\n\n```bash\ngo build -o build/glance .\n```\n\nTo build for a specific OS and architecture, run:\n\n```bash\nGOOS=linux GOARCH=amd64 go build -o build/glance .\n```\n\n[*click here for a full list of GOOS and GOARCH combinations*](https://go.dev/doc/install/source#:~:text=$GOOS%20and%20$GOARCH)\n\nAlternatively, if you just want to run the app without creating a binary, like when you're testing out changes, you can run:\n\n```bash\ngo run .\n```\n<hr>\n</details>\n\n<details>\n<summary><strong>Build project and Docker image with Docker</strong></summary>\n<br>\n\nRequirements: [Docker](https://docs.docker.com/engine/install/)\n\nTo build the project and image using just Docker, run:\n\n*(replace `owner` with your name or organization)*\n\n```bash\ndocker build -t owner/glance:latest .\n```\n\nIf you wish to push the image to a registry (by default Docker Hub), run:\n\n```bash\ndocker push owner/glance:latest\n```\n\n<hr>\n</details>\n\n<br>\n\n## Contributing guidelines\n\n* 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\n* Please don't submit PRs for feature requests that are either in the roadmap<sup>[1]</sup>, backlog<sup>[2]</sup> or icebox<sup>[3]</sup>\n* Use `dev` for the base branch if you're adding new features or fixing bugs, otherwise use `main`\n* Avoid introducing new dependencies\n* Avoid making backwards-incompatible configuration changes\n* Avoid introducing new colors or hard-coding colors, use the standard `primary`, `positive` and `negative`\n* For icons, try to use [heroicons](https://heroicons.com/) where applicable\n* Provide a screenshot of the changes if UI related where possible\n* No `package.json`\n\n<details>\n<summary><strong><sup>[1] [2] [3]</sup></strong></summary>\n\n[1] The feature likely already has work put into it that may conflict with your implementation\n\n[2] The demand, implementation or functionality for this feature is not yet clear\n\n[3] No plans to add this feature for the time being\n\n</details>\n\n<br>\n\n## Thank you\n\nTo 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.\n"
  },
  {
    "path": "docs/configuration.md",
    "content": "# Configuring Glance\n\n- [Preconfigured page](#preconfigured-page)\n- [The config file](#the-config-file)\n  - [Auto reload](#auto-reload)\n  - [Environment variables](#environment-variables)\n    - [Other ways of providing tokens/passwords/secrets](#other-ways-of-providing-tokenspasswordssecrets)\n  - [Including other config files](#including-other-config-files)\n  - [Icons](#icons)\n  - [Config schema](#config-schema)\n- [Authentication](#authentication)\n- [Server](#server)\n- [Document](#document)\n- [Branding](#branding)\n- [Theme](#theme)\n  - [Available themes](#available-themes)\n- [Pages & Columns](#pages--columns)\n- [Widgets](#widgets)\n  - [RSS](#rss)\n  - [Videos](#videos)\n  - [Hacker News](#hacker-news)\n  - [Lobsters](#lobsters)\n  - [Reddit](#reddit)\n  - [Search](#search-widget)\n  - [Group](#group)\n  - [Split Column](#split-column)\n  - [Custom API](#custom-api)\n  - [Extension](#extension)\n  - [Weather](#weather)\n  - [Todo](#todo)\n  - [Monitor](#monitor)\n  - [Releases](#releases)\n  - [Docker Containers](#docker-containers)\n  - [DNS Stats](#dns-stats)\n  - [Server Stats](#server-stats)\n  - [Repository](#repository)\n  - [Bookmarks](#bookmarks)\n  - [Calendar](#calendar)\n  - [Calendar (legacy)](#calendar-legacy)\n  - [ChangeDetection.io](#changedetectionio)\n  - [Clock](#clock)\n  - [Markets](#markets)\n  - [Twitch Channels](#twitch-channels)\n  - [Twitch Top Games](#twitch-top-games)\n  - [iframe](#iframe)\n  - [HTML](#html)\n\n\n## Preconfigured page\nIf 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:\n\n![](images/preconfigured-page-preview.png)\n\nConfigure the widgets, add more of them, add extra pages, etc. Make it your own!\n\n## The config file\n\n### Auto reload\nAutomatic 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.\n\n> [!NOTE]\n>\n> 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.\n\n> [!CAUTION]\n>\n> 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.\n\n### Environment variables\nInserting 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:\n\n```yaml\nserver:\n  host: ${HOST}\n  port: ${PORT}\n```\n\nCan also be in the middle of a string:\n\n```yaml\n- type: rss\n  title: ${RSS_TITLE}\n  feeds:\n    - url: http://domain.com/rss/${RSS_CATEGORY}.xml\n```\n\nWorks with any type of value, not just strings:\n\n```yaml\n- type: rss\n  limit: ${RSS_LIMIT}\n```\n\nIf 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 `\\`:\n\n```yaml\nsomething: \\${NOT_AN_ENV_VAR}\n```\n\n#### Other ways of providing tokens/passwords/secrets\n\nYou can use [Docker secrets](https://docs.docker.com/compose/how-tos/use-secrets/) with the following syntax:\n\n```yaml\n# This will be replaced with the contents of the file /run/secrets/github_token\n# so long as the secret `github_token` is provided to the container\ntoken: ${secret:github_token}\n```\n\nAlternatively, you can load the contents of a file who's path is provided by an environment variable:\n\n`docker-compose.yml`\n```yaml\nservices:\n  glance:\n    image: glanceapp/glance\n    environment:\n      - TOKEN_FILE=/home/user/token\n    volumes:\n      - /home/user/token:/home/user/token\n```\n\n`glance.yml`\n```yaml\ntoken: ${readFileFromEnv:TOKEN_FILE}\n```\n\n> [!NOTE]\n>\n> The contents of the file will be stripped of any leading/trailing whitespace before being used.\n\n### Including other config files\nIncluding 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:\n\n```yaml\npages:\n  - $include: home.yml\n  - $include: videos.yml\n  - $include: homelab.yml\n```\n\nThe 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:\n\n`glance.yml`\n\n```yaml\npages:\n  - name: Home\n    columns:\n      - size: full\n        widgets:\n          - $include: rss.yml\n  - name: News\n    columns:\n      - size: full\n        widgets:\n          - type: group\n            widgets:\n              - $include: rss.yml\n              - type: reddit\n                subreddit: news\n```\n\n`rss.yml`\n\n```yaml\n- type: rss\n  title: News\n  feeds:\n    - url: ${RSS_URL}\n```\n\nThe `$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.\n\nIf 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:\n\n```sh\nglance --config /path/to/glance.yml config:print | less -N\n```\n\nThis is a bit more convoluted when running Glance inside a Docker container:\n\n```sh\ndocker run --rm -v ./glance.yml:/app/config/glance.yml glanceapp/glance config:print | less -N\n```\n\nThis assumes that the config you want to print is in your current working directory and is named `glance.yml`.\n\n## Icons\n\nFor 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:\n\n```yml\nicon: si:immich # si for Simple icons https://simpleicons.org/\nicon: sh:immich # sh for selfh.st icons https://selfh.st/icons/\nicon: di:immich # di for Dashboard icons https://github.com/homarr-labs/dashboard-icons\nicon: mdi:camera # mdi for Material Design icons https://pictogrammers.com/library/mdi/\n```\n\n> [!NOTE]\n>\n> 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.\n\nIcons 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:\n\n```yaml\nicon: auto-invert https://example.com/path/to/icon.png # with a URL\nicon: auto-invert sh:glance-dark # with a selfh.st icon\n```\n\nThis expects the icon to be black and will automatically invert it to white when using a dark theme.\n\n## Config schema\n\nFor 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!\n\n## Authentication\n\nTo 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:\n\n```yaml\nauth:\n  secret-key: # this must be set to a random value generated using the secret:make CLI command\n  users:\n    admin:\n      password: 123456\n    svilen:\n      password: 123456\n```\n\nTo generate a secret key, run the following command:\n\n```sh\n./glance secret:make\n```\n\nOr with Docker:\n\n```sh\ndocker run --rm glanceapp/glance secret:make\n```\n\n### Using hashed passwords\n\nIf 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:\n\n```sh\n./glance password:hash mysecretpassword\n```\n\nOr with Docker:\n\n```sh\ndocker run --rm glanceapp/glance password:hash mysecretpassword\n```\n\nThen, in your config file use the `password-hash` property instead of `password`:\n\n```yaml\nauth:\n  secret-key: # this must be set to a random value generated using the secret:make CLI command\n  users:\n    admin:\n      password-hash: $2a$10$o6SXqiccI3DDP2dN4ADumuOeIHET6Q4bUMYZD6rT2Aqt6XQ3DyO.6\n```\n\n### Preventing brute-force attacks\n\nGlance 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`:\n\n```yaml\nserver:\n  proxied: true\n```\n\nWhen 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.\n\n## Server\nServer configuration is done through a top level `server` property. Example:\n\n```yaml\nserver:\n  port: 8080\n  assets-path: /home/user/glance-assets\n```\n\n### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| host | string | no |  |\n| port | number | no | 8080 |\n| proxied | boolean | no | false |\n| base-url | string | no | |\n| assets-path | string | no |  |\n\n#### `host`\nThe 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.\n\n#### `port`\nA number between 1 and 65,535, so long as that port isn't already used by anything else.\n\n#### `proxied`\nSet 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.\n\n#### `base-url`\nThe 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.\n\n> [!IMPORTANT]\n> You need to strip the `base-url` prefix before forwarding the request to the Glance server.\n> 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).\n\n#### `assets-path`\nThe 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.\n\n> [!IMPORTANT]\n>\n> 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.\n> Example:\n>\n> If your assets are in:\n> ```\n> /home/user/glance-assets\n> ```\n>\n> You should mount:\n> ```\n> /home/user/glance-assets:/app/assets\n> ```\n>\n> And your config should contain:\n> ```\n> assets-path: /app/assets\n> ```\n\n##### Examples\n\nSay you have a directory `glance-assets` with a file `gitea-icon.png` in it and you specify your assets path like:\n\n```yaml\nassets-path: /home/user/glance-assets\n```\n\nTo be able to point to an asset from your assets path, use the `/assets/` path like such:\n\n```yaml\nicon: /assets/gitea-icon.png\n```\n\n## Document\nIf you want to insert custom HTML into the `<head>` of the document for all pages, you can do so by using the `document` property. Example:\n\n```yaml\ndocument:\n  head: |\n    <script src=\"/assets/custom.js\"></script>\n```\n\n## Branding\nYou can adjust the various parts of the branding through a top level `branding` property. Example:\n\n```yaml\nbranding:\n  custom-footer: |\n    <p>Powered by <a href=\"https://github.com/glanceapp/glance\">Glance</a></p>\n  logo-url: /assets/logo.png\n  favicon-url: /assets/logo.png\n  app-name: \"My Dashboard\"\n  app-icon-url: \"/assets/app-icon.png\"\n  app-background-color: \"#151519\"\n```\n\n### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| hide-footer | bool | no | false |\n| custom-footer | string | no |  |\n| logo-text | string | no | G |\n| logo-url | string | no | |\n| favicon-url | string | no | |\n| app-name | string | no | Glance |\n| app-icon-url | string | no | Glance's default icon |\n| app-background-color | string | no | Glance's default background color |\n\n#### `hide-footer`\nHides the footer when set to `true`.\n\n#### `custom-footer`\nSpecify custom HTML to use for the footer.\n\n#### `logo-text`\nSpecify custom text to use instead of the \"G\" found in the navigation.\n\n#### `logo-url`\nSpecify 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.\n\n#### `favicon-url`\nSpecify a URL to a custom image to use for the favicon.\n\n#### `app-name`\nSpecify the name of the web app shown in browser tab and PWA.\n\n#### `app-icon-url`\nSpecify URL for PWA and browser tab icon (512x512 PNG).\n\n#### `app-background-color`\nSpecify background color for PWA. Must be a valid CSS color.\n\n## Theme\nTheming 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.\n\nExample:\n\n```yaml\ntheme:\n  # This will be the default theme\n  background-color: 100 20 10\n  primary-color: 40 90 40\n  contrast-multiplier: 1.1\n\n  disable-picker: false\n  presets:\n    gruvbox-dark:\n      background-color: 0 0 16\n      primary-color: 43 59 81\n      positive-color: 61 66 44\n      negative-color: 6 96 59\n\n    zebra:\n      light: true\n      background-color: 0 0 95\n      primary-color: 0 0 10\n      negative-color: 0 90 50\n```\n\n### Available themes\nIf 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.\n\n### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| light | boolean | no | false |\n| background-color | HSL | no | 240 8 9 |\n| primary-color | HSL | no | 43 50 70 |\n| positive-color | HSL | no | same as `primary-color` |\n| negative-color | HSL | no | 0 70 70 |\n| contrast-multiplier | number | no | 1 |\n| text-saturation-multiplier | number | no | 1 |\n| custom-css-file | string | no | |\n| disable-picker | bool | false | |\n| presets | object | no | |\n\n#### `light`\nWhether 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.\n\n#### `background-color`\nColor of the page and widgets.\n\n#### `primary-color`\nColor used across the page, largely to indicate unvisited links.\n\n#### `positive-color`\nUsed 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.\n\n#### `negative-color`\nOppposite of `positive-color`.\n\n#### `contrast-multiplier`\nUsed 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:\n\n![difference between 1 and 1.3 contrast](images/contrast-multiplier-example.png)\n\n#### `text-saturation-multiplier`\nUsed 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.\n\n#### `custom-css-file`\nPath to a custom CSS file, either external or one from within the server configured assets path. Example:\n\n```yaml\ntheme:\n  custom-css-file: /assets/my-style.css\n```\n\n> [!TIP]\n>\n> 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:\n>\n> ```css\n> .widget-type-rss a {\n>     font-size: 1.5rem;\n> }\n> ```\n>\n> In addition, you can also use the `css-class` property which is available on every widget to set custom class names for individual widgets.\n\n#### `disable-picker`\nWhen 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.\n\n#### `presets`\nDefine 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.\n\nExample:\n\n```yaml\ntheme:\n  presets:\n    my-custom-dark-theme:\n      background-color: 229 19 23\n      contrast-multiplier: 1.2\n      primary-color: 222 74 74\n      positive-color: 96 44 68\n      negative-color: 359 68 71\n    my-custom-light-theme:\n      light: true\n      background-color: 220 23 95\n      contrast-multiplier: 1.1\n      primary-color: 220 91 54\n      positive-color: 109 58 40\n      negative-color: 347 87 44\n```\n\nTo override the default dark and light themes, use the key names `default-dark` and `default-light`.\n\n## Pages & Columns\n![illustration of pages and columns](images/pages-and-columns-illustration.png)\n\nUsing pages and columns is how widgets are organized. Each page contains up to 3 columns and each column can have any number of widgets.\n\n### Pages\nPages 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:\n\n```yaml\npages:\n  - name: Home\n    columns: ...\n\n  - name: Videos\n    columns: ...\n\n  - name: Homelab\n    columns: ...\n```\n\n### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| name | string | yes | |\n| slug | string | no | |\n| width | string | no | |\n| desktop-navigation-width | string | no | |\n| center-vertically | boolean | no | false |\n| hide-desktop-navigation | boolean | no | false |\n| show-mobile-header | boolean | no | false |\n| head-widgets | array | no | |\n| columns | array | yes | |\n\n#### `name`\nThe name of the page which gets shown in the navigation bar.\n\n#### `slug`\nThe 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.\n\n#### `width`\nThe maximum width of the page on desktop. Possible values are `default`, `slim` and `wide`.\n\n#### `desktop-navigation-width`\nThe 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`.\n\nHere are the pixel equivalents for each value:\n\n* default: `1600px`\n* slim: `1100px`\n* wide: `1920px`\n\n> [!NOTE]\n>\n> When using `slim`, the maximum number of columns allowed for that page is `2`.\n\n#### `center-vertically`\nWhen set to `true`, vertically centers the content on the page. Has no effect if the content is taller than the height of the viewport.\n\n#### `hide-desktop-navigation`\nWhether to show the navigation links at the top of the page on desktop.\n\n#### `show-mobile-header`\nWhether 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.\n\nPreview:\n\n![](images/mobile-header-preview.png)\n\n#### `head-widgets`\n\nHead 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:\n\n![](images/head-widgets-preview.png)\n\n```yaml\npages:\n  - name: Home\n    head-widgets:\n      - type: markets\n        hide-header: true\n        markets:\n          - symbol: SPY\n            name: S&P 500\n          - symbol: BTC-USD\n            name: Bitcoin\n          - symbol: NVDA\n            name: NVIDIA\n          - symbol: AAPL\n            name: Apple\n          - symbol: MSFT\n            name: Microsoft\n\n    columns:\n      - size: small\n        widgets:\n          - type: calendar\n      - size: full\n        widgets:\n          - type: hacker-news\n      - size: small\n        widgets:\n          - type: weather\n            location: London, United Kingdom\n```\n\n### Columns\nColumns 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:\n\n```yaml\npages:\n  - name: Home\n    columns:\n      - size: small\n        widgets: ...\n      - size: full\n        widgets: ...\n      - size: small\n        widgets: ...\n```\n\n### Properties\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| size | string | yes |\n| widgets | array | no |\n\nHere are some of the possible column configurations:\n\n![column configuration small-full-small](images/column-configuration-1.png)\n\n```yaml\ncolumns:\n  - size: small\n    widgets: ...\n  - size: full\n    widgets: ...\n  - size: small\n    widgets: ...\n```\n\n![column configuration small-full-small](images/column-configuration-2.png)\n\n```yaml\ncolumns:\n  - size: full\n    widgets: ...\n  - size: small\n    widgets: ...\n```\n\n![column configuration small-full-small](images/column-configuration-3.png)\n\n```yaml\ncolumns:\n  - size: full\n    widgets: ...\n  - size: full\n    widgets: ...\n```\n\n## Widgets\nWidgets are defined for each column using a `widgets` property. Example:\n\n```yaml\npages:\n  - name: Home\n    columns:\n      - size: small\n        widgets:\n          - type: weather\n            location: London, United Kingdom\n```\n\n> [!NOTE]\n>\n> Currently not all widgets are designed to fit every column size, however some widgets offer different \"styles\" that help alleviate this limitation.\n\n### Shared Properties\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| type | string | yes |\n| title | string | no |\n| title-url | string | no |\n| hide-header | boolean | no | false |\n| cache | string | no |\n| css-class | string | no |\n\n#### `type`\nUsed to specify the widget.\n\n#### `title`\nThe title of the widget. If left blank it will be defined by the widget.\n\n#### `title-url`\nThe URL to go to when clicking on the widget's title. If left blank it will be defined by the widget (if available).\n\n#### `hide-header`\nWhen set to `true`, the header (title) of the widget will be hidden. You cannot hide the header of the group widget.\n\n> [!NOTE]\n>\n> 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.\n\n#### `cache`\nHow 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:\n\n```yaml\ncache: 30s # 30 seconds\ncache: 5m  # 5 minutes\ncache: 2h  # 2 hours\ncache: 1d  # 1 day\n```\n\n> [!NOTE]\n>\n> Not all widgets can have their cache duration modified. The calendar and weather widgets update on the hour and this cannot be changed.\n\n#### `css-class`\nSet custom CSS classes for the specific widget instance.\n\n### RSS\nDisplay a list of articles from multiple RSS feeds.\n\nExample:\n\n```yaml\n- type: rss\n  title: News\n  style: horizontal-cards\n  feeds:\n    - url: https://feeds.bloomberg.com/markets/news.rss\n      title: Bloomberg\n    - url: https://moxie.foxbusiness.com/google-publisher/markets.xml\n      title: Fox Business\n    - url: https://moxie.foxbusiness.com/google-publisher/technology.xml\n      title: Fox Business\n```\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| style | string | no | vertical-list |\n| feeds | array | yes |\n| thumbnail-height | float | no | 10 |\n| card-height | float | no | 27 |\n| limit | integer | no | 25 |\n| preserve-order | bool | no | false |\n| single-line-titles | boolean | no | false |\n| collapse-after | integer | no | 5 |\n\n##### `limit`\nThe maximum number of articles to show.\n\n##### `collapse-after`\nHow many articles are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n##### `preserve-order`\nWhen 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.\n\n##### `single-line-titles`\nWhen set to `true`, truncates the title of each post if it exceeds one line. Only applies when the style is set to `vertical-list`.\n\n##### `style`\nUsed to change the appearance of the widget. Possible values are:\n\n* `vertical-list` - suitable for `full` and `small` columns\n* `detailed-list` - suitable for `full` columns\n* `horizontal-cards` - suitable for `full` columns\n* `horizontal-cards-2` - suitable for `full` columns\n\nBelow is a preview of each style:\n\n`vertical-list`\n\n![preview of vertical-list style for RSS widget](images/rss-feed-vertical-list-preview.png)\n\n`detailed-list`\n\n![preview of detailed-list style for RSS widget](images/rss-widget-detailed-list-preview.png)\n\n`horizontal-cards`\n\n![preview of horizontal-cards style for RSS widget](images/rss-feed-horizontal-cards-preview.png)\n\n`horizontal-cards-2`\n\n![preview of horizontal-cards-2 style for RSS widget](images/rss-widget-horizontal-cards-2-preview.png)\n\n##### `thumbnail-height`\nUsed 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`.\n\n##### `card-height`\nUsed to modify the height of cards when using the `horizontal-cards-2` style. The default value is `27` and the units are `rem`.\n\n##### `feeds`\nAn array of RSS/atom feeds. The title can optionally be changed.\n\n###### Properties for each feed\n| Name | Type | Required | Default | Notes |\n| ---- | ---- | -------- | ------- | ----- |\n| url | string | yes | | |\n| title | string | no | the title provided by the feed | |\n| hide-categories | boolean | no | false | Only applicable for `detailed-list` style |\n| hide-description | boolean | no | false | Only applicable for `detailed-list` style |\n| limit | integer | no | | |\n| item-link-prefix | string | no | | |\n| headers | key (string) & value (string) | no | | |\n\n###### `limit`\nThe 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.\n\n###### `item-link-prefix`\nIf 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.\n\n###### `headers`\nOptionally specify the headers that will be sent with the request. Example:\n\n```yaml\n- type: rss\n  feeds:\n    - url: https://domain.com/rss\n      headers:\n        User-Agent: Custom User Agent\n```\n\n### Videos\nDisplay a list of the latest videos from specific YouTube channels.\n\nExample:\n\n```yaml\n- type: videos\n  channels:\n    - UCXuqSBlHAE6Xw-yeJA0Tunw\n    - UCBJycsmduvYEL83R_U4JriQ\n    - UCHnyfMqiRRG1u-2MsSQLbXA\n```\n\nPreview:\n![](images/videos-widget-preview.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| channels | array | yes | |\n| playlists | array | no | |\n| limit | integer | no | 25 |\n| style | string | no | horizontal-cards |\n| collapse-after | integer | no | 7 |\n| collapse-after-rows | integer | no | 4 |\n| include-shorts | boolean | no | false |\n| video-url-template | string | no | https://www.youtube.com/watch?v={VIDEO-ID} |\n\n##### `channels`\nA list of channels IDs.\n\nOne way of getting the ID of a channel is going to the channel's page and clicking on its description:\n\n![](images/videos-channel-description-example.png)\n\nThen scroll down and click on \"Share channel\", then \"Copy channel ID\":\n\n![](images/videos-copy-channel-id-example.png)\n\n##### `playlists`\n\nA list of playlist IDs:\n\n```yaml\n- type: videos\n  playlists:\n    - PL8mG-RkN2uTyZZ00ObwZxxoG_nJbs3qec\n    - PL8mG-RkN2uTxTK4m_Vl2dYR9yE41kRdBg\n```\n\nThe playlist ID can be found in its link which is in the form of\n```\nhttps://www.youtube.com...&list={ID}&...\n```\n\n##### `limit`\nThe maximum number of videos to show.\n\n##### `collapse-after`\nSpecify the number of videos to show when using the `vertical-list` style before the \"SHOW MORE\" button appears.\n\n##### `collapse-after-rows`\nSpecify the number of rows to show when using the `grid-cards` style before the \"SHOW MORE\" button appears.\n\n##### `style`\nUsed to change the appearance of the widget. Possible values are `horizontal-cards`, `vertical-list` and `grid-cards`.\n\nPreview of `vertical-list`:\n\n![](images/videos-widget-vertical-list-preview.png)\n\nPreview of `grid-cards`:\n\n![](images/videos-widget-grid-cards-preview.png)\n\n##### `video-url-template`\nUsed to replace the default link for videos. Useful when you're running your own YouTube front-end. Example:\n\n```yaml\nvideo-url-template: https://invidious.your-domain.com/watch?v={VIDEO-ID}\n```\n\nPlaceholders:\n\n`{VIDEO-ID}` - the ID of the video\n\n### Hacker News\nDisplay a list of posts from [Hacker News](https://news.ycombinator.com/).\n\nExample:\n\n```yaml\n- type: hacker-news\n  limit: 15\n  collapse-after: 5\n```\n\nPreview:\n![](images/hacker-news-widget-preview.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| limit | integer | no | 15 |\n| collapse-after | integer | no | 5 |\n| comments-url-template | string | no | https://news.ycombinator.com/item?id={POST-ID} |\n| sort-by | string | no | top |\n| extra-sort-by | string | no | |\n\n##### `comments-url-template`\nUsed to replace the default link for post comments. Useful if you want to use an alternative front-end. Example:\n\n```yaml\ncomments-url-template: https://www.hckrnws.com/stories/{POST-ID}\n```\n\nPlaceholders:\n\n`{POST-ID}` - the ID of the post\n\n##### `sort-by`\nUsed to specify the order in which the posts should get returned. Possible values are `top`, `new`, and `best`.\n\n##### `extra-sort-by`\nCan 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`.\n\nThe `engagement` sort tries to place the posts with the most points and comments on top, also prioritizing recent over old posts.\n\n### Lobsters\nDisplay a list of posts from [Lobsters](https://lobste.rs).\n\nExample:\n\n```yaml\n- type: lobsters\n  sort-by: hot\n  tags:\n    - go\n    - security\n    - linux\n  limit: 15\n  collapse-after: 5\n```\n\nPreview:\n![](images/lobsters-widget-preview.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| instance-url | string | no | https://lobste.rs/ |\n| custom-url | string | no | |\n| limit | integer | no | 15 |\n| collapse-after | integer | no | 5 |\n| sort-by | string | no | hot |\n| tags | array | no | |\n\n##### `instance-url`\nThe base URL for a lobsters instance hosted somewhere other than on lobste.rs. Example:\n\n```yaml\ninstance-url: https://www.journalduhacker.net/\n```\n\n##### `custom-url`\nA custom URL to retrieve lobsters posts from. If this is specified, the `instance-url`, `sort-by` and `tags` properties are ignored.\n\n##### `limit`\nThe maximum number of posts to show.\n\n##### `collapse-after`\nHow many posts are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n##### `sort-by`\nThe sort order in which posts are returned. Possible options are `hot` and `new`.\n\n##### `tags`\nLimit to posts containing one of the given tags. **You cannot specify a sort order when filtering by tags, it will default to `hot`.**\n\n### Reddit\nDisplay a list of posts from a specific subreddit.\n\n> [!WARNING]\n>\n> Reddit does not allow unauthorized API access from VPS IPs, if you're hosting Glance on a VPS you will get a 403\n> response. As a workaround you can either [register an app on Reddit](https://ssl.reddit.com/prefs/apps/) and use the\n> generated ID and secret in the widget configuration to authenticate your requests (see `app-auth` property), use a proxy\n> (see `proxy` property) or route the traffic from Glance through a VPN.\n\nExample:\n\n```yaml\n- type: reddit\n  subreddit: technology\n```\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| subreddit | string | yes |  |\n| style | string | no | vertical-list |\n| show-thumbnails | boolean | no | false |\n| show-flairs | boolean | no | false |\n| limit | integer | no | 15 |\n| collapse-after | integer | no | 5 |\n| comments-url-template | string | no | https://www.reddit.com/{POST-PATH} |\n| request-url-template | string | no |  |\n| proxy | string or multiple parameters | no |  |\n| sort-by | string | no | hot |\n| top-period | string | no | day |\n| search | string | no | |\n| extra-sort-by | string | no | |\n| app-auth | object | no | |\n\n##### `subreddit`\nThe subreddit for which to fetch the posts from.\n\n##### `style`\nUsed 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.\n\n`vertical-list`\n\n![](images/reddit-widget-preview.png)\n\n`horizontal-cards`\n\n![](images/reddit-widget-horizontal-cards-preview.png)\n\n`vertical-cards`\n\n![](images/reddit-widget-vertical-cards-preview.png)\n\n##### `show-thumbnails`\nShows or hides thumbnails next to the post. This only works if the `style` is `vertical-list`. Preview:\n\n![](images/reddit-widget-vertical-list-thumbnails.png)\n\n> [!NOTE]\n>\n> Thumbnails don't work for some subreddits due to Reddit's API not returning the thumbnail URL. No workaround for this yet.\n\n##### `show-flairs`\nShows post flairs when set to `true`.\n\n##### `limit`\nThe maximum number of posts to show.\n\n##### `collapse-after`\nHow 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.\n\n##### `comments-url-template`\nUsed 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:\n\n```yaml\ncomments-url-template: https://old.reddit.com/{POST-PATH}\n```\n\nPlaceholders:\n\n`{POST-PATH}` - the full path to the post, such as:\n\n```\nr/selfhosted/comments/bsp01i/welcome_to_rselfhosted_please_read_this_first/\n```\n\n`{POST-ID}` - the ID that comes after `/comments/`\n\n`{SUBREDDIT}` - the subreddit name\n\n##### `request-url-template`\nA 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.\n\nPlaceholders:\n\n`{REQUEST-URL}` - will be templated and replaced with the expanded request URL (i.e. https://www.reddit.com/r/selfhosted/hot.json). Example:\n\n```\nhttps://proxy/{REQUEST-URL}\nhttps://your.proxy/?url={REQUEST-URL}\n```\n\n##### `proxy`\nA 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:\n\n```yaml\nproxy: http://user:pass@proxy.com:8080\nproxy: https://user:pass@proxy.com:443\n```\n\nAlternatively, you can specify the proxy URL as well as additional options by using multiple parameters:\n\n```yaml\nproxy:\n  url: http://proxy.com:8080\n  allow-insecure: true\n  timeout: 10s\n```\n\n###### `allow-insecure`\nWhen set to `true`, allows the use of insecure connections such as when the proxy has a self-signed certificate.\n\n###### `timeout`\nThe 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\n\n##### `sort-by`\nCan be used to specify the order in which the posts should get returned. Possible values are `hot`, `new`, `top` and `rising`.\n\n##### `top-period`\nAvailable only when `sort-by` is set to `top`. Possible values are `hour`, `day`, `week`, `month`, `year` and `all`.\n\n##### `search`\nKeywords 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**:\n\n![](images/reddit-field-search.png)\n\n##### `extra-sort-by`\nCan 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`.\n\nThe `engagement` sort tries to place the posts with the most points and comments on top, also prioritizing recent over old posts.\n\n##### `app-auth`\n```yaml\nwidgets:\n  - type: reddit\n    subreddit: technology\n    app-auth:\n      name: ${REDDIT_APP_NAME}\n      id: ${REDDIT_APP_CLIENT_ID}\n      secret: ${REDDIT_APP_SECRET}\n```\n\nTo register an app on Reddit, go to [this page](https://ssl.reddit.com/prefs/apps/).\n\n### Search Widget\nDisplay a search bar that can be used to search for specific terms on various search engines.\n\nExample:\n\n```yaml\n- type: search\n  search-engine: duckduckgo\n  bangs:\n    - title: YouTube\n      shortcut: \"!yt\"\n      url: https://www.youtube.com/results?search_query={QUERY}\n```\n\nPreview:\n\n![](images/search-widget-preview.png)\n\n#### Keyboard shortcuts\n| Keys | Action | Condition |\n| ---- | ------ | --------- |\n| <kbd>S</kbd> | Focus the search bar | Not already focused on another input field |\n| <kbd>Enter</kbd> | Perform search in the same tab | Search input is focused and not empty |\n| <kbd>Ctrl</kbd> + <kbd>Enter</kbd> | Perform search in a new tab | Search input is focused and not empty |\n| <kbd>Escape</kbd> | Leave focus | Search input is focused |\n| <kbd>Up</kbd> | Insert the last search query since the page was opened into the input field | Search input is focused |\n\n> [!TIP]\n>\n> 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. <kbd>Ctrl</kbd> + <kbd>Enter</kbd> will then show results in the same tab.\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| search-engine | string | no | duckduckgo |\n| new-tab | boolean | no | false |\n| autofocus | boolean | no | false |\n| target | string | no | _blank |\n| placeholder | string | no | Type here to search… |\n| bangs | array | no | |\n\n##### `search-engine`\nEither a value from the table below or a URL to a custom search engine. Use `{QUERY}` to indicate where the query value gets placed.\n\n| Name | URL |\n| ---- | --- |\n| duckduckgo | `https://duckduckgo.com/?q={QUERY}` |\n| google | `https://www.google.com/search?q={QUERY}` |\n| bing | `https://www.bing.com/search?q={QUERY}` |\n| perplexity | `https://www.perplexity.ai/search?q={QUERY}` |\n| kagi | `https://kagi.com/search?q={QUERY}` |\n| startpage | `https://www.startpage.com/search?q={QUERY}` |\n\n##### `new-tab`\nWhen set to `true`, swaps the shortcuts for showing results in the same or new tab, defaulting to showing results in a new tab.\n\n##### `autofocus`\nWhen set to `true`, automatically focuses the search input on page load.\n\n##### `target`\nThe target to use when opening the search results in a new tab. Possible values are `_blank`, `_self`, `_parent` and `_top`.\n\n##### `placeholder`\nWhen set, modifies the text displayed in the input field before typing.\n\n##### `bangs`\nWhat 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:\n\n![](images/search-widget-bangs-preview.png)\n\n##### Properties for each bang\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| title | string | no |\n| shortcut | string | yes |\n| url | string | yes |\n\n###### `title`\nOptional title that will appear on the right side of the search bar when the query starts with the associated shortcut.\n\n###### `shortcut`\nAny value you wish to use as the shortcut for the search engine. It does not have to start with `!`.\n\n> [!IMPORTANT]\n>\n> 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:\n> ```yaml\n> shortcut: \"!yt\"\n>```\n\n###### `url`\nThe URL of the search engine. Use `{QUERY}` to indicate where the query value gets placed. Examples:\n\n```yaml\nurl: https://www.reddit.com/search?q={QUERY}\nurl: https://store.steampowered.com/search/?term={QUERY}\nurl: https://www.amazon.com/s?k={QUERY}\n```\n\n### Group\nGroup 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.\n\nExample:\n\n```yaml\n- type: group\n  widgets:\n    - type: reddit\n      subreddit: gamingnews\n      show-thumbnails: true\n      collapse-after: 6\n    - type: reddit\n      subreddit: games\n    - type: reddit\n      subreddit: pcgaming\n      show-thumbnails: true\n```\n\nPreview:\n\n![](images/group-widget-preview.png)\n\n#### Sharing properties\n\nTo avoid repetition you can use [YAML anchors](https://support.atlassian.com/bitbucket-cloud/docs/yaml-anchors/) and share properties between widgets.\n\nExample:\n\n```yaml\n- type: group\n  define: &shared-properties\n      type: reddit\n      show-thumbnails: true\n      collapse-after: 6\n  widgets:\n    - subreddit: gamingnews\n      <<: *shared-properties\n    - subreddit: games\n      <<: *shared-properties\n    - subreddit: pcgaming\n      <<: *shared-properties\n```\n\n### Split Column\nSplits 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.\n\nTwo widgets side by side in a `full` column:\n\n![](images/split-column-widget-preview.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\n# ...\n- size: full\n  widgets:\n    - type: split-column\n      widgets:\n        - type: hacker-news\n          collapse-after: 3\n        - type: lobsters\n          collapse-after: 3\n\n    - type: videos\n# ...\n```\n</details>\n<br>\n\nYou can also achieve a number of different full page layouts using just this widget, such as:\n\n3 column layout where all columns have equal width:\n\n![](images/split-column-widget-3-columns.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\npages:\n  - name: Home\n    columns:\n      - size: full\n        widgets:\n          - type: split-column\n            max-columns: 3\n            widgets:\n              - type: reddit\n                subreddit: selfhosted\n                collapse-after: 15\n              - type: reddit\n                subreddit: homelab\n                collapse-after: 15\n              - type: reddit\n                subreddit: sysadmin\n                collapse-after: 15\n```\n</details>\n<br>\n\n4 column layout where all columns have equal width (and the page is set to `width: wide`):\n\n![](images/split-column-widget-4-columns.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\npages:\n  - name: Home\n    width: wide\n    columns:\n      - size: full\n        widgets:\n          - type: split-column\n            max-columns: 4\n            widgets:\n              - type: reddit\n                subreddit: selfhosted\n                collapse-after: 15\n              - type: reddit\n                subreddit: homelab\n                collapse-after: 15\n              - type: reddit\n                subreddit: linux\n                collapse-after: 15\n              - type: reddit\n                subreddit: sysadmin\n                collapse-after: 15\n```\n</details>\n<br>\n\nMasonry layout with up to 5 columns where all columns have equal width (and the page is set to `width: wide`):\n\n![](images/split-column-widget-masonry.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\ndefine:\n  - &subreddit-settings\n    type: reddit\n    collapse-after: 5\n\npages:\n  - name: Home\n    width: wide\n    columns:\n      - size: full\n        widgets:\n          - type: split-column\n            max-columns: 5\n            widgets:\n              - subreddit: selfhosted\n                <<: *subreddit-settings\n              - subreddit: homelab\n                <<: *subreddit-settings\n              - subreddit: linux\n                <<: *subreddit-settings\n              - subreddit: sysadmin\n                <<: *subreddit-settings\n              - subreddit: DevOps\n                <<: *subreddit-settings\n              - subreddit: Networking\n                <<: *subreddit-settings\n              - subreddit: DataHoarding\n                <<: *subreddit-settings\n              - subreddit: OpenSource\n                <<: *subreddit-settings\n              - subreddit: Privacy\n                <<: *subreddit-settings\n              - subreddit: FreeSoftware\n                <<: *subreddit-settings\n```\n</details>\n<br>\n\nJust 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.\n\n\n### Custom API\n\nDisplay data from a JSON API using a custom template.\n\n> [!NOTE]\n>\n> The configuration of this widget requires some basic knowledge of programming, HTML, CSS, the Go template language and Glance-specific concepts.\n\nExamples:\n\n![](images/custom-api-preview-1.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\n- type: custom-api\n  title: Random Fact\n  cache: 6h\n  url: https://uselessfacts.jsph.pl/api/v2/facts/random\n  template: |\n    <p class=\"size-h4 color-paragraph\">{{ .JSON.String \"text\" }}</p>\n```\n</details>\n<br>\n\n![](images/custom-api-preview-2.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\n- type: custom-api\n  title: Immich stats\n  cache: 1d\n  url: https://${IMMICH_URL}/api/server/statistics\n  headers:\n    x-api-key: ${IMMICH_API_KEY}\n    Accept: application/json\n  template: |\n    <div class=\"flex justify-between text-center\">\n      <div>\n          <div class=\"color-highlight size-h3\">{{ .JSON.Int \"photos\" | formatNumber }}</div>\n          <div class=\"size-h6\">PHOTOS</div>\n      </div>\n      <div>\n          <div class=\"color-highlight size-h3\">{{ .JSON.Int \"videos\" | formatNumber }}</div>\n          <div class=\"size-h6\">VIDEOS</div>\n      </div>\n      <div>\n          <div class=\"color-highlight size-h3\">{{ div (.JSON.Int \"usage\" | toFloat) 1073741824 | toInt | formatNumber }}GB</div>\n          <div class=\"size-h6\">USAGE</div>\n      </div>\n    </div>\n```\n</details>\n<br>\n\n![](images/custom-api-preview-3.png)\n\n<details>\n<summary>View <code>glance.yml</code></summary>\n<br>\n\n```yaml\n- type: custom-api\n  title: Steam Specials\n  cache: 12h\n  url: https://store.steampowered.com/api/featuredcategories?cc=us\n  template: |\n    <ul class=\"list list-gap-10 collapsible-container\" data-collapse-after=\"5\">\n    {{ range .JSON.Array \"specials.items\" }}\n      <li>\n        <a class=\"size-h4 color-highlight block text-truncate\" href=\"https://store.steampowered.com/app/{{ .Int \"id\" }}/\">{{ .String \"name\" }}</a>\n        <ul class=\"list-horizontal-text\">\n          <li>{{ div (.Int \"final_price\" | toFloat) 100 | printf \"$%.2f\" }}</li>\n          {{ $discount := .Int \"discount_percent\" }}\n          <li{{ if ge $discount 40 }} class=\"color-positive\"{{ end }}>{{ $discount }}% off</li>\n        </ul>\n      </li>\n    {{ end }}\n    </ul>\n```\n</details>\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| url | string | no | |\n| headers | key (string) & value (string) | no | |\n| method | string | no | GET |\n| body-type | string | no | json |\n| body | any | no | |\n| frameless | boolean | no | false |\n| allow-insecure | boolean | no | false |\n| skip-json-validation | boolean | no | false |\n| template | string | yes | |\n| options | map | no | |\n| parameters | key (string) & value (string|array) | no | |\n| subrequests | map of requests | no | |\n\n##### `url`\nThe URL to fetch the data from. It must be accessible from the server that Glance is running on.\n\n##### `headers`\nOptionally specify the headers that will be sent with the request. Example:\n\n```yaml\nheaders:\n  x-api-key: your-api-key\n  Accept: application/json\n```\n\n##### `method`\nThe HTTP method to use when making the request. Possible values are `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` and `HEAD`.\n\n##### `body-type`\nThe type of the body that will be sent with the request. Possible values are `json`, and `string`.\n\n##### `body`\nThe body that will be sent with the request. It can be a string or a map. Example:\n\n```yaml\nbody-type: json\nbody:\n  key1: value1\n  key2: value2\n  multiple-items:\n    - item1\n    - item2\n```\n\n```yaml\nbody-type: string\nbody: |\n  key1=value1&key2=value2\n```\n\n##### `frameless`\nWhen set to `true`, removes the border and padding around the widget.\n\n##### `allow-insecure`\nWhether to ignore invalid/self-signed certificates.\n\n##### `skip-json-validation`\nWhen 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.\n\n##### `template`\nThe 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).\n\n##### `options`\nA map of options that will be passed to the template and can be used to modify the behavior of the widget.\n\n<details>\n<summary>View examples</summary>\n\n<br>\n\nInstead of defining options within the template and having to modify the template itself like such:\n\n```yaml\n- type: custom-api\n  template: |\n    {{ /* User configurable options */ }}\n    {{ $collapseAfter := 5 }}\n    {{ $showThumbnails := true }}\n    {{ $showFlairs := false }}\n\n     <ul class=\"list list-gap-10 collapsible-container\" data-collapse-after=\"{{ $collapseAfter }}\">\n      {{ if $showThumbnails }}\n        <li>\n          <img src=\"{{ .JSON.String \"thumbnail\" }}\" alt=\"thumbnail\" />\n        </li>\n      {{ end }}\n      {{ if $showFlairs }}\n        <li>\n          <span class=\"flair\">{{ .JSON.String \"flair\" }}</span>\n        </li>\n      {{ end }}\n     </ul>\n```\n\nYou can use the `options` property to retrieve and define default values for these variables:\n\n```yaml\n- type: custom-api\n  template: |\n    <ul class=\"list list-gap-10 collapsible-container\" data-collapse-after=\"{{ .Options.IntOr \"collapse-after\" 5 }}\">\n      {{ if (.Options.BoolOr \"show-thumbnails\" true) }}\n        <li>\n          <img src=\"{{ .JSON.String \"thumbnail\" }}\" alt=\"thumbnail\" />\n        </li>\n      {{ end }}\n      {{ if (.Options.BoolOr \"show-flairs\" false) }}\n        <li>\n          <span class=\"flair\">{{ .JSON.String \"flair\" }}</span>\n        </li>\n      {{ end }}\n    </ul>\n```\n\nThis way, you can optionally specify the `collapse-after`, `show-thumbnails` and `show-flairs` properties in the widget configuration:\n\n```yaml\n- type: custom-api\n  options:\n    collapse-after: 5\n    show-thumbnails: true\n    show-flairs: false\n```\n\nWhich means you can reuse the same template for multiple widgets with different options:\n\n```yaml\n# 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/\ncustom-widgets:\n  - &example-widget\n    type: custom-api\n    template: |\n      {{ .Options.StringOr \"custom-option\" \"not defined\" }}\n\npages:\n  - name: Home\n    columns:\n      - size: full\n        widgets:\n          - <<: *example-widget\n            options:\n              custom-option: \"Value 1\"\n\n          - <<: *example-widget\n            options:\n              custom-option: \"Value 2\"\n```\n\nCurrently, the available methods on the `.Options` object are: `StringOr`, `IntOr`, `BoolOr` and `FloatOr`.\n\n</details>\n\n##### `parameters`\nA list of keys and values that will be sent to the custom-api as query paramters.\n\n##### `subrequests`\nA map of additional requests that will be executed concurrently and then made available in the template via the `.Subrequest` property. Example:\n\n```yaml\n- type: custom-api\n  cache: 2h\n  subrequests:\n    another-one:\n      url: https://uselessfacts.jsph.pl/api/v2/facts/random\n  title: Random Fact\n  url: https://uselessfacts.jsph.pl/api/v2/facts/random\n  template: |\n    <p class=\"size-h4 color-paragraph\">{{ .JSON.String \"text\" }}</p>\n    <p class=\"size-h4 color-paragraph margin-top-15\">{{ (.Subrequest \"another-one\").JSON.String \"text\" }}</p>\n```\n\nThe subrequests support all the same properties as the main request, except for `subrequests` itself, so you can use `headers`, `parameters`, etc.\n\n`(.Subrequest \"key\")` can be a little cumbersome to write, so you can define a variable to make it easier:\n\n```yaml\n  template: |\n    {{ $anotherOne := .Subrequest \"another-one\" }}\n    <p>{{ $anotherOne.JSON.String \"text\" }}</p>\n```\n\nYou can also access the `.Response` property of a subrequest as you would with the main request:\n\n```yaml\n  template: |\n    {{ $anotherOne := .Subrequest \"another-one\" }}\n    <p>{{ $anotherOne.Response.StatusCode }}</p>\n```\n\n> [!NOTE]\n>\n> Setting this property will override any query parameters that are already in the URL.\n\n```yaml\nparameters:\n  param1: value1\n  param2:\n    - item1\n    - item2\n```\n\n### Extension\nDisplay 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).\n\n```yaml\n- type: extension\n  url: https://domain.com/widget/display-a-message\n  allow-potentially-dangerous-html: true\n  parameters:\n    message: Hello, world!\n```\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| url | string | yes | |\n| fallback-content-type | string | no | |\n| allow-potentially-dangerous-html | boolean | no | false |\n| headers | key & value | no | |\n| parameters | key & value | no | |\n\n##### `url`\nThe URL of the extension. **Note that the query gets stripped from this URL and the one defined by `parameters` gets used instead.**\n\n##### `fallback-content-type`\nOptionally 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`.\n\n##### `headers`\nOptionally specify the headers that will be sent with the request. Example:\n\n```yaml\nheaders:\n  x-api-key: ${SECRET_KEY}\n```\n\n##### `allow-potentially-dangerous-html`\nWhether to allow the extension to display HTML.\n\n> [!WARNING]\n>\n> 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.\n\n##### `parameters`\nA list of keys and values that will be sent to the extension as query paramters.\n\n### Weather\nDisplay weather information for a specific location. The data is provided by https://open-meteo.com/.\n\nExample:\n\n```yaml\n- type: weather\n  units: metric\n  hour-format: 12h\n  location: London, United Kingdom\n```\n\n> [!NOTE]\n>\n> US cities which have common names can have their state specified as the second parameter as such:\n>\n> * Greenville, North Carolina, United States\n> * Greenville, South Carolina, United States\n> * Greenville, Mississippi, United States\n\n\nPreview:\n\n![](images/weather-widget-preview.png)\n\nEach 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.\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| location | string | yes |  |\n| units | string | no | metric |\n| hour-format | string | no | 12h |\n| hide-location | boolean | no | false |\n| show-area-name | boolean | no | false |\n\n##### `location`\nThe 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.\n\n##### `units`\nWhether to show the temperature in celsius or fahrenheit, possible values are `metric` or `imperial`.\n\n#### `hour-format`\nWhether to show the hours of the day in 12-hour format or 24-hour format. Possible values are `12h` and `24h`.\n\n##### `hide-location`\nOptionally don't display the location name on the widget.\n\n##### `show-area-name`\nWhether to display the state/administrative area in the location name. If set to `true` the location will be displayed as:\n\n```\nGreenville, North Carolina, United States\n```\n\nOtherwise, if set to `false` (which is the default) it'll be displayed as:\n\n```\nGreenville, United States\n```\n\n### Todo\n\nA simple to-do list that allows you to add, edit and delete tasks. The tasks are stored in the browser's local storage.\n\nExample:\n\n```yaml\n- type: to-do\n```\n\nPreview:\n\n![](images/todo-widget-preview.png)\n\nTo reorder tasks, drag and drop them by grabbing the top side of the task:\n\n![](images/reorder-todo-tasks-prevew.gif)\n\nTo delete a task, hover over it and click on the trash icon.\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| id | string | no | |\n\n##### `id`\n\nThe 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.\n\n#### Keyboard shortcuts\n| Keys | Action | Condition |\n| ---- | ------ | --------- |\n| <kbd>Enter</kbd> | Add a task to the bottom of the list | When the \"Add a task\" field is focused |\n| <kbd>Ctrl</kbd> + <kbd>Enter</kbd> | Add a task to the top of the list | When the \"Add a task\" field is focused |\n| <kbd>Down Arrow</kbd> | Focus the last task that was added | When the \"Add a task\" field is focused |\n| <kbd>Escape</kbd> | Focus the \"Add a task\" field | When a task is focused |\n\n### Monitor\nDisplay 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.\n\nExample:\n\n```yaml\n- type: monitor\n  cache: 1m\n  title: Services\n  sites:\n    - title: Jellyfin\n      url: https://jellyfin.yourdomain.com\n      icon: /assets/jellyfin-logo.png\n    - title: Gitea\n      url: https://gitea.yourdomain.com\n      icon: /assets/gitea-logo.png\n    - title: Immich\n      url: https://immich.yourdomain.com\n      icon: /assets/immich-logo.png\n    - title: AdGuard Home\n      url: https://adguard.yourdomain.com\n      icon: /assets/adguard-logo.png\n    - title: Vaultwarden\n      url: https://vault.yourdomain.com\n      icon: /assets/vaultwarden-logo.png\n```\n\nPreview:\n\n![](images/monitor-widget-preview.png)\n\nYou can hover over the \"ERROR\" text to view more information.\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| sites | array | yes | |\n| style | string | no | |\n| show-failing-only | boolean | no | false |\n\n##### `show-failing-only`\nShows only a list of failing sites when set to `true`.\n\n##### `style`\nUsed to change the appearance of the widget. Possible values are `compact`.\n\nPreview of `compact`:\n\n![](images/monitor-widget-compact-preview.png)\n\n##### `sites`\n\nProperties for each site:\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| title | string | yes | |\n| url | string | yes | |\n| check-url | string | no | |\n| error-url | string | no | |\n| icon | string | no | |\n| timeout | string | no | 3s |\n| allow-insecure | boolean | no | false |\n| same-tab | boolean | no | false |\n| alt-status-codes | array | no | |\n| basic-auth | object | no | |\n\n`title`\n\nThe title used to indicate the site.\n\n`url`\n\nThe 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.\n\n`check-url`\n\nThe URL which will be requested and its response will determine the status of the site. If not specified, the `url` property is used.\n\n`error-url`\n\nIf the monitored service returns an error, the user will be redirected here. If not specified, the `url` property is used.\n\n`icon`\n\nSee [Icons](#icons) for more information on how to specify icons.\n\n`timeout`\n\nHow 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.\n\n`allow-insecure`\n\nWhether to ignore invalid/self-signed certificates.\n\n`same-tab`\n\nWhether to open the link in the same or a new tab.\n\n`alt-status-codes`\n\nStatus codes other than 200 that you want to return \"OK\".\n\n```yaml\nalt-status-codes:\n  - 403\n```\n\n`basic-auth`\n\nHTTP Basic Authentication credentials for protected sites.\n\n```yaml\nbasic-auth:\n  username: your-username\n  password: your-password\n```\n\n### Releases\nDisplay a list of latest releases for specific repositories on Github, GitLab, Codeberg or Docker Hub.\n\nExample:\n\n```yaml\n- type: releases\n  show-source-icon: true\n  repositories:\n    - go-gitea/gitea\n    - jellyfin/jellyfin\n    - glanceapp/glance\n    - codeberg:redict/redict\n    - gitlab:fdroid/fdroidclient\n    - dockerhub:gotify/server\n```\n\nPreview:\n\n![](images/releases-widget-preview.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| repositories | array | yes |  |\n| show-source-icon | boolean | no | false |  |\n| token | string | no | |\n| gitlab-token | string | no | |\n| limit | integer | no | 10 |\n| collapse-after | integer | no | 5 |\n\n##### `repositories`\nA 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:\n\n```yaml\nrepositories:\n  - gitlab:inkscape/inkscape\n  - dockerhub:glanceapp/glance\n  - codeberg:redict/redict\n```\n\nOfficial images on Docker Hub can be specified by omitting the owner:\n\n```yaml\nrepositories:\n  - dockerhub:nginx\n  - dockerhub:node\n  - dockerhub:alpine\n```\n\nYou can also specify exact tags for Docker Hub images:\n\n```yaml\nrepositories:\n  - dockerhub:nginx:latest\n  - dockerhub:nginx:stable-alpine\n```\n\nTo include prereleases you can specify the repository as an object and use the `include-prereleases` property:\n\n**Note: This feature is currently only available for GitHub repositories.**\n\n```yaml\nrepositories:\n  - gitlab:inkscape/inkscape\n  - repository: glanceapp/glance\n    include-prereleases: true\n  - codeberg:redict/redict\n```\n\n##### `show-source-icon`\nShows an icon of the source (GitHub/GitLab/Codeberg/Docker Hub) next to the repository name when set to `true`.\n\n##### `token`\nWithout 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.\n\nYou 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:\n\n```yaml\nservices:\n  glance:\n    image: glanceapp/glance\n    environment:\n      - GITHUB_TOKEN=<your token>\n```\n\nand then use it in your `glance.yml` like this:\n\n```yaml\n- type: releases\n  token: ${GITHUB_TOKEN}\n  repositories: ...\n```\n\nThis way you can safely check your `glance.yml` in version control without exposing the token.\n\n##### `gitlab-token`\nSame as the above but used when fetching GitLab releases.\n\n##### `limit`\nThe maximum number of releases to show.\n\n#### `collapse-after`\nHow many releases are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n### Docker Containers\n\nDisplay the status of your Docker containers along with an icon and an optional short description.\n\n![](images/docker-containers-preview.png)\n\n```yaml\n- type: docker-containers\n  hide-by-default: false\n```\n\n> [!NOTE]\n>\n> 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:\n>\n> ```yaml\n> services:\n>   glance:\n>     image: glanceapp/glance\n>     volumes:\n>       - /var/run/docker.sock:/var/run/docker.sock\n> ```\n\nConfiguration of the containers is done via labels applied to each container:\n\n```yaml\n  jellyfin:\n    image: jellyfin/jellyfin:latest\n    labels:\n      glance.name: Jellyfin\n      glance.icon: si:jellyfin\n      glance.url: https://jellyfin.domain.com\n      glance.description: Movies & shows\n```\n\nAlternatively, 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:\n\n```yaml\n- type: docker-containers\n  containers:\n    container_name_1:\n      name: Container Name\n      description: Description of the container\n      url: https://container.domain.com\n      icon: si:container-icon\n      hide: false\n```\n\nFor services with multiple containers you can specify a `glance.id` on the \"main\" container and `glance.parent` on each \"child\" container:\n\n<details>\n<summary>View <code>docker-compose.yml</code></summary>\n<br>\n\n```yaml\nservices:\n  immich-server:\n    image: ghcr.io/immich-app/immich-server\n    labels:\n      glance.name: Immich\n      glance.icon: si:immich\n      glance.url: https://immich.domain.com\n      glance.description: Image & video management\n      glance.id: immich\n\n  redis:\n    image: docker.io/redis:6.2-alpine\n    labels:\n      glance.parent: immich\n      glance.name: Redis\n\n  database:\n    image: docker.io/tensorchord/pgvecto-rs:pg14-v0.2.0\n    labels:\n      glance.parent: immich\n      glance.name: DB\n\n  proxy:\n    image: nginx:stable\n    labels:\n      glance.parent: immich\n      glance.name: Proxy\n```\n</details>\n<br>\n\nThis will place all child containers under the `Immich` container when hovering over its icon:\n\n![](images/docker-container-parent.png)\n\nIf any of the child containers are down, their status will propagate up to the parent container:\n\n![](images/docker-container-parent2.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| hide-by-default | boolean | no | false |\n| format-container-names | boolean | no | false |\n| sock-path | string | no | /var/run/docker.sock |\n| category | string | no | |\n| running-only | boolean | no | false |\n\n##### `hide-by-default`\nWhether 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.\n\n##### `format-container-names`\nWhen set to `true`, automatically converts container names such as `container_name_1` into `Container Name 1`.\n\n##### `sock-path`\nThe 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).\n\n###### `category`\nFilter 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.\n\n<details>\n<summary>View example</summary>\n<br>\n\n\n```yaml\nservices:\n  jellyfin:\n    image: jellyfin/jellyfin:latest\n    labels:\n      glance.name: Jellyfin\n      glance.icon: si:jellyfin\n      glance.url: https://jellyfin.domain.com\n      glance.category: media\n\n  gitea:\n    image: gitea/gitea:latest\n    labels:\n      glance.name: Gitea\n      glance.icon: si:gitea\n      glance.url: https://gitea.domain.com\n      glance.category: dev-tools\n\n  vaultwarden:\n    image: vaultwarden/server:latest\n    labels:\n      glance.name: Vaultwarden\n      glance.icon: si:vaultwarden\n      glance.url: https://vaultwarden.domain.com\n      glance.category: dev-tools\n```\n\nThen you can use the `category` property to filter the containers:\n\n```yaml\n- type: docker-containers\n  title: Dev tool containers\n  category: dev-tools\n\n- type: docker-containers\n  title: Media containers\n  category: media\n```\n\n</details>\n\n##### `running-only`\nWhether 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.\n\n#### Labels\n| Name | Description |\n| ---- | ----------- |\n| glance.name | The name displayed in the UI. If not specified, the name of the container will be used. |\n| glance.icon | See [Icons](#icons) for more information on how to specify icons |\n| glance.url | The URL that the user will be redirected to when clicking on the container. |\n| glance.same-tab | Whether to open the link in the same or a new tab. Default is `false`. |\n| glance.description | A short description displayed in the UI. Default is empty. |\n| glance.hide | Whether to hide the container. If set to `true` the container will not be displayed. Defaults to `false`. |\n| glance.id | The custom ID of the container. Used to group containers under a single parent. |\n| glance.parent | The ID of the parent container. Used to group containers under a single parent. |\n| glance.category | The category of the container. Used to filter containers by category. |\n\n### DNS Stats\nDisplay statistics from a self-hosted ad-blocking DNS resolver such as AdGuard Home, Pi-hole, or Technitium.\n\nExample:\n\n```yaml\n- type: dns-stats\n  service: adguard\n  url: https://adguard.domain.com/\n  username: admin\n  password: ${ADGUARD_PASSWORD}\n```\n\nPreview:\n\n![](images/dns-stats-widget-preview.png)\n\n> [!NOTE]\n>\n> 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.\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| service | string | no | pihole |\n| allow-insecure | bool | no | false |\n| url | string | yes |  |\n| username | string | when service is `adguard` |  |\n| password | string | when service is `adguard` or `pihole-v6` |  |\n| token | string | when service is `pihole` |  |\n| hide-graph | bool | no | false |\n| hide-top-domains | bool | no | false |\n| hour-format | string | no | 12h |\n\n##### `service`\nEither `adguard`, `technitium`, or `pihole` (major version 5 and below) or `pihole-v6` (major version 6 and above).\n\n##### `allow-insecure`\nWhether to allow invalid/self-signed certificates when making the request to the service.\n\n##### `url`\nThe base URL of the service.\n\n##### `username`\nOnly required when using AdGuard Home. The username used to log into the admin dashboard.\n\n##### `password`\nRequired when using AdGuard Home, where the password is the one used to log into the admin dashboard.\n\nAlso 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`.\n\n##### `token`\nRequired when using Pi-hole major version 5 or earlier. The API token which can be found in `Settings -> API -> Show API token`.\n\nAlso required when using Technitium, an API token can be generated at `Administration -> Sessions -> Create Token`.\n\n##### `hide-graph`\nWhether to hide the graph showing the number of queries over time.\n\n##### `hide-top-domains`\nWhether to hide the list of top blocked domains.\n\n##### `hour-format`\nWhether to display the relative time in the graph in `12h` or `24h` format.\n\n### Server Stats\nDisplay statistics such as CPU usage, memory usage and disk usage of the server Glance is running on or other servers.\n\nExample:\n\n```yaml\n- type: server-stats\n  servers:\n    - type: local\n      name: Services\n```\n\nPreview:\n\n![](images/server-stats-preview.gif)\n\n> [!NOTE]\n>\n> This widget is currently under development, some features might not function as expected or may change.\n\nTo 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.\n\nIn 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:\n\n![](images/server-stats-flame-icon.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| servers | array | no |  |\n\n##### `servers`\nIf not provided it will display the statistics of the server Glance is running on.\n\n##### Properties for both `local` and `remote` servers\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| type | string | yes |  |\n| name | string | no |  |\n| hide-swap | boolean | no | false |\n\n###### `type`\nWhether to display statistics for the local server or a remote server. Possible values are `local` and `remote`.\n\n###### `name`\nThe name of the server which will be displayed on the widget. If not provided it will default to the server's hostname.\n\n###### `hide-swap`\nWhether to hide the swap usage.\n\n##### Properties for the `local` server\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| cpu-temp-sensor | string | no |  |\n| hide-mountpoints-by-default | boolean | no | false |\n| mountpoints | map\\[string\\]object | no |  |\n\n###### `cpu-temp-sensor`\nThe 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.\n\n###### `hide-mountpoints-by-default`\nIf set to `true` you'll have to manually make each mountpoint visible by adding a `hide: false` property to it like so:\n\n```yaml\n- type: server-stats\n  servers:\n    - type: local\n      hide-mountpoints-by-default: true\n      mountpoints:\n        \"/\":\n          hide: false\n        \"/mnt/data\":\n          hide: false\n```\n\nThis is useful if you're running Glance inside of a container which usually mounts a lot of irrelevant filesystems.\n\n###### `mountpoints`\nA 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:\n\n```yaml\nmountpoints:\n  \"/\":\n    name: Root\n  \"/mnt/data\":\n    name: Data\n  \"/boot/efi\":\n    hide: true\n```\n\n##### Properties for each `mountpoint`\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| name | string | no |  |\n| hide | boolean | no | false |\n\n###### `name`\nThe name of the mountpoint which will be displayed on the widget. If not provided it will default to the mountpoint's path.\n\n###### `hide`\nWhether to hide this mountpoint from the widget.\n\n##### Properties for `remote` servers\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| url | string | yes |  |\n| token | string | no |  |\n| timeout | string | no | 3s |\n\n###### `url`\nThe URL and port of the server to fetch the statistics from.\n\n###### `token`\nThe authentication token to use when fetching the statistics.\n\n###### `timeout`\nThe 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\n\n### Repository\nDisplay general information about a repository as well as a list of the latest open pull requests and issues.\n\nExample:\n\n```yaml\n- type: repository\n  repository: glanceapp/glance\n  pull-requests-limit: 5\n  issues-limit: 3\n  commits-limit: 3\n```\n\nPreview:\n\n![](images/repository-preview.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| repository | string | yes |  |\n| token | string | no | |\n| pull-requests-limit | integer | no | 3 |\n| issues-limit | integer | no | 3 |\n| commits-limit | integer | no | -1 |\n\n##### `repository`\nThe owner and repository name that will have their information displayed.\n\n##### `token`\nWithout 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.\n\n##### `pull-requests-limit`\nThe maximum number of latest open pull requests to show. Set to `-1` to not show any.\n\n##### `issues-limit`\nThe maximum number of latest open issues to show. Set to `-1` to not show any.\n\n##### `commits-limit`\nThe maximum number of lastest commits to show from the default branch. Set to `-1` to not show any.\n\n### Bookmarks\nDisplay a list of links which can be grouped.\n\nExample:\n\n```yaml\n- type: bookmarks\n  groups:\n    - links:\n        - title: Gmail\n          url: https://mail.google.com/mail/u/0/\n        - title: Amazon\n          url: https://www.amazon.com/\n        - title: Github\n          url: https://github.com/\n        - title: Wikipedia\n          url: https://en.wikipedia.org/\n    - title: Entertainment\n      color: 10 70 50\n      links:\n        - title: Netflix\n          url: https://www.netflix.com/\n        - title: Disney+\n          url: https://www.disneyplus.com/\n        - title: YouTube\n          url: https://www.youtube.com/\n        - title: Prime Video\n          url: https://www.primevideo.com/\n    - title: Social\n      color: 200 50 50\n      links:\n        - title: Reddit\n          url: https://www.reddit.com/\n        - title: Twitter\n          url: https://twitter.com/\n        - title: Instagram\n          url: https://www.instagram.com/\n```\n\nPreview:\n\n![](images/bookmarks-widget-preview.png)\n\n\n#### Properties\n\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| groups | array | yes |\n\n##### `groups`\nAn array of groups which can optionally have a title and a custom color.\n\n###### Properties for each group\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| title | string | no | |\n| color | HSL | no | the primary color of the theme |\n| links | array | yes | |\n| same-tab | boolean | no | false |\n| hide-arrow | boolean | no | false |\n| target | string | no | |\n\n> [!TIP]\n>\n> 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.\n\n###### Properties for each link\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| title | string | yes | |\n| url | string | yes | |\n| description | string | no | |\n| icon | string | no | |\n| same-tab | boolean | no | false |\n| hide-arrow | boolean | no | false |\n| target | string | no | |\n\n`icon`\n\nSee [Icons](#icons) for more information on how to specify icons.\n\n`same-tab`\n\nWhether to open the link in the same tab or a new one.\n\n`hide-arrow`\n\nWhether to hide the colored arrow on each link.\n\n`target`\n\nSet 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`.\n\n### ChangeDetection.io\nDisplay a list watches from changedetection.io.\n\nExample\n\n```yaml\n- type: change-detection\n  instance-url: https://changedetection.mydomain.com/\n  token: ${CHANGE_DETECTION_TOKEN}\n```\n\nPreview:\n\n![](images/change-detection-widget-preview.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| instance-url | string | no | `https://www.changedetection.io` |\n| token | string | no |  |\n| limit | integer | no | 10 |\n| collapse-after | integer | no | 5 |\n| watches | array of strings | no |  |\n\n##### `instance-url`\nThe URL pointing to your instance of `changedetection.io`.\n\n##### `token`\nThe API access token which can be found in `SETTINGS > API`. Optionally, you can specify this using an environment variable with the syntax `${VARIABLE_NAME}`.\n\n##### `limit`\nThe maximum number of watches to show.\n\n##### `collapse-after`\nHow many watches are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n##### `watches`\nBy 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:\n\n```yaml\n  - type: change-detection\n    watches:\n      - 1abca041-6d4f-4554-aa19-809147f538d3\n      - 705ed3e4-ea86-4d25-a064-822a6425be2c\n```\n\n### Clock\nDisplay a clock showing the current time and date. Optionally, also display the the time in other timezones.\n\nExample:\n\n```yaml\n- type: clock\n  hour-format: 24h\n  timezones:\n    - timezone: Europe/Paris\n      label: Paris\n    - timezone: America/New_York\n      label: New York\n    - timezone: Asia/Tokyo\n      label: Tokyo\n```\n\nPreview:\n\n![](images/clock-widget-preview.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| hour-format | string | no | 24h |\n| timezones | array | no |  |\n\n##### `hour-format`\nWhether to show the time in 12 or 24 hour format. Possible values are `12h` and `24h`.\n\n#### Properties for each timezone\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| timezone | string | yes | |\n| label | string | no | |\n\n##### `timezone`\nA 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).\n\n##### `label`\nOptionally, override the display value for the timezone to something more meaningful such as \"Home\", \"Work\" or anything else.\n\n\n### Calendar\nDisplay a calendar.\n\nExample:\n\n```yaml\n- type: calendar\n  first-day-of-week: monday\n```\n\nPreview:\n\n![](images/calendar-widget-preview.png)\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| first-day-of-week | string | no | monday |\n\n##### `first-day-of-week`\nThe day of the week that the calendar starts on. All week days are available as possible values.\n\n### Calendar (legacy)\nDisplay a calendar.\n\nExample:\n\n```yaml\n- type: calendar-legacy\n  start-sunday: false\n```\n\nPreview:\n\n![](images/calendar-legacy-widget-preview.png)\n\n> [!NOTE]\n>\n> This widget is deprecated and may be removed in a future version.\n\n#### Properties\n\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| start-sunday | boolean | no | false |\n\n##### `start-sunday`\nWhether calendar weeks start on Sunday or Monday.\n\n> [!NOTE]\n>\n> There is currently little customizability available for the calendar. Extra features will be added in the future.\n\n### Markets\nDisplay a list of markets, their current value, change for the day and a small 21d chart. Data is taken from Yahoo Finance.\n\nExample:\n\n```yaml\n- type: markets\n  markets:\n    - symbol: SPY\n      name: S&P 500\n    - symbol: BTC-USD\n      name: Bitcoin\n      chart-link: https://www.tradingview.com/chart/?symbol=INDEX:BTCUSD\n    - symbol: NVDA\n      name: NVIDIA\n    - symbol: AAPL\n      symbol-link: https://www.google.com/search?tbm=nws&q=apple\n      name: Apple\n```\n\nPreview:\n\n![](images/markets-widget-preview.png)\n\n#### Properties\n\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| markets | array | yes |\n| sort-by | string | no |\n| chart-link-template | string | no |\n| symbol-link-template | string | no |\n\n##### `markets`\nAn array of markets for which to display information about.\n\n##### `sort-by`\nBy 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%).\n\n##### `chart-link-template`\nA 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:\n\n```yaml\nchart-link-template: https://www.tradingview.com/chart/?symbol={SYMBOL}\n```\n\n##### `symbol-link-template`\nA 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:\n\n```yaml\nsymbol-link-template: https://www.google.com/search?tbm=nws&q={SYMBOL}\n```\n\n###### Properties for each market\n| Name | Type | Required |\n| ---- | ---- | -------- |\n| symbol | string | yes |\n| name | string | no |\n| symbol-link | string | no |\n| chart-link | string | no |\n\n`symbol`\n\nThe symbol, as seen in Yahoo Finance.\n\n`name`\n\nThe name that will be displayed under the symbol.\n\n`symbol-link`\n\nThe link to go to when clicking on the symbol.\n\n`chart-link`\n\nThe link to go to when clicking on the chart.\n\n### Twitch Channels\nDisplay a list of channels from Twitch.\n\nExample:\n\n```yaml\n- type: twitch-channels\n  channels:\n    - jembawls\n    - giantwaffle\n    - asmongold\n    - cohhcarnage\n    - j_blow\n    - xQc\n```\n\nPreview:\n\n![](images/twitch-channels-widget-preview.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| channels | array | yes | |\n| collapse-after | integer | no | 5 |\n| sort-by | string | no | viewers |\n\n##### `channels`\nA list of channels to display.\n\n##### `collapse-after`\nHow many channels are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n##### `sort-by`\nCan be used to specify the order in which the channels are displayed. Possible values are `viewers` and `live`.\n\n### Twitch top games\nDisplay a list of games with the most viewers on Twitch.\n\nExample:\n\n```yaml\n- type: twitch-top-games\n  exclude:\n    - just-chatting\n    - pools-hot-tubs-and-beaches\n    - music\n    - art\n    - asmr\n```\n\nPreview:\n\n![](images/twitch-top-games-widget-preview.png)\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| exclude | array | no | |\n| limit | integer | no | 10 |\n| collapse-after | integer | no | 5 |\n\n##### `exclude`\nA list of categories that will never be shown. You must provide the slug found by clicking on the category and looking at the URL:\n\n```\nhttps://www.twitch.tv/directory/category/grand-theft-auto-v\n                                         ^^^^^^^^^^^^^^^^^^\n```\n\n##### `limit`\nThe maximum number of games to show.\n\n##### `collapse-after`\nHow many games are visible before the \"SHOW MORE\" button appears. Set to `-1` to never collapse.\n\n### iframe\nEmbed an iframe as a widget.\n\nExample:\n\n```yaml\n- type: iframe\n  source: <url>\n  height: 400\n```\n\n#### Properties\n| Name | Type | Required | Default |\n| ---- | ---- | -------- | ------- |\n| source | string | yes | |\n| height | integer | no | 300 |\n\n##### `source`\nThe source of the iframe.\n\n##### `height`\nThe height of the iframe. The minimum allowed height is 50.\n\n### HTML\nEmbed any HTML.\n\nExample:\n\n```yaml\n- type: html\n  source: |\n    <p>Hello, <span class=\"color-primary\">World</span>!</p>\n```\n\nNote the use of `|` after `source:`, this allows you to insert a multi-line string.\n"
  },
  {
    "path": "docs/custom-api.md",
    "content": "[Jump to function definitions](#functions)\n\n## Examples\n\nThe best way to get an idea of how the templates work would be with a bunch examples. Here are the most common use cases:\n\nJSON response:\n\n```json\n{\n  \"title\": \"My Title\",\n  \"content\": \"My Content\",\n}\n```\n\nTo access the two fields in the JSON response, you would use the following:\n\n```html\n<div>{{ .JSON.String \"title\" }}</div>\n<div>{{ .JSON.String \"content\" }}</div>\n```\n\nOutput:\n\n```html\n<div>My Title</div>\n<div>My Content</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n{\n  \"author\": \"John Doe\",\n  \"posts\": [\n    {\n      \"title\": \"My Title\",\n      \"content\": \"My Content\"\n    },\n    {\n      \"title\": \"My Title 2\",\n      \"content\": \"My Content 2\"\n    }\n  ]\n}\n```\n\nTo loop through the array of posts, you would use the following:\n\n```html\n{{ range .JSON.Array \"posts\" }}\n  <div>{{ .String \"title\" }}</div>\n  <div>{{ .String \"content\" }}</div>\n{{ end }}\n```\n\nOutput:\n\n```html\n<div>My Title</div>\n<div>My Content</div>\n<div>My Title 2</div>\n<div>My Content 2</div>\n```\n\nNotice the missing `.JSON` when accessing the title and content, this is because the range function sets the context to the current array element.\n\nIf you want to access the top-level context within the range, you can use the following:\n\n```html\n{{ range .JSON.Array \"posts\" }}\n  <div>{{ .String \"title\" }}</div>\n  <div>{{ .String \"content\" }}</div>\n  <div>{{ $.JSON.String \"author\" }}</div>\n{{ end }}\n```\n\nOutput:\n\n```html\n<div>My Title</div>\n<div>My Content</div>\n<div>John Doe</div>\n<div>My Title 2</div>\n<div>My Content 2</div>\n<div>John Doe</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n[\n    \"Apple\",\n    \"Banana\",\n    \"Cherry\",\n    \"Watermelon\"\n]\n```\n\nSomewhat 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:\n\n```html\n{{ range .JSON.Array \"\" }}\n  <div>{{ .String \"\" }}</div>\n{{ end }}\n```\n\nOutput:\n\n```html\n<div>Apple</div>\n<div>Banana</div>\n<div>Cherry</div>\n<div>Watermelon</div>\n```\n\nTo access an item at a specific index, you could use the following:\n\n```html\n<div>{{ .JSON.String \"0\" }}</div>\n```\n\nOutput:\n\n```html\n<div>Apple</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n{\n    \"user\": {\n        \"address\": {\n            \"city\": \"New York\",\n            \"state\": \"NY\"\n        }\n    }\n}\n```\n\nTo easily access deeply nested objects, you can use the following dot notation:\n\n```html\n<div>{{ .JSON.String \"user.address.city\" }}</div>\n<div>{{ .JSON.String \"user.address.state\" }}</div>\n```\n\nOutput:\n\n```html\n<div>New York</div>\n<div>NY</div>\n```\n\nUsing indexes anywhere in the path is also supported:\n\n```json\n{\n    \"users\": [\n        {\n            \"name\": \"John Doe\"\n        },\n        {\n            \"name\": \"Jane Doe\"\n        }\n    ]\n}\n```\n\n```html\n<div>{{ .JSON.String \"users.0.name\" }}</div>\n<div>{{ .JSON.String \"users.1.name\" }}</div>\n```\n\nOutput:\n\n```html\n<div>John Doe</div>\n<div>Jane Doe</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n{\n    \"user\": {\n        \"name\": \"John Doe\",\n        \"age\": 30\n    }\n}\n```\n\nTo check if a field exists, you can use the following:\n\n```html\n{{ if .JSON.Exists \"user.age\" }}\n  <div>{{ .JSON.Int \"user.age\" }}</div>\n{{ else }}\n  <div>Age not provided</div>\n{{ end }}\n```\n\nOutput:\n\n```html\n<div>30</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n{\n    \"price\": 100,\n    \"discount\": 10\n}\n```\n\nCalculations 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.\n\n```html\n<div>{{ sub (.JSON.Int \"price\") (.JSON.Int \"discount\") }}</div>\n```\n\nOutput:\n\n```html\n<div>90</div>\n```\n\nOther operations include `add`, `mul`, `div` and `mod`.\n\n<hr>\n\nJSON response:\n\n```json\n{\n  \"posts\": [\n    {\n      \"title\": \"Exploring the Depths of Quantum Computing\",\n      \"date\": \"2023-10-27T10:00:00Z\"\n    },\n    {\n      \"title\": \"A Beginner's Guide to Sustainable Living\",\n      \"date\": \"2023-11-15T14:30:00+01:00\"\n    },\n    {\n      \"title\": \"The Art of Baking Sourdough Bread\",\n      \"date\": \"2023-12-03T08:45:22-08:00\"\n    }\n  ]\n}\n```\n\nTo parse the date and display the relative time (e.g. 2h, 1d, etc), you would use the following:\n\n```\n{{ range .JSON.Array \"posts\" }}\n  <div>{{ .String \"title\" }}</div>\n  <div {{ .String \"date\" | parseTime \"rfc3339\" | toRelativeTime }}></div>\n{{ end }}\n```\n\nThe `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).\n\nOutput:\n\n```html\n<div>Exploring the Depths of Quantum Computing</div>\n<div data-dynamic-relative-time=\"1698400800\"></div>\n\n<div>A Beginner's Guide to Sustainable Living</div>\n<div data-dynamic-relative-time=\"1700055000\"></div>\n\n<div>The Art of Baking Sourdough Bread</div>\n<div data-dynamic-relative-time=\"1701621922\"></div>\n```\n\nYou 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.\n\nThe 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.\n\n<hr>\n\nIn some instances, you may want to know the status code of the response. This can be done using the following:\n\n```html\n{{ if eq .Response.StatusCode 200 }}\n  <p>Success!</p>\n{{ else }}\n  <p>Failed to fetch data</p>\n{{ end }}\n```\n\nYou can also access the response headers:\n\n```html\n<div>{{ .Response.Header.Get \"Content-Type\" }}</div>\n```\n\n<hr>\n\nJSON response:\n\n```json\n{\"name\": \"Steve\", \"age\": 30}\n{\"name\": \"Alex\", \"age\": 25}\n{\"name\": \"John\", \"age\": 35}\n```\n\nThe 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:\n\n```yaml\n- type: custom-api\n  skip-json-validation: true\n```\n\nThen, to iterate over each object you can use `.JSONLines`:\n\n```html\n{{ range .JSONLines }}\n  <p>{{ .String \"name\" }} is {{ .Int \"age\" }} years old</p>\n{{ end }}\n```\n\nOutput:\n\n```html\n<p>Steve is 30 years old</p>\n<p>Alex is 25 years old</p>\n<p>John is 35 years old</p>\n```\n\nFor 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:\n\n```html\n{{ range .JSON.Array \"..#.name\" }}\n  <p>{{ .String \"\" }}</p>\n{{ end }}\n```\n\nOutput:\n\n```html\n<p>Steve</p>\n<p>Alex</p>\n<p>John</p>\n```\n\n<hr>\n\nIn 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:\n\n```yaml\n- type: custom-api\n  url: https://api.example.com/get-id-of-something\n  template: |\n    {{ $theID := .JSON.String \"id\" }}\n\n    {{\n      $something := newRequest (concat \"https://api.example.com/something/\" $theID)\n        | withParameter \"key\" \"value\"\n        | withHeader \"Authorization\" \"Bearer token\"\n        | getResponse\n    }}\n\n    {{ $something.JSON.String \"title\" }}\n```\n\nHere, `$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.\n\nIf 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:\n\n```yaml\n- type: custom-api\n  title: Events from the last 24h\n  template: |\n    {{\n      $events := newRequest \"https://api.example.com/events\"\n        | withParameter \"after\" (offsetNow \"-24h\" | formatTime \"rfc3339\")\n        | getResponse\n    }}\n\n    {{ if eq $events.Response.StatusCode 200 }}\n      {{ range $events.JSON.Array \"events\" }}\n        <div>{{ .String \"title\" }}</div>\n        <div {{ .String \"date\" | parseTime \"rfc3339\" | toRelativeTime }}></div>\n      {{ end }}\n    {{ else }}\n      <p>Failed to fetch data: {{ $events.Response.Status }}</p>\n    {{ end }}\n```\n\n*Note that you need to manually check for the correct status code.*\n\n## Functions\n\nThe following functions are available on the `JSON` object:\n\n- `String(key string) string`: Returns the value of the key as a string.\n- `Int(key string) int`: Returns the value of the key as an integer.\n- `Float(key string) float`: Returns the value of the key as a float.\n- `Bool(key string) bool`: Returns the value of the key as a boolean.\n- `Array(key string) []JSON`: Returns the value of the key as an array of `JSON` objects.\n- `Exists(key string) bool`: Returns true if the key exists in the JSON object.\n\nThe following functions are available on the `Options` object:\n\n- `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.\n- `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.\n- `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.\n- `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.\n- `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.\n\nThe following helper functions provided by Glance are available:\n\n- `toFloat(i int) float`: Converts an integer to a float.\n- `toInt(f float) int`: Converts a float to an integer.\n- `toRelativeTime(t time.Time) template.HTMLAttr`: Converts Time to a relative time such as 2h, 1d, etc which dynamically updates. **NOTE:** the value of this function should be used as an attribute in an HTML tag, e.g. `<span {{ toRelativeTime .Time }}></span>`.\n- `now() time.Time`: Returns the current time.\n- `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\".\n- `duration(str string) time.Duration`: Parses a string such as `1h`, `24h`, `5h30m`, etc into a `time.Duration`.\n- `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\".\n- `formatTime(layout string, s string) time.Time`: Formats a `time.Time` into a string. The layout uses the same format as `parseTime`.\n- `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.\n- `parseRelativeTime(layout string, s string) time.Time`: A shorthand for `{{ .String \"date\" | parseTime \"rfc3339\" | toRelativeTime }}`.\n- `add(a, b float) float`: Adds two numbers.\n- `sub(a, b float) float`: Subtracts two numbers.\n- `mul(a, b float) float`: Multiplies two numbers.\n- `div(a, b float) float`: Divides two numbers.\n- `mod(a, b int) int`: Remainder after dividing a by b (a % b).\n- `formatApproxNumber(n int) string`: Formats a number to be more human-readable, e.g. 1000 -> 1k.\n- `formatNumber(n float|int) string`: Formats a number with commas, e.g. 1000 -> 1,000.\n- `trimPrefix(prefix string, str string) string`: Trims the prefix from a string.\n- `trimSuffix(suffix string, str string) string`: Trims the suffix from a string.\n- `trimSpace(str string) string`: Trims whitespace from a string on both ends.\n- `replaceAll(old string, new string, str string) string`: Replaces all occurrences of a string in a string.\n- `replaceMatches(pattern string, replacement string, str string) string`: Replaces all occurrences of a regular expression in a string.\n- `findMatch(pattern string, str string) string`: Finds the first match of a regular expression in a string.\n- `findSubmatch(pattern string, str string) string`: Finds the first submatch of a regular expression in a string.\n- `sortByString(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by a string key in either ascending or descending order.\n- `sortByInt(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by an integer key in either ascending or descending order.\n- `sortByFloat(key string, order string, arr []JSON): []JSON`: Sorts an array of JSON objects by a float key in either ascending or descending order.\n- `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).\n- `concat(strings ...string) string`: Concatenates multiple strings together.\n- `unique(key string, arr []JSON) []JSON`: Returns a unique array of JSON objects based on the given key.\n- `percentChange(current float, previous float) float`: Calculates the percentage change between two numbers.\n- `startOfDay(t time.Time) time.Time`: Returns the start of the day for a given time.\n- `endOfDay(t time.Time) time.Time`: Returns the end of the day for a given time.\n\nThe following helper functions provided by Go's `text/template` are available:\n\n- `eq(a, b any) bool`: Compares two values for equality.\n- `ne(a, b any) bool`: Compares two values for inequality.\n- `lt(a, b any) bool`: Compares two values for less than.\n- `le(a, b any) bool`: Compares two values for less than or equal to.\n- `gt(a, b any) bool`: Compares two values for greater than.\n- `ge(a, b any) bool`: Compares two values for greater than or equal to.\n- `and(args ...bool) bool`: Returns true if **all** arguments are true; accepts two or more boolean values.\n- `or(args ...bool) bool`: Returns true if **any** argument is true; accepts two or more boolean values.\n- `not(a bool) bool`: Returns the opposite of the value.\n- `index(a any, b int) any`: Returns the value at the specified index of an array.\n- `len(a any) int`: Returns the length of an array.\n- `printf(format string, a ...any) string`: Returns a formatted string.\n"
  },
  {
    "path": "docs/extensions.md",
    "content": "# Extensions\n\n> [!IMPORTANT]\n>\n> **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.**\n\n## Overview\n\nWith 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:\n\n![](images/extension-overview.png)\n\nIf you know how to setup an HTTP server and a bit of HTML and CSS you're ready to start building your own extensions.\n\n> [!TIP]\n>\n> 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:\n> ```yaml\n> - type: extension\n>   url: http://localhost:8081\n>   cache: 1s\n> ```\n\n## Headers\n\n### `Widget-Title`\nUsed to specify the title of the widget. If not provided, the widget's title will be \"Extension\".\n\n### `Widget-Title-URL`\nUsed 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.\n\n### `Widget-Content-Type`\nUsed to specify the content type that will be returned by the extension. If not provided, the content will be shown as plain text.\n\n### `Widget-Content-Frameless`\nWhen set to `true`, the widget's content will be displayed without the default background or \"frame\".\n\n## Content Types\n\n> [!NOTE]\n>\n> 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.\n\n### `html`\nDisplays 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.\n\n\n#### Using existing classes and functionality\nMost of the features seen throughout Glance can easily be used in your custom HTML extensions. Below is an example of some of these features:\n\n```html\n<p class=\"color-subdue\">Text with subdued color</p>\n<p>Text with base color</p>\n<p class=\"color-highlight\">Text with highlighted color</p>\n<p class=\"color-primary\">Text with primary color</p>\n<p class=\"color-positive\">Text with positive color</p>\n<p class=\"color-negative\">Text with negative color</p>\n\n<hr class=\"margin-block-15\">\n\n<p class=\"size-h1\">Font size 1</p>\n<p class=\"size-h2\">Font size 2</p>\n<p class=\"size-h3\">Font size 3</p>\n<p class=\"size-h4\">Font size 4</p>\n<p class=\"size-base\">Font size base</p>\n<p class=\"size-h5\">Font size 5</p>\n<p class=\"size-h6\">Font size 6</p>\n\n<hr class=\"margin-block-15\">\n\n<a class=\"visited-indicator\" href=\"#notvisitedprobably\">Link with visited indicator</a>\n\n<hr class=\"margin-block-15\">\n\n<a class=\"color-primary-if-not-visited\" href=\"#notvisitedprobably\">Link with primary color if not visited</a>\n\n<hr class=\"margin-block-15\">\n\n<p>Event happened <span data-dynamic-relative-time=\"<unix timestamp>\"></span> ago</p>\n\n<hr class=\"margin-block-15\">\n\n<ul class=\"list-horizontal-text\">\n    <li>horizontal</li>\n    <li>list</li>\n    <li>with</li>\n    <li>multiple</li>\n    <li>text</li>\n    <li>items</li>\n</ul>\n\n<hr class=\"margin-block-15\">\n\n<ul class=\"list list-gap-10 list-with-separator\">\n    <li>list</li>\n    <li>with</li>\n    <li>gap</li>\n    <li>and</li>\n    <li>horizontal</li>\n    <li>lines</li>\n</ul>\n\n<hr class=\"margin-block-15\">\n\n<ul class=\"list collapsible-container\" data-collapse-after=\"3\">\n    <li>collapsible</li>\n    <li>list</li>\n    <li>with</li>\n    <li>many</li>\n    <li>items</li>\n    <li>that</li>\n    <li>will</li>\n    <li>appear</li>\n    <li>when</li>\n    <li>you</li>\n    <li>click</li>\n    <li>the</li>\n    <li>button</li>\n    <li>below</li>\n</ul>\n\n<hr class=\"margin-bottom-15\">\n\n<p class=\"margin-bottom-10\">Lazily loaded image:</p>\n\n<img src=\"https://picsum.photos/200\" alt=\"\" loading=\"lazy\">\n\n<hr class=\"margin-block-15\">\n\n<p class=\"margin-bottom-10\">List of posts:</p>\n\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"5\">\n    <li>\n        <a class=\"size-h3 color-primary-if-not-visited\" href=\"#link\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatum, ipsa?</a>\n        <ul class=\"list-horizontal-text\">\n            <li data-dynamic-relative-time=\"<unix timestamp>\"></li>\n            <li>3,321 points</li>\n            <li>139 comments</li>\n        </ul>\n    </li>\n    <li>\n        <a class=\"size-h3 color-primary-if-not-visited\" href=\"#link\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatum, ipsa?</a>\n        <ul class=\"list-horizontal-text\">\n            <li data-dynamic-relative-time=\"<unix timestamp>\"></li>\n            <li>3,321 points</li>\n            <li>139 comments</li>\n        </ul>\n    </li>\n    <li>\n        <a class=\"size-h3 color-primary-if-not-visited\" href=\"#link\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Voluptatum, ipsa?</a>\n        <ul class=\"list-horizontal-text\">\n            <li data-dynamic-relative-time=\"<unix timestamp>\"></li>\n            <li>3,321 points</li>\n            <li>139 comments</li>\n        </ul>\n    </li>\n</ul>\n```\n\nAll of that will result in the following:\n\n![](images/extension-html-reusing-existing-features-preview.png)\n\n**Class names or features may change, once again, you are responsible for maintaining your own extensions.**\n"
  },
  {
    "path": "docs/glance.yml",
    "content": "pages:\n  - name: Home\n    # Optionally, if you only have a single page you can hide the desktop navigation for a cleaner look\n    # hide-desktop-navigation: true\n    columns:\n      - size: small\n        widgets:\n          - type: calendar\n            first-day-of-week: monday\n\n          - type: rss\n            limit: 10\n            collapse-after: 3\n            cache: 12h\n            feeds:\n              - url: https://selfh.st/rss/\n                title: selfh.st\n                limit: 4\n              - url: https://ciechanow.ski/atom.xml\n              - url: https://www.joshwcomeau.com/rss.xml\n                title: Josh Comeau\n              - url: https://samwho.dev/rss.xml\n              - url: https://ishadeed.com/feed.xml\n                title: Ahmad Shadeed\n\n          - type: twitch-channels\n            channels:\n              - theprimeagen\n              - j_blow\n              - giantwaffle\n              - cohhcarnage\n              - christitustech\n              - EJ_SA\n\n      - size: full\n        widgets:\n          - type: group\n            widgets:\n              - type: hacker-news\n              - type: lobsters\n\n          - type: videos\n            channels:\n              - UCXuqSBlHAE6Xw-yeJA0Tunw # Linus Tech Tips\n              - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling\n              - UCsBjURrPoezykLs9EqgamOA # Fireship\n              - UCBJycsmduvYEL83R_U4JriQ # Marques Brownlee\n              - UCHnyfMqiRRG1u-2MsSQLbXA # Veritasium\n\n          - type: group\n            widgets:\n              - type: reddit\n                subreddit: technology\n                show-thumbnails: true\n              - type: reddit\n                subreddit: selfhosted\n                show-thumbnails: true\n\n      - size: small\n        widgets:\n          - type: weather\n            location: London, United Kingdom\n            units: metric # alternatively \"imperial\"\n            hour-format: 12h # alternatively \"24h\"\n            # Optionally hide the location from being displayed in the widget\n            # hide-location: true\n\n          - type: markets\n            markets:\n              - symbol: SPY\n                name: S&P 500\n              - symbol: BTC-USD\n                name: Bitcoin\n              - symbol: NVDA\n                name: NVIDIA\n              - symbol: AAPL\n                name: Apple\n              - symbol: MSFT\n                name: Microsoft\n\n          - type: releases\n            cache: 1d\n            # Without authentication the Github API allows for up to 60 requests per hour. You can create a\n            # read-only token from your Github account settings and use it here to increase the limit.\n            # token: ...\n            repositories:\n              - glanceapp/glance\n              - go-gitea/gitea\n              - immich-app/immich\n              - syncthing/syncthing\n\n  # Add more pages here:\n  # - name: Your page name\n  #   columns:\n  #     - size: small\n  #       widgets:\n  #         # Add widgets here\n\n  #     - size: full\n  #       widgets:\n  #         # Add widgets here\n\n  #     - size: small\n  #       widgets:\n  #         # Add widgets here\n"
  },
  {
    "path": "docs/preconfigured-pages.md",
    "content": "# Preconfigured pages\n\nDon't want to spend time configuring pages from scratch? No problem! Simply copy the config from the ones below.\n\nPull requests with your page configurations are welcome!\n\n> [!NOTE]\n>\n> Pages must be placed under a top level `pages:` key, you can read more about that [here](configuration.md#pages).\n\n## Startpage\n\n![](images/startpage-preview.png)\n\n<details>\n<summary>View config (requires Glance <code>v0.6.0</code> or higher)</summary>\n\n```yaml\n- name: Startpage\n  width: slim\n  hide-desktop-navigation: true\n  center-vertically: true\n  columns:\n    - size: full\n      widgets:\n        - type: search\n          autofocus: true\n\n        - type: monitor\n          cache: 1m\n          title: Services\n          sites:\n            - title: Jellyfin\n              url: https://yourdomain.com/\n              icon: si:jellyfin\n            - title: Gitea\n              url: https://yourdomain.com/\n              icon: si:gitea\n            - title: qBittorrent # only for Linux ISOs, of course\n              url: https://yourdomain.com/\n              icon: si:qbittorrent\n            - title: Immich\n              url: https://yourdomain.com/\n              icon: si:immich\n            - title: AdGuard Home\n              url: https://yourdomain.com/\n              icon: si:adguard\n            - title: Vaultwarden\n              url: https://yourdomain.com/\n              icon: si:vaultwarden\n\n        - type: bookmarks\n          groups:\n            - title: General\n              links:\n                - title: Gmail\n                  url: https://mail.google.com/mail/u/0/\n                - title: Amazon\n                  url: https://www.amazon.com/\n                - title: Github\n                  url: https://github.com/\n            - title: Entertainment\n              links:\n                - title: YouTube\n                  url: https://www.youtube.com/\n                - title: Prime Video\n                  url: https://www.primevideo.com/\n                - title: Disney+\n                  url: https://www.disneyplus.com/\n            - title: Social\n              links:\n                - title: Reddit\n                  url: https://www.reddit.com/\n                - title: Twitter\n                  url: https://twitter.com/\n                - title: Instagram\n                  url: https://www.instagram.com/\n```\n</details>\n\n## Markets\n\n![](images/markets-page-preview.png)\n\n<details>\n<summary>View config (requires Glance <code>v0.6.0</code> or higher)</summary>\n\n```yaml\n- name: Markets\n  columns:\n    - size: small\n      widgets:\n        - type: markets\n          title: Indices\n          markets:\n            - symbol: SPY\n              name: S&P 500\n            - symbol: DX-Y.NYB\n              name: Dollar Index\n\n        - type: markets\n          title: Crypto\n          markets:\n            - symbol: BTC-USD\n              name: Bitcoin\n            - symbol: ETH-USD\n              name: Ethereum\n\n        - type: markets\n          title: Stocks\n          sort-by: absolute-change\n          markets:\n            - symbol: NVDA\n              name: NVIDIA\n            - symbol: AAPL\n              name: Apple\n            - symbol: MSFT\n              name: Microsoft\n            - symbol: GOOGL\n              name: Google\n            - symbol: AMD\n              name: AMD\n            - symbol: RDDT\n              name: Reddit\n            - symbol: AMZN\n              name: Amazon\n            - symbol: TSLA\n              name: Tesla\n            - symbol: INTC\n              name: Intel\n            - symbol: META\n              name: Meta\n\n    - size: full\n      widgets:\n        - type: rss\n          title: News\n          style: horizontal-cards\n          feeds:\n            - url: https://feeds.bloomberg.com/markets/news.rss\n              title: Bloomberg\n            - url: https://moxie.foxbusiness.com/google-publisher/markets.xml\n              title: Fox Business\n            - url: https://moxie.foxbusiness.com/google-publisher/technology.xml\n              title: Fox Business\n\n        - type: group\n          widgets:\n            - type: reddit\n              show-thumbnails: true\n              subreddit: technology\n            - type: reddit\n              show-thumbnails: true\n              subreddit: wallstreetbets\n\n        - type: videos\n          style: grid-cards\n          collapse-after-rows: 3\n          channels:\n            - UCvSXMi2LebwJEM1s4bz5IBA # New Money\n            - UCV6KDgJskWaEckne5aPA0aQ # Graham Stephan\n            - UCAzhpt9DmG6PnHXjmJTvRGQ # Federal Reserve\n\n    - size: small\n      widgets:\n        - type: rss\n          title: News\n          limit: 30\n          collapse-after: 13\n          feeds:\n            - url: https://www.ft.com/technology?format=rss\n              title: Financial Times\n            - url: https://feeds.a.dj.com/rss/RSSMarketsMain.xml\n              title: Wall Street Journal\n```\n</details>\n\n## Gaming\n\n![](images/gaming-page-preview.png)\n\n<details>\n<summary>View config (requires Glance <code>v0.6.0</code> or higher)</summary>\n\n```yaml\n- name: Gaming\n  columns:\n    - size: small\n      widgets:\n        - type: twitch-top-games\n          limit: 20\n          collapse-after: 13\n          exclude:\n            - just-chatting\n            - pools-hot-tubs-and-beaches\n            - music\n            - art\n            - asmr\n\n    - size: full\n      widgets:\n        - type: group\n          widgets:\n            - type: reddit\n              show-thumbnails: true\n              subreddit: pcgaming\n            - type: reddit\n              subreddit: games\n\n        - type: videos\n          style: grid-cards\n          collapse-after-rows: 3\n          channels:\n            - UCNvzD7Z-g64bPXxGzaQaa4g # gameranx\n            - UCZ7AeeVbyslLM_8-nVy2B8Q # Skill Up\n            - UCHDxYLv8iovIbhrfl16CNyg # GameLinked\n            - UC9PBzalIcEQCsiIkq36PyUA # Digital Foundry\n\n    - size: small\n      widgets:\n        - type: reddit\n          subreddit: gamingnews\n          limit: 7\n          style: vertical-cards\n```\n</details>\n"
  },
  {
    "path": "docs/themes.md",
    "content": "# Themes\n\n## Dark\n\n### Teal City\n![screenshot](images/themes/teal-city.png)\n```yaml\ntheme:\n  background-color: 225 14 15\n  primary-color: 157 47 65\n  contrast-multiplier: 1.1\n```\n\n### Catppuccin Frappe\n![screenshot](images/themes/catppuccin-frappe.png)\n```yaml\ntheme:\n  background-color: 229 19 23\n  contrast-multiplier: 1.2\n  primary-color: 222 74 74\n  positive-color: 96 44 68\n  negative-color: 359 68 71\n```\n\n### Catppuccin Macchiato\n![screenshot](images/themes/catppuccin-macchiato.png)\n```yaml\ntheme:\n  background-color: 232 23 18\n  contrast-multiplier: 1.2\n  primary-color: 220 83 75\n  positive-color: 105 48 72\n  negative-color: 351 74 73\n```\n\n### Catppuccin Mocha\n![screenshot](images/themes/catppuccin-mocha.png)\n```yaml\ntheme:\n  background-color: 240 21 15\n  contrast-multiplier: 1.2\n  primary-color: 217 92 83\n  positive-color: 115 54 76\n  negative-color: 347 70 65\n```\n\n### Camouflage\n![screenshot](images/themes/camouflage.png)\n```yaml\ntheme:\n  background-color: 186 21 20\n  contrast-multiplier: 1.2\n  primary-color: 97 13 80\n```\n\n### Gruvbox Dark\n![screenshot](images/themes/gruvbox.png)\n```yaml\ntheme:\n  background-color: 0 0 16\n  primary-color: 43 59 81\n  positive-color: 61 66 44\n  negative-color: 6 96 59\n```\n\n### Kanagawa Dark\n![screenshot](images/themes/kanagawa-dark.png)\n```yaml\ntheme:\n  background-color: 240 13 14\n  primary-color: 51 33 68\n  negative-color: 358 100 68\n  contrast-multiplier: 1.2\n```\n\n### Tucan\n![screenshot](images/themes/tucan.png)\n```yaml\ntheme:\n  background-color: 50 1 6\n  primary-color: 24 97 58\n  negative-color: 209 88 54\n```\n\n### Dracula\n![screenshot](images/themes/dracula.png)\n```yaml\ntheme:\n  background-color: 231 15 21\n  primary-color: 265 89 79\n  contrast-multiplier: 1.2\n  positive-color: 135 94 66\n  negative-color: 0 100 67\n```\n\n### Shades of Purple\n![screenshot](images/themes/shades-of-purple.png)\n```yaml\ntheme:\n  background-color: 243 33 25\n  contrast-multiplier: 1.2\n  primary-color: 50 100 49\n  positive-color: 98 82 71\n  negative-color: 12 77 52\n```\n\n### Neon Pink \n![screenshot](images/themes/neon-pink.png)\n```yaml\ntheme:\n  background-color: 240 27 11\n  contrast-multiplier: 1.5\n  primary-color: 321 100 71\n  positive-color: 165 78 51\n  negative-color: 360 100 71\n```\n\n## Light\n\n### Catppuccin Latte\n![screenshot](images/themes/catppuccin-latte.png)\n```yaml\ntheme:\n  light: true\n  background-color: 220 23 95\n  contrast-multiplier: 1.0\n  primary-color: 220 91 54\n  positive-color: 109 58 40\n  negative-color: 347 87 44\n```\n\n### Peachy\n![screenshot](images/themes/peachy.png)\n```yaml\ntheme:\n  light: true\n  background-color: 28 40 77\n  primary-color: 155 100 20\n  negative-color: 0 100 60\n  contrast-multiplier: 1.1\n  text-saturation-multiplier: 0.5\n```\n\n### Zebra\n![screenshot](images/themes/zebra.png)\n```yaml\ntheme:\n  light: true\n  background-color: 0 0 95\n  primary-color: 0 0 10\n  negative-color: 0 90 50\n```\n"
  },
  {
    "path": "docs/v0.7.0-upgrade.md",
    "content": "## Upgrading to v0.7.0 from previous versions\n\nIn 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.\n\n### Before\n\nVersions before v0.7.0 used a `docker-compose.yml` that looked like the following:\n\n```yaml\nservices:\n  glance:\n    image: glanceapp/glance\n    volumes:\n      - ./glance.yml:/app/glance.yml\n    ports:\n      - 8080:8080\n```\n\nAnd expected you to have the following directory structure:\n\n```plaintext\nglance/\n    docker-compose.yml\n    glance.yml\n```\n\n### After\n\nWith the release of v0.7.0, the recommended `docker-compose.yml` looks like the following:\n\n```yaml\nservices:\n  glance:\n    container_name: glance\n    image: glanceapp/glance\n    volumes:\n      - ./config:/app/config\n    ports:\n      - 8080:8080\n```\n\nAnd expects you to have the following directory structure:\n\n```plaintext\nglance/\n    docker-compose.yml\n    config/\n        glance.yml\n```\n\n## Why this change was necessary\n\n1. 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\n2. v0.7.0 added automatic reloads when the configuration file changes, which based on testing didn't work when mounting a single file\n3. 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\n\nTaking all of these into account, it felt like the right time to implement the change.\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/glanceapp/glance\n\ngo 1.24.3\n\nrequire (\n\tgithub.com/fsnotify/fsnotify v1.9.0\n\tgithub.com/mmcdole/gofeed v1.3.0\n\tgithub.com/shirou/gopsutil/v4 v4.25.4\n\tgithub.com/tidwall/gjson v1.18.0\n\tgolang.org/x/crypto v0.38.0\n\tgolang.org/x/text v0.25.0\n\tgopkg.in/yaml.v3 v3.0.1\n)\n\nrequire (\n\tgithub.com/PuerkitoBio/goquery v1.10.3 // indirect\n\tgithub.com/andybalholm/cascadia v1.3.3 // indirect\n\tgithub.com/ebitengine/purego v0.8.4 // indirect\n\tgithub.com/go-ole/go-ole v1.3.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect\n\tgithub.com/mmcdole/goxpp v1.1.1 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/tidwall/match v1.1.1 // indirect\n\tgithub.com/tidwall/pretty v1.2.1 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.15 // indirect\n\tgithub.com/tklauser/numcpus v0.10.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgolang.org/x/net v0.40.0 // indirect\n\tgolang.org/x/sys v0.33.0 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/PuerkitoBio/goquery v1.10.3 h1:pFYcNSqHxBD06Fpj/KsbStFRsgRATgnf3LeXiUkhzPo=\ngithub.com/PuerkitoBio/goquery v1.10.3/go.mod h1:tMUX0zDMHXYlAQk6p35XxQMqMweEKB7iK7iLNd4RH4Y=\ngithub.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=\ngithub.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.8.4 h1:CF7LEKg5FFOsASUj0+QwaXf8Ht6TlFxg09+S9wz0omw=\ngithub.com/ebitengine/purego v0.8.4/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=\ngithub.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=\ngithub.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc=\ngithub.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mmcdole/gofeed v1.3.0 h1:5yn+HeqlcvjMeAI4gu6T+crm7d0anY85+M+v6fIFNG4=\ngithub.com/mmcdole/gofeed v1.3.0/go.mod h1:9TGv2LcJhdXePDzxiuMnukhV2/zb6VtnZt1mS+SjkLE=\ngithub.com/mmcdole/goxpp v1.1.1 h1:RGIX+D6iQRIunGHrKqnA2+700XMCnNv0bAOOv5MUhx8=\ngithub.com/mmcdole/goxpp v1.1.1/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/shirou/gopsutil/v4 v4.25.4 h1:cdtFO363VEOOFrUCjZRh4XVJkb548lyF0q0uTeMqYPw=\ngithub.com/shirou/gopsutil/v4 v4.25.4/go.mod h1:xbuxyoZj+UsgnZrENu3lQivsngRR5BdjbJwf2fv4szA=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=\ngithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=\ngithub.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=\ngithub.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=\ngithub.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=\ngithub.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=\ngithub.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=\ngithub.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=\ngithub.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=\ngithub.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=\ngithub.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=\ngithub.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=\ngithub.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=\ngolang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=\ngolang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=\ngolang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=\ngolang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=\ngolang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=\ngolang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=\ngolang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=\ngolang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=\ngolang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=\ngolang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=\ngolang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=\ngolang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=\ngolang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=\ngolang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=\ngolang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=\ngolang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=\ngolang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=\ngolang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=\ngolang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=\ngolang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=\ngolang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=\ngolang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=\ngolang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=\ngolang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=\ngolang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=\ngolang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=\ngolang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=\ngolang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=\ngolang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=\ngolang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/glance/auth.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\tmathrand \"math/rand/v2\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\nconst AUTH_SESSION_COOKIE_NAME = \"session_token\"\nconst AUTH_RATE_LIMIT_WINDOW = 5 * time.Minute\nconst AUTH_RATE_LIMIT_MAX_ATTEMPTS = 5\n\nconst AUTH_TOKEN_SECRET_LENGTH = 32\nconst AUTH_USERNAME_HASH_LENGTH = 32\nconst AUTH_SECRET_KEY_LENGTH = AUTH_TOKEN_SECRET_LENGTH + AUTH_USERNAME_HASH_LENGTH\nconst AUTH_TIMESTAMP_LENGTH = 4 // uint32\nconst AUTH_TOKEN_DATA_LENGTH = AUTH_USERNAME_HASH_LENGTH + AUTH_TIMESTAMP_LENGTH\n\n// How long the token will be valid for\nconst AUTH_TOKEN_VALID_PERIOD = 14 * 24 * time.Hour // 14 days\n// How long the token has left before it should be regenerated\nconst AUTH_TOKEN_REGEN_BEFORE = 7 * 24 * time.Hour // 7 days\n\nvar loginPageTemplate = mustParseTemplate(\"login.html\", \"document.html\", \"footer.html\")\n\ntype doWhenUnauthorized int\n\nconst (\n\tredirectToLogin doWhenUnauthorized = iota\n\tshowUnauthorizedJSON\n)\n\ntype failedAuthAttempt struct {\n\tattempts int\n\tfirst    time.Time\n}\n\nfunc generateSessionToken(username string, secret []byte, now time.Time) (string, error) {\n\tif len(secret) != AUTH_SECRET_KEY_LENGTH {\n\t\treturn \"\", fmt.Errorf(\"secret key length is not %d bytes\", AUTH_SECRET_KEY_LENGTH)\n\t}\n\n\tusernameHash, err := computeUsernameHash(username, secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata := make([]byte, AUTH_TOKEN_DATA_LENGTH)\n\tcopy(data, usernameHash)\n\texpires := now.Add(AUTH_TOKEN_VALID_PERIOD).Unix()\n\tbinary.LittleEndian.PutUint32(data[AUTH_USERNAME_HASH_LENGTH:], uint32(expires))\n\n\th := hmac.New(sha256.New, secret[0:AUTH_TOKEN_SECRET_LENGTH])\n\th.Write(data)\n\n\tsignature := h.Sum(nil)\n\tencodedToken := base64.StdEncoding.EncodeToString(append(data, signature...))\n\t// encodedToken ends up being (hashed username + expiration timestamp + signature) encoded as base64\n\n\treturn encodedToken, nil\n}\n\nfunc computeUsernameHash(username string, secret []byte) ([]byte, error) {\n\tif len(secret) != AUTH_SECRET_KEY_LENGTH {\n\t\treturn nil, fmt.Errorf(\"secret key length is not %d bytes\", AUTH_SECRET_KEY_LENGTH)\n\t}\n\n\th := hmac.New(sha256.New, secret[AUTH_TOKEN_SECRET_LENGTH:])\n\th.Write([]byte(username))\n\n\treturn h.Sum(nil), nil\n}\n\nfunc verifySessionToken(token string, secretBytes []byte, now time.Time) ([]byte, bool, error) {\n\ttokenBytes, err := base64.StdEncoding.DecodeString(token)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif len(tokenBytes) != AUTH_TOKEN_DATA_LENGTH+32 {\n\t\treturn nil, false, fmt.Errorf(\"token length is invalid\")\n\t}\n\n\tif len(secretBytes) != AUTH_SECRET_KEY_LENGTH {\n\t\treturn nil, false, fmt.Errorf(\"secret key length is not %d bytes\", AUTH_SECRET_KEY_LENGTH)\n\t}\n\n\tusernameHashBytes := tokenBytes[0:AUTH_USERNAME_HASH_LENGTH]\n\ttimestampBytes := tokenBytes[AUTH_USERNAME_HASH_LENGTH : AUTH_USERNAME_HASH_LENGTH+AUTH_TIMESTAMP_LENGTH]\n\tprovidedSignatureBytes := tokenBytes[AUTH_TOKEN_DATA_LENGTH:]\n\n\th := hmac.New(sha256.New, secretBytes[0:32])\n\th.Write(tokenBytes[0:AUTH_TOKEN_DATA_LENGTH])\n\texpectedSignatureBytes := h.Sum(nil)\n\n\tif !hmac.Equal(expectedSignatureBytes, providedSignatureBytes) {\n\t\treturn nil, false, fmt.Errorf(\"signature does not match\")\n\t}\n\n\texpiresTimestamp := int64(binary.LittleEndian.Uint32(timestampBytes))\n\tif now.Unix() > expiresTimestamp {\n\t\treturn nil, false, fmt.Errorf(\"token has expired\")\n\t}\n\n\treturn usernameHashBytes,\n\t\t// True if the token should be regenerated\n\t\ttime.Unix(expiresTimestamp, 0).Add(-AUTH_TOKEN_REGEN_BEFORE).Before(now),\n\t\tnil\n}\n\nfunc makeAuthSecretKey(length int) (string, error) {\n\tkey := make([]byte, length)\n\t_, err := rand.Read(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(key), nil\n}\n\nfunc (a *application) handleAuthenticationAttempt(w http.ResponseWriter, r *http.Request) {\n\tif r.Header.Get(\"Content-Type\") != \"application/json\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\twaitOnFailure := 1*time.Second - time.Duration(mathrand.IntN(500))*time.Millisecond\n\n\tip := a.addressOfRequest(r)\n\n\ta.authAttemptsMu.Lock()\n\texceededRateLimit, retryAfter := func() (bool, int) {\n\t\tattempt, exists := a.failedAuthAttempts[ip]\n\t\tif !exists {\n\t\t\ta.failedAuthAttempts[ip] = &failedAuthAttempt{\n\t\t\t\tattempts: 1,\n\t\t\t\tfirst:    time.Now(),\n\t\t\t}\n\n\t\t\treturn false, 0\n\t\t}\n\n\t\telapsed := time.Since(attempt.first)\n\t\tif elapsed < AUTH_RATE_LIMIT_WINDOW && attempt.attempts >= AUTH_RATE_LIMIT_MAX_ATTEMPTS {\n\t\t\treturn true, max(1, int(AUTH_RATE_LIMIT_WINDOW.Seconds()-elapsed.Seconds()))\n\t\t}\n\n\t\tattempt.attempts++\n\t\treturn false, 0\n\t}()\n\n\tif exceededRateLimit {\n\t\ta.authAttemptsMu.Unlock()\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.Header().Set(\"Retry-After\", strconv.Itoa(retryAfter))\n\t\tw.WriteHeader(http.StatusTooManyRequests)\n\t\treturn\n\t} else {\n\t\t// Clean up old failed attempts\n\t\tfor ipOfAttempt := range a.failedAuthAttempts {\n\t\t\tif time.Since(a.failedAuthAttempts[ipOfAttempt].first) > AUTH_RATE_LIMIT_WINDOW {\n\t\t\t\tdelete(a.failedAuthAttempts, ipOfAttempt)\n\t\t\t}\n\t\t}\n\t\ta.authAttemptsMu.Unlock()\n\t}\n\n\tbody, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar creds struct {\n\t\tUsername string `json:\"username\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\terr = json.Unmarshal(body, &creds)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlogAuthFailure := func() {\n\t\tlog.Printf(\n\t\t\t\"Failed login attempt for user '%s' from %s\",\n\t\t\tcreds.Username, ip,\n\t\t)\n\t}\n\n\tif len(creds.Username) == 0 || len(creds.Password) == 0 {\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif len(creds.Username) > 50 || len(creds.Password) > 100 {\n\t\tlogAuthFailure()\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tu, exists := a.Config.Auth.Users[creds.Username]\n\tif !exists {\n\t\tlogAuthFailure()\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif err := bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(creds.Password)); err != nil {\n\t\tlogAuthFailure()\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\ttoken, err := generateSessionToken(creds.Username, a.authSecretKey, time.Now())\n\tif err != nil {\n\t\tlog.Printf(\"Could not compute session token during login attempt: %v\", err)\n\t\ttime.Sleep(waitOnFailure)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\ta.setAuthSessionCookie(w, r, token, time.Now().Add(AUTH_TOKEN_VALID_PERIOD))\n\n\ta.authAttemptsMu.Lock()\n\tdelete(a.failedAuthAttempts, ip)\n\ta.authAttemptsMu.Unlock()\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc (a *application) isAuthorized(w http.ResponseWriter, r *http.Request) bool {\n\tif !a.RequiresAuth {\n\t\treturn true\n\t}\n\n\ttoken, err := r.Cookie(AUTH_SESSION_COOKIE_NAME)\n\tif err != nil || token.Value == \"\" {\n\t\treturn false\n\t}\n\n\tusernameHash, shouldRegenerate, err := verifySessionToken(token.Value, a.authSecretKey, time.Now())\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tusername, exists := a.usernameHashToUsername[string(usernameHash)]\n\tif !exists {\n\t\treturn false\n\t}\n\n\t_, exists = a.Config.Auth.Users[username]\n\tif !exists {\n\t\treturn false\n\t}\n\n\tif shouldRegenerate {\n\t\tnewToken, err := generateSessionToken(username, a.authSecretKey, time.Now())\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not compute session token during regeneration: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\ta.setAuthSessionCookie(w, r, newToken, time.Now().Add(AUTH_TOKEN_VALID_PERIOD))\n\t}\n\n\treturn true\n}\n\n// Handles sending the appropriate response for an unauthorized request and returns true if the request was unauthorized\nfunc (a *application) handleUnauthorizedResponse(w http.ResponseWriter, r *http.Request, fallback doWhenUnauthorized) bool {\n\tif a.isAuthorized(w, r) {\n\t\treturn false\n\t}\n\n\tswitch fallback {\n\tcase redirectToLogin:\n\t\thttp.Redirect(w, r, a.Config.Server.BaseURL+\"/login\", http.StatusSeeOther)\n\tcase showUnauthorizedJSON:\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(`{\"error\": \"Unauthorized\"}`))\n\t}\n\n\treturn true\n}\n\n// Maybe this should be a POST request instead?\nfunc (a *application) handleLogoutRequest(w http.ResponseWriter, r *http.Request) {\n\ta.setAuthSessionCookie(w, r, \"\", time.Now().Add(-1*time.Hour))\n\thttp.Redirect(w, r, a.Config.Server.BaseURL+\"/login\", http.StatusSeeOther)\n}\n\nfunc (a *application) setAuthSessionCookie(w http.ResponseWriter, r *http.Request, token string, expires time.Time) {\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName:     AUTH_SESSION_COOKIE_NAME,\n\t\tValue:    token,\n\t\tExpires:  expires,\n\t\tSecure:   strings.ToLower(r.Header.Get(\"X-Forwarded-Proto\")) == \"https\",\n\t\tPath:     a.Config.Server.BaseURL + \"/\",\n\t\tSameSite: http.SameSiteLaxMode,\n\t\tHttpOnly: true,\n\t})\n}\n\nfunc (a *application) handleLoginPageRequest(w http.ResponseWriter, r *http.Request) {\n\tif a.isAuthorized(w, r) {\n\t\thttp.Redirect(w, r, a.Config.Server.BaseURL+\"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\tdata := &templateData{\n\t\tApp: a,\n\t}\n\ta.populateTemplateRequestData(&data.Request, r)\n\n\tvar responseBytes bytes.Buffer\n\terr := loginPageTemplate.Execute(&responseBytes, data)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tw.Write(responseBytes.Bytes())\n}\n"
  },
  {
    "path": "internal/glance/auth_test.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"encoding/base64\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestAuthTokenGenerationAndVerification(t *testing.T) {\n\tsecret, err := makeAuthSecretKey(AUTH_SECRET_KEY_LENGTH)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to generate secret key: %v\", err)\n\t}\n\n\tsecretBytes, err := base64.StdEncoding.DecodeString(secret)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to decode secret key: %v\", err)\n\t}\n\n\tif len(secretBytes) != AUTH_SECRET_KEY_LENGTH {\n\t\tt.Fatalf(\"Secret key length is not %d bytes\", AUTH_SECRET_KEY_LENGTH)\n\t}\n\n\tnow := time.Now()\n\tusername := \"admin\"\n\n\ttoken, err := generateSessionToken(username, secretBytes, now)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to generate session token: %v\", err)\n\t}\n\n\tusernameHashBytes, shouldRegen, err := verifySessionToken(token, secretBytes, now)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to verify session token: %v\", err)\n\t}\n\n\tif shouldRegen {\n\t\tt.Fatal(\"Token should not need to be regenerated immediately after generation\")\n\t}\n\n\tcomputedUsernameHash, err := computeUsernameHash(username, secretBytes)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to compute username hash: %v\", err)\n\t}\n\n\tif !bytes.Equal(usernameHashBytes, computedUsernameHash) {\n\t\tt.Fatal(\"Username hash does not match the expected value\")\n\t}\n\n\t// Test token regeneration\n\ttimeRightAfterRegenPeriod := now.Add(AUTH_TOKEN_VALID_PERIOD - AUTH_TOKEN_REGEN_BEFORE + 2*time.Second)\n\t_, shouldRegen, err = verifySessionToken(token, secretBytes, timeRightAfterRegenPeriod)\n\tif err != nil {\n\t\tt.Fatalf(\"Token verification should not fail during regeneration period, err: %v\", err)\n\t}\n\n\tif !shouldRegen {\n\t\tt.Fatal(\"Token should have been marked for regeneration\")\n\t}\n\n\t// Test token expiration\n\t_, _, err = verifySessionToken(token, secretBytes, now.Add(AUTH_TOKEN_VALID_PERIOD+2*time.Second))\n\tif err == nil {\n\t\tt.Fatal(\"Expected token verification to fail after token expiration\")\n\t}\n\n\t// Test tampered token\n\tdecodedToken, err := base64.StdEncoding.DecodeString(token)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to decode token: %v\", err)\n\t}\n\n\t// If any of the bytes are off by 1, the token should be considered invalid\n\tfor i := range len(decodedToken) {\n\t\ttampered := make([]byte, len(decodedToken))\n\t\tcopy(tampered, decodedToken)\n\t\ttampered[i] += 1\n\n\t\t_, _, err = verifySessionToken(base64.StdEncoding.EncodeToString(tampered), secretBytes, now)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected token verification to fail for tampered token at index %d\", i)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "internal/glance/cli.go",
    "content": "package glance\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/shirou/gopsutil/v4/disk\"\n\t\"github.com/shirou/gopsutil/v4/sensors\"\n)\n\ntype cliIntent uint8\n\nconst (\n\tcliIntentVersionPrint cliIntent = iota\n\tcliIntentServe\n\tcliIntentConfigValidate\n\tcliIntentConfigPrint\n\tcliIntentDiagnose\n\tcliIntentSensorsPrint\n\tcliIntentMountpointInfo\n\tcliIntentSecretMake\n\tcliIntentPasswordHash\n)\n\ntype cliOptions struct {\n\tintent     cliIntent\n\tconfigPath string\n\targs       []string\n}\n\nfunc parseCliOptions() (*cliOptions, error) {\n\tvar args []string\n\n\targs = os.Args[1:]\n\tif len(args) == 1 && (args[0] == \"--version\" || args[0] == \"-v\" || args[0] == \"version\") {\n\t\treturn &cliOptions{\n\t\t\tintent: cliIntentVersionPrint,\n\t\t}, nil\n\t}\n\n\tflags := flag.NewFlagSet(\"\", flag.ExitOnError)\n\tflags.Usage = func() {\n\t\tfmt.Println(\"Usage: glance [options] command\")\n\n\t\tfmt.Println(\"\\nOptions:\")\n\t\tflags.PrintDefaults()\n\n\t\tfmt.Println(\"\\nCommands:\")\n\t\tfmt.Println(\"  config:validate       Validate the config file\")\n\t\tfmt.Println(\"  config:print          Print the parsed config file with embedded includes\")\n\t\tfmt.Println(\"  password:hash <pwd>   Hash a password\")\n\t\tfmt.Println(\"  secret:make           Generate a random secret key\")\n\t\tfmt.Println(\"  sensors:print         List all sensors\")\n\t\tfmt.Println(\"  mountpoint:info       Print information about a given mountpoint path\")\n\t\tfmt.Println(\"  diagnose              Run diagnostic checks\")\n\t}\n\n\tconfigPath := flags.String(\"config\", \"glance.yml\", \"Set config path\")\n\terr := flags.Parse(os.Args[1:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar intent cliIntent\n\targs = flags.Args()\n\tunknownCommandErr := fmt.Errorf(\"unknown command: %s\", strings.Join(args, \" \"))\n\n\tif len(args) == 0 {\n\t\tintent = cliIntentServe\n\t} else if len(args) == 1 {\n\t\tif args[0] == \"config:validate\" {\n\t\t\tintent = cliIntentConfigValidate\n\t\t} else if args[0] == \"config:print\" {\n\t\t\tintent = cliIntentConfigPrint\n\t\t} else if args[0] == \"sensors:print\" {\n\t\t\tintent = cliIntentSensorsPrint\n\t\t} else if args[0] == \"diagnose\" {\n\t\t\tintent = cliIntentDiagnose\n\t\t} else if args[0] == \"secret:make\" {\n\t\t\tintent = cliIntentSecretMake\n\t\t} else {\n\t\t\treturn nil, unknownCommandErr\n\t\t}\n\t} else if len(args) == 2 {\n\t\tif args[0] == \"password:hash\" {\n\t\t\tintent = cliIntentPasswordHash\n\t\t} else {\n\t\t\treturn nil, unknownCommandErr\n\t\t}\n\t} else if len(args) == 2 {\n\t\tif args[0] == \"mountpoint:info\" {\n\t\t\tintent = cliIntentMountpointInfo\n\t\t} else {\n\t\t\treturn nil, unknownCommandErr\n\t\t}\n\t} else {\n\t\treturn nil, unknownCommandErr\n\t}\n\n\treturn &cliOptions{\n\t\tintent:     intent,\n\t\tconfigPath: *configPath,\n\t\targs:       args,\n\t}, nil\n}\n\nfunc cliSensorsPrint() int {\n\ttempSensors, err := sensors.SensorsTemperatures()\n\tif err != nil {\n\t\tif warns, ok := err.(*sensors.Warnings); ok {\n\t\t\tfmt.Printf(\"Could not retrieve information for some sensors (%v):\\n\", err)\n\t\t\tfor _, w := range warns.List {\n\t\t\t\tfmt.Printf(\" - %v\\n\", w)\n\t\t\t}\n\t\t\tfmt.Println()\n\t\t} else {\n\t\t\tfmt.Printf(\"Failed to retrieve sensor information: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tif len(tempSensors) == 0 {\n\t\tfmt.Println(\"No sensors found\")\n\t\treturn 0\n\t}\n\n\tfmt.Println(\"Sensors found:\")\n\tfor _, sensor := range tempSensors {\n\t\tfmt.Printf(\" %s: %.1f°C\\n\", sensor.SensorKey, sensor.Temperature)\n\t}\n\n\treturn 0\n}\n\nfunc cliMountpointInfo(requestedPath string) int {\n\tusage, err := disk.Usage(requestedPath)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to retrieve info for path %s: %v\\n\", requestedPath, err)\n\t\tif warns, ok := err.(*disk.Warnings); ok {\n\t\t\tfor _, w := range warns.List {\n\t\t\t\tfmt.Printf(\" - %v\\n\", w)\n\t\t\t}\n\t\t}\n\n\t\treturn 1\n\t}\n\n\tfmt.Println(\"Path:\", usage.Path)\n\tfmt.Println(\"FS type:\", ternary(usage.Fstype == \"\", \"unknown\", usage.Fstype))\n\tfmt.Printf(\"Used percent: %.1f%%\\n\", usage.UsedPercent)\n\n\treturn 0\n}\n"
  },
  {
    "path": "internal/glance/config-fields.go",
    "content": "package glance\n\nimport (\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nvar hslColorFieldPattern = regexp.MustCompile(`^(?:hsla?\\()?([\\d\\.]+)(?: |,)+([\\d\\.]+)%?(?: |,)+([\\d\\.]+)%?\\)?$`)\n\nconst (\n\thslHueMax        = 360\n\thslSaturationMax = 100\n\thslLightnessMax  = 100\n)\n\ntype hslColorField struct {\n\tH float64\n\tS float64\n\tL float64\n}\n\nfunc (c *hslColorField) String() string {\n\treturn fmt.Sprintf(\"hsl(%.1f, %.1f%%, %.1f%%)\", c.H, c.S, c.L)\n}\n\nfunc (c *hslColorField) ToHex() string {\n\treturn hslToHex(c.H, c.S, c.L)\n}\n\nfunc (c1 *hslColorField) SameAs(c2 *hslColorField) bool {\n\tif c1 == nil && c2 == nil {\n\t\treturn true\n\t}\n\tif c1 == nil || c2 == nil {\n\t\treturn false\n\t}\n\treturn c1.H == c2.H && c1.S == c2.S && c1.L == c2.L\n}\n\nfunc (c *hslColorField) UnmarshalYAML(node *yaml.Node) error {\n\tvar value string\n\n\tif err := node.Decode(&value); err != nil {\n\t\treturn err\n\t}\n\n\tmatches := hslColorFieldPattern.FindStringSubmatch(value)\n\n\tif len(matches) != 4 {\n\t\treturn fmt.Errorf(\"invalid HSL color format: %s\", value)\n\t}\n\n\thue, err := strconv.ParseFloat(matches[1], 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif hue > hslHueMax {\n\t\treturn fmt.Errorf(\"HSL hue must be between 0 and %d\", hslHueMax)\n\t}\n\n\tsaturation, err := strconv.ParseFloat(matches[2], 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif saturation > hslSaturationMax {\n\t\treturn fmt.Errorf(\"HSL saturation must be between 0 and %d\", hslSaturationMax)\n\t}\n\n\tlightness, err := strconv.ParseFloat(matches[3], 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif lightness > hslLightnessMax {\n\t\treturn fmt.Errorf(\"HSL lightness must be between 0 and %d\", hslLightnessMax)\n\t}\n\n\tc.H = hue\n\tc.S = saturation\n\tc.L = lightness\n\n\treturn nil\n}\n\nvar durationFieldPattern = regexp.MustCompile(`^(\\d+)(s|m|h|d)$`)\n\ntype durationField time.Duration\n\nfunc (d *durationField) UnmarshalYAML(node *yaml.Node) error {\n\tvar value string\n\n\tif err := node.Decode(&value); err != nil {\n\t\treturn err\n\t}\n\n\tmatches := durationFieldPattern.FindStringSubmatch(value)\n\n\tif len(matches) != 3 {\n\t\treturn fmt.Errorf(\"invalid duration format: %s\", value)\n\t}\n\n\tduration, err := strconv.Atoi(matches[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch matches[2] {\n\tcase \"s\":\n\t\t*d = durationField(time.Duration(duration) * time.Second)\n\tcase \"m\":\n\t\t*d = durationField(time.Duration(duration) * time.Minute)\n\tcase \"h\":\n\t\t*d = durationField(time.Duration(duration) * time.Hour)\n\tcase \"d\":\n\t\t*d = durationField(time.Duration(duration) * 24 * time.Hour)\n\t}\n\n\treturn nil\n}\n\ntype customIconField struct {\n\tURL        template.URL\n\tAutoInvert bool\n}\n\nfunc newCustomIconField(value string) customIconField {\n\tconst autoInvertPrefix = \"auto-invert \"\n\tfield := customIconField{}\n\n\tif strings.HasPrefix(value, autoInvertPrefix) {\n\t\tfield.AutoInvert = true\n\t\tvalue = strings.TrimPrefix(value, autoInvertPrefix)\n\t}\n\n\tprefix, icon, found := strings.Cut(value, \":\")\n\tif !found {\n\t\tfield.URL = template.URL(value)\n\t\treturn field\n\t}\n\n\tbasename, ext, found := strings.Cut(icon, \".\")\n\tif !found {\n\t\text = \"svg\"\n\t\tbasename = icon\n\t}\n\n\tif ext != \"svg\" && ext != \"png\" {\n\t\text = \"svg\"\n\t}\n\n\tswitch prefix {\n\tcase \"si\":\n\t\tfield.AutoInvert = true\n\t\tfield.URL = template.URL(\"https://cdn.jsdelivr.net/npm/simple-icons@latest/icons/\" + basename + \".svg\")\n\tcase \"di\":\n\t\tfield.URL = template.URL(\"https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/\" + ext + \"/\" + basename + \".\" + ext)\n\tcase \"mdi\":\n\t\tfield.AutoInvert = true\n\t\tfield.URL = template.URL(\"https://cdn.jsdelivr.net/npm/@mdi/svg@latest/svg/\" + basename + \".svg\")\n\tcase \"sh\":\n\t\tfield.URL = template.URL(\"https://cdn.jsdelivr.net/gh/selfhst/icons/\" + ext + \"/\" + basename + \".\" + ext)\n\tdefault:\n\t\tfield.URL = template.URL(value)\n\t}\n\n\treturn field\n}\n\nfunc (i *customIconField) UnmarshalYAML(node *yaml.Node) error {\n\tvar value string\n\tif err := node.Decode(&value); err != nil {\n\t\treturn err\n\t}\n\n\t*i = newCustomIconField(value)\n\treturn nil\n}\n\ntype proxyOptionsField struct {\n\tURL           string        `yaml:\"url\"`\n\tAllowInsecure bool          `yaml:\"allow-insecure\"`\n\tTimeout       durationField `yaml:\"timeout\"`\n\tclient        *http.Client  `yaml:\"-\"`\n}\n\nfunc (p *proxyOptionsField) UnmarshalYAML(node *yaml.Node) error {\n\ttype proxyOptionsFieldAlias proxyOptionsField\n\talias := (*proxyOptionsFieldAlias)(p)\n\tvar proxyURL string\n\n\tif err := node.Decode(&proxyURL); err != nil {\n\t\tif err := node.Decode(alias); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif proxyURL == \"\" && p.URL == \"\" {\n\t\treturn nil\n\t}\n\n\tif p.URL != \"\" {\n\t\tproxyURL = p.URL\n\t}\n\n\tparsedUrl, err := url.Parse(proxyURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing proxy URL: %v\", err)\n\t}\n\n\tvar timeout = defaultClientTimeout\n\tif p.Timeout > 0 {\n\t\ttimeout = time.Duration(p.Timeout)\n\t}\n\n\tp.client = &http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: &http.Transport{\n\t\t\tProxy:           http.ProxyURL(parsedUrl),\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: p.AllowInsecure},\n\t\t},\n\t}\n\n\treturn nil\n}\n\ntype queryParametersField map[string][]string\n\nfunc (q *queryParametersField) UnmarshalYAML(node *yaml.Node) error {\n\tvar decoded map[string]any\n\n\tif err := node.Decode(&decoded); err != nil {\n\t\treturn err\n\t}\n\n\t*q = make(queryParametersField)\n\n\t// TODO: refactor the duplication in the switch cases if any more types get added\n\tfor key, value := range decoded {\n\t\tswitch v := value.(type) {\n\t\tcase string:\n\t\t\t(*q)[key] = []string{v}\n\t\tcase int, int8, int16, int32, int64, float32, float64:\n\t\t\t(*q)[key] = []string{fmt.Sprintf(\"%v\", v)}\n\t\tcase bool:\n\t\t\t(*q)[key] = []string{fmt.Sprintf(\"%t\", v)}\n\t\tcase []string:\n\t\t\t(*q)[key] = append((*q)[key], v...)\n\t\tcase []any:\n\t\t\tfor _, item := range v {\n\t\t\t\tswitch item := item.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\t(*q)[key] = append((*q)[key], item)\n\t\t\t\tcase int, int8, int16, int32, int64, float32, float64:\n\t\t\t\t\t(*q)[key] = append((*q)[key], fmt.Sprintf(\"%v\", item))\n\t\t\t\tcase bool:\n\t\t\t\t\t(*q)[key] = append((*q)[key], fmt.Sprintf(\"%t\", item))\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"invalid query parameter value type: %T\", item)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"invalid query parameter value type: %T\", value)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (q *queryParametersField) toQueryString() string {\n\tquery := url.Values{}\n\n\tfor key, values := range *q {\n\t\tfor _, value := range values {\n\t\t\tquery.Add(key, value)\n\t\t}\n\t}\n\n\treturn query.Encode()\n}\n"
  },
  {
    "path": "internal/glance/config.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"iter\"\n\t\"log\"\n\t\"maps\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/fsnotify/fsnotify\"\n\t\"gopkg.in/yaml.v3\"\n)\n\nconst CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT = 20\n\nconst (\n\tconfigVarTypeEnv         = \"env\"\n\tconfigVarTypeSecret      = \"secret\"\n\tconfigVarTypeFileFromEnv = \"readFileFromEnv\"\n)\n\ntype config struct {\n\tServer struct {\n\t\tHost       string `yaml:\"host\"`\n\t\tPort       uint16 `yaml:\"port\"`\n\t\tProxied    bool   `yaml:\"proxied\"`\n\t\tAssetsPath string `yaml:\"assets-path\"`\n\t\tBaseURL    string `yaml:\"base-url\"`\n\t} `yaml:\"server\"`\n\n\tAuth struct {\n\t\tSecretKey string           `yaml:\"secret-key\"`\n\t\tUsers     map[string]*user `yaml:\"users\"`\n\t} `yaml:\"auth\"`\n\n\tDocument struct {\n\t\tHead template.HTML `yaml:\"head\"`\n\t} `yaml:\"document\"`\n\n\tTheme struct {\n\t\tthemeProperties `yaml:\",inline\"`\n\t\tCustomCSSFile   string `yaml:\"custom-css-file\"`\n\n\t\tDisablePicker bool                                     `yaml:\"disable-picker\"`\n\t\tPresets       orderedYAMLMap[string, *themeProperties] `yaml:\"presets\"`\n\t} `yaml:\"theme\"`\n\n\tBranding struct {\n\t\tHideFooter         bool          `yaml:\"hide-footer\"`\n\t\tCustomFooter       template.HTML `yaml:\"custom-footer\"`\n\t\tLogoText           string        `yaml:\"logo-text\"`\n\t\tLogoURL            string        `yaml:\"logo-url\"`\n\t\tFaviconURL         string        `yaml:\"favicon-url\"`\n\t\tFaviconType        string        `yaml:\"-\"`\n\t\tAppName            string        `yaml:\"app-name\"`\n\t\tAppIconURL         string        `yaml:\"app-icon-url\"`\n\t\tAppBackgroundColor string        `yaml:\"app-background-color\"`\n\t} `yaml:\"branding\"`\n\n\tPages []page `yaml:\"pages\"`\n}\n\ntype user struct {\n\tPassword           string `yaml:\"password\"`\n\tPasswordHashString string `yaml:\"password-hash\"`\n\tPasswordHash       []byte `yaml:\"-\"`\n}\n\ntype page struct {\n\tTitle                  string  `yaml:\"name\"`\n\tSlug                   string  `yaml:\"slug\"`\n\tWidth                  string  `yaml:\"width\"`\n\tDesktopNavigationWidth string  `yaml:\"desktop-navigation-width\"`\n\tShowMobileHeader       bool    `yaml:\"show-mobile-header\"`\n\tHideDesktopNavigation  bool    `yaml:\"hide-desktop-navigation\"`\n\tCenterVertically       bool    `yaml:\"center-vertically\"`\n\tHeadWidgets            widgets `yaml:\"head-widgets\"`\n\tColumns                []struct {\n\t\tSize    string  `yaml:\"size\"`\n\t\tWidgets widgets `yaml:\"widgets\"`\n\t} `yaml:\"columns\"`\n\tPrimaryColumnIndex int8       `yaml:\"-\"`\n\tmu                 sync.Mutex `yaml:\"-\"`\n}\n\nfunc newConfigFromYAML(contents []byte) (*config, error) {\n\tcontents, err := parseConfigVariables(contents)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &config{}\n\tconfig.Server.Port = 8080\n\n\terr = yaml.Unmarshal(contents, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = isConfigStateValid(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor p := range config.Pages {\n\t\tfor w := range config.Pages[p].HeadWidgets {\n\t\t\tif err := config.Pages[p].HeadWidgets[w].initialize(); err != nil {\n\t\t\t\treturn nil, formatWidgetInitError(err, config.Pages[p].HeadWidgets[w])\n\t\t\t}\n\t\t}\n\n\t\tfor c := range config.Pages[p].Columns {\n\t\t\tfor w := range config.Pages[p].Columns[c].Widgets {\n\t\t\t\tif err := config.Pages[p].Columns[c].Widgets[w].initialize(); err != nil {\n\t\t\t\t\treturn nil, formatWidgetInitError(err, config.Pages[p].Columns[c].Widgets[w])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn config, nil\n}\n\nvar envVariableNamePattern = regexp.MustCompile(`^[A-Z0-9_]+$`)\nvar configVariablePattern = regexp.MustCompile(`(^|.)\\$\\{(?:([a-zA-Z]+):)?([a-zA-Z0-9_-]+)\\}`)\n\n// Parses variables defined in the config such as:\n// ${API_KEY} \t\t\t\t            - gets replaced with the value of the API_KEY environment variable\n// \\${API_KEY} \t\t\t\t\t        - escaped, gets used as is without the \\ in the config\n// ${secret:api_key} \t\t\t        - value gets loaded from /run/secrets/api_key\n// ${readFileFromEnv:PATH_TO_SECRET}    - value gets loaded from the file path specified in the environment variable PATH_TO_SECRET\n//\n// TODO: don't match against commented out sections, not sure exactly how since\n// variables can be placed anywhere and used to modify the YAML structure itself\nfunc parseConfigVariables(contents []byte) ([]byte, error) {\n\tvar err error\n\n\treplaced := configVariablePattern.ReplaceAllFunc(contents, func(match []byte) []byte {\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tgroups := configVariablePattern.FindSubmatch(match)\n\t\tif len(groups) != 4 {\n\t\t\t// we can't handle this match, this shouldn't happen unless the number of groups\n\t\t\t// in the regex has been changed without updating the below code\n\t\t\treturn match\n\t\t}\n\n\t\tprefix := string(groups[1])\n\t\tif prefix == `\\` {\n\t\t\tif len(match) >= 2 {\n\t\t\t\treturn match[1:]\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\ttypeAsString, variableName := string(groups[2]), string(groups[3])\n\t\tvariableType := ternary(typeAsString == \"\", configVarTypeEnv, typeAsString)\n\n\t\tparsedValue, returnOriginal, localErr := parseConfigVariableOfType(variableType, variableName)\n\t\tif localErr != nil {\n\t\t\terr = fmt.Errorf(\"parsing variable: %v\", localErr)\n\t\t\treturn nil\n\t\t}\n\n\t\tif returnOriginal {\n\t\t\treturn match\n\t\t}\n\n\t\treturn []byte(prefix + parsedValue)\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn replaced, nil\n}\n\n// When the bool return value is true, it indicates that the caller should use the original value\nfunc parseConfigVariableOfType(variableType, variableName string) (string, bool, error) {\n\tswitch variableType {\n\tcase configVarTypeEnv:\n\t\tif !envVariableNamePattern.MatchString(variableName) {\n\t\t\treturn \"\", true, nil\n\t\t}\n\n\t\tv, found := os.LookupEnv(variableName)\n\t\tif !found {\n\t\t\treturn \"\", false, fmt.Errorf(\"environment variable %s not found\", variableName)\n\t\t}\n\n\t\treturn v, false, nil\n\tcase configVarTypeSecret:\n\t\tsecretPath := filepath.Join(\"/run/secrets\", variableName)\n\t\tsecret, err := os.ReadFile(secretPath)\n\t\tif err != nil {\n\t\t\treturn \"\", false, fmt.Errorf(\"reading secret file: %v\", err)\n\t\t}\n\n\t\treturn strings.TrimSpace(string(secret)), false, nil\n\tcase configVarTypeFileFromEnv:\n\t\tif !envVariableNamePattern.MatchString(variableName) {\n\t\t\treturn \"\", true, nil\n\t\t}\n\n\t\tfilePath, found := os.LookupEnv(variableName)\n\t\tif !found {\n\t\t\treturn \"\", false, fmt.Errorf(\"readFileFromEnv: environment variable %s not found\", variableName)\n\t\t}\n\n\t\tif !filepath.IsAbs(filePath) {\n\t\t\treturn \"\", false, fmt.Errorf(\"readFileFromEnv: file path %s is not absolute\", filePath)\n\t\t}\n\n\t\tfileContents, err := os.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\treturn \"\", false, fmt.Errorf(\"readFileFromEnv: reading file from %s: %v\", variableName, err)\n\t\t}\n\n\t\treturn strings.TrimSpace(string(fileContents)), false, nil\n\tdefault:\n\t\treturn \"\", true, nil\n\t}\n}\n\nfunc formatWidgetInitError(err error, w widget) error {\n\treturn fmt.Errorf(\"%s widget: %v\", w.GetType(), err)\n}\n\nvar configIncludePattern = regexp.MustCompile(`(?m)^([ \\t]*)(?:-[ \\t]*)?(?:!|\\$)include:[ \\t]*(.+)$`)\n\nfunc parseYAMLIncludes(mainFilePath string) ([]byte, map[string]struct{}, error) {\n\treturn recursiveParseYAMLIncludes(mainFilePath, nil, 0)\n}\n\nfunc recursiveParseYAMLIncludes(mainFilePath string, includes map[string]struct{}, depth int) ([]byte, map[string]struct{}, error) {\n\tif depth > CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT {\n\t\treturn nil, nil, fmt.Errorf(\"recursion depth limit of %d reached\", CONFIG_INCLUDE_RECURSION_DEPTH_LIMIT)\n\t}\n\n\tmainFileContents, err := os.ReadFile(mainFilePath)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"reading %s: %w\", mainFilePath, err)\n\t}\n\n\tmainFileAbsPath, err := filepath.Abs(mainFilePath)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"getting absolute path of %s: %w\", mainFilePath, err)\n\t}\n\tmainFileDir := filepath.Dir(mainFileAbsPath)\n\n\tif includes == nil {\n\t\tincludes = make(map[string]struct{})\n\t}\n\tvar includesLastErr error\n\n\tmainFileContents = configIncludePattern.ReplaceAllFunc(mainFileContents, func(match []byte) []byte {\n\t\tif includesLastErr != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tmatches := configIncludePattern.FindSubmatch(match)\n\t\tif len(matches) != 3 {\n\t\t\tincludesLastErr = fmt.Errorf(\"invalid include match: %v\", matches)\n\t\t\treturn nil\n\t\t}\n\n\t\tindent := string(matches[1])\n\t\tincludeFilePath := strings.TrimSpace(string(matches[2]))\n\t\tif !filepath.IsAbs(includeFilePath) {\n\t\t\tincludeFilePath = filepath.Join(mainFileDir, includeFilePath)\n\t\t}\n\n\t\tvar fileContents []byte\n\t\tvar err error\n\n\t\tincludes[includeFilePath] = struct{}{}\n\n\t\tfileContents, includes, err = recursiveParseYAMLIncludes(includeFilePath, includes, depth+1)\n\t\tif err != nil {\n\t\t\tincludesLastErr = err\n\t\t\treturn nil\n\t\t}\n\n\t\treturn []byte(prefixStringLines(indent, string(fileContents)))\n\t})\n\n\tif includesLastErr != nil {\n\t\treturn nil, nil, includesLastErr\n\t}\n\n\treturn mainFileContents, includes, nil\n}\n\nfunc configFilesWatcher(\n\tmainFilePath string,\n\tlastContents []byte,\n\tlastIncludes map[string]struct{},\n\tonChange func(newContents []byte),\n\tonErr func(error),\n) (func() error, error) {\n\tmainFileAbsPath, err := filepath.Abs(mainFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting absolute path of main file: %w\", err)\n\t}\n\n\t// TODO: refactor, flaky\n\tlastIncludes[mainFileAbsPath] = struct{}{}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating watcher: %w\", err)\n\t}\n\n\tupdateWatchedFiles := func(previousWatched map[string]struct{}, newWatched map[string]struct{}) {\n\t\tfor filePath := range previousWatched {\n\t\t\tif _, ok := newWatched[filePath]; !ok {\n\t\t\t\twatcher.Remove(filePath)\n\t\t\t}\n\t\t}\n\n\t\tfor filePath := range newWatched {\n\t\t\tif _, ok := previousWatched[filePath]; !ok {\n\t\t\t\tif err := watcher.Add(filePath); err != nil {\n\t\t\t\t\tlog.Printf(\n\t\t\t\t\t\t\"Could not add file to watcher, changes to this file will not trigger a reload. path: %s, error: %v\",\n\t\t\t\t\t\tfilePath, err,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tupdateWatchedFiles(nil, lastIncludes)\n\n\t// needed for lastContents and lastIncludes because they get updated in multiple goroutines\n\tmu := sync.Mutex{}\n\n\tparseAndCompareBeforeCallback := func() {\n\t\tcurrentContents, currentIncludes, err := parseYAMLIncludes(mainFilePath)\n\t\tif err != nil {\n\t\t\tonErr(fmt.Errorf(\"parsing main file contents for comparison: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// TODO: refactor, flaky\n\t\tcurrentIncludes[mainFileAbsPath] = struct{}{}\n\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\n\t\tif !maps.Equal(currentIncludes, lastIncludes) {\n\t\t\tupdateWatchedFiles(lastIncludes, currentIncludes)\n\t\t\tlastIncludes = currentIncludes\n\t\t}\n\n\t\tif !bytes.Equal(lastContents, currentContents) {\n\t\t\tlastContents = currentContents\n\t\t\tonChange(currentContents)\n\t\t}\n\t}\n\n\tconst debounceDuration = 500 * time.Millisecond\n\tvar debounceTimer *time.Timer\n\tdebouncedParseAndCompareBeforeCallback := func() {\n\t\tif debounceTimer != nil {\n\t\t\tdebounceTimer.Stop()\n\t\t\tdebounceTimer.Reset(debounceDuration)\n\t\t} else {\n\t\t\tdebounceTimer = time.AfterFunc(debounceDuration, parseAndCompareBeforeCallback)\n\t\t}\n\t}\n\n\tdeleteLastInclude := func(filePath string) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tfileAbsPath, _ := filepath.Abs(filePath)\n\t\tdelete(lastIncludes, fileAbsPath)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, isOpen := <-watcher.Events:\n\t\t\t\tif !isOpen {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif event.Has(fsnotify.Write) {\n\t\t\t\t\tdebouncedParseAndCompareBeforeCallback()\n\t\t\t\t} else if event.Has(fsnotify.Rename) {\n\t\t\t\t\t// on linux the file will no longer be watched after a rename, on windows\n\t\t\t\t\t// it will continue to be watched with the new name but we have no access to\n\t\t\t\t\t// the new name in this event in order to stop watching it manually and match the\n\t\t\t\t\t// behavior in linux, may lead to weird unintended behaviors on windows as we're\n\t\t\t\t\t// only handling renames from linux's perspective\n\t\t\t\t\t// see https://github.com/fsnotify/fsnotify/issues/255\n\n\t\t\t\t\t// remove the old file from our manually tracked includes, calling\n\t\t\t\t\t// debouncedParseAndCompareBeforeCallback will re-add it if it's still\n\t\t\t\t\t// required after it triggers\n\t\t\t\t\tdeleteLastInclude(event.Name)\n\n\t\t\t\t\t// wait for file to maybe get created again\n\t\t\t\t\t// see https://github.com/glanceapp/glance/pull/358\n\t\t\t\t\tfor range 10 {\n\t\t\t\t\t\tif _, err := os.Stat(event.Name); err == nil {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t\t\t}\n\n\t\t\t\t\tdebouncedParseAndCompareBeforeCallback()\n\t\t\t\t} else if event.Has(fsnotify.Remove) {\n\t\t\t\t\tdeleteLastInclude(event.Name)\n\t\t\t\t\tdebouncedParseAndCompareBeforeCallback()\n\t\t\t\t}\n\t\t\tcase err, isOpen := <-watcher.Errors:\n\t\t\t\tif !isOpen {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tonErr(fmt.Errorf(\"watcher error: %w\", err))\n\t\t\t}\n\t\t}\n\t}()\n\n\tonChange(lastContents)\n\n\treturn func() error {\n\t\tif debounceTimer != nil {\n\t\t\tdebounceTimer.Stop()\n\t\t}\n\n\t\treturn watcher.Close()\n\t}, nil\n}\n\n// TODO: Refactor, we currently validate in two different places, this being\n// one of them, which doesn't modify the data and only checks for logical errors\n// and then again when creating the application which does modify the data and do\n// further validation. Would be better if validation was done in a single place.\nfunc isConfigStateValid(config *config) error {\n\tif len(config.Pages) == 0 {\n\t\treturn fmt.Errorf(\"no pages configured\")\n\t}\n\n\tif len(config.Auth.Users) > 0 && config.Auth.SecretKey == \"\" {\n\t\treturn fmt.Errorf(\"secret-key must be set when users are configured\")\n\t}\n\n\tfor username := range config.Auth.Users {\n\t\tif username == \"\" {\n\t\t\treturn fmt.Errorf(\"user has no name\")\n\t\t}\n\n\t\tif len(username) < 3 {\n\t\t\treturn errors.New(\"usernames must be at least 3 characters\")\n\t\t}\n\n\t\tuser := config.Auth.Users[username]\n\n\t\tif user.Password == \"\" {\n\t\t\tif user.PasswordHashString == \"\" {\n\t\t\t\treturn fmt.Errorf(\"user %s must have a password or a password-hash set\", username)\n\t\t\t}\n\t\t} else if len(user.Password) < 6 {\n\t\t\treturn fmt.Errorf(\"the password for %s must be at least 6 characters\", username)\n\t\t}\n\t}\n\n\tif config.Server.AssetsPath != \"\" {\n\t\tif _, err := os.Stat(config.Server.AssetsPath); os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"assets directory does not exist: %s\", config.Server.AssetsPath)\n\t\t}\n\t}\n\n\tfor i := range config.Pages {\n\t\tpage := &config.Pages[i]\n\n\t\tif page.Title == \"\" {\n\t\t\treturn fmt.Errorf(\"page %d has no name\", i+1)\n\t\t}\n\n\t\tif page.Width != \"\" && (page.Width != \"wide\" && page.Width != \"slim\" && page.Width != \"default\") {\n\t\t\treturn fmt.Errorf(\"page %d: width can only be either wide or slim\", i+1)\n\t\t}\n\n\t\tif page.DesktopNavigationWidth != \"\" {\n\t\t\tif page.DesktopNavigationWidth != \"wide\" && page.DesktopNavigationWidth != \"slim\" && page.DesktopNavigationWidth != \"default\" {\n\t\t\t\treturn fmt.Errorf(\"page %d: desktop-navigation-width can only be either wide or slim\", i+1)\n\t\t\t}\n\t\t}\n\n\t\tif len(page.Columns) == 0 {\n\t\t\treturn fmt.Errorf(\"page %d has no columns\", i+1)\n\t\t}\n\n\t\tif page.Width == \"slim\" {\n\t\t\tif len(page.Columns) > 2 {\n\t\t\t\treturn fmt.Errorf(\"page %d is slim and cannot have more than 2 columns\", i+1)\n\t\t\t}\n\t\t} else {\n\t\t\tif len(page.Columns) > 3 {\n\t\t\t\treturn fmt.Errorf(\"page %d has more than 3 columns\", i+1)\n\t\t\t}\n\t\t}\n\n\t\tcolumnSizesCount := make(map[string]int)\n\n\t\tfor j := range page.Columns {\n\t\t\tcolumn := &page.Columns[j]\n\n\t\t\tif column.Size != \"small\" && column.Size != \"full\" {\n\t\t\t\treturn fmt.Errorf(\"column %d of page %d: size can only be either small or full\", j+1, i+1)\n\t\t\t}\n\n\t\t\tcolumnSizesCount[page.Columns[j].Size]++\n\t\t}\n\n\t\tfull := columnSizesCount[\"full\"]\n\n\t\tif full > 2 || full == 0 {\n\t\t\treturn fmt.Errorf(\"page %d must have either 1 or 2 full width columns\", i+1)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// Read-only way to store ordered maps from a YAML structure\ntype orderedYAMLMap[K comparable, V any] struct {\n\tkeys []K\n\tdata map[K]V\n}\n\nfunc newOrderedYAMLMap[K comparable, V any](keys []K, values []V) (*orderedYAMLMap[K, V], error) {\n\tif len(keys) != len(values) {\n\t\treturn nil, fmt.Errorf(\"keys and values must have the same length\")\n\t}\n\n\tom := &orderedYAMLMap[K, V]{\n\t\tkeys: make([]K, len(keys)),\n\t\tdata: make(map[K]V, len(keys)),\n\t}\n\n\tcopy(om.keys, keys)\n\n\tfor i := range keys {\n\t\tom.data[keys[i]] = values[i]\n\t}\n\n\treturn om, nil\n}\n\nfunc (om *orderedYAMLMap[K, V]) Items() iter.Seq2[K, V] {\n\treturn func(yield func(K, V) bool) {\n\t\tfor _, key := range om.keys {\n\t\t\tvalue, ok := om.data[key]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !yield(key, value) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (om *orderedYAMLMap[K, V]) Get(key K) (V, bool) {\n\tvalue, ok := om.data[key]\n\treturn value, ok\n}\n\nfunc (self *orderedYAMLMap[K, V]) Merge(other *orderedYAMLMap[K, V]) *orderedYAMLMap[K, V] {\n\tmerged := &orderedYAMLMap[K, V]{\n\t\tkeys: make([]K, 0, len(self.keys)+len(other.keys)),\n\t\tdata: make(map[K]V, len(self.data)+len(other.data)),\n\t}\n\n\tmerged.keys = append(merged.keys, self.keys...)\n\tmaps.Copy(merged.data, self.data)\n\n\tfor _, key := range other.keys {\n\t\tif _, exists := self.data[key]; !exists {\n\t\t\tmerged.keys = append(merged.keys, key)\n\t\t}\n\t}\n\tmaps.Copy(merged.data, other.data)\n\n\treturn merged\n}\n\nfunc (om *orderedYAMLMap[K, V]) UnmarshalYAML(node *yaml.Node) error {\n\tif node.Kind != yaml.MappingNode {\n\t\treturn fmt.Errorf(\"orderedMap: expected mapping node, got %d\", node.Kind)\n\t}\n\n\tif len(node.Content)%2 != 0 {\n\t\treturn fmt.Errorf(\"orderedMap: expected even number of content items, got %d\", len(node.Content))\n\t}\n\n\tom.keys = make([]K, len(node.Content)/2)\n\tom.data = make(map[K]V, len(node.Content)/2)\n\n\tfor i := 0; i < len(node.Content); i += 2 {\n\t\tkeyNode := node.Content[i]\n\t\tvalueNode := node.Content[i+1]\n\n\t\tvar key K\n\t\tif err := keyNode.Decode(&key); err != nil {\n\t\t\treturn fmt.Errorf(\"orderedMap: decoding key: %v\", err)\n\t\t}\n\n\t\tif _, ok := om.data[key]; ok {\n\t\t\treturn fmt.Errorf(\"orderedMap: duplicate key %v\", key)\n\t\t}\n\n\t\tvar value V\n\t\tif err := valueNode.Decode(&value); err != nil {\n\t\t\treturn fmt.Errorf(\"orderedMap: decoding value: %v\", err)\n\t\t}\n\n\t\t(*om).keys[i/2] = key\n\t\t(*om).data[key] = value\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/glance/diagnose.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst httpTestRequestTimeout = 15 * time.Second\n\nvar diagnosticSteps = []diagnosticStep{\n\t{\n\t\tname: \"resolve cloudflare.com through Cloudflare DoH\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequestWithHeaders(\"GET\", \"https://1.1.1.1/dns-query?name=cloudflare.com\", map[string]string{\n\t\t\t\t\"accept\": \"application/dns-json\",\n\t\t\t}, 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"resolve cloudflare.com through Google DoH\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://8.8.8.8/resolve?name=cloudflare.com\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"resolve github.com\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testDNSResolution(\"github.com\")\n\t\t},\n\t},\n\t{\n\t\tname: \"resolve reddit.com\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testDNSResolution(\"reddit.com\")\n\t\t},\n\t},\n\t{\n\t\tname: \"resolve twitch.tv\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testDNSResolution(\"twitch.tv\")\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from YouTube RSS feed\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://www.youtube.com/feeds/videos.xml?channel_id=UCZU9T1ceaOgwfLRq7OKFU4Q\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Twitch.tv GQL\",\n\t\tfn: func() (string, error) {\n\t\t\t// this should always return 0 bytes, we're mainly looking for a 200 status code\n\t\t\treturn testHttpRequest(\"OPTIONS\", \"https://gql.twitch.tv/gql\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from GitHub API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://api.github.com\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Open-Meteo API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://geocoding-api.open-meteo.com/v1/search?name=London\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Reddit API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequestWithHeaders(\"GET\", \"https://www.reddit.com/search.json\", map[string]string{\n\t\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0\",\n\t\t\t}, 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Yahoo finance API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequestWithHeaders(\"GET\", \"https://query1.finance.yahoo.com/v8/finance/chart/NVDA\", map[string]string{\n\t\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:137.0) Gecko/20100101 Firefox/137.0\",\n\t\t\t}, 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Hacker News Firebase API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://hacker-news.firebaseio.com/v0/topstories.json\", 200)\n\t\t},\n\t},\n\t{\n\t\tname: \"fetch data from Docker Hub API\",\n\t\tfn: func() (string, error) {\n\t\t\treturn testHttpRequest(\"GET\", \"https://hub.docker.com/v2/namespaces/library/repositories/ubuntu/tags/latest\", 200)\n\t\t},\n\t},\n}\n\nfunc runDiagnostic() {\n\tfmt.Println(\"```\")\n\tfmt.Println(\"Glance version: \" + buildVersion)\n\tfmt.Println(\"Go version: \" + runtime.Version())\n\tfmt.Printf(\"Platform: %s / %s / %d CPUs\\n\", runtime.GOOS, runtime.GOARCH, runtime.NumCPU())\n\tfmt.Println(\"In Docker container: \" + ternary(isRunningInsideDockerContainer(), \"yes\", \"no\"))\n\n\tfmt.Printf(\"\\nChecking network connectivity, this may take up to %d seconds...\\n\\n\", int(httpTestRequestTimeout.Seconds()))\n\n\tvar wg sync.WaitGroup\n\tfor i := range diagnosticSteps {\n\t\tstep := &diagnosticSteps[i]\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tstart := time.Now()\n\t\t\tstep.extraInfo, step.err = step.fn()\n\t\t\tstep.elapsed = time.Since(start)\n\t\t}()\n\t}\n\twg.Wait()\n\n\tfor _, step := range diagnosticSteps {\n\t\tvar extraInfo string\n\n\t\tif step.extraInfo != \"\" {\n\t\t\textraInfo = \"| \" + step.extraInfo + \" \"\n\t\t}\n\n\t\tfmt.Printf(\n\t\t\t\"%s %s %s| %dms\\n\",\n\t\t\tternary(step.err == nil, \"✓ Can\", \"✗ Can't\"),\n\t\t\tstep.name,\n\t\t\textraInfo,\n\t\t\tstep.elapsed.Milliseconds(),\n\t\t)\n\n\t\tif step.err != nil {\n\t\t\tfmt.Printf(\"└╴ error: %v\\n\", step.err)\n\t\t}\n\t}\n\tfmt.Println(\"```\")\n}\n\ntype diagnosticStep struct {\n\tname      string\n\tfn        func() (string, error)\n\textraInfo string\n\terr       error\n\telapsed   time.Duration\n}\n\nfunc testHttpRequest(method, url string, expectedStatusCode int) (string, error) {\n\treturn testHttpRequestWithHeaders(method, url, nil, expectedStatusCode)\n}\n\nfunc testHttpRequestWithHeaders(method, url string, headers map[string]string, expectedStatusCode int) (string, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), httpTestRequestTimeout)\n\tdefer cancel()\n\n\trequest, _ := http.NewRequestWithContext(ctx, method, url, nil)\n\tfor key, value := range headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := defaultHTTPClient.Do(request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprintableBody := strings.ReplaceAll(string(body), \"\\n\", \"\")\n\tif len(printableBody) > 50 {\n\t\tprintableBody = printableBody[:50] + \"...\"\n\t}\n\tif len(printableBody) > 0 {\n\t\tprintableBody = \", \" + printableBody\n\t}\n\n\textraInfo := fmt.Sprintf(\"%d bytes%s\", len(body), printableBody)\n\n\tif response.StatusCode != expectedStatusCode {\n\t\treturn extraInfo, fmt.Errorf(\"expected status code %d, got %d\", expectedStatusCode, response.StatusCode)\n\t}\n\n\treturn extraInfo, nil\n}\n\nfunc testDNSResolution(domain string) (string, error) {\n\tips, err := net.LookupIP(domain)\n\n\tvar ipStrings []string\n\tif err == nil {\n\t\tfor i := range ips {\n\t\t\tipStrings = append(ipStrings, ips[i].String())\n\t\t}\n\t}\n\n\treturn strings.Join(ipStrings, \", \"), err\n}\n"
  },
  {
    "path": "internal/glance/embed.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"crypto/md5\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"log\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n//go:embed static\nvar _staticFS embed.FS\n\n//go:embed templates\nvar _templateFS embed.FS\n\nvar staticFS, _ = fs.Sub(_staticFS, \"static\")\nvar templateFS, _ = fs.Sub(_templateFS, \"templates\")\n\nfunc readAllFromStaticFS(path string) ([]byte, error) {\n\t// For some reason fs.FS only works with forward slashes, so in case we're\n\t// running on Windows or pass paths with backslashes we need to replace them.\n\tpath = strings.ReplaceAll(path, \"\\\\\", \"/\")\n\n\tfile, err := staticFS.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn io.ReadAll(file)\n}\n\nvar staticFSHash = func() string {\n\thash, err := computeFSHash(staticFS)\n\tif err != nil {\n\t\tlog.Printf(\"Could not compute static assets cache key: %v\", err)\n\t\treturn strconv.FormatInt(time.Now().Unix(), 10)\n\t}\n\n\treturn hash\n}()\n\nfunc computeFSHash(files fs.FS) (string, error) {\n\thash := md5.New()\n\n\terr := fs.WalkDir(files, \".\", func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfile, err := files.Open(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := io.Copy(hash, file); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn hex.EncodeToString(hash.Sum(nil))[:10], nil\n}\n\nvar cssImportPattern = regexp.MustCompile(`(?m)^@import \"(.*?)\";$`)\nvar cssSingleLineCommentPattern = regexp.MustCompile(`(?m)^\\s*\\/\\*.*?\\*\\/$`)\n\n// Yes, we bundle at runtime, give comptime pls\nvar bundledCSSContents = func() []byte {\n\tconst mainFilePath = \"css/main.css\"\n\n\tvar recursiveParseImports func(path string, depth int) ([]byte, error)\n\trecursiveParseImports = func(path string, depth int) ([]byte, error) {\n\t\tif depth > 20 {\n\t\t\treturn nil, errors.New(\"maximum import depth reached, is one of your imports circular?\")\n\t\t}\n\n\t\tmainFileContents, err := readAllFromStaticFS(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Normalize line endings, otherwise the \\r's make the regex not match\n\t\tmainFileContents = bytes.ReplaceAll(mainFileContents, []byte(\"\\r\\n\"), []byte(\"\\n\"))\n\n\t\tmainFileDir := filepath.Dir(path)\n\t\tvar importLastErr error\n\n\t\tparsed := cssImportPattern.ReplaceAllFunc(mainFileContents, func(match []byte) []byte {\n\t\t\tif importLastErr != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tmatches := cssImportPattern.FindSubmatch(match)\n\t\t\tif len(matches) != 2 {\n\t\t\t\timportLastErr = fmt.Errorf(\n\t\t\t\t\t\"import didn't return expected number of capture groups: %s, expected 2, got %d\",\n\t\t\t\t\tmatch, len(matches),\n\t\t\t\t)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\timportFilePath := filepath.Join(mainFileDir, string(matches[1]))\n\t\t\timportContents, err := recursiveParseImports(importFilePath, depth+1)\n\t\t\tif err != nil {\n\t\t\t\timportLastErr = err\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn importContents\n\t\t})\n\n\t\tif importLastErr != nil {\n\t\t\treturn nil, importLastErr\n\t\t}\n\n\t\treturn parsed, nil\n\t}\n\n\tcontents, err := recursiveParseImports(mainFilePath, 0)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"building CSS bundle: %v\", err))\n\t}\n\n\t// We could strip a bunch more unnecessary characters, but the biggest\n\t// win comes from removing the whitespace at the beginning of lines\n\t// since that's at least 4 bytes per property, which yielded a ~20% reduction.\n\tcontents = cssSingleLineCommentPattern.ReplaceAll(contents, nil)\n\tcontents = whitespaceAtBeginningOfLinePattern.ReplaceAll(contents, nil)\n\tcontents = bytes.ReplaceAll(contents, []byte(\"\\n\"), []byte(\"\"))\n\n\treturn contents\n}()\n"
  },
  {
    "path": "internal/glance/glance.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\nvar (\n\tpageTemplate        = mustParseTemplate(\"page.html\", \"document.html\", \"footer.html\")\n\tpageContentTemplate = mustParseTemplate(\"page-content.html\")\n\tmanifestTemplate    = mustParseTemplate(\"manifest.json\")\n)\n\nconst STATIC_ASSETS_CACHE_DURATION = 24 * time.Hour\n\nvar reservedPageSlugs = []string{\"login\", \"logout\"}\n\ntype application struct {\n\tVersion   string\n\tCreatedAt time.Time\n\tConfig    config\n\n\tparsedManifest []byte\n\n\tslugToPage map[string]*page\n\twidgetByID map[uint64]widget\n\n\tRequiresAuth           bool\n\tauthSecretKey          []byte\n\tusernameHashToUsername map[string]string\n\tauthAttemptsMu         sync.Mutex\n\tfailedAuthAttempts     map[string]*failedAuthAttempt\n}\n\nfunc newApplication(c *config) (*application, error) {\n\tapp := &application{\n\t\tVersion:    buildVersion,\n\t\tCreatedAt:  time.Now(),\n\t\tConfig:     *c,\n\t\tslugToPage: make(map[string]*page),\n\t\twidgetByID: make(map[uint64]widget),\n\t}\n\tconfig := &app.Config\n\n\t//\n\t// Init auth\n\t//\n\n\tif len(config.Auth.Users) > 0 {\n\t\tsecretBytes, err := base64.StdEncoding.DecodeString(config.Auth.SecretKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decoding secret-key: %v\", err)\n\t\t}\n\n\t\tif len(secretBytes) != AUTH_SECRET_KEY_LENGTH {\n\t\t\treturn nil, fmt.Errorf(\"secret-key must be exactly %d bytes\", AUTH_SECRET_KEY_LENGTH)\n\t\t}\n\n\t\tapp.usernameHashToUsername = make(map[string]string)\n\t\tapp.failedAuthAttempts = make(map[string]*failedAuthAttempt)\n\t\tapp.RequiresAuth = true\n\n\t\tfor username := range config.Auth.Users {\n\t\t\tuser := config.Auth.Users[username]\n\t\t\tusernameHash, err := computeUsernameHash(username, secretBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"computing username hash for user %s: %v\", username, err)\n\t\t\t}\n\t\t\tapp.usernameHashToUsername[string(usernameHash)] = username\n\n\t\t\tif user.PasswordHashString != \"\" {\n\t\t\t\tuser.PasswordHash = []byte(user.PasswordHashString)\n\t\t\t\tuser.PasswordHashString = \"\"\n\t\t\t} else {\n\t\t\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"hashing password for user %s: %v\", username, err)\n\t\t\t\t}\n\n\t\t\t\tuser.Password = \"\"\n\t\t\t\tuser.PasswordHash = hashedPassword\n\t\t\t}\n\t\t}\n\n\t\tapp.authSecretKey = secretBytes\n\t}\n\n\t//\n\t// Init themes\n\t//\n\n\tif !config.Theme.DisablePicker {\n\t\tthemeKeys := make([]string, 0, 2)\n\t\tthemeProps := make([]*themeProperties, 0, 2)\n\n\t\tdefaultDarkTheme, ok := config.Theme.Presets.Get(\"default-dark\")\n\t\tif ok && !config.Theme.SameAs(defaultDarkTheme) || !config.Theme.SameAs(&themeProperties{}) {\n\t\t\tthemeKeys = append(themeKeys, \"default-dark\")\n\t\t\tthemeProps = append(themeProps, &themeProperties{})\n\t\t}\n\n\t\tthemeKeys = append(themeKeys, \"default-light\")\n\t\tthemeProps = append(themeProps, &themeProperties{\n\t\t\tLight:                    true,\n\t\t\tBackgroundColor:          &hslColorField{240, 13, 95},\n\t\t\tPrimaryColor:             &hslColorField{230, 100, 30},\n\t\t\tNegativeColor:            &hslColorField{0, 70, 50},\n\t\t\tContrastMultiplier:       1.3,\n\t\t\tTextSaturationMultiplier: 0.5,\n\t\t})\n\n\t\tthemePresets, err := newOrderedYAMLMap(themeKeys, themeProps)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"creating theme presets: %v\", err)\n\t\t}\n\t\tconfig.Theme.Presets = *themePresets.Merge(&config.Theme.Presets)\n\n\t\tfor key, properties := range config.Theme.Presets.Items() {\n\t\t\tproperties.Key = key\n\t\t\tif err := properties.init(); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"initializing preset theme %s: %v\", key, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tconfig.Theme.Key = \"default\"\n\tif err := config.Theme.init(); err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing default theme: %v\", err)\n\t}\n\n\t//\n\t// Init pages\n\t//\n\n\tapp.slugToPage[\"\"] = &config.Pages[0]\n\n\tproviders := &widgetProviders{\n\t\tassetResolver: app.StaticAssetPath,\n\t}\n\n\tfor p := range config.Pages {\n\t\tpage := &config.Pages[p]\n\t\tpage.PrimaryColumnIndex = -1\n\n\t\tif page.Slug == \"\" {\n\t\t\tpage.Slug = titleToSlug(page.Title)\n\t\t}\n\n\t\tif slices.Contains(reservedPageSlugs, page.Slug) {\n\t\t\treturn nil, fmt.Errorf(\"page slug \\\"%s\\\" is reserved\", page.Slug)\n\t\t}\n\n\t\tapp.slugToPage[page.Slug] = page\n\n\t\tif page.Width == \"default\" {\n\t\t\tpage.Width = \"\"\n\t\t}\n\n\t\tif page.DesktopNavigationWidth == \"\" && page.DesktopNavigationWidth != \"default\" {\n\t\t\tpage.DesktopNavigationWidth = page.Width\n\t\t}\n\n\t\tfor i := range page.HeadWidgets {\n\t\t\twidget := page.HeadWidgets[i]\n\t\t\tapp.widgetByID[widget.GetID()] = widget\n\t\t\twidget.setProviders(providers)\n\t\t}\n\n\t\tfor c := range page.Columns {\n\t\t\tcolumn := &page.Columns[c]\n\n\t\t\tif page.PrimaryColumnIndex == -1 && column.Size == \"full\" {\n\t\t\t\tpage.PrimaryColumnIndex = int8(c)\n\t\t\t}\n\n\t\t\tfor w := range column.Widgets {\n\t\t\t\twidget := column.Widgets[w]\n\t\t\t\tapp.widgetByID[widget.GetID()] = widget\n\t\t\t\twidget.setProviders(providers)\n\t\t\t}\n\t\t}\n\t}\n\n\tconfig.Server.BaseURL = strings.TrimRight(config.Server.BaseURL, \"/\")\n\tconfig.Theme.CustomCSSFile = app.resolveUserDefinedAssetPath(config.Theme.CustomCSSFile)\n\tconfig.Branding.LogoURL = app.resolveUserDefinedAssetPath(config.Branding.LogoURL)\n\n\tconfig.Branding.FaviconURL = ternary(\n\t\tconfig.Branding.FaviconURL == \"\",\n\t\tapp.StaticAssetPath(\"favicon.svg\"),\n\t\tapp.resolveUserDefinedAssetPath(config.Branding.FaviconURL),\n\t)\n\n\tconfig.Branding.FaviconType = ternary(\n\t\tstrings.HasSuffix(config.Branding.FaviconURL, \".svg\"),\n\t\t\"image/svg+xml\",\n\t\t\"image/png\",\n\t)\n\n\tif config.Branding.AppName == \"\" {\n\t\tconfig.Branding.AppName = \"Glance\"\n\t}\n\n\tif config.Branding.AppIconURL == \"\" {\n\t\tconfig.Branding.AppIconURL = app.StaticAssetPath(\"app-icon.png\")\n\t}\n\n\tif config.Branding.AppBackgroundColor == \"\" {\n\t\tconfig.Branding.AppBackgroundColor = config.Theme.BackgroundColorAsHex\n\t}\n\n\tmanifest, err := executeTemplateToString(manifestTemplate, templateData{App: app})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing manifest.json: %v\", err)\n\t}\n\tapp.parsedManifest = []byte(manifest)\n\n\treturn app, nil\n}\n\nfunc (p *page) updateOutdatedWidgets() {\n\tnow := time.Now()\n\n\tvar wg sync.WaitGroup\n\tcontext := context.Background()\n\n\tfor w := range p.HeadWidgets {\n\t\twidget := p.HeadWidgets[w]\n\n\t\tif !widget.requiresUpdate(&now) {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twidget.update(context)\n\t\t}()\n\t}\n\n\tfor c := range p.Columns {\n\t\tfor w := range p.Columns[c].Widgets {\n\t\t\twidget := p.Columns[c].Widgets[w]\n\n\t\t\tif !widget.requiresUpdate(&now) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\twidget.update(context)\n\t\t\t}()\n\t\t}\n\t}\n\n\twg.Wait()\n}\n\nfunc (a *application) resolveUserDefinedAssetPath(path string) string {\n\tif strings.HasPrefix(path, \"/assets/\") {\n\t\treturn a.Config.Server.BaseURL + path\n\t}\n\n\treturn path\n}\n\ntype templateRequestData struct {\n\tTheme *themeProperties\n}\n\ntype templateData struct {\n\tApp     *application\n\tPage    *page\n\tRequest templateRequestData\n}\n\nfunc (a *application) populateTemplateRequestData(data *templateRequestData, r *http.Request) {\n\ttheme := &a.Config.Theme.themeProperties\n\n\tif !a.Config.Theme.DisablePicker {\n\t\tselectedTheme, err := r.Cookie(\"theme\")\n\t\tif err == nil {\n\t\t\tpreset, exists := a.Config.Theme.Presets.Get(selectedTheme.Value)\n\t\t\tif exists {\n\t\t\t\ttheme = preset\n\t\t\t}\n\t\t}\n\t}\n\n\tdata.Theme = theme\n}\n\nfunc (a *application) handlePageRequest(w http.ResponseWriter, r *http.Request) {\n\tpage, exists := a.slugToPage[r.PathValue(\"page\")]\n\tif !exists {\n\t\ta.handleNotFound(w, r)\n\t\treturn\n\t}\n\n\tif a.handleUnauthorizedResponse(w, r, redirectToLogin) {\n\t\treturn\n\t}\n\n\tdata := templateData{\n\t\tPage: page,\n\t\tApp:  a,\n\t}\n\ta.populateTemplateRequestData(&data.Request, r)\n\n\tvar responseBytes bytes.Buffer\n\terr := pageTemplate.Execute(&responseBytes, data)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tw.Write(responseBytes.Bytes())\n}\n\nfunc (a *application) handlePageContentRequest(w http.ResponseWriter, r *http.Request) {\n\tpage, exists := a.slugToPage[r.PathValue(\"page\")]\n\tif !exists {\n\t\ta.handleNotFound(w, r)\n\t\treturn\n\t}\n\n\tif a.handleUnauthorizedResponse(w, r, showUnauthorizedJSON) {\n\t\treturn\n\t}\n\n\tpageData := templateData{\n\t\tPage: page,\n\t}\n\n\tvar err error\n\tvar responseBytes bytes.Buffer\n\n\tfunc() {\n\t\tpage.mu.Lock()\n\t\tdefer page.mu.Unlock()\n\n\t\tpage.updateOutdatedWidgets()\n\t\terr = pageContentTemplate.Execute(&responseBytes, pageData)\n\t}()\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tw.Write(responseBytes.Bytes())\n}\n\nfunc (a *application) addressOfRequest(r *http.Request) string {\n\tremoteAddrWithoutPort := func() string {\n\t\tfor i := len(r.RemoteAddr) - 1; i >= 0; i-- {\n\t\t\tif r.RemoteAddr[i] == ':' {\n\t\t\t\treturn r.RemoteAddr[:i]\n\t\t\t}\n\t\t}\n\n\t\treturn r.RemoteAddr\n\t}\n\n\tif !a.Config.Server.Proxied {\n\t\treturn remoteAddrWithoutPort()\n\t}\n\n\t// This should probably be configurable or look for multiple headers, not just this one\n\tforwardedFor := r.Header.Get(\"X-Forwarded-For\")\n\tif forwardedFor == \"\" {\n\t\treturn remoteAddrWithoutPort()\n\t}\n\n\tips := strings.Split(forwardedFor, \",\")\n\tif len(ips) == 0 || ips[0] == \"\" {\n\t\treturn remoteAddrWithoutPort()\n\t}\n\n\treturn ips[0]\n}\n\nfunc (a *application) handleNotFound(w http.ResponseWriter, _ *http.Request) {\n\t// TODO: add proper not found page\n\tw.WriteHeader(http.StatusNotFound)\n\tw.Write([]byte(\"Page not found\"))\n}\n\nfunc (a *application) handleWidgetRequest(w http.ResponseWriter, r *http.Request) {\n\t// TODO: this requires a rework of the widget update logic so that rather\n\t// than locking the entire page we lock individual widgets\n\tw.WriteHeader(http.StatusNotImplemented)\n\n\t// widgetValue := r.PathValue(\"widget\")\n\n\t// widgetID, err := strconv.ParseUint(widgetValue, 10, 64)\n\t// if err != nil {\n\t// \ta.handleNotFound(w, r)\n\t// \treturn\n\t// }\n\n\t// widget, exists := a.widgetByID[widgetID]\n\n\t// if !exists {\n\t// \ta.handleNotFound(w, r)\n\t// \treturn\n\t// }\n\n\t// widget.handleRequest(w, r)\n}\n\nfunc (a *application) StaticAssetPath(asset string) string {\n\treturn a.Config.Server.BaseURL + \"/static/\" + staticFSHash + \"/\" + asset\n}\n\nfunc (a *application) VersionedAssetPath(asset string) string {\n\treturn a.Config.Server.BaseURL + asset +\n\t\t\"?v=\" + strconv.FormatInt(a.CreatedAt.Unix(), 10)\n}\n\nfunc (a *application) server() (func() error, func() error) {\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"GET /{$}\", a.handlePageRequest)\n\tmux.HandleFunc(\"GET /{page}\", a.handlePageRequest)\n\n\tmux.HandleFunc(\"GET /api/pages/{page}/content/{$}\", a.handlePageContentRequest)\n\n\tif !a.Config.Theme.DisablePicker {\n\t\tmux.HandleFunc(\"POST /api/set-theme/{key}\", a.handleThemeChangeRequest)\n\t}\n\n\tmux.HandleFunc(\"/api/widgets/{widget}/{path...}\", a.handleWidgetRequest)\n\tmux.HandleFunc(\"GET /api/healthz\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t})\n\n\tif a.RequiresAuth {\n\t\tmux.HandleFunc(\"GET /login\", a.handleLoginPageRequest)\n\t\tmux.HandleFunc(\"GET /logout\", a.handleLogoutRequest)\n\t\tmux.HandleFunc(\"POST /api/authenticate\", a.handleAuthenticationAttempt)\n\t}\n\n\tmux.Handle(\n\t\tfmt.Sprintf(\"GET /static/%s/{path...}\", staticFSHash),\n\t\thttp.StripPrefix(\n\t\t\t\"/static/\"+staticFSHash,\n\t\t\tfileServerWithCache(http.FS(staticFS), STATIC_ASSETS_CACHE_DURATION),\n\t\t),\n\t)\n\n\tassetCacheControlValue := fmt.Sprintf(\n\t\t\"public, max-age=%d\",\n\t\tint(STATIC_ASSETS_CACHE_DURATION.Seconds()),\n\t)\n\n\tmux.HandleFunc(fmt.Sprintf(\"GET /static/%s/css/bundle.css\", staticFSHash), func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Cache-Control\", assetCacheControlValue)\n\t\tw.Header().Add(\"Content-Type\", \"text/css; charset=utf-8\")\n\t\tw.Write(bundledCSSContents)\n\t})\n\n\tmux.HandleFunc(\"GET /manifest.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Cache-Control\", assetCacheControlValue)\n\t\tw.Header().Add(\"Content-Type\", \"application/json\")\n\t\tw.Write(a.parsedManifest)\n\t})\n\n\tvar absAssetsPath string\n\tif a.Config.Server.AssetsPath != \"\" {\n\t\tabsAssetsPath, _ = filepath.Abs(a.Config.Server.AssetsPath)\n\t\tassetsFS := fileServerWithCache(http.Dir(a.Config.Server.AssetsPath), 2*time.Hour)\n\t\tmux.Handle(\"/assets/{path...}\", http.StripPrefix(\"/assets/\", assetsFS))\n\t}\n\n\tserver := http.Server{\n\t\tAddr:    fmt.Sprintf(\"%s:%d\", a.Config.Server.Host, a.Config.Server.Port),\n\t\tHandler: mux,\n\t}\n\n\tstart := func() error {\n\t\tlog.Printf(\"Starting server on %s:%d (base-url: \\\"%s\\\", assets-path: \\\"%s\\\")\\n\",\n\t\t\ta.Config.Server.Host,\n\t\t\ta.Config.Server.Port,\n\t\t\ta.Config.Server.BaseURL,\n\t\t\tabsAssetsPath,\n\t\t)\n\n\t\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tstop := func() error {\n\t\treturn server.Close()\n\t}\n\n\treturn start, stop\n}\n"
  },
  {
    "path": "internal/glance/main.go",
    "content": "package glance\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/bcrypt\"\n)\n\nvar buildVersion = \"dev\"\n\nfunc Main() int {\n\toptions, err := parseCliOptions()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn 1\n\t}\n\n\tswitch options.intent {\n\tcase cliIntentVersionPrint:\n\t\tfmt.Println(buildVersion)\n\tcase cliIntentServe:\n\t\t// remove in v0.10.0\n\t\tif serveUpdateNoticeIfConfigLocationNotMigrated(options.configPath) {\n\t\t\treturn 1\n\t\t}\n\n\t\tif err := serveApp(options.configPath); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn 1\n\t\t}\n\tcase cliIntentConfigValidate:\n\t\tcontents, _, err := parseYAMLIncludes(options.configPath)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not parse config file: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tif _, err := newConfigFromYAML(contents); err != nil {\n\t\t\tfmt.Printf(\"Config file is invalid: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\tcase cliIntentConfigPrint:\n\t\tcontents, _, err := parseYAMLIncludes(options.configPath)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not parse config file: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(string(contents))\n\tcase cliIntentSensorsPrint:\n\t\treturn cliSensorsPrint()\n\tcase cliIntentMountpointInfo:\n\t\treturn cliMountpointInfo(options.args[1])\n\tcase cliIntentDiagnose:\n\t\trunDiagnostic()\n\tcase cliIntentSecretMake:\n\t\tkey, err := makeAuthSecretKey(AUTH_SECRET_KEY_LENGTH)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to make secret key: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(key)\n\tcase cliIntentPasswordHash:\n\t\tpassword := options.args[1]\n\n\t\tif password == \"\" {\n\t\t\tfmt.Println(\"Password cannot be empty\")\n\t\t\treturn 1\n\t\t}\n\n\t\tif len(password) < 6 {\n\t\t\tfmt.Println(\"Password must be at least 6 characters long\")\n\t\t\treturn 1\n\t\t}\n\n\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to hash password: %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(string(hashedPassword))\n\t}\n\n\treturn 0\n}\n\nfunc serveApp(configPath string) error {\n\t// TODO: refactor if this gets any more complex, the current implementation is\n\t// difficult to reason about due to all of the callbacks and simultaneous operations,\n\t// use a single goroutine and a channel to initiate synchronous changes to the server\n\texitChannel := make(chan struct{})\n\thadValidConfigOnStartup := false\n\tvar stopServer func() error\n\n\tonChange := func(newContents []byte) {\n\t\tif stopServer != nil {\n\t\t\tlog.Println(\"Config file changed, reloading...\")\n\t\t}\n\n\t\tconfig, err := newConfigFromYAML(newContents)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Config has errors: %v\", err)\n\n\t\t\tif !hadValidConfigOnStartup {\n\t\t\t\tclose(exitChannel)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tapp, err := newApplication(config)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create application: %v\", err)\n\n\t\t\tif !hadValidConfigOnStartup {\n\t\t\t\tclose(exitChannel)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tif !hadValidConfigOnStartup {\n\t\t\thadValidConfigOnStartup = true\n\t\t}\n\n\t\tif stopServer != nil {\n\t\t\tif err := stopServer(); err != nil {\n\t\t\t\tlog.Printf(\"Error while trying to stop server: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tgo func() {\n\t\t\tvar startServer func() error\n\t\t\tstartServer, stopServer = app.server()\n\n\t\t\tif err := startServer(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to start server: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\tonErr := func(err error) {\n\t\tlog.Printf(\"Error watching config files: %v\", err)\n\t}\n\n\tconfigContents, configIncludes, err := parseYAMLIncludes(configPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing config: %w\", err)\n\t}\n\n\tstopWatching, err := configFilesWatcher(configPath, configContents, configIncludes, onChange, onErr)\n\tif err == nil {\n\t\tdefer stopWatching()\n\t} else {\n\t\tlog.Printf(\"Error starting file watcher, config file changes will require a manual restart. (%v)\", err)\n\n\t\tconfig, err := newConfigFromYAML(configContents)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"validating config file: %w\", err)\n\t\t}\n\n\t\tapp, err := newApplication(config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating application: %w\", err)\n\t\t}\n\n\t\tstartServer, _ := app.server()\n\t\tif err := startServer(); err != nil {\n\t\t\treturn fmt.Errorf(\"starting server: %w\", err)\n\t\t}\n\t}\n\n\t<-exitChannel\n\treturn nil\n}\n\nfunc serveUpdateNoticeIfConfigLocationNotMigrated(configPath string) bool {\n\tif !isRunningInsideDockerContainer() {\n\t\treturn false\n\t}\n\n\tif _, err := os.Stat(configPath); err == nil {\n\t\treturn false\n\t}\n\n\t// glance.yml wasn't mounted to begin with or was incorrectly mounted as a directory\n\tif stat, err := os.Stat(\"glance.yml\"); err != nil || stat.IsDir() {\n\t\treturn false\n\t}\n\n\ttemplateFile, _ := templateFS.Open(\"v0.7-update-notice-page.html\")\n\tbodyContents, _ := io.ReadAll(templateFile)\n\n\tfmt.Println(\"!!! WARNING !!!\")\n\tfmt.Println(\"The default location of glance.yml in the Docker image has changed starting from v0.7.0.\")\n\tfmt.Println(\"Please see https://github.com/glanceapp/glance/blob/main/docs/v0.7.0-upgrade.md for more information.\")\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.FS(staticFS))))\n\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\tw.Header().Set(\"Content-Type\", \"text/html\")\n\t\tw.Write([]byte(bodyContents))\n\t})\n\n\tserver := http.Server{\n\t\tAddr:    \":8080\",\n\t\tHandler: mux,\n\t}\n\tserver.ListenAndServe()\n\n\treturn true\n}\n"
  },
  {
    "path": "internal/glance/static/css/forum-posts.css",
    "content": ".forum-post-list-thumbnail {\n    flex-shrink: 0;\n    width: 6rem;\n    height: 4.1rem;\n    border-radius: var(--border-radius);\n    object-fit: cover;\n    border: 1px solid var(--color-separator);\n    margin-top: 0.1rem;\n}\n\n.forum-post-tags-container {\n    transform: translateY(-0.15rem);\n}\n\n@container widget (max-width: 550px) {\n    .forum-post-autohide {\n        display: none;\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/css/login.css",
    "content": ".login-bounds {\n    max-width: 500px;\n    padding: 0 2rem;\n}\n\n.form-label {\n    text-transform: uppercase;\n    margin-bottom: 0.5rem;\n}\n\n.form-input {\n    transition: border-color .2s;\n}\n\n.form-input input {\n    border: 0;\n    background: none;\n    width: 100%;\n    height: 5.2rem;\n    font: inherit;\n    outline: none;\n    color: var(--color-text-highlight);\n}\n\n.form-input-icon {\n    width: 2rem;\n    height: 2rem;\n    margin-top: -0.1rem;\n    opacity: 0.5;\n}\n\n.form-input input[type=\"password\"] {\n    letter-spacing: 0.3rem;\n    font-size: 0.9em;\n}\n\n.form-input input[type=\"password\"]::placeholder {\n    letter-spacing: 0;\n    font-size: var(--font-size-base);\n}\n\n.form-input:hover {\n    border-color: var(--color-progress-border);\n}\n\n.form-input:focus-within {\n    border-color: var(--color-primary);\n    transition-duration: .7s;\n}\n\n.login-button {\n    width: 100%;\n    display: block;\n    padding: 1rem;\n    background: none;\n    border: 1px solid var(--color-text-subdue);\n    border-radius: var(--border-radius);\n    color: var(--color-text-paragraph);\n    cursor: pointer;\n    font: inherit;\n    font-size: var(--font-size-h4);\n    display: flex;\n    gap: .5rem;\n    align-items: center;\n    justify-content: center;\n    transition: all .3s, margin-top 0s;\n    margin-top: 3rem;\n}\n\n.login-button:not(:disabled) {\n    box-shadow: 0 0 10px 1px var(--color-separator);\n}\n\n.login-error-message:not(:empty) + .login-button {\n    margin-top: 2rem;\n}\n\n.login-button:focus, .login-button:hover {\n    outline: none;\n    border-color: var(--color-primary);\n    color: var(--color-primary);\n}\n\n.login-button:disabled {\n    border-color: var(--color-separator);\n    color: var(--color-text-subdue);\n    cursor: not-allowed;\n}\n\n.login-button svg {\n    width: 1.7rem;\n    height: 1.7rem;\n    transition: transform .2s;\n}\n\n.login-button:not(:disabled):hover svg, .login-button:not(:disabled):focus svg {\n    transform: translateX(.5rem);\n}\n\n.animate-entrance {\n    animation: fieldReveal 0.7s backwards;\n    animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1);\n}\n\n.animate-entrance:nth-child(1) { animation-delay: .1s; }\n.animate-entrance:nth-child(2) { animation-delay: .2s; }\n.animate-entrance:nth-child(4) { animation-delay: .3s; }\n\n@keyframes fieldReveal {\n    from {\n        opacity: 0.0001;\n        transform: translateY(4rem);\n    }\n}\n\n.login-error-message {\n    color: var(--color-negative);\n    font-size: var(--font-size-base);\n    padding: 1.3rem calc(var(--widget-content-horizontal-padding) + 1px);\n    position: relative;\n    margin-top: 2rem;\n    animation: errorMessageEntrance 0.4s backwards cubic-bezier(0.34, 1.56, 0.64, 1);\n}\n\n@keyframes errorMessageEntrance {\n    from {\n        opacity: 0;\n        transform: scale(1.1);\n    }\n}\n\n.login-error-message:empty {\n    display: none;\n}\n\n.login-error-message::before {\n    content: \"\";\n    position: absolute;\n    inset: 0;\n    border-radius: var(--border-radius);\n    background: var(--color-negative);\n    opacity: 0.05;\n    z-index: -1;\n}\n\n.footer {\n    animation-delay: .4s;\n    animation-duration: 1s;\n}\n\n.toggle-password-visibility {\n    background: none;\n    border: none;\n    cursor: pointer;\n}\n"
  },
  {
    "path": "internal/glance/static/css/main.css",
    "content": "@font-face {\n    font-family: 'JetBrains Mono';\n    font-style: normal;\n    font-weight: 400;\n    font-display: swap;\n    src: url('../fonts/JetBrainsMono-Regular.woff2') format('woff2');\n}\n\n:root {\n    font-size: 10px;\n\n    --scheme: ;\n    --bgh: 240;\n    --bgs: 8%;\n    --bgl: 9%;\n    --bghs: var(--bgh), var(--bgs);\n    --cm: 1;\n    --tsm: 1;\n\n    --widget-gap: 23px;\n    --widget-content-vertical-padding: 15px;\n    --widget-content-horizontal-padding: 17px;\n    --widget-content-padding: var(--widget-content-vertical-padding) var(--widget-content-horizontal-padding);\n    --content-bounds-padding: 15px;\n    --border-radius: 5px;\n    --mobile-navigation-height: 50px;\n\n    --color-primary: hsl(43, 50%, 70%);\n    --color-positive: var(--color-primary);\n    --color-negative: hsl(0, 70%, 70%);\n    --color-background: hsl(var(--bghs), var(--bgl));\n    --color-widget-background-hsl-values: var(--bghs), calc(var(--bgl) + 1%);\n    --color-widget-background: hsl(var(--color-widget-background-hsl-values));\n    --color-separator: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 4% * var(--cm))));\n    --color-widget-content-border: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 4%)));\n    --color-widget-background-highlight: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 4%)));\n    --color-popover-background: hsl(var(--bgh), calc(var(--bgs) + 3%), calc(var(--bgl) + 3%));\n    --color-popover-border: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 12%)));\n    --color-progress-border: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 10% * var(--cm))));\n    --color-progress-value: hsl(var(--bgh), calc(var(--bgs) * var(--tsm)), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 26% * var(--cm))));\n    --color-vertical-progress-value: hsl(var(--bgh), calc(var(--bgs) * var(--tsm)), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 28% * var(--cm))));\n    --color-graph-gridlines: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 6% * var(--cm))));\n\n    --ths: var(--bgh), calc(var(--bgs) * var(--tsm));\n    --color-text-highlight: hsl(var(--ths), calc(var(--scheme) var(--cm) * 85%));\n    --color-text-paragraph: hsl(var(--ths), calc(var(--scheme) var(--cm) * 73%));\n    --color-text-base: hsl(var(--ths), calc(var(--scheme) var(--cm) * 58%));\n    --color-text-base-muted: hsl(var(--ths), calc(var(--scheme) var(--cm) * 52%));\n    --color-text-subdue: hsl(var(--ths), calc(var(--scheme) var(--cm) * 35%));\n\n    --font-size-h1: 1.7rem;\n    --font-size-h2: 1.6rem;\n    --font-size-h3: 1.5rem;\n    --font-size-h4: 1.4rem;\n    --font-size-base: 1.3rem;\n    --font-size-h5: 1.2rem;\n    --font-size-h6: 1.1rem;\n}\n\n/* Do not change the order of the below imports unless you know what you're doing */\n\n@import \"site.css\";\n@import \"widgets.css\";\n@import \"popover.css\";\n@import \"utils.css\";\n@import \"mobile.css\";\n"
  },
  {
    "path": "internal/glance/static/css/mobile.css",
    "content": "@media (max-width: 1190px) {\n    .header-container {\n        display: none;\n    }\n\n    .page-column-small .size-title-dynamic {\n        font-size: var(--font-size-h3);\n    }\n\n    .page-column-small {\n        width: 100%;\n        flex-shrink: 1;\n    }\n\n    .page-column {\n        display: none;\n        animation: columnEntrance .0s cubic-bezier(0.25, 1, 0.5, 1) backwards;\n    }\n\n    .page-columns-transitioned .page-column {\n        animation-duration: .3s;\n    }\n\n    @keyframes columnEntrance {\n        from {\n            opacity: 0;\n            transform: scaleX(0.95);\n        }\n    }\n\n    .mobile-navigation-offset {\n        height: var(--mobile-navigation-height);\n        flex-shrink: 0;\n    }\n\n    .mobile-navigation {\n        display: block;\n        position: fixed;\n        bottom: 0;\n        transform: translateY(calc(100% - var(--mobile-navigation-height)));\n        left: var(--content-bounds-padding);\n        right: var(--content-bounds-padding);\n        z-index: 11;\n        background-color: var(--color-widget-background);\n        border: 1px solid var(--color-widget-content-border);\n        border-bottom: 0;\n        border-radius: var(--border-radius) var(--border-radius) 0 0;\n        transition: transform .3s;\n    }\n\n    .mobile-navigation-actions > * {\n        padding-block: 1.1rem;\n        padding-inline: var(--content-bounds-padding);\n        cursor: pointer;\n        transition: background-color 50ms;\n    }\n\n    .mobile-navigation-actions > *:active {\n        background-color: var(--color-widget-background-highlight);\n    }\n\n    .mobile-navigation:has(.mobile-navigation-page-links-input:checked) .hamburger-icon {\n        --spacing: 7px;\n        color: var(--color-primary);\n        height: 2px;\n    }\n\n    .mobile-navigation:has(.mobile-navigation-page-links-input:checked) {\n        transform: translateY(0);\n    }\n\n    .mobile-navigation-page-links {\n        border-top: 1px solid var(--color-widget-content-border);\n        border-bottom: 1px solid var(--color-widget-content-border);\n        padding: 20px var(--content-bounds-padding);\n        display: flex;\n        align-items: center;\n        overflow-x: auto;\n        scrollbar-width: thin;\n        gap: 2.5rem;\n    }\n\n    .mobile-navigation-icons {\n        display: flex;\n        justify-content: space-around;\n        align-items: center;\n    }\n\n    body:has(.mobile-navigation-input[value=\"0\"]:checked) .page-columns > :nth-child(1),\n    body:has(.mobile-navigation-input[value=\"1\"]:checked) .page-columns > :nth-child(2),\n    body:has(.mobile-navigation-input[value=\"2\"]:checked) .page-columns > :nth-child(3) {\n        display: block;\n    }\n\n    .mobile-navigation-label {\n        display: flex;\n        flex: 1;\n        max-width: 50px;\n        height: var(--mobile-navigation-height);\n        justify-content: center;\n        align-items: center;\n        cursor: pointer;\n        font-size: 15px;\n        line-height: var(--mobile-navigation-height);\n    }\n\n    .mobile-navigation-pill {\n        display: block;\n        background: var(--color-text-base);\n        height: 10px;\n        width: 10px;\n        border-radius: 10px;\n        transition: width .3s, background-color .3s;\n    }\n\n    .mobile-navigation-label:hover > .mobile-navigation-pill {\n        background-color: var(--color-text-highlight);\n    }\n\n    .mobile-navigation-label:hover {\n        color: var(--color-text-highlight);\n    }\n\n    .mobile-navigation-input:checked + .mobile-navigation-pill {\n        background: var(--color-primary);\n        width: 30px;\n    }\n\n    .mobile-navigation-input, .mobile-navigation-page-links-input {\n        display: none;\n    }\n\n    .hamburger-icon {\n        --spacing: 4px;\n        width: 1em;\n        height: 1px;\n        background-color: currentColor;\n        transition: color .3s, box-shadow .3s;\n        box-shadow: 0 calc(var(--spacing) * -1) 0 0 currentColor, 0 var(--spacing) 0 0 currentColor;\n    }\n\n    .expand-toggle-button.container-expanded {\n        bottom: var(--mobile-navigation-height);\n    }\n\n    .cards-grid + .expand-toggle-button.container-expanded {\n        /* hides content that peeks through the rounded borders of the mobile navigation */\n        box-shadow: 0 var(--border-radius) 0 0 var(--color-background);\n    }\n\n    .weather-column-rain::before {\n        background-size: 7px 7px;\n    }\n\n    .ios .search-input {\n        /* so that iOS Safari does not zoom the page when the input is focused */\n        font-size: 16px;\n    }\n}\n\n@media (max-width: 1190px) and (display-mode: standalone) {\n    :root {\n        --safe-area-inset-bottom: env(safe-area-inset-bottom, 0);\n    }\n\n    .ios .body-content {\n        height: 100dvh;\n    }\n\n    .expand-toggle-button.container-expanded {\n        bottom: calc(var(--mobile-navigation-height) + var(--safe-area-inset-bottom));\n    }\n\n    .mobile-navigation {\n        transform: translateY(calc(100% - var(--mobile-navigation-height) - var(--safe-area-inset-bottom)));\n        padding-bottom: var(--safe-area-inset-bottom);\n    }\n\n    .mobile-navigation-icons {\n        padding-bottom: var(--safe-area-inset-bottom);\n        transition: padding-bottom .3s;\n    }\n\n    .mobile-navigation-offset {\n        height: calc(var(--mobile-navigation-height) + var(--safe-area-inset-bottom));\n    }\n\n    .mobile-navigation-icons:has(.mobile-navigation-page-links-input:checked) {\n        padding-bottom: 0;\n    }\n}\n\n@media (display-mode: standalone) {\n    body {\n        padding-top: env(safe-area-inset-top, 0);\n    }\n}\n\n@media (max-width: 550px) {\n    :root {\n        font-size: 9.4px;\n        --widget-gap: 15px;\n        --widget-content-vertical-padding: 10px;\n        --widget-content-horizontal-padding: 10px;\n        --content-bounds-padding: 10px;\n    }\n\n    .dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; }\n\n    .row-reverse-on-mobile {\n        flex-direction: row-reverse;\n    }\n\n    .hide-on-mobile, .thumbnail-container:has(> .hide-on-mobile) {\n        display: none\n    }\n\n    .mobile-reachability-header {\n        display: block;\n        font-size: 3rem;\n        padding: 10vh 1rem;\n        text-align: center;\n        color: var(--color-text-highlight);\n        animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;\n    }\n\n    .rss-detailed-thumbnail > * {\n        height: 6rem;\n    }\n\n    .rss-detailed-description {\n        line-clamp: 3;\n        -webkit-line-clamp: 3;\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/css/popover.css",
    "content": ".popover-container, [data-popover-html] {\n    display: none;\n}\n\n.popover-container {\n    --triangle-size: 10px;\n    --triangle-offset: 50%;\n    --triangle-margin: calc(var(--triangle-size) + 3px);\n    --entrance-y-offset: 8px;\n    --entrance-direction: calc(var(--entrance-y-offset) * -1);\n\n    z-index: 20;\n    position: absolute;\n    padding-top: var(--triangle-margin);\n    padding-inline: var(--content-bounds-padding);\n}\n\n.popover-container.position-above {\n    --entrance-direction: var(--entrance-y-offset);\n    padding-top: 0;\n    padding-bottom: var(--triangle-margin);\n}\n\n.popover-frame {\n    --shadow-properties: 0 15px 20px -10px;\n    --shadow-color: hsla(var(--bghs), calc(var(--bgl) * 0.2), 0.5);\n    position: relative;\n    padding: 10px;\n    background: var(--color-popover-background);\n    border: 1px solid var(--color-popover-border);\n    border-radius: 5px;\n    animation: popoverFrameEntrance 0.3s backwards cubic-bezier(0.16, 1, 0.3, 1);\n    box-shadow: var(--shadow-properties) var(--shadow-color);\n}\n\n.popover-frame::before {\n    content: '';\n    position: absolute;\n    width: var(--triangle-size);\n    height: var(--triangle-size);\n    transform: rotate(45deg);\n    background-color: var(--color-popover-background);\n    border-top-left-radius: 2px;\n    border-left: 1px solid var(--color-popover-border);\n    border-top: 1px solid var(--color-popover-border);\n    left: calc(var(--triangle-offset) - (var(--triangle-size) / 2));\n    top: calc(var(--triangle-size) / 2 * -1 - 1px);\n}\n\n.popover-container.position-above .popover-frame::before {\n    transform: rotate(-135deg);\n    top: auto;\n    bottom: calc(var(--triangle-size) / 2 * -1 - 1px);\n}\n\n.popover-container.position-above .popover-frame {\n    --shadow-properties: 0 10px 20px -10px;\n}\n\n@keyframes popoverFrameEntrance {\n    from {\n        opacity: 0;\n        transform: translateY(var(--entrance-direction));\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/css/site.css",
    "content": ":root[data-scheme=light] {\n    --scheme: 100% -;\n}\n\n.page {\n    height: 100%;\n    padding-block: var(--widget-gap);\n}\n\n.page-content, .page.content-ready .page-loading-container {\n    display: none;\n}\n\n.page.content-ready > .page-content {\n    display: block;\n    animation: pageContentEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;\n}\n\n.page-column-small .size-title-dynamic {\n    font-size: var(--font-size-h4);\n}\n\n.page-column-full .size-title-dynamic {\n    font-size: var(--font-size-h3);\n}\n\npre {\n    font: inherit;\n}\n\n\ninput[type=\"text\"] {\n    width: 100%;\n    border: 0;\n    background: none;\n    font: inherit;\n    color: inherit;\n}\n\nbutton {\n    font: inherit;\n    border: 0;\n    cursor: pointer;\n    background: none;\n    color: inherit;\n}\n\n::selection {\n    background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 20%)));\n    color: var(--color-text-highlight);\n}\n\n::-webkit-scrollbar-thumb {\n    background: var(--color-text-subdue);\n    border-radius: var(--border-radius);\n}\n\n::-webkit-scrollbar {\n    background: var(--color-background);\n    height: 5px;\n    width: 10px;\n}\n\n*:focus-visible {\n    outline: 2px solid var(--color-primary);\n    outline-offset: 0.1rem;\n    border-radius: var(--border-radius);\n}\n\n*, *::before, *::after {\n    box-sizing: border-box;\n}\n\n* {\n    padding: 0;\n    margin: 0;\n}\n\nhr {\n    border: 0;\n    height: 1px;\n    background-color: var(--color-separator);\n}\n\nimg, svg {\n    display: block;\n    max-width: 100%;\n}\n\nimg[loading=lazy].loaded:not(.finished-transition) {\n    transition: opacity .4s;\n}\n\nimg[loading=lazy].cached:not(.finished-transition) {\n    transition: none;\n}\n\nimg[loading=lazy]:not(.loaded, .cached) {\n    opacity: 0;\n}\n\nhtml {\n    scrollbar-color: var(--color-text-subdue) transparent;\n    scroll-behavior: smooth;\n}\n\nhtml, body, .body-content {\n    height: 100%;\n}\n\nh1, h2, h3, h4, h5 {\n    font: inherit;\n}\n\na {\n    text-decoration: none;\n    color: inherit;\n    overflow-wrap: break-word;\n}\n\nul {\n    list-style: none;\n}\n\nbody {\n    font-size: 1.3rem;\n    font-family: 'JetBrains Mono', monospace;\n    font-variant-ligatures: none;\n    line-height: 1.6;\n    color: var(--color-text-base);\n    background-color: var(--color-background);\n    overflow-y: scroll;\n}\n\n.page-column-small {\n    width: 300px;\n    flex-shrink: 0;\n}\n\n.page-column-full {\n    width: 100%;\n    min-width: 0;\n}\n\n.page-columns {\n    display: flex;\n    gap: var(--widget-gap);\n}\n\n@keyframes pageContentEntrance {\n    from {\n        opacity: 0;\n        transform: translateY(10px);\n    }\n}\n\n.page-loading-container {\n    height: 100%;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    animation: loadingContainerEntrance 200ms backwards;\n    animation-delay: 150ms;\n    font-size: 2rem;\n}\n\n.page-loading-container > .loading-icon {\n    translate: 0 -250%;\n}\n\n@keyframes loadingContainerEntrance {\n    from {\n        /* Using 0.001 instead of 0 fixes a random 1s freeze on Chrome on page load when all */\n        /* elements have opacity 0 and are animated in. I don't want to be a web dev anymore. */\n        opacity: 0.001;\n    }\n}\n\n.loading-icon {\n    min-width: 1.5em;\n    width: 1.5em;\n    height: 1.5em;\n    border: 0.25em solid hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 12%)));\n    border-top-color: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%)));\n    border-radius: 50%;\n    animation: loadingIconSpin 800ms infinite linear;\n}\n\n@keyframes loadingIconSpin {\n    to {\n        transform: rotate(360deg);\n    }\n}\n\n.notice-icon {\n    width: 0.7rem;\n    height: 0.7rem;\n    border-radius: 50%;\n}\n\n.notice-icon-major {\n    background: var(--color-negative);\n}\n\n.notice-icon-minor {\n    border: 1px solid var(--color-negative);\n}\n\nkbd {\n    font: inherit;\n    padding: 0.1rem 0.8rem;\n    border-radius: var(--border-radius);\n    border: 2px solid var(--color-widget-background-highlight);\n    box-shadow: 0 2px 0 var(--color-widget-background-highlight);\n    user-select: none;\n    transition: transform .1s, box-shadow .1s;\n    font-size: var(--font-size-h5);\n    cursor: pointer;\n}\n\nkbd:active {\n    transform: translateY(2px);\n    box-shadow: 0 0 0 0 var(--color-widget-background-highlight);\n}\n\n.content-bounds {\n    max-width: 1600px;\n    width: 100%;\n    margin-inline: auto;\n    padding: 0 var(--content-bounds-padding);\n}\n\n.content-bounds-wide {\n    max-width: 1920px;\n}\n\n.content-bounds-slim {\n    max-width: 1100px;\n}\n\n.page.center-vertically {\n    display: flex;\n    justify-content: center;\n    flex-direction: column;\n}\n\n.header-container {\n    margin-top: calc(var(--widget-gap) / 2);\n    --header-height: 45px;\n    --header-items-gap: 2.5rem;\n}\n\n.header {\n    display: flex;\n    height: var(--header-height);\n    gap: var(--header-items-gap);\n}\n\n.logo {\n    height: 100%;\n    flex-shrink: 0;\n    line-height: var(--header-height);\n    font-size: 2rem;\n    color: var(--color-text-highlight);\n    border-right: 1px solid var(--color-widget-content-border);\n    padding-right: var(--widget-content-horizontal-padding);\n}\n\n.logo:has(img, svg) {\n    display: flex;\n    align-items: center;\n}\n\n.logo img {\n    max-height: 2.7rem;\n}\n\n.nav {\n    overflow-x: auto;\n    min-width: 0;\n    height: 100%;\n    gap: var(--header-items-gap);\n}\n\n.nav .nav-item {\n    line-height: var(--header-height);\n}\n\n.footer {\n    padding-bottom: calc(var(--widget-gap) * 1.5);\n    padding-top: calc(var(--widget-gap) / 2);\n    animation: loadingContainerEntrance 200ms backwards;\n    animation-delay: 150ms;\n}\n\n.mobile-navigation, .mobile-reachability-header {\n    display: none;\n}\n\n.nav-item {\n    display: block;\n    height: 100%;\n    border-bottom: 2px solid transparent;\n    transition: color .3s, border-color .3s;\n    font-size: var(--font-size-h3);\n    flex-shrink: 0;\n}\n\n.nav-item:not(.nav-item-current):hover {\n    border-bottom-color: var(--color-text-subdue);\n    color: var(--color-text-highlight);\n}\n\n.nav-item.nav-item-current {\n    border-bottom-color: var(--color-primary);\n    color: var(--color-text-highlight);\n}\n\n.logout-button {\n    width: 2rem;\n    height: 2rem;\n    stroke: var(--color-text-subdue);\n    transition: stroke .2s;\n}\n\n.logout-button:hover, .logout-button:focus {\n    stroke: var(--color-text-highlight);\n}\n\n.theme-choices {\n    --presets-per-row: 2;\n    display: grid;\n    grid-template-columns: repeat(var(--presets-per-row), 1fr);\n    align-items: center;\n    gap: 1.35rem;\n}\n\n.theme-choices:has(> :nth-child(3)) {\n    --presets-per-row: 3;\n}\n\n.theme-preset {\n    background-color: var(--color);\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    gap: 0.5rem;\n    height: 2rem;\n    padding-inline: 0.5rem;\n    border-radius: 0.3rem;\n    border: none;\n    cursor: pointer;\n    position: relative;\n}\n\n.theme-choices .theme-preset::before {\n    content: '';\n    position: absolute;\n    inset: -.4rem;\n    border-radius: .7rem;\n    border: 2px solid transparent;\n    transition: border-color .3s;\n}\n\n.theme-choices .theme-preset:hover::before {\n    border-color: var(--color-text-subdue);\n}\n\n.theme-choices .theme-preset.current::before {\n    border-color: var(--color-text-base);\n}\n\n.theme-preset-light {\n    gap: 0.3rem;\n    height: 1.8rem;\n}\n\n.theme-color {\n    background-color: var(--color);\n    width: 0.9rem;\n    height: 0.9rem;\n    border-radius: 0.2rem;\n}\n\n.theme-preset-light .theme-color {\n    width: 1rem;\n    height: 1rem;\n    border-radius: 0.3rem;\n}\n\n.current-theme-preview {\n    opacity: 0.4;\n    transition: opacity .3s;\n}\n\n.theme-picker.popover-active .current-theme-preview, .theme-picker:hover {\n    opacity: 1;\n}\n"
  },
  {
    "path": "internal/glance/static/css/utils.css",
    "content": ".masonry {\n    display: flex;\n    gap: var(--widget-gap);\n}\n\n.masonry-column {\n    flex: 1;\n    display: flex;\n    flex-direction: column;\n}\n\n.widget-small-content-bounds {\n    max-width: 350px;\n    margin: 0 auto;\n}\n\n.visually-hidden {\n    clip-path: inset(50%);\n    height: 1px;\n    overflow: hidden;\n    position: absolute;\n    white-space: nowrap;\n    width: 1px;\n}\n\n.list-horizontal-text {\n    display: flex;\n    list-style: none;\n    flex-wrap: wrap;\n    align-items: center;\n}\n\n.list-horizontal-text > *:not(:last-child)::after {\n    content: '•' / \"\";\n    color: var(--color-text-subdue);\n    margin: 0 0.4rem;\n    position: relative;\n    top: 0.1rem;\n}\n\n.summary {\n    width: 100%;\n    cursor: pointer;\n    word-spacing: -0.18em;\n    user-select: none;\n    list-style: none;\n    position: relative;\n    display: flex;\n    z-index: 1;\n}\n\n.summary::-webkit-details-marker {\n    display: none;\n}\n\n.details[open] .summary {\n    margin-bottom: .8rem;\n}\n\n.summary::before {\n    content: \"\";\n    position: absolute;\n    inset: -.3rem -.8rem;\n    border-radius: var(--border-radius);\n    background-color: var(--color-widget-background-highlight);\n    opacity: 0;\n    transition: opacity 0.2s;\n    z-index: -1;\n}\n\n.details[open] .summary::before, .summary:hover::before {\n    opacity: 1;\n}\n\n.details:not([open]) .list-with-transition {\n    display: none;\n}\n\n.summary::after {\n    content: \"◀\" / \"\";\n    font-size: 1.2em;\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    line-height: 1.3em;\n    right: 0;\n    transition: rotate .5s cubic-bezier(0.22, 1, 0.36, 1);\n}\n\ndetails[open] .summary::after {\n    rotate: -90deg;\n}\n\n/* TODO: refactor, otherwise I hope I never have to change dynamic columns again */\n.dynamic-columns {\n    --list-half-gap: 0.5rem;\n    gap: var(--widget-content-vertical-padding) var(--widget-content-horizontal-padding);\n    display: grid;\n    grid-template-columns: repeat(var(--columns-per-row), 1fr);\n}\n\n.dynamic-columns > * {\n    padding-left: var(--widget-content-horizontal-padding);\n    border-left: 1px solid var(--color-separator);\n    min-width: 0;\n}\n\n.dynamic-columns > *:first-child {\n    padding-top: 0;\n    border-top: none;\n    border-left: none;\n}\n\n.dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; }\n.dynamic-columns:has(> :nth-child(2)) { --columns-per-row: 2; }\n.dynamic-columns:has(> :nth-child(3)) { --columns-per-row: 3; }\n.dynamic-columns:has(> :nth-child(4)) { --columns-per-row: 4; }\n.dynamic-columns:has(> :nth-child(5)) { --columns-per-row: 5; }\n\n@container widget (max-width: 599px) {\n    .dynamic-columns { gap: 0; }\n    .dynamic-columns:has(> :nth-child(1)) { --columns-per-row: 1; }\n    .dynamic-columns > * {\n        border-left: none;\n        padding-left: 0;\n    }\n    .dynamic-columns > *:not(:first-child) {\n        margin-top: calc(var(--list-half-gap) * 2);\n    }\n    .dynamic-columns.list-with-separator > *:not(:first-child) {\n        margin-top: var(--list-half-gap);\n        border-top: 1px solid var(--color-separator);\n        padding-top: var(--list-half-gap);\n    }\n}\n@container widget (min-width: 600px) and (max-width: 849px) {\n    .dynamic-columns:has(> :nth-child(2)) { --columns-per-row: 2; }\n    .dynamic-columns > :nth-child(2n-1) {\n        border-left: none;\n        padding-left: 0;\n    }\n}\n@container widget (min-width: 850px) and (max-width: 1249px) {\n    .dynamic-columns:has(> :nth-child(3)) { --columns-per-row: 3; }\n    .dynamic-columns > :nth-child(3n+1) {\n        border-left: none;\n        padding-left: 0;\n    }\n}\n@container widget (min-width: 1250px) and (max-width: 1499px) {\n    .dynamic-columns:has(> :nth-child(4)) { --columns-per-row: 4; }\n    .dynamic-columns > :nth-child(4n+1) {\n        border-left: none;\n        padding-left: 0;\n    }\n}\n@container widget (min-width: 1500px) {\n    .dynamic-columns:has(> :nth-child(5)) { --columns-per-row: 5; }\n    .dynamic-columns > :nth-child(5n+1) {\n        border-left: none;\n        padding-left: 0;\n    }\n}\n\n.cards-vertical {\n    flex-direction: column;\n}\n\n.cards-horizontal {\n    --cards-per-row: 6.5;\n}\n\n.cards-horizontal, .cards-vertical {\n    --cards-gap: calc(var(--widget-content-vertical-padding) * 0.7);\n    display: flex;\n    gap: var(--cards-gap);\n}\n\n.card {\n    display: flex;\n    flex-direction: column;\n}\n\n.cards-horizontal .card {\n    flex-shrink: 0;\n    width: calc(100% / var(--cards-per-row) - var(--cards-gap) * (var(--cards-per-row) - 1) / var(--cards-per-row));\n}\n\n.cards-grid .card {\n    min-width: 0;\n}\n\n.cards-horizontal {\n    overflow-x: auto;\n    scrollbar-width: thin;\n    padding-bottom: 1rem;\n}\n\n.cards-grid {\n    --cards-per-row: 6;\n    display: grid;\n    grid-template-columns: repeat(var(--cards-per-row), 1fr);\n    gap: calc(var(--widget-content-vertical-padding) * 0.7);\n}\n\n@container widget (max-width: 1300px) { .cards-horizontal { --cards-per-row: 5.5; } }\n@container widget (max-width: 1100px) { .cards-horizontal { --cards-per-row: 4.5; } }\n@container widget (max-width: 850px) { .cards-horizontal { --cards-per-row: 3.5; } }\n@container widget (max-width: 750px) { .cards-horizontal { --cards-per-row: 3.5; } }\n@container widget (max-width: 650px) { .cards-horizontal { --cards-per-row: 2.5; } }\n@container widget (max-width: 450px) { .cards-horizontal { --cards-per-row: 2.3; } }\n\n@container widget (max-width: 1300px) { .cards-grid { --cards-per-row: 5; } }\n@container widget (max-width: 1100px) { .cards-grid { --cards-per-row: 4; } }\n@container widget (max-width: 850px) { .cards-grid { --cards-per-row: 3; } }\n@container widget (max-width: 750px) { .cards-grid { --cards-per-row: 3; } }\n@container widget (max-width: 650px) { .cards-grid { --cards-per-row: 2; } }\n\n.text-truncate,\n.single-line-titles .title\n{\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n}\n\n.single-line-titles .title {\n    display: block;\n}\n\n.text-truncate-2-lines, .text-truncate-3-lines {\n    overflow: hidden;\n    text-overflow: ellipsis;\n    display: -webkit-box;\n    -webkit-box-orient: vertical;\n}\n\n.text-truncate-3-lines { line-clamp: 3; -webkit-line-clamp: 3; }\n.text-truncate-2-lines { line-clamp: 2; -webkit-line-clamp: 2; }\n\n.visited-indicator:not(.text-truncate)::after,\n.visited-indicator.text-truncate::before {\n    content: '↗' / \"\";\n    margin-left: 0.5em;\n    display: inline-block;\n    position: relative;\n    top: 0.15em;\n    color: var(--color-text-base);\n}\n\n.visited-indicator.text-truncate {\n    direction: rtl;\n    text-align: left;\n}\n\n.visited-indicator:not(:visited)::before, .visited-indicator:not(:visited)::after {\n    color: var(--color-primary);\n}\n\n.page-columns-transitioned .list-with-transition > * { animation: collapsibleItemReveal .25s backwards; }\n.list-with-transition > *:nth-child(2) { animation-delay: 30ms; }\n.list-with-transition > *:nth-child(3) { animation-delay: 60ms; }\n.list-with-transition > *:nth-child(4) { animation-delay: 90ms; }\n.list-with-transition > *:nth-child(5) { animation-delay: 120ms; }\n.list-with-transition > *:nth-child(6) { animation-delay: 150ms; }\n.list-with-transition > *:nth-child(7) { animation-delay: 180ms; }\n.list-with-transition > *:nth-child(8) { animation-delay: 210ms; }\n\n.list > *:not(:first-child) {\n    margin-top: calc(var(--list-half-gap) * 2);\n}\n\n.list.list-with-separator > *:not(:first-child) {\n    margin-top: var(--list-half-gap);\n    border-top: 1px solid var(--color-separator);\n    padding-top: var(--list-half-gap);\n}\n\n.collapsible-container:not(.container-expanded) > .collapsible-item {\n    display: none;\n}\n\n.collapsible-item {\n    animation: collapsibleItemReveal .25s backwards;\n}\n\n@keyframes collapsibleItemReveal {\n    from {\n        opacity: 0;\n        transform: translateY(10px);\n    }\n}\n\n.expand-toggle-button {\n    font: inherit;\n    border: 0;\n    cursor: pointer;\n    display: block;\n    width: 100%;\n    text-align: left;\n    color: var(--color-text-base);\n    text-transform: uppercase;\n    font-size: var(--font-size-h4);\n    padding: var(--widget-content-vertical-padding) 0;\n    background: var(--color-widget-background);\n}\n\n.expand-toggle-button.container-expanded {\n    position: sticky;\n    /* -1px to hide 1px gap on chrome */\n    bottom: -1px;\n}\n\n.expand-toggle-button-icon {\n    display: inline-block;\n    margin-left: 1rem;\n    position: relative;\n    top: -.2rem;\n}\n\n.expand-toggle-button-icon::before {\n    content: '' / \"\";\n    font-size: 0.8rem;\n    transform: rotate(90deg);\n    line-height: 1;\n    display: inline-block;\n    transition: transform 0.3s;\n}\n\n.expand-toggle-button.container-expanded .expand-toggle-button-icon::before {\n    transform: rotate(-90deg);\n}\n\n.cards-grid.collapsible-container + .expand-toggle-button {\n    text-align: center;\n    margin-top: 0.5rem;\n    background-color: var(--color-background);\n}\n\n.widget-content:has(.expand-toggle-button:last-child) {\n    padding-bottom: 0;\n}\n\n.carousel-container {\n    position: relative;\n}\n\n.carousel-container::before, .carousel-container::after {\n    content: '';\n    position: absolute;\n    width: 2rem;\n    top: 0;\n    bottom: 1rem;\n    z-index: 10;\n    opacity: 0;\n    pointer-events: none;\n    transition-duration: 0.2s;\n}\n\n.carousel-container::before {\n    background: linear-gradient(to right, var(--color-background), transparent);\n}\n\n.carousel-container::after {\n    right: 0;\n    background: linear-gradient(to left, var(--color-background), transparent);\n}\n\n.carousel-container.show-left-cutoff::before, .carousel-container.show-right-cutoff::after {\n    opacity: 1;\n}\n\n.attachments {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.5rem;\n}\n\n:root:not([data-scheme=light]) .flat-icon {\n    filter: invert(1);\n}\n\n.attachments > * {\n    border-radius: var(--border-radius);\n    padding: 0.1rem 0.5rem;\n    font-size: var(--font-size-h6);\n    background-color: var(--color-separator);\n}\n\n.progress-bar {\n    border: 1px solid var(--color-progress-border);\n    border-radius: var(--border-radius);\n    display: flex;\n    flex-direction: column;\n    gap: 2px;\n    padding: 2px;\n    height: 1.5rem;\n    /* naughty, but oh so beautiful */\n    margin-inline: -3px;\n}\n\n.progress-bar-combined {\n    height: 3rem;\n}\n\n.popover-active > .progress-bar {\n    transition: border-color .3s;\n    border-color: var(--color-text-subdue);\n}\n\n.progress-value {\n    --half-border-radius: calc(var(--border-radius) / 2);\n    border-radius: 0 var(--half-border-radius) var(--half-border-radius) 0;\n    background: var(--color-progress-value);\n    width: calc(var(--percent) * 1%);\n    min-width: 1px;\n    flex: 1;\n}\n\n.progress-value:first-child {\n    border-top-left-radius: var(--half-border-radius);\n}\n\n.progress-value:last-child {\n    border-bottom-left-radius: var(--half-border-radius);\n}\n\n.progress-value-notice {\n    background: linear-gradient(to right, var(--color-progress-value) 65%, var(--color-negative));\n}\n\n.value-separator {\n    min-width: 2rem;\n    margin-inline: 0.8rem;\n    flex: 1;\n    height: calc(1em * 1.1);\n    border-bottom: 1px dotted var(--color-text-subdue);\n}\n\n.thumbnail {\n    filter: grayscale(0.2) contrast(0.9);\n    opacity: 0.8;\n    transition: filter 0.2s, opacity .2s;\n}\n\n.thumbnail-container {\n    flex-shrink: 0;\n    border: 1px solid var(--color-separator);\n    border-radius: var(--border-radius);\n}\n\n.thumbnail-container > * {\n    border-radius: var(--border-radius);\n    object-fit: cover;\n}\n\n.thumbnail-parent:hover .thumbnail {\n    opacity: 1;\n    filter: none;\n}\n\n\n.hide-scrollbars {\n    scrollbar-width: none;\n}\n\n/* Hide on Safari and Chrome */\n.hide-scrollbars::-webkit-scrollbar {\n    display: none;\n}\n\n.ui-icon {\n    width: 2.3rem;\n    height: 2.3rem;\n    display: block;\n    flex-shrink: 0;\n}\n\n.size-h1 { font-size: var(--font-size-h1); }\n.size-h2 { font-size: var(--font-size-h2); }\n.size-h3 { font-size: var(--font-size-h3); }\n.size-h4 { font-size: var(--font-size-h4); }\n.size-base { font-size: var(--font-size-base); }\n.size-h5 { font-size: var(--font-size-h5); }\n.size-h6 { font-size: var(--font-size-h6); }\n\n.color-highlight { color: var(--color-text-highlight); }\n.color-paragraph { color: var(--color-text-paragraph); }\n.color-base { color: var(--color-text-base); }\n.color-subdue { color: var(--color-text-subdue); }\n.color-negative { color: var(--color-negative); }\n.color-positive { color: var(--color-positive); }\n.color-primary { color: var(--color-primary); }\n\n.color-primary-if-not-visited:not(:visited) {\n    color: var(--color-primary);\n}\n\n.drag-and-drop-container {\n    position: relative;\n}\n\n.drag-and-drop-decoy {\n    outline: 1px dashed var(--color-primary);\n    opacity: 0.25;\n    border-radius: var(--border-radius);\n}\n\n.drag-and-drop-draggable {\n    position: absolute;\n    cursor: grabbing !important;\n}\n\n.drag-and-drop-draggable:empty {\n    display: none;\n}\n\n.drag-and-drop-draggable * {\n    cursor: grabbing !important;\n}\n\n.auto-scaling-textarea-container {\n    position: relative;\n}\n\n.auto-scaling-textarea {\n    position: absolute;\n    inset: 0;\n    background: none;\n    border: none;\n    font: inherit;\n    resize: none;\n    color: inherit;\n    overflow: hidden;\n}\n\n.auto-scaling-textarea:focus {\n    outline: none;\n}\n\n.auto-scaling-textarea-mimic {\n    white-space: pre-wrap;\n    min-height: 1lh;\n    user-select: none;\n    word-wrap: break-word;\n    font: inherit;\n    visibility: hidden;\n}\n\n.cursor-help { cursor: help; }\n.rounded { border-radius: var(--border-radius); }\n.break-all { word-break: break-all; }\n.text-left { text-align: left; }\n.text-right { text-align: right; }\n.text-center { text-align: center; }\n.text-elevate { margin-top: -0.2em; }\n.text-compact { word-spacing: -0.18em; }\n.text-very-compact { word-spacing: -0.35em; }\n.rtl { direction: rtl; }\n.shrink { flex-shrink: 1; }\n.shrink-0 { flex-shrink: 0; }\n.min-width-0 { min-width: 0; }\n.max-width-100 { max-width: 100%; }\n.block { display: block; }\n.inline-block { display: inline-block; }\n.overflow-hidden { overflow: hidden; }\n.relative { position: relative; }\n.flex { display: flex; }\n.flex-1 { flex: 1; }\n.flex-wrap { flex-wrap: wrap; }\n.flex-nowrap { flex-wrap: nowrap; }\n.justify-between { justify-content: space-between; }\n.justify-stretch { justify-content: stretch; }\n.justify-evenly { justify-content: space-evenly; }\n.justify-center { justify-content: center; }\n.justify-end { justify-content: end; }\n.uppercase { text-transform: uppercase; }\n.grow { flex-grow: 1; }\n.flex-column { flex-direction: column; }\n.items-center { align-items: center; }\n.self-center { align-self: center; }\n.items-start { align-items: start; }\n.items-end { align-items: end; }\n.gap-5 { gap: 0.5rem; }\n.gap-7 { gap: 0.7rem; }\n.gap-10 { gap: 1rem; }\n.gap-12 { gap: 1.2rem; }\n.gap-15 { gap: 1.5rem; }\n.gap-20 { gap: 2rem; }\n.gap-25 { gap: 2.5rem; }\n.gap-35 { gap: 3.5rem; }\n.gap-45 { gap: 4.5rem; }\n.gap-55 { gap: 5.5rem; }\n.margin-left-auto { margin-left: auto; }\n.margin-top-3 { margin-top: 0.3rem; }\n.margin-top-5 { margin-top: 0.5rem; }\n.margin-top-7 { margin-top: 0.7rem; }\n.margin-top-10 { margin-top: 1rem; }\n.margin-top-15 { margin-top: 1.5rem; }\n.margin-top-20 { margin-top: 2rem; }\n.margin-top-25 { margin-top: 2.5rem; }\n.margin-top-35 { margin-top: 3.5rem; }\n.margin-top-40 { margin-top: 4rem; }\n.margin-top-auto { margin-top: auto; }\n.margin-block-3 { margin-block: 0.3rem; }\n.margin-block-5 { margin-block: 0.5rem; }\n.margin-block-7 { margin-block: 0.7rem; }\n.margin-block-8 { margin-block: 0.8rem; }\n.margin-block-10 { margin-block: 1rem; }\n.margin-block-15 { margin-block: 1.5rem; }\n.margin-bottom-3 { margin-bottom: 0.3rem; }\n.margin-bottom-5 { margin-bottom: 0.5rem; }\n.margin-bottom-7 { margin-bottom: 0.7rem; }\n.margin-bottom-10 { margin-bottom: 1rem; }\n.margin-bottom-15 { margin-bottom: 1.5rem; }\n.margin-bottom-auto { margin-bottom: auto; }\n.margin-bottom-widget { margin-bottom: var(--widget-content-vertical-padding); }\n.padding-widget { padding: var(--widget-content-padding); }\n.padding-block-widget { padding-block: var(--widget-content-vertical-padding); }\n.padding-inline-widget { padding-inline: var(--widget-content-horizontal-padding); }\n.pointer-events-none { pointer-events: none; }\n.select-none { user-select: none; }\n.padding-block-5 { padding-block: 0.5rem; }\n.scale-half { transform: scale(0.5); }\n.list { --list-half-gap: 0rem; }\n.list-gap-2 { --list-half-gap: 0.1rem; }\n.list-gap-4 { --list-half-gap: 0.2rem; }\n.list-gap-8 { --list-half-gap: 0.4rem; }\n.list-gap-10 { --list-half-gap: 0.5rem; }\n.list-gap-14 { --list-half-gap: 0.7rem; }\n.list-gap-20 { --list-half-gap: 1rem; }\n.list-gap-24 { --list-half-gap: 1.2rem; }\n.list-gap-34 { --list-half-gap: 1.7rem; }\n\n@media (max-width: 1190px) {\n    .size-base-on-mobile { font-size: var(--font-size-base); }\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-bookmarks.css",
    "content": ".bookmarks-group {\n    --bookmarks-group-color: var(--color-primary);\n}\n\n.bookmarks-group-title {\n    color: var(--bookmarks-group-color);\n}\n\n.bookmarks-link:not(.bookmarks-link-no-arrow)::after {\n    content: '↗' / \"\";\n    margin-left: 0.5em;\n    display: inline-block;\n    position: relative;\n    top: 0.15em;\n    color: var(--bookmarks-group-color);\n}\n\n.bookmarks-icon-container {\n    margin-block: 0.1rem;\n    background-color: var(--color-widget-background-highlight);\n    border-radius: var(--border-radius);\n    padding: 0.5rem;\n    opacity: 0.7;\n    flex-shrink: 0;\n}\n\n.bookmarks-icon {\n    width: 20px;\n    height: 20px;\n    opacity: 0.8;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-calendar.css",
    "content": ".old-calendar-day {\n    width: calc(100% / 7);\n    text-align: center;\n    padding: 0.6rem 0;\n}\n\n.old-calendar-day-today {\n    border-radius: var(--border-radius);\n    background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) (var(--bgl)) + 6%)));\n    color: var(--color-text-highlight);\n}\n\n.calendar-dates {\n    text-align: center;\n    display: grid;\n    grid-template-columns: repeat(7, 1fr);\n    gap: 2px;\n}\n\n.calendar-date {\n    padding: 0.4rem 0;\n    color: var(--color-text-base);\n    position: relative;\n    border-radius: var(--border-radius);\n    background: none;\n    border: none;\n    font: inherit;\n}\n\n.calendar-current-date {\n    border-radius: var(--border-radius);\n    background-color: var(--color-popover-border);\n    color: var(--color-text-highlight);\n}\n\n.calendar-spillover-date {\n    color: var(--color-text-subdue);\n}\n\n.calendar-header-button {\n    position: relative;\n    cursor: pointer;\n    width: 2rem;\n    height: 2rem;\n    z-index: 1;\n    background: none;\n    border: none;\n}\n\n.calendar-header-button::before {\n    content: '';\n    position: absolute;\n    inset: -0.2rem;\n    border-radius: var(--border-radius);\n    background-color: var(--color-text-subdue);\n    opacity: 0;\n    transition: opacity 0.2s;\n    z-index: -1;\n}\n\n.calendar-header-button:hover::before {\n    opacity: 0.4;\n}\n\n.calendar-undo-button {\n    display: inline-block;\n    vertical-align: text-top;\n    width: 2rem;\n    height: 2rem;\n    margin-left: 0.7rem;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-clock.css",
    "content": ".clock-time {\n    min-width: 8ch;\n}\n\n.clock-time span {\n    color: var(--color-text-highlight);\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-dns-stats.css",
    "content": ".dns-stats-totals {\n    transition: opacity .3s;\n    transition-delay: 50ms;\n}\n\n.dns-stats:has(.dns-stats-graph .popover-active) .dns-stats-totals {\n    opacity: 0.1;\n    transition-delay: 0s;\n}\n\n.dns-stats-graph {\n    --graph-height: 70px;\n    height: var(--graph-height);\n    position: relative;\n    margin-bottom: 2.5rem;\n}\n\n.dns-stats-graph-gridlines-container {\n    position: absolute;\n    inset: 0;\n}\n\n.dns-stats-graph-gridlines {\n    height: 100%;\n    width: 100%;\n}\n\n.dns-stats-graph-columns {\n    display: flex;\n    height: 100%;\n}\n\n.dns-stats-graph-column {\n    display: flex;\n    justify-content: flex-end;\n    align-items: center;\n    flex-direction: column;\n    width: calc(100% / 8);\n    position: relative;\n}\n\n.dns-stats-graph-column::before {\n    content: '';\n    position: absolute;\n    inset: 1px 0;\n    opacity: 0;\n    background: var(--color-text-base);\n    transition: opacity .2s;\n}\n\n.dns-stats-graph-column:hover::before {\n    opacity: 0.05;\n}\n\n.dns-stats-graph-bar {\n    width: 14px;\n    height: calc((var(--bar-height) / 100) * var(--graph-height));\n    border: 1px solid var(--color-progress-border);\n    border-radius: var(--border-radius) var(--border-radius) 0 0;\n    display: flex;\n    background: var(--color-widget-background);\n    padding: 2px 2px 0 2px;\n    flex-direction: column;\n    gap: 2px;\n    transition: border-color .2s;\n    min-height: 10px;\n}\n\n.dns-stats-graph-column.popover-active .dns-stats-graph-bar {\n    border-color: var(--color-text-subdue);\n    border-bottom-color: var(--color-progress-border);\n}\n\n.dns-stats-graph-bar > * {\n    border-radius: 2px;\n    background: var(--color-vertical-progress-value);\n    min-height: 1px;\n}\n\n.dns-stats-graph-bar > .queries {\n    flex-grow: 1;\n}\n\n.dns-stats-graph-bar > *:last-child {\n    border-bottom-right-radius: 0;\n    border-bottom-left-radius: 0;\n}\n\n.dns-stats-graph-bar > .blocked {\n    background-color: var(--color-negative);\n    flex-basis: calc(var(--percent) - 1px);\n}\n\n.dns-stats-graph-column:nth-child(even) .dns-stats-graph-time {\n    opacity: 1;\n    transform: translateY(0);\n}\n\n.dns-stats-graph-time, .dns-stats-graph-columns:hover .dns-stats-graph-time {\n    position: absolute;\n    font-size: var(--font-size-h6);\n    inset-inline: 0;\n    text-align: center;\n    height: 2.5rem;\n    line-height: 2.5rem;\n    top: 100%;\n    user-select: none;\n    opacity: 0;\n    transform: translateY(-0.5rem);\n    transition: opacity .2s, transform .2s;\n}\n\n.dns-stats-graph-column:hover .dns-stats-graph-time {\n    opacity: 1;\n    transform: translateY(0);\n}\n\n.dns-stats-graph-columns:hover .dns-stats-graph-column:not(:hover) .dns-stats-graph-time {\n    opacity: 0;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-docker-containers.css",
    "content": ".docker-container-icon {\n    display: block;\n    filter: grayscale(0.4);\n    object-fit: contain;\n    aspect-ratio: 1 / 1;\n    width: 2.7rem;\n    opacity: 0.8;\n    transition: filter 0.3s, opacity 0.3s;\n}\n\n.docker-container-icon.flat-icon {\n    opacity: 0.7;\n}\n\n.docker-container:hover .docker-container-icon {\n    opacity: 1;\n}\n\n.docker-container:hover .docker-container-icon:not(.flat-icon) {\n    filter: grayscale(0);\n}\n\n.docker-container-status-icon {\n    width: 2rem;\n    height: 2rem;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-group.css",
    "content": ".widget-group-header {\n    overflow-x: auto;\n    scrollbar-width: thin;\n}\n\n.widget-group-title {\n    background: none;\n    font: inherit;\n    border: none;\n    text-transform: uppercase;\n    border-bottom: 1px dotted transparent;\n    cursor: pointer;\n    flex-shrink: 0;\n    transition: color .3s, border-color .3s;\n    color: var(--color-text-subdue);\n    line-height: calc(1.6em - 1px);\n}\n\n.widget-group-title:hover:not(.widget-group-title-current) {\n    color: var(--color-text-base);\n}\n\n.widget-group-title-current {\n    border-bottom-color: var(--color-text-base-muted);\n    color: var(--color-text-base);\n}\n\n.widget-group-content {\n    animation: widgetGroupContentEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;\n}\n\n.widget-group-content[data-direction=\"right\"] {\n    --direction: 5px;\n}\n\n.widget-group-content[data-direction=\"left\"] {\n    --direction: -5px;\n}\n\n@keyframes widgetGroupContentEntrance {\n    from {\n        opacity: 0;\n        transform: translateX(var(--direction));\n    }\n}\n\n.widget-group-content:not(.widget-group-content-current) {\n    display: none;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-markets.css",
    "content": ".market-chart {\n    margin-left: auto;\n    width: 6.5rem;\n    flex-shrink: 0;\n}\n\n.market-chart svg {\n    width: 100%;\n}\n\n.market-values {\n    min-width: 8rem;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-monitor.css",
    "content": ".monitor-site-icon {\n    display: block;\n    opacity: 0.8;\n    filter: grayscale(0.4);\n    object-fit: contain;\n    aspect-ratio: 1 / 1;\n    width: 3.2rem;\n    position: relative;\n    top: -0.1rem;\n    transition: filter 0.3s, opacity 0.3s;\n}\n\n.monitor-site-icon.flat-icon {\n    opacity: 0.7;\n}\n\n.monitor-site:hover .monitor-site-icon {\n    opacity: 1;\n}\n\n.monitor-site:hover .monitor-site-icon:not(.flat-icon) {\n    filter: grayscale(0);\n}\n\n.monitor-site-status-icon {\n    flex-shrink: 0;\n    margin-left: auto;\n    width: 2rem;\n    height: 2rem;\n}\n\n.monitor-site-status-icon-compact {\n    width: 1.8rem;\n    height: 1.8rem;\n    flex-shrink: 0;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-reddit.css",
    "content": ".reddit-card-thumbnail {\n    width: 100%;\n    height: 100%;\n    object-fit: cover;\n    object-position: 0% 20%;\n    opacity: 0.15;\n    filter: blur(1px);\n}\n\n.reddit-card-thumbnail-container {\n    position: absolute;\n    inset: 0;\n    overflow: hidden;\n    border-radius: var(--border-radius);\n}\n\n.reddit-card-thumbnail-container::after {\n    content: '';\n    position: absolute;\n    inset: 0;\n    background: linear-gradient(0deg, var(--color-widget-background) 10%, transparent);\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-releases.css",
    "content": ".release-source-icon {\n    width: 16px;\n    height: 16px;\n    flex-shrink: 0;\n    opacity: 0.4;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-rss.css",
    "content": ".rss-card-image {\n    height: var(--rss-thumbnail-height, 10rem);\n    object-fit: cover;\n    border-radius: var(--border-radius) var(--border-radius) 0 0;\n}\n\n.rss-card-2 {\n    position: relative;\n    height: var(--rss-card-height, 27rem);\n    overflow: hidden;\n}\n\n.rss-card-2::before {\n    content: '';\n    position: absolute;\n    inset: 0;\n    pointer-events: none;\n    background-image: linear-gradient(\n        0deg,\n        var(--color-widget-background),\n        hsla(var(--color-widget-background-hsl-values), 0.8) 6rem, transparent 14rem\n    );\n    z-index: 2;\n}\n\n.rss-card-2-image {\n    position: absolute;\n    width: 100%;\n    height: 100%;\n    object-fit: cover;\n    /* +1px is required to fix some weird graphical bug where the image overflows on the bottom in firefox */\n    border-radius: calc(var(--border-radius) + 1px);\n    opacity: 0.9;\n    z-index: 1;\n}\n\n.rss-card-2-content {\n    position: absolute;\n    inset-inline: 0;\n    bottom: var(--widget-content-vertical-padding);\n    z-index: 3;\n}\n\n.rss-detailed-description {\n    max-width: 55rem;\n    color: var(--color-text-base-muted);\n}\n\n.rss-detailed-thumbnail {\n    margin-top: 0.3rem;\n}\n\n.rss-detailed-thumbnail > * {\n    aspect-ratio: 3 / 2;\n    height: 8.7rem;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-search.css",
    "content": ".search-icon {\n    width: 2.3rem;\n}\n\n.search-icon-container {\n    position: relative;\n    flex-shrink: 0;\n}\n\n/* gives a wider hit area for the 3 people that will notice the animation : ) */\n.search-icon-container::before {\n    content: '';\n    position: absolute;\n    inset: -1rem;\n}\n\n.search-icon-container:hover > .search-icon {\n    animation: searchIconHover 2.9s forwards;\n}\n\n@keyframes searchIconHover {\n    0%, 39% { translate: 0 0; }\n    20% { scale: 1.3; }\n    40% { scale: 1; }\n    50% { translate: -30% 30%; }\n    70% { translate: 30% -30%; }\n    90% { translate: -30% -30%; }\n    100% { translate: 0 0; }\n}\n\n.search {\n    transition: border-color .2s;\n    position: relative;\n}\n\n.search:hover {\n    border-color: var(--color-text-subdue);\n}\n\n.search:focus-within {\n    border-color: var(--color-primary);\n}\n\n.search-input {\n    border: 0;\n    background: none;\n    width: 100%;\n    height: 6rem;\n    font: inherit;\n    outline: none;\n    color: var(--color-text-highlight);\n}\n\n.search-input::placeholder {\n    color: var(--color-text-base-muted);\n    opacity: 1;\n}\n\n.search-bangs { display: none; }\n\n.search-bang {\n    border-radius: calc(var(--border-radius) * 2);\n    background: var(--color-widget-background-highlight);\n    padding: 0.3rem 1rem;\n    flex-shrink: 0;\n    font-size: var(--font-size-h5);\n    animation: searchBangsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards;\n}\n\n@keyframes searchBangsEntrance {\n    0% {\n        opacity: 0;\n        transform: translateX(-10px);\n    }\n}\n\n.search-bang:empty {\n    display: none;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-server-stats.css",
    "content": ".widget-type-server-info {\n    position: relative;\n}\n\n.server + .server {\n    margin-top: 3rem;\n}\n\n.server {\n    gap: 1rem;\n    display: flex;\n    flex-direction: column;\n}\n\n.server-info {\n    align-items: center;\n    display: flex;\n    justify-content: space-between;\n    gap: 1.5rem;\n    flex-shrink: 1;\n    min-width: 0;\n}\n\n.server-details {\n    min-width: 0;\n}\n\n.server-icon {\n    height: 3rem;\n    width: 3rem;\n}\n\n.server-spicy-cpu-icon {\n    height: 1em;\n    align-self: center;\n    margin-left: 0.4em;\n    margin-bottom: 0.2rem;\n}\n\n.server-stats {\n    display: flex;\n    gap: 1.5rem;\n    margin-top: 0.5rem;\n}\n\n.server-stat-unavailable {\n    opacity: 0.5;\n}\n\n@container widget (min-width: 650px) {\n    .server {\n        gap: 2rem;\n        flex-direction: row;\n        align-items: center;\n    }\n\n    .server + .server {\n        margin-top: 1rem;\n    }\n\n    .server-info {\n        flex-direction: row-reverse;\n        justify-content: unset;\n        margin-right: auto;\n        z-index: 1;\n    }\n\n    .server-stats {\n        flex-direction: row;\n        justify-content: right;\n        min-width: 450px;\n        margin-top: 0;\n        gap: 2rem;\n        padding-bottom: 0.8rem;\n        z-index: 1;\n    }\n\n    .server-stats > * {\n        max-width: 200px;\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-todo.css",
    "content": ".todo-widget {\n    padding-top: 4rem;\n}\n\n.todo-plus-icon {\n    --icon-color: var(--color-text-subdue);\n    position: relative;\n    width: 1.4rem;\n    height: 1.4rem;\n}\n\n.todo-plus-icon::before, .todo-plus-icon::after {\n    content: \"\";\n    position: absolute;\n    background-color: var(--icon-color);\n    transition: background-color .2s;\n}\n\n.todo-plus-icon::before {\n    width: 2px;\n    inset-block: 0.2rem;\n    left: 50%;\n    transform: translateX(-50%);\n}\n\n.todo-plus-icon::after {\n    height: 2px;\n    inset-inline: 0.2rem;\n    top: 50%;\n    transform: translateY(-50%);\n}\n\n.todo-input textarea::placeholder {\n    color: var(--color-text-base-muted);\n}\n\n.todo-input {\n    position: relative;\n    color: var(--color-text-highlight);\n}\n\n.todo-input:focus-within .todo-plus-icon {\n    --icon-color: var(--color-text-base);\n}\n\n.todo-item {\n    transform-origin: center;\n    padding: 0.5rem 0;\n}\n\n.todo-item-checkbox {\n    -webkit-appearance: none;\n    appearance: none;\n    border: 2px solid var(--color-text-subdue);\n    width: 1.4rem;\n    height: 1.4rem;\n    position: relative;\n    cursor: pointer;\n    border-radius: 0.3rem;\n    transition: border-color .2s;\n}\n\n.todo-item-checkbox::before {\n    content: \"\";\n    inset: -1rem;\n    position: absolute;\n}\n\n.todo-item-checkbox::after {\n    content: '';\n    position: absolute;\n    inset: 0.3rem;\n    border-radius: 0.1rem;\n    opacity: 0;\n    transition: opacity .2s;\n}\n\n.todo-item-checkbox:checked::after {\n    background: var(--color-primary);\n    opacity: 1;\n}\n\n.todo-item-checkbox:focus-visible {\n    outline: none;\n    border-color: var(--color-primary);\n}\n\n.todo-item-text {\n    color: var(--color-text-base);\n    transition: color .35s;\n}\n\n.todo-item-text:focus {\n    color: var(--color-text-highlight);\n}\n\n.todo-item-drag-handle {\n    position: absolute;\n    top: -0.5rem;\n    inset-inline: 0;\n    height: 1rem;\n    cursor: grab;\n}\n\n.todo-item.is-being-dragged .todo-item-drag-handle {\n    height: 3rem;\n    top: -1.5rem;\n}\n\n.todo-item:has(.todo-item-checkbox:checked) .todo-item-text {\n    text-decoration: line-through;\n    color: var(--color-text-subdue);\n}\n\n.todo-item-delete {\n    width: 1.5rem;\n    height: 1.5rem;\n    opacity: 0;\n    transition: opacity .2s;\n    outline-offset: .5rem;\n}\n\n.todo-item:hover .todo-item-delete, .todo-item:focus-within .todo-item-delete {\n    opacity: 1;\n}\n\n.todo-item.is-being-dragged .todo-item-delete {\n    opacity: 0;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-twitch.css",
    "content": ".twitch-category-thumbnail {\n    width: 5rem;\n    aspect-ratio: 3 / 4;\n    border-radius: var(--border-radius);\n}\n\n.twitch-channel-avatar {\n    aspect-ratio: 1;\n    border-radius: 50%;\n}\n\n.twitch-channel-avatar-container {\n    width: 4.4rem;\n    height: 4.4rem;\n    border: 2px solid var(--color-text-subdue);\n    padding: 2px;\n    border-radius: 50%;\n    position: relative;\n    flex-shrink: 0;\n}\n\n.twitch-channel-live .twitch-channel-avatar-container {\n    border: 2px solid var(--color-positive);\n    margin-bottom: 1rem;\n}\n\n.twitch-channel-live .twitch-channel-avatar-container::after {\n    content: 'LIVE';\n    position: absolute;\n    background: var(--color-positive);\n    color: var(--color-widget-background);\n    font-size: var(--font-size-h6);\n    left: 50%;\n    bottom: -35%;\n    border-radius: var(--border-radius);\n    padding-inline: 0.3rem;\n    transform: translate(-50%);\n    border: 2px solid var(--color-widget-background);\n}\n\n.twitch-stream-preview {\n    max-width: 100%;\n    width: 400px;\n    aspect-ratio: 16 / 9;\n    border-radius: var(--border-radius);\n    object-fit: cover;\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-videos.css",
    "content": ".video-thumbnail {\n    width: 100%;\n    aspect-ratio: 16 / 8.9;\n    object-fit: cover;\n    border-radius: var(--border-radius) var(--border-radius) 0 0;\n}\n\n.video-horizontal-list-thumbnail {\n    height: 4rem;\n    aspect-ratio: 16 / 8.9;\n    object-fit: cover;\n    border-radius: var(--border-radius);\n}\n"
  },
  {
    "path": "internal/glance/static/css/widget-weather.css",
    "content": ".weather-column {\n    position: relative;\n    display: flex;\n    align-items: center;\n    justify-content: end;\n    flex-direction: column;\n    width: calc(100% / 12);\n    padding-top: 3px;\n}\n\n.weather-column-value, .weather-columns:hover .weather-column-value {\n    font-size: 13px;\n    color: var(--color-text-highlight);\n    letter-spacing: -0.1rem;\n    margin-right: 0.1rem;\n    position: relative;\n    margin-bottom: 0.3rem;\n    opacity: 0;\n    transform: translateY(0.5rem);\n    transition: opacity .2s, transform .2s;\n    user-select: none;\n}\n\n.weather-column-current .weather-column-value, .weather-column:hover .weather-column-value {\n    opacity: 1;\n    transform: translateY(0);\n}\n\n.weather-column-value::after {\n    position: absolute;\n    content: '°';\n    left: 100%;\n    color: var(--color-text-subdue);\n}\n\n.weather-column-value.weather-column-value-negative::before {\n    position: absolute;\n    content: '-';\n    right: 100%;\n}\n\n.weather-bar, .weather-columns:hover .weather-bar {\n    height: calc(20px + var(--weather-bar-height) * 40px);\n    width: 6px;\n    background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 18%)));\n    border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 24%)));\n    border-bottom: 0;\n    border-radius: 6px 6px 0 0;\n    mask-image: linear-gradient(0deg, transparent 0, #000 10px);\n    -webkit-mask-image: linear-gradient(0deg, transparent 0, #000 10px);\n    transition: background-color .2s, border-color .2s, width .2s;\n}\n\n.weather-column-current .weather-bar, .weather-column:hover .weather-bar {\n    width: 10px;\n    background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%)));\n    border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 50%)));\n}\n\n.weather-column-rain {\n    position: absolute;\n    inset: 0;\n    bottom: 20%;\n    overflow: hidden;\n    mask-image: linear-gradient(0deg, transparent 40%, #000);\n    -webkit-mask-image: linear-gradient(0deg, transparent 40%, #000);\n}\n\n.weather-column-rain::before {\n    content: '';\n    position: absolute;\n    /* TODO: figure out a way to make it look continuous between columns, right now */\n    /* depending on the width of the page the rain inside two columns next to each other */\n    /* can overlap and look bad */\n    background: radial-gradient(circle at 4px 4px, hsl(200, 90%, 70%, 0.4) 1px, transparent 0);\n    background-size: 8px 8px;\n    transform: rotate(45deg) translate(-50%, 25%);\n    height: 130%;\n    aspect-ratio: 1;\n    left: 55%;\n}\n\n.weather-column:nth-child(3) .weather-column-time,\n.weather-column:nth-child(7) .weather-column-time,\n.weather-column:nth-child(11) .weather-column-time {\n    opacity: 1;\n    transform: translateY(0);\n}\n\n.weather-column-time, .weather-columns:hover .weather-column-time {\n    margin-top: 0.3rem;\n    font-size: var(--font-size-h6);\n    opacity: 0;\n    transform: translateY(-0.5rem);\n    transition: opacity .2s, transform .2s;\n    user-select: none;\n}\n\n.weather-column:hover .weather-column-time {\n    opacity: 1;\n    transform: translateY(0);\n}\n\n.weather-column-daylight {\n    position: absolute;\n    inset: 0;\n    background: linear-gradient(0deg, transparent 30px, hsl(50, 50%, 30%, 0.2));\n}\n\n.weather-column-daylight-sunrise {\n    border-radius: 20px 0 0 0;\n}\n\n.weather-column-daylight-sunset {\n    border-radius: 0 20px 0 0;\n}\n\n.location-icon {\n    width: 0.8em;\n    height: 0.8em;\n    border-radius: 0 50% 50% 50%;\n    background-color: currentColor;\n    transform: rotate(225deg) translate(.1em, .1em);\n    position: relative;\n    flex-shrink: 0;\n}\n\n.location-icon::after {\n    content: '';\n    position: absolute;\n    z-index: 2;\n    width: .4em;\n    height: .4em;\n    border-radius: 50%;\n    background-color: var(--color-widget-background);\n    top: 50%;\n    left: 50%;\n    transform: translate(-50%, -50%);\n}\n"
  },
  {
    "path": "internal/glance/static/css/widgets.css",
    "content": "@import \"widget-bookmarks.css\";\n@import \"widget-calendar.css\";\n@import \"widget-clock.css\";\n@import \"widget-dns-stats.css\";\n@import \"widget-docker-containers.css\";\n@import \"widget-group.css\";\n@import \"widget-markets.css\";\n@import \"widget-monitor.css\";\n@import \"widget-reddit.css\";\n@import \"widget-releases.css\";\n@import \"widget-rss.css\";\n@import \"widget-search.css\";\n@import \"widget-server-stats.css\";\n@import \"widget-twitch.css\";\n@import \"widget-videos.css\";\n@import \"widget-weather.css\";\n@import \"widget-todo.css\";\n\n@import \"forum-posts.css\";\n\n.widget-error-header {\n    display: flex;\n    align-items: center;\n    justify-content: space-between;\n    position: relative;\n    margin-bottom: 1.8rem;\n    z-index: 1;\n}\n\n.widget-error-header::before {\n    content: '';\n    position: absolute;\n    inset: calc(0rem - (var(--widget-content-vertical-padding) / 2)) calc(0rem - (var(--widget-content-horizontal-padding) / 2));\n    background: var(--color-negative);\n    opacity: 0.05;\n    border-radius: var(--border-radius);\n    z-index: -1;\n}\n\n.widget-error-icon {\n    width: 2.4rem;\n    height: 2.4rem;\n    flex-shrink: 0;\n    stroke: var(--color-negative);\n    opacity: 0.6;\n}\n\n.head-widgets {\n    margin-bottom: var(--widget-gap);\n}\n\n.widget-content {\n    container-type: inline-size;\n    container-name: widget;\n}\n\n.widget-content:not(.widget-content-frameless) {\n    padding: var(--widget-content-padding);\n}\n\n.widget-content:not(.widget-content-frameless), .widget-content-frame {\n    background: var(--color-widget-background);\n    border-radius: var(--border-radius);\n    border: 1px solid var(--color-widget-content-border);\n    box-shadow: 0px 3px 0px 0px hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl)) - 0.5%));\n}\n\n.widget-header {\n    padding: 0 calc(var(--widget-content-horizontal-padding) + 1px);\n    font-size: var(--font-size-h4);\n    margin-bottom: 0.9rem;\n    display: flex;\n    align-items: center;\n    gap: 1rem;\n}\n\n.widget-beta-icon {\n    width: 1.6rem;\n    height: 1.6rem;\n    flex-shrink: 0;\n    transition: transform .45s, opacity .45s, stroke .45s;\n    opacity: 0.7;\n}\n\n.widget-beta-icon:hover, .widget-header .popover-active > .widget-beta-icon {\n    fill: var(--color-text-highlight);\n    transform: translateY(-10%) scale(1.3);\n    opacity: 1;\n}\n\n.widget + .widget {\n    margin-top: var(--widget-gap);\n}\n"
  },
  {
    "path": "internal/glance/static/js/animations.js",
    "content": "export const easeOutQuint = 'cubic-bezier(0.22, 1, 0.36, 1)';\n\nexport function directions(anim, opt, ...dirs) {\n    return dirs.map(dir => anim({ direction: dir, ...opt }));\n}\n\nexport function slideFade({\n    direction = 'left',\n    fill = 'backwards',\n    duration = 200,\n    distance = '1rem',\n    easing = 'ease',\n    offset = 0,\n}) {\n    const axis = direction === 'left' || direction === 'right' ? 'X' : 'Y';\n    const negative = direction === 'left' || direction === 'up' ? '-' : '';\n    const amount = negative + distance;\n\n    return {\n        keyframes: [\n            {\n                offset: offset,\n                opacity: 0,\n                transform: `translate${axis}(${amount})`,\n            }\n        ],\n        options: {\n            duration: duration,\n            easing: easing,\n            fill: fill,\n        },\n    };\n}\n\n\nexport function animateReposition(\n    element,\n    onAnimEnd,\n    animOptions = { duration: 400, easing: easeOutQuint }\n) {\n    const rectBefore = element.getBoundingClientRect();\n\n    return () => {\n        const rectAfter = element.getBoundingClientRect();\n        const offsetY = rectBefore.y - rectAfter.y;\n        const offsetX = rectBefore.x - rectAfter.x;\n\n        element.animate({\n            keyframes: [\n                { transform: `translate(${offsetX}px, ${offsetY}px)` },\n                { transform: 'none' }\n            ],\n            options: animOptions\n        }, onAnimEnd);\n\n        return rectAfter;\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/js/calendar.js",
    "content": "import { directions, easeOutQuint, slideFade } from \"./animations.js\";\nimport { elem, repeat, text } from \"./templating.js\";\n\nconst FULL_MONTH_SLOTS = 7*6;\nconst WEEKDAY_ABBRS = [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"];\nconst MONTH_NAMES = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\nconst leftArrowSvg = `<svg stroke=\"var(--color-text-base)\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" xmlns=\"http://www.w3.org/2000/svg\">\n  <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 19.5 8.25 12l7.5-7.5\" />\n</svg>`;\n\nconst rightArrowSvg = `<svg stroke=\"var(--color-text-base)\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" xmlns=\"http://www.w3.org/2000/svg\">\n  <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"m8.25 4.5 7.5 7.5-7.5 7.5\" />\n</svg>`;\n\nconst undoArrowSvg = `<svg stroke=\"var(--color-text-base)\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" xmlns=\"http://www.w3.org/2000/svg\">\n  <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 15 3 9m0 0 6-6M3 9h12a6 6 0 0 1 0 12h-3\" />\n</svg>`;\n\nconst [datesExitLeft, datesExitRight] = directions(\n    slideFade, { distance: \"2rem\", duration: 120, offset: 1 },\n    \"left\", \"right\"\n);\n\nconst [datesEntranceLeft, datesEntranceRight] = directions(\n    slideFade, { distance: \"0.8rem\", duration: 500, easing: easeOutQuint },\n    \"left\", \"right\"\n);\n\nconst undoEntrance = slideFade({ direction: \"left\", distance: \"100%\", duration: 300 });\n\nexport default function(element) {\n    element.swapWith(Calendar(\n        Number(element.dataset.firstDayOfWeek ?? 1)\n    ));\n}\n\n// TODO: when viewing the previous/next month, display the current date if it's within the spill-over days\nfunction Calendar(firstDay) {\n    let header, dates;\n    let advanceTimeTicker;\n    let now = new Date();\n    let activeDate;\n\n    const update = (newDate) => {\n        header.component.update(now, newDate);\n        dates.component.update(now, newDate);\n        activeDate = newDate;\n    };\n\n    const autoAdvanceNow = () => {\n        advanceTimeTicker = setTimeout(() => {\n            // TODO: don't auto advance if looking at a different month\n            update(now = new Date());\n            autoAdvanceNow();\n        }, msTillNextDay());\n    };\n\n    const adjacentMonth = (dir) => new Date(activeDate.getFullYear(), activeDate.getMonth() + dir, 1);\n    const nextClicked = () => update(adjacentMonth(1));\n    const prevClicked = () => update(adjacentMonth(-1));\n    const undoClicked = () => update(now);\n\n    const calendar = elem().classes(\"calendar\").append(\n        header = Header(nextClicked, prevClicked, undoClicked),\n        dates = Dates(firstDay)\n    );\n\n    update(now);\n    autoAdvanceNow();\n\n    return calendar.component({\n        suspend: () => clearTimeout(advanceTimeTicker)\n    });\n}\n\nfunction Header(nextClicked, prevClicked, undoClicked) {\n    let month, monthNumber, year, undo;\n    const button = () => elem(\"button\").classes(\"calendar-header-button\");\n\n    const monthAndYear = elem().classes(\"size-h2\", \"color-highlight\").append(\n        month = text(),\n        \" \",\n        year = elem(\"span\").classes(\"size-h3\"),\n        undo = button()\n            .hide()\n            .classes(\"calendar-undo-button\")\n            .attr(\"title\", \"Back to current month\")\n            .on(\"click\", undoClicked)\n            .html(undoArrowSvg)\n    );\n\n    const monthSwitcher = elem()\n        .classes(\"flex\", \"gap-7\", \"items-center\")\n        .append(\n            button()\n                .attr(\"title\", \"Previous month\")\n                .on(\"click\", prevClicked)\n                .html(leftArrowSvg),\n            monthNumber = elem()\n                .classes(\"color-highlight\")\n                .styles({ marginTop: \"0.1rem\" }),\n            button()\n                .attr(\"title\", \"Next month\")\n                .on(\"click\", nextClicked)\n                .html(rightArrowSvg),\n        );\n\n    return elem().classes(\"flex\", \"justify-between\", \"items-center\").append(\n        monthAndYear,\n        monthSwitcher\n    ).component({\n        update: function (now, newDate) {\n            month.text(MONTH_NAMES[newDate.getMonth()]);\n            year.text(newDate.getFullYear());\n            const m = newDate.getMonth() + 1;\n            monthNumber.text((m < 10 ? \"0\" : \"\") + m);\n\n            if (!datesWithinSameMonth(now, newDate)) {\n                if (undo.isHidden()) undo.show().animate(undoEntrance);\n            } else {\n                undo.hide();\n            }\n\n            return this;\n        }\n    });\n}\n\nfunction Dates(firstDay) {\n    let dates, lastRenderedDate;\n\n    const updateFullMonth = function(now, newDate) {\n        const firstWeekday = new Date(newDate.getFullYear(), newDate.getMonth(), 1).getDay();\n        const previousMonthSpilloverDays = (firstWeekday - firstDay + 7) % 7 || 7;\n        const currentMonthDays = daysInMonth(newDate.getFullYear(), newDate.getMonth());\n        const nextMonthSpilloverDays = FULL_MONTH_SLOTS - (previousMonthSpilloverDays + currentMonthDays);\n        const previousMonthDays = daysInMonth(newDate.getFullYear(), newDate.getMonth() - 1)\n        const isCurrentMonth = datesWithinSameMonth(now, newDate);\n        const currentDate = now.getDate();\n\n        let children = dates.children;\n        let index = 0;\n\n        for (let i = 0; i < FULL_MONTH_SLOTS; i++) {\n            children[i].clearClasses(\"calendar-spillover-date\", \"calendar-current-date\");\n        }\n\n        for (let i = 0; i < previousMonthSpilloverDays; i++, index++) {\n            children[index].classes(\"calendar-spillover-date\").text(\n                previousMonthDays - previousMonthSpilloverDays + i + 1\n            )\n        }\n\n        for (let i = 1; i <= currentMonthDays; i++, index++) {\n            children[index]\n                .classesIf(isCurrentMonth && i === currentDate, \"calendar-current-date\")\n                .text(i);\n        }\n\n        for (let i = 0; i < nextMonthSpilloverDays; i++, index++) {\n            children[index].classes(\"calendar-spillover-date\").text(i + 1);\n        }\n\n        lastRenderedDate = newDate;\n    };\n\n    const update = function(now, newDate) {\n        if (lastRenderedDate === undefined || datesWithinSameMonth(newDate, lastRenderedDate)) {\n            updateFullMonth(now, newDate);\n            return;\n        }\n\n        const next = newDate > lastRenderedDate;\n        dates.animateUpdate(\n            () => updateFullMonth(now, newDate),\n            next ? datesExitLeft : datesExitRight,\n            next ? datesEntranceRight : datesEntranceLeft,\n        );\n    }\n\n    return elem().append(\n        elem().classes(\"calendar-dates\", \"margin-top-15\").append(\n            ...repeat(7, (i) => elem().classes(\"size-h6\", \"color-subdue\").text(\n                WEEKDAY_ABBRS[(firstDay + i) % 7]\n            ))\n        ),\n\n        dates = elem().classes(\"calendar-dates\", \"margin-top-3\").append(\n            ...elem().classes(\"calendar-date\").duplicate(FULL_MONTH_SLOTS)\n        )\n    ).component({ update });\n}\n\nfunction datesWithinSameMonth(d1, d2) {\n    return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();\n}\n\nfunction daysInMonth(year, month) {\n    return new Date(year, month + 1, 0).getDate();\n}\n\nfunction msTillNextDay(now) {\n    now = now || new Date();\n\n    return 86_400_000 - (\n      now.getMilliseconds() +\n      now.getSeconds() * 1000 +\n      now.getMinutes() * 60_000 +\n      now.getHours() * 3_600_000\n    );\n}\n"
  },
  {
    "path": "internal/glance/static/js/login.js",
    "content": "import { find } from \"./templating.js\";\n\nconst AUTH_ENDPOINT = pageData.baseURL + \"/api/authenticate\";\n\nconst showPasswordSVG = `<svg class=\"form-input-icon\" stroke=\"var(--color-text-base)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M3.98 8.223A10.477 10.477 0 0 0 1.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.451 10.451 0 0 1 12 4.5c4.756 0 8.773 3.162 10.065 7.498a10.522 10.522 0 0 1-4.293 5.774M6.228 6.228 3 3m3.228 3.228 3.65 3.65m7.894 7.894L21 21m-3.228-3.228-3.65-3.65m0 0a3 3 0 1 0-4.243-4.243m4.242 4.242L9.88 9.88\" />\n</svg>`;\n\nconst hidePasswordSVG = `<svg class=\"form-input-icon\" stroke=\"var(--color-text-base)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z\" />\n    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z\" />\n</svg>`;\n\nconst container = find(\"#login-container\");\nconst usernameInput = find(\"#username\");\nconst passwordInput = find(\"#password\");\nconst errorMessage = find(\"#error-message\");\nconst loginButton = find(\"#login-button\");\nconst toggleVisibilityButton = find(\"#toggle-password-visibility\");\n\nconst state = {\n    lastUsername: \"\",\n    lastPassword: \"\",\n    isLoading: false,\n    isRateLimited: false\n};\n\nconst lang = {\n    showPassword: \"Show password\",\n    hidePassword: \"Hide password\",\n    incorrectCredentials: \"Incorrect username or password\",\n    rateLimited: \"Too many login attempts, try again in a few minutes\",\n    unknownError: \"An error occurred, please try again\",\n};\n\ncontainer.clearStyles(\"display\");\nsetTimeout(() => usernameInput.focus(), 200);\n\ntoggleVisibilityButton\n    .html(showPasswordSVG)\n    .attr(\"title\", lang.showPassword)\n    .on(\"click\", function() {\n        if (passwordInput.type === \"password\") {\n            passwordInput.type = \"text\";\n            toggleVisibilityButton.html(hidePasswordSVG).attr(\"title\", lang.hidePassword);\n            return;\n        }\n\n        passwordInput.type = \"password\";\n        toggleVisibilityButton.html(showPasswordSVG).attr(\"title\", lang.showPassword);\n    });\n\nfunction enableLoginButtonIfCriteriaMet() {\n    const usernameValue = usernameInput.value.trim();\n    const passwordValue = passwordInput.value.trim();\n\n    const usernameValid = usernameValue.length >= 3;\n    const passwordValid = passwordValue.length >= 6;\n\n    const isUsingLastCredentials =\n           usernameValue === state.lastUsername\n        && passwordValue === state.lastPassword;\n\n    loginButton.disabled = !(\n           usernameValid\n        && passwordValid\n        && !isUsingLastCredentials\n        && !state.isLoading\n        && !state.isRateLimited\n    );\n}\n\nusernameInput.on(\"input\", enableLoginButtonIfCriteriaMet);\npasswordInput.on(\"input\", enableLoginButtonIfCriteriaMet);\n\nasync function handleLoginAttempt() {\n    state.lastUsername = usernameInput.value;\n    state.lastPassword = passwordInput.value;\n    errorMessage.text(\"\");\n\n    loginButton.disable();\n    state.isLoading = true;\n\n    const response = await fetch(AUTH_ENDPOINT, {\n        method: \"POST\",\n        headers: {\n            \"Content-Type\": \"application/json\"\n        },\n        body: JSON.stringify({\n            username: usernameInput.value,\n            password: passwordInput.value\n        }),\n    });\n\n    state.isLoading = false;\n    if (response.status === 200) {\n        setTimeout(() => { window.location.href = pageData.baseURL + \"/\"; }, 300);\n\n        container.animate({\n            keyframes: [{ offset: 1, transform: \"scale(0.95)\", opacity: 0 }],\n            options: { duration: 300, easing: \"ease\", fill: \"forwards\" }}\n        );\n\n        find(\"footer\")?.animate({\n            keyframes: [{ offset: 1, opacity: 0 }],\n            options: { duration: 300, easing: \"ease\", fill: \"forwards\", delay: 50 }\n        });\n    } else if (response.status === 401) {\n        errorMessage.text(lang.incorrectCredentials);\n        passwordInput.focus();\n    } else if (response.status === 429) {\n        errorMessage.text(lang.rateLimited);\n        state.isRateLimited = true;\n        const retryAfter = response.headers.get(\"Retry-After\") || 30;\n        setTimeout(() => {\n            state.lastUsername = \"\";\n            state.lastPassword = \"\";\n            state.isRateLimited = false;\n\n            enableLoginButtonIfCriteriaMet();\n        }, retryAfter * 1000);\n    } else {\n        errorMessage.text(lang.unknownError);\n        passwordInput.focus();\n    }\n}\n\nloginButton.disable().on(\"click\", handleLoginAttempt);\n"
  },
  {
    "path": "internal/glance/static/js/masonry.js",
    "content": "\nimport { clamp } from \"./utils.js\";\n\nexport function setupMasonries() {\n    const masonryContainers = document.getElementsByClassName(\"masonry\");\n\n    for (let i = 0; i < masonryContainers.length; i++) {\n        const container = masonryContainers[i];\n\n        const options = {\n            minColumnWidth: container.dataset.minColumnWidth || 330,\n            maxColumns: container.dataset.maxColumns || 6,\n        };\n\n        const items = Array.from(container.children);\n        let previousColumnsCount = 0;\n\n        const render = function() {\n            const columnsCount = clamp(\n                Math.floor(container.offsetWidth / options.minColumnWidth),\n                1,\n                Math.min(options.maxColumns, items.length)\n            );\n\n            if (columnsCount === previousColumnsCount) {\n                return;\n            } else {\n                container.textContent = \"\";\n                previousColumnsCount = columnsCount;\n            }\n\n            const columnsFragment = document.createDocumentFragment();\n\n            for (let i = 0; i < columnsCount; i++) {\n                const column = document.createElement(\"div\");\n                column.className = \"masonry-column\";\n                columnsFragment.append(column);\n            }\n\n            for (let i = 0; i < items.length; i++) {\n                columnsFragment.children[i % columnsCount].appendChild(items[i]);\n            }\n\n            container.append(columnsFragment);\n        };\n\n        const observer = new ResizeObserver(() => requestAnimationFrame(render));\n        observer.observe(container);\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/js/page.js",
    "content": "import { setupPopovers } from './popover.js';\nimport { setupMasonries } from './masonry.js';\nimport { throttledDebounce, isElementVisible, openURLInNewTab } from './utils.js';\nimport { elem, find, findAll } from './templating.js';\n\nasync function fetchPageContent(pageData) {\n    // TODO: handle non 200 status codes/time outs\n    // TODO: add retries\n    const response = await fetch(`${pageData.baseURL}/api/pages/${pageData.slug}/content/`);\n    const content = await response.text();\n\n    return content;\n}\n\nfunction setupCarousels() {\n    const carouselElements = document.getElementsByClassName(\"carousel-container\");\n\n    if (carouselElements.length == 0) {\n        return;\n    }\n\n    for (let i = 0; i < carouselElements.length; i++) {\n        const carousel = carouselElements[i];\n        carousel.classList.add(\"show-right-cutoff\");\n        const itemsContainer = carousel.getElementsByClassName(\"carousel-items-container\")[0];\n\n        const determineSideCutoffs = () => {\n            if (itemsContainer.scrollLeft != 0) {\n                carousel.classList.add(\"show-left-cutoff\");\n            } else {\n                carousel.classList.remove(\"show-left-cutoff\");\n            }\n\n            if (Math.ceil(itemsContainer.scrollLeft) + itemsContainer.clientWidth < itemsContainer.scrollWidth) {\n                carousel.classList.add(\"show-right-cutoff\");\n            } else {\n                carousel.classList.remove(\"show-right-cutoff\");\n            }\n        }\n\n        const determineSideCutoffsRateLimited = throttledDebounce(determineSideCutoffs, 20, 100);\n\n        itemsContainer.addEventListener(\"scroll\", determineSideCutoffsRateLimited);\n        window.addEventListener(\"resize\", determineSideCutoffsRateLimited);\n\n        afterContentReady(determineSideCutoffs);\n    }\n}\n\nconst minuteInSeconds = 60;\nconst hourInSeconds = minuteInSeconds * 60;\nconst dayInSeconds = hourInSeconds * 24;\nconst monthInSeconds = dayInSeconds * 30.4;\nconst yearInSeconds = dayInSeconds * 365;\n\nfunction timestampToRelativeTime(timestamp) {\n    let delta = Math.round((Date.now() / 1000) - timestamp);\n    let prefix = \"\";\n\n    if (delta < 0) {\n        delta = -delta;\n        prefix = \"in \";\n    }\n\n    if (delta < minuteInSeconds) {\n        return prefix + \"1m\";\n    }\n    if (delta < hourInSeconds) {\n        return prefix + Math.floor(delta / minuteInSeconds) + \"m\";\n    }\n    if (delta < dayInSeconds) {\n        return prefix + Math.floor(delta / hourInSeconds) + \"h\";\n    }\n    if (delta < monthInSeconds) {\n        return prefix + Math.floor(delta / dayInSeconds) + \"d\";\n    }\n    if (delta < yearInSeconds) {\n        return prefix + Math.floor(delta / monthInSeconds) + \"mo\";\n    }\n\n    return prefix + Math.floor(delta / yearInSeconds) + \"y\";\n}\n\nfunction updateRelativeTimeForElements(elements)\n{\n    for (let i = 0; i < elements.length; i++)\n    {\n        const element = elements[i];\n        const timestamp = element.dataset.dynamicRelativeTime;\n\n        if (timestamp === undefined)\n            continue\n\n        element.textContent = timestampToRelativeTime(timestamp);\n    }\n}\n\nfunction setupSearchBoxes() {\n    const searchWidgets = document.getElementsByClassName(\"search\");\n\n    if (searchWidgets.length == 0) {\n        return;\n    }\n\n    for (let i = 0; i < searchWidgets.length; i++) {\n        const widget = searchWidgets[i];\n        const defaultSearchUrl = widget.dataset.defaultSearchUrl;\n        const target = widget.dataset.target || \"_blank\";\n        const newTab = widget.dataset.newTab === \"true\";\n        const inputElement = widget.getElementsByClassName(\"search-input\")[0];\n        const bangElement = widget.getElementsByClassName(\"search-bang\")[0];\n        const bangs = widget.querySelectorAll(\".search-bangs > input\");\n        const bangsMap = {};\n        const kbdElement = widget.getElementsByTagName(\"kbd\")[0];\n        let currentBang = null;\n        let lastQuery = \"\";\n\n        for (let j = 0; j < bangs.length; j++) {\n            const bang = bangs[j];\n            bangsMap[bang.dataset.shortcut] = bang;\n        }\n\n        const handleKeyDown = (event) => {\n            if (event.key == \"Escape\") {\n                inputElement.blur();\n                return;\n            }\n\n            if (event.key == \"Enter\") {\n                const input = inputElement.value.trim();\n                let query;\n                let searchUrlTemplate;\n\n                if (currentBang != null) {\n                    query = input.slice(currentBang.dataset.shortcut.length + 1);\n                    searchUrlTemplate = currentBang.dataset.url;\n                } else {\n                    query = input;\n                    searchUrlTemplate = defaultSearchUrl;\n                }\n                if (query.length == 0 && currentBang == null) {\n                    return;\n                }\n\n                const url = searchUrlTemplate.replace(\"!QUERY!\", encodeURIComponent(query));\n\n                if (newTab && !event.ctrlKey || !newTab && event.ctrlKey) {\n                    window.open(url, target).focus();\n                } else {\n                    window.location.href = url;\n                }\n\n                lastQuery = query;\n                inputElement.value = \"\";\n\n                return;\n            }\n\n            if (event.key == \"ArrowUp\" && lastQuery.length > 0) {\n                inputElement.value = lastQuery;\n                return;\n            }\n        };\n\n        const changeCurrentBang = (bang) => {\n            currentBang = bang;\n            bangElement.textContent = bang != null ? bang.dataset.title : \"\";\n        }\n\n        const handleInput = (event) => {\n            const value = event.target.value.trim();\n            if (value in bangsMap) {\n                changeCurrentBang(bangsMap[value]);\n                return;\n            }\n\n            const words = value.split(\" \");\n            if (words.length >= 2 && words[0] in bangsMap) {\n                changeCurrentBang(bangsMap[words[0]]);\n                return;\n            }\n\n            changeCurrentBang(null);\n        };\n\n        inputElement.addEventListener(\"focus\", () => {\n            document.addEventListener(\"keydown\", handleKeyDown);\n            document.addEventListener(\"input\", handleInput);\n        });\n        inputElement.addEventListener(\"blur\", () => {\n            document.removeEventListener(\"keydown\", handleKeyDown);\n            document.removeEventListener(\"input\", handleInput);\n        });\n\n        document.addEventListener(\"keydown\", (event) => {\n            if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;\n            if (event.code != \"KeyS\") return;\n\n            inputElement.focus();\n            event.preventDefault();\n        });\n\n        kbdElement.addEventListener(\"mousedown\", () => {\n            requestAnimationFrame(() => inputElement.focus());\n        });\n    }\n}\n\nfunction setupDynamicRelativeTime() {\n    const elements = document.querySelectorAll(\"[data-dynamic-relative-time]\");\n    const updateInterval = 60 * 1000;\n    let lastUpdateTime = Date.now();\n\n    updateRelativeTimeForElements(elements);\n\n    const updateElementsAndTimestamp = () => {\n        updateRelativeTimeForElements(elements);\n        lastUpdateTime = Date.now();\n    };\n\n    const scheduleRepeatingUpdate = () => setInterval(updateElementsAndTimestamp, updateInterval);\n\n    if (document.hidden === undefined) {\n        scheduleRepeatingUpdate();\n        return;\n    }\n\n    let timeout = scheduleRepeatingUpdate();\n\n    document.addEventListener(\"visibilitychange\", () => {\n        if (document.hidden) {\n            clearTimeout(timeout);\n            return;\n        }\n\n        const delta = Date.now() - lastUpdateTime;\n\n        if (delta >= updateInterval) {\n            updateElementsAndTimestamp();\n            timeout = scheduleRepeatingUpdate();\n            return;\n        }\n\n        timeout = setTimeout(() => {\n            updateElementsAndTimestamp();\n            timeout = scheduleRepeatingUpdate();\n        }, updateInterval - delta);\n    });\n}\n\nfunction setupGroups() {\n    const groups = document.getElementsByClassName(\"widget-type-group\");\n\n    if (groups.length == 0) {\n        return;\n    }\n\n    for (let g = 0; g < groups.length; g++) {\n        const group = groups[g];\n        const titles = group.getElementsByClassName(\"widget-header\")[0].children;\n        const tabs = group.getElementsByClassName(\"widget-group-contents\")[0].children;\n        let current = 0;\n\n        for (let t = 0; t < titles.length; t++) {\n            const title = titles[t];\n\n            if (title.dataset.titleUrl !== undefined) {\n                title.addEventListener(\"mousedown\", (event) => {\n                    if (event.button != 1) {\n                        return;\n                    }\n\n                    openURLInNewTab(title.dataset.titleUrl, false);\n                    event.preventDefault();\n                });\n            }\n\n            title.addEventListener(\"click\", () => {\n                if (t == current) {\n                    if (title.dataset.titleUrl !== undefined) {\n                        openURLInNewTab(title.dataset.titleUrl);\n                    }\n\n                    return;\n                }\n\n                for (let i = 0; i < titles.length; i++) {\n                    titles[i].classList.remove(\"widget-group-title-current\");\n                    titles[i].setAttribute(\"aria-selected\", \"false\");\n                    tabs[i].classList.remove(\"widget-group-content-current\");\n                    tabs[i].setAttribute(\"aria-hidden\", \"true\");\n                }\n\n                if (current < t) {\n                    tabs[t].dataset.direction = \"right\";\n                } else {\n                    tabs[t].dataset.direction = \"left\";\n                }\n\n                current = t;\n\n                title.classList.add(\"widget-group-title-current\");\n                title.setAttribute(\"aria-selected\", \"true\");\n                tabs[t].classList.add(\"widget-group-content-current\");\n                tabs[t].setAttribute(\"aria-hidden\", \"false\");\n            });\n        }\n    }\n}\n\nfunction setupLazyImages() {\n    const images = document.querySelectorAll(\"img[loading=lazy]\");\n\n    if (images.length == 0) {\n        return;\n    }\n\n    function imageFinishedTransition(image) {\n        image.classList.add(\"finished-transition\");\n    }\n\n    afterContentReady(() => {\n        setTimeout(() => {\n            for (let i = 0; i < images.length; i++) {\n                const image = images[i];\n\n                if (image.complete) {\n                    image.classList.add(\"cached\");\n                    setTimeout(() => imageFinishedTransition(image), 1);\n                } else {\n                    // TODO: also handle error event\n                    image.addEventListener(\"load\", () => {\n                        image.classList.add(\"loaded\");\n                        setTimeout(() => imageFinishedTransition(image), 400);\n                    });\n                }\n            }\n        }, 1);\n    });\n}\n\nfunction attachExpandToggleButton(collapsibleContainer) {\n    const showMoreText = \"Show more\";\n    const showLessText = \"Show less\";\n\n    let expanded = false;\n    const button = document.createElement(\"button\");\n    const icon = document.createElement(\"span\");\n    icon.classList.add(\"expand-toggle-button-icon\");\n    const textNode = document.createTextNode(showMoreText);\n    button.classList.add(\"expand-toggle-button\");\n    button.append(textNode, icon);\n    button.addEventListener(\"click\", () => {\n        expanded = !expanded;\n\n        if (expanded) {\n            collapsibleContainer.classList.add(\"container-expanded\");\n            button.classList.add(\"container-expanded\");\n            textNode.nodeValue = showLessText;\n            return;\n        }\n\n        const topBefore = button.getClientRects()[0].top;\n\n        collapsibleContainer.classList.remove(\"container-expanded\");\n        button.classList.remove(\"container-expanded\");\n        textNode.nodeValue = showMoreText;\n\n        const topAfter = button.getClientRects()[0].top;\n\n        if (topAfter > 0)\n            return;\n\n        window.scrollBy({\n            top: topAfter - topBefore,\n            behavior: \"instant\"\n        });\n    });\n\n    collapsibleContainer.after(button);\n\n    return button;\n};\n\n\nfunction setupCollapsibleLists() {\n    const collapsibleLists = document.querySelectorAll(\".list.collapsible-container\");\n\n    if (collapsibleLists.length == 0) {\n        return;\n    }\n\n    for (let i = 0; i < collapsibleLists.length; i++) {\n        const list = collapsibleLists[i];\n\n        if (list.dataset.collapseAfter === undefined) {\n            continue;\n        }\n\n        const collapseAfter = parseInt(list.dataset.collapseAfter);\n\n        if (collapseAfter == -1) {\n            continue;\n        }\n\n        if (list.children.length <= collapseAfter) {\n            continue;\n        }\n\n        attachExpandToggleButton(list);\n\n        for (let c = collapseAfter; c < list.children.length; c++) {\n            const child = list.children[c];\n            child.classList.add(\"collapsible-item\");\n            child.style.animationDelay = ((c - collapseAfter) * 20).toString() + \"ms\";\n        }\n    }\n}\n\nfunction setupCollapsibleGrids() {\n    const collapsibleGridElements = document.querySelectorAll(\".cards-grid.collapsible-container\");\n\n    if (collapsibleGridElements.length == 0) {\n        return;\n    }\n\n    for (let i = 0; i < collapsibleGridElements.length; i++) {\n        const gridElement = collapsibleGridElements[i];\n\n        if (gridElement.dataset.collapseAfterRows === undefined) {\n            continue;\n        }\n\n        const collapseAfterRows = parseInt(gridElement.dataset.collapseAfterRows);\n\n        if (collapseAfterRows == -1) {\n            continue;\n        }\n\n        const getCardsPerRow = () => {\n            return parseInt(getComputedStyle(gridElement).getPropertyValue('--cards-per-row'));\n        };\n\n        const button = attachExpandToggleButton(gridElement);\n\n        let cardsPerRow;\n\n        const resolveCollapsibleItems = () => requestAnimationFrame(() => {\n            const hideItemsAfterIndex = cardsPerRow * collapseAfterRows;\n\n            if (hideItemsAfterIndex >= gridElement.children.length) {\n                button.style.display = \"none\";\n            } else {\n                button.style.removeProperty(\"display\");\n            }\n\n            let row = 0;\n\n            for (let i = 0; i < gridElement.children.length; i++) {\n                const child = gridElement.children[i];\n\n                if (i >= hideItemsAfterIndex) {\n                    child.classList.add(\"collapsible-item\");\n                    child.style.animationDelay = (row * 40).toString() + \"ms\";\n\n                    if (i % cardsPerRow + 1 == cardsPerRow) {\n                        row++;\n                    }\n                } else {\n                    child.classList.remove(\"collapsible-item\");\n                    child.style.removeProperty(\"animation-delay\");\n                }\n            }\n        });\n\n        const observer = new ResizeObserver(() => {\n            if (!isElementVisible(gridElement)) {\n                return;\n            }\n\n            const newCardsPerRow = getCardsPerRow();\n\n            if (cardsPerRow == newCardsPerRow) {\n                return;\n            }\n\n            cardsPerRow = newCardsPerRow;\n            resolveCollapsibleItems();\n        });\n\n        afterContentReady(() => observer.observe(gridElement));\n    }\n}\n\nconst contentReadyCallbacks = [];\n\nfunction afterContentReady(callback) {\n    contentReadyCallbacks.push(callback);\n}\n\nconst weekDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n\nfunction makeSettableTimeElement(element, hourFormat) {\n    const fragment = document.createDocumentFragment();\n    const hour = document.createElement('span');\n    const minute = document.createElement('span');\n    const amPm = document.createElement('span');\n    fragment.append(hour, document.createTextNode(':'), minute);\n\n    if (hourFormat == '12h') {\n        fragment.append(document.createTextNode(' '), amPm);\n    }\n\n    element.append(fragment);\n\n    return (date) => {\n        const hours = date.getHours();\n\n        if (hourFormat == '12h') {\n            amPm.textContent = hours < 12 ? 'AM' : 'PM';\n            hour.textContent = hours % 12 || 12;\n        } else {\n            hour.textContent = hours < 10 ? '0' + hours : hours;\n        }\n\n        const minutes = date.getMinutes();\n        minute.textContent = minutes < 10 ? '0' + minutes : minutes;\n    };\n};\n\nfunction timeInZone(now, zone) {\n    let timeInZone;\n\n    try {\n        timeInZone = new Date(now.toLocaleString('en-US', { timeZone: zone }));\n    } catch (e) {\n        // TODO: indicate to the user that this is an invalid timezone\n        console.error(e);\n        timeInZone = now\n    }\n\n    const diffInMinutes = Math.round((timeInZone.getTime() - now.getTime()) / 1000 / 60);\n\n    return { time: timeInZone, diffInMinutes: diffInMinutes };\n}\n\nfunction zoneDiffText(diffInMinutes) {\n    if (diffInMinutes == 0) {\n        return \"\";\n    }\n\n    const sign = diffInMinutes < 0 ? \"-\" : \"+\";\n    const signText = diffInMinutes < 0 ? \"behind\" : \"ahead\";\n\n    diffInMinutes = Math.abs(diffInMinutes);\n\n    const hours = Math.floor(diffInMinutes / 60);\n    const minutes = diffInMinutes % 60;\n    const hourSuffix = hours == 1 ? \"\" : \"s\";\n\n    if (minutes == 0) {\n        return { text: `${sign}${hours}h`, title: `${hours} hour${hourSuffix} ${signText}` };\n    }\n\n    if (hours == 0) {\n        return { text: `${sign}${minutes}m`, title: `${minutes} minutes ${signText}` };\n    }\n\n    return { text: `${sign}${hours}h~`, title: `${hours} hour${hourSuffix} and ${minutes} minutes ${signText}` };\n}\n\nfunction setupClocks() {\n    const clocks = document.getElementsByClassName('clock');\n\n    if (clocks.length == 0) {\n        return;\n    }\n\n    const updateCallbacks = [];\n\n    for (var i = 0; i < clocks.length; i++) {\n        const clock = clocks[i];\n        const hourFormat = clock.dataset.hourFormat;\n        const localTimeContainer = clock.querySelector('[data-local-time]');\n        const localDateElement = localTimeContainer.querySelector('[data-date]');\n        const localWeekdayElement = localTimeContainer.querySelector('[data-weekday]');\n        const localYearElement = localTimeContainer.querySelector('[data-year]');\n        const timeZoneContainers = clock.querySelectorAll('[data-time-in-zone]');\n\n        const setLocalTime = makeSettableTimeElement(\n            localTimeContainer.querySelector('[data-time]'),\n            hourFormat\n        );\n\n        updateCallbacks.push((now) => {\n            setLocalTime(now);\n            localDateElement.textContent = now.getDate() + ' ' + monthNames[now.getMonth()];\n            localWeekdayElement.textContent = weekDayNames[now.getDay()];\n            localYearElement.textContent = now.getFullYear();\n        });\n\n        for (var z = 0; z < timeZoneContainers.length; z++) {\n            const timeZoneContainer = timeZoneContainers[z];\n            const diffElement = timeZoneContainer.querySelector('[data-time-diff]');\n\n            const setZoneTime = makeSettableTimeElement(\n                timeZoneContainer.querySelector('[data-time]'),\n                hourFormat\n            );\n\n            updateCallbacks.push((now) => {\n                const { time, diffInMinutes } = timeInZone(now, timeZoneContainer.dataset.timeInZone);\n                setZoneTime(time);\n                const { text, title } = zoneDiffText(diffInMinutes);\n                diffElement.textContent = text;\n                diffElement.title = title;\n            });\n        }\n    }\n\n    const updateClocks = () => {\n        const now = new Date();\n\n        for (var i = 0; i < updateCallbacks.length; i++)\n            updateCallbacks[i](now);\n\n        setTimeout(updateClocks, (60 - now.getSeconds()) * 1000);\n    };\n\n    updateClocks();\n}\n\nasync function setupCalendars() {\n    const elems = document.getElementsByClassName(\"calendar\");\n    if (elems.length == 0) return;\n\n    // TODO: implement prefetching, currently loads as a nasty waterfall of requests\n    const calendar = await import ('./calendar.js');\n\n    for (let i = 0; i < elems.length; i++)\n        calendar.default(elems[i]);\n}\n\nasync function setupTodos() {\n    const elems = Array.from(document.getElementsByClassName(\"todo\"));\n    if (elems.length == 0) return;\n\n    const todo = await import ('./todo.js');\n\n    for (let i = 0; i < elems.length; i++){\n        todo.default(elems[i]);\n    }\n}\n\nfunction setupTruncatedElementTitles() {\n    const elements = document.querySelectorAll(\".text-truncate, .single-line-titles .title, .text-truncate-2-lines, .text-truncate-3-lines\");\n\n    if (elements.length == 0) {\n        return;\n    }\n\n    for (let i = 0; i < elements.length; i++) {\n        const element = elements[i];\n        if (element.getAttribute(\"title\") === null)\n            element.title = element.innerText.trim().replace(/\\s+/g, \" \");\n    }\n}\n\nasync function changeTheme(key, onChanged) {\n    const themeStyleElem = find(\"#theme-style\");\n\n    const response = await fetch(`${pageData.baseURL}/api/set-theme/${key}`, {\n        method: \"POST\",\n    });\n\n    if (response.status != 200) {\n        alert(\"Failed to set theme: \" + response.statusText);\n        return;\n    }\n    const newThemeStyle = await response.text();\n\n    const tempStyle = elem(\"style\")\n        .html(\"* { transition: none !important; }\")\n        .appendTo(document.head);\n\n    themeStyleElem.html(newThemeStyle);\n    document.documentElement.setAttribute(\"data-theme\", key);\n    document.documentElement.setAttribute(\"data-scheme\", response.headers.get(\"X-Scheme\"));\n    typeof onChanged == \"function\" && onChanged();\n    setTimeout(() => { tempStyle.remove(); }, 10);\n}\n\nfunction initThemePicker() {\n    const themeChoicesInMobileNav = find(\".mobile-navigation .theme-choices\");\n    if (!themeChoicesInMobileNav) return;\n\n    const themeChoicesInHeader = find(\".header-container .theme-choices\");\n\n    if (themeChoicesInHeader) {\n        themeChoicesInHeader.replaceWith(\n            themeChoicesInMobileNav.cloneNode(true)\n        );\n    }\n\n    const presetElems = findAll(\".theme-choices .theme-preset\");\n    let themePreviewElems = document.getElementsByClassName(\"current-theme-preview\");\n    let isLoading = false;\n\n    presetElems.forEach((presetElement) => {\n        const themeKey = presetElement.dataset.key;\n\n        if (themeKey === undefined) {\n            return;\n        }\n\n        if (themeKey == pageData.theme) {\n            presetElement.classList.add(\"current\");\n        }\n\n        presetElement.addEventListener(\"click\", () => {\n            if (themeKey == pageData.theme) return;\n            if (isLoading) return;\n\n            isLoading = true;\n            changeTheme(themeKey, function() {\n                isLoading = false;\n                pageData.theme = themeKey;\n                presetElems.forEach((e) => { e.classList.remove(\"current\"); });\n\n                Array.from(themePreviewElems).forEach((preview) => {\n                    preview.querySelector(\".theme-preset\").replaceWith(\n                        presetElement.cloneNode(true)\n                    );\n                })\n\n                presetElems.forEach((e) => {\n                    if (e.dataset.key != themeKey) return;\n                    e.classList.add(\"current\");\n                });\n            });\n        });\n    })\n}\n\nasync function setupPage() {\n    initThemePicker();\n\n    const pageElement = document.getElementById(\"page\");\n    const pageContentElement = document.getElementById(\"page-content\");\n    const pageContent = await fetchPageContent(pageData);\n\n    pageContentElement.innerHTML = pageContent;\n\n    try {\n        setupPopovers();\n        setupClocks()\n        await setupCalendars();\n        await setupTodos();\n        setupCarousels();\n        setupSearchBoxes();\n        setupCollapsibleLists();\n        setupCollapsibleGrids();\n        setupGroups();\n        setupMasonries();\n        setupDynamicRelativeTime();\n        setupLazyImages();\n    } finally {\n        pageElement.classList.add(\"content-ready\");\n        pageElement.setAttribute(\"aria-busy\", \"false\");\n\n        for (let i = 0; i < contentReadyCallbacks.length; i++) {\n            contentReadyCallbacks[i]();\n        }\n\n        setTimeout(() => {\n            setupTruncatedElementTitles();\n        }, 50);\n\n        setTimeout(() => {\n            document.body.classList.add(\"page-columns-transitioned\");\n        }, 300);\n    }\n}\n\nsetupPage();\n"
  },
  {
    "path": "internal/glance/static/js/popover.js",
    "content": "const defaultShowDelayMs = 200;\nconst defaultHideDelayMs = 500;\nconst defaultMaxWidth = \"300px\";\nconst defaultDistanceFromTarget = \"0px\"\nconst htmlContentSelector = \"[data-popover-html]\";\n\nlet activeTarget = null;\nlet pendingTarget = null;\nlet cleanupOnHidePopover = null;\nlet togglePopoverTimeout = null;\n\nconst containerElement = document.createElement(\"div\");\nconst containerComputedStyle = getComputedStyle(containerElement);\ncontainerElement.addEventListener(\"mouseenter\", clearTogglePopoverTimeout);\ncontainerElement.addEventListener(\"mouseleave\", handleMouseLeave);\ncontainerElement.classList.add(\"popover-container\");\n\nconst frameElement = document.createElement(\"div\");\nframeElement.classList.add(\"popover-frame\");\n\nconst contentElement = document.createElement(\"div\");\ncontentElement.classList.add(\"popover-content\");\n\nframeElement.append(contentElement);\ncontainerElement.append(frameElement);\ndocument.body.append(containerElement);\n\nconst queueRepositionContainer = () => requestAnimationFrame(repositionContainer);\nconst observer = new ResizeObserver(queueRepositionContainer);\n\nfunction handleMouseEnter(event) {\n    clearTogglePopoverTimeout();\n    const target = event.target;\n    pendingTarget = target;\n    const showDelay = target.dataset.popoverShowDelay || defaultShowDelayMs;\n\n    if (activeTarget !== null) {\n        if (activeTarget !== target) {\n            hidePopover();\n            requestAnimationFrame(() => requestAnimationFrame(showPopover));\n        } else if (activeTarget.dataset.popoverTrigger === \"click\") {\n            hidePopover();\n        }\n\n        return;\n    }\n\n    togglePopoverTimeout = setTimeout(showPopover, showDelay);\n}\n\nfunction handleMouseLeave(event) {\n    clearTogglePopoverTimeout();\n    const target = activeTarget || event.target;\n    togglePopoverTimeout = setTimeout(hidePopover, target.dataset.popoverHideDelay || defaultHideDelayMs);\n}\n\nfunction clearTogglePopoverTimeout() {\n    clearTimeout(togglePopoverTimeout);\n}\n\nfunction showPopover() {\n    if (pendingTarget === null) return;\n\n    activeTarget = pendingTarget;\n    pendingTarget = null;\n\n    const popoverType = activeTarget.dataset.popoverType;\n\n    if (popoverType === \"text\") {\n        const text = activeTarget.dataset.popoverText;\n        if (text === undefined || text === \"\") return;\n        contentElement.textContent = text;\n    } else if (popoverType === \"html\") {\n        const htmlContent = activeTarget.querySelector(htmlContentSelector);\n        if (htmlContent === null) return;\n        /**\n         * The reason for all of the below shenanigans is that I want to preserve\n         * all attached event listeners of the original HTML content. This is so I don't have to\n         * re-setup events for things like lazy images, they'd just work as expected.\n         */\n        const placeholder = document.createComment(\"\");\n        htmlContent.replaceWith(placeholder);\n        contentElement.replaceChildren(htmlContent);\n        htmlContent.removeAttribute(\"data-popover-html\");\n        cleanupOnHidePopover = () => {\n            htmlContent.setAttribute(\"data-popover-html\", \"\");\n            placeholder.replaceWith(htmlContent);\n            placeholder.remove();\n        };\n    } else {\n        return;\n    }\n\n    const contentMaxWidth = activeTarget.dataset.popoverMaxWidth || defaultMaxWidth;\n\n    if (activeTarget.dataset.popoverTextAlign !== undefined) {\n        contentElement.style.textAlign = activeTarget.dataset.popoverTextAlign;\n    } else {\n        contentElement.style.removeProperty(\"text-align\");\n    }\n\n    contentElement.style.maxWidth = contentMaxWidth;\n    activeTarget.classList.add(\"popover-active\");\n    document.addEventListener(\"keydown\", handleHidePopoverOnEscape);\n    window.addEventListener(\"scroll\", queueRepositionContainer);\n    window.addEventListener(\"resize\", queueRepositionContainer);\n    observer.observe(containerElement);\n}\n\nfunction repositionContainer() {\n    if (activeTarget === null) return;\n\n    containerElement.style.display = \"block\";\n\n    const targetBounds = activeTarget.dataset.popoverAnchor !== undefined\n        ? activeTarget.querySelector(activeTarget.dataset.popoverAnchor).getBoundingClientRect()\n        : activeTarget.getBoundingClientRect();\n\n    const containerBounds = containerElement.getBoundingClientRect();\n    const containerInlinePadding = parseInt(containerComputedStyle.getPropertyValue(\"padding-inline\"));\n    const targetBoundsWidthOffset = targetBounds.width * (activeTarget.dataset.popoverTargetOffset || 0.5);\n    const position = activeTarget.dataset.popoverPosition || \"below\";\n    const popoverOffest = activeTarget.dataset.popoverOffset || 0.5;\n    const left = Math.round(targetBounds.left + targetBoundsWidthOffset - (containerBounds.width * popoverOffest));\n\n    if (left < 0) {\n        containerElement.style.left = 0;\n        containerElement.style.removeProperty(\"right\");\n        containerElement.style.setProperty(\"--triangle-offset\", targetBounds.left - containerInlinePadding + targetBoundsWidthOffset + \"px\");\n    } else if (left + containerBounds.width > window.innerWidth) {\n        containerElement.style.removeProperty(\"left\");\n        containerElement.style.right = 0;\n        containerElement.style.setProperty(\"--triangle-offset\", containerBounds.width - containerInlinePadding - (document.documentElement.clientWidth - targetBounds.left - targetBoundsWidthOffset) + -1 + \"px\");\n    } else {\n        containerElement.style.removeProperty(\"right\");\n        containerElement.style.left = left + \"px\";\n        containerElement.style.setProperty(\"--triangle-offset\", ((targetBounds.left + targetBoundsWidthOffset) - left - containerInlinePadding) + -1 + \"px\");\n    }\n\n    const distanceFromTarget = activeTarget.dataset.popoverMargin || defaultDistanceFromTarget;\n    const topWhenAbove = targetBounds.top + window.scrollY - containerBounds.height;\n    const topWhenBelow = targetBounds.top + window.scrollY + targetBounds.height;\n\n    if (\n        position === \"above\" && topWhenAbove > window.scrollY ||\n        (position === \"below\" && topWhenBelow + containerBounds.height > window.scrollY + window.innerHeight)\n    ) {\n        containerElement.classList.add(\"position-above\");\n        frameElement.style.removeProperty(\"margin-top\");\n        frameElement.style.marginBottom = distanceFromTarget;\n        containerElement.style.top = topWhenAbove + \"px\";\n    } else {\n        containerElement.classList.remove(\"position-above\");\n        frameElement.style.removeProperty(\"margin-bottom\");\n        frameElement.style.marginTop = distanceFromTarget;\n        containerElement.style.top = topWhenBelow + \"px\";\n    }\n}\n\nfunction hidePopover() {\n    if (activeTarget === null) return;\n\n    activeTarget.classList.remove(\"popover-active\");\n    containerElement.style.display = \"none\";\n    containerElement.style.removeProperty(\"top\");\n    containerElement.style.removeProperty(\"left\");\n    containerElement.style.removeProperty(\"right\");\n    document.removeEventListener(\"keydown\", handleHidePopoverOnEscape);\n    window.removeEventListener(\"scroll\", queueRepositionContainer);\n    window.removeEventListener(\"resize\", queueRepositionContainer);\n    observer.unobserve(containerElement);\n\n    if (cleanupOnHidePopover !== null) {\n        cleanupOnHidePopover();\n        cleanupOnHidePopover = null;\n    }\n\n    activeTarget = null;\n}\n\nfunction handleHidePopoverOnEscape(event) {\n    if (event.key === \"Escape\") {\n        hidePopover();\n    }\n}\n\nexport function setupPopovers() {\n    const targets = document.querySelectorAll(\"[data-popover-type]\");\n\n    for (let i = 0; i < targets.length; i++) {\n        const target = targets[i];\n\n        if (target.dataset.popoverTrigger === \"click\") {\n            target.addEventListener(\"click\", handleMouseEnter);\n        } else {\n            target.addEventListener(\"mouseenter\", handleMouseEnter);\n        }\n\n        target.addEventListener(\"mouseleave\", handleMouseLeave);\n    }\n}\n"
  },
  {
    "path": "internal/glance/static/js/templating.js",
    "content": "export function elem(tag = \"div\") {\n    return document.createElement(tag);\n}\n\nexport function fragment(...children) {\n    const f = document.createDocumentFragment();\n    if (children) f.append(...children);\n    return f;\n}\n\nexport function text(str = \"\") {\n    return document.createTextNode(str);\n}\n\nexport function repeat(n, fn) {\n    const elems = Array(n);\n\n    for (let i = 0; i < n; i++)\n        elems[i] = fn(i);\n\n    return elems;\n}\n\nexport function find(selector) {\n    return document.querySelector(selector);\n}\n\nexport function findAll(selector) {\n    return document.querySelectorAll(selector);\n}\n\n\nHTMLCollection.prototype.map = function(fn) {\n    return Array.from(this).map(fn);\n}\n\nHTMLCollection.prototype.indexOf = function(element) {\n    return Array.prototype.indexOf.call(this, element);\n}\n\nconst ep = HTMLElement.prototype;\nconst fp = DocumentFragment.prototype;\nconst tp = Text.prototype;\n\nep.classes = function(...classes) {\n    this.classList.add(...classes);\n    return this;\n}\n\nep.find = function(selector) {\n    return this.querySelector(selector);\n}\n\nep.findAll = function(selector) {\n    return this.querySelectorAll(selector);\n}\n\nep.classesIf = function(cond, ...classes) {\n    cond ? this.classList.add(...classes) : this.classList.remove(...classes);\n    return this;\n}\n\nep.hide = function() {\n    this.style.display = \"none\";\n    return this;\n}\n\nep.show = function() {\n    this.style.removeProperty(\"display\");\n    return this;\n}\n\nep.showIf = function(cond) {\n    cond ? this.show() : this.hide();\n    return this;\n}\n\nep.isHidden = function() {\n    return this.style.display === \"none\";\n}\n\nep.clearClasses = function(...classes) {\n    classes.length ? this.classList.remove(...classes) : this.className = \"\";\n    return this;\n}\n\nep.hasClass = function(className) {\n    return this.classList.contains(className);\n}\n\nep.attr = function(name, value) {\n    this.setAttribute(name, value);\n    return this;\n}\n\nep.attrs = function(attrs) {\n    for (const [name, value] of Object.entries(attrs))\n        this.setAttribute(name, value);\n    return this;\n}\n\nep.tap = function(fn) {\n    fn(this);\n    return this;\n}\n\nep.text = function(text) {\n    this.innerText = text;\n    return this;\n}\n\nep.html = function(html) {\n    this.innerHTML = html;\n    return this;\n}\n\nep.appendTo = function(parent) {\n    parent.appendChild(this);\n    return this;\n}\n\nep.swapWith = function(element) {\n    this.replaceWith(element);\n    return element;\n}\n\nep.on = function(event, callback, options) {\n    if (typeof event === \"string\") {\n        this.addEventListener(event, callback, options);\n        return this;\n    }\n\n    for (let i = 0; i < event.length; i++)\n        this.addEventListener(event[i], callback, options);\n\n    return this;\n}\n\nconst epAppend = ep.append;\nep.append = function(...children) {\n    epAppend.apply(this, children);\n    return this;\n}\n\nep.duplicate = function(n) {\n    const elems = Array(n);\n\n    for (let i = 0; i < n; i++)\n        elems[i] = this.cloneNode(true);\n\n    return elems;\n}\n\nep.styles = function(s) {\n    Object.assign(this.style, s);\n    return this;\n}\n\nep.clearStyles = function(...props) {\n    for (let i = 0; i < props.length; i++)\n        this.style.removeProperty(props[i]);\n    return this;\n}\n\nep.disable = function() {\n    this.disabled = true;\n    return this;\n}\n\nep.enable = function() {\n    this.disabled = false;\n    return this;\n}\n\nconst epAnimate = ep.animate;\nep.animate = function(anim, callback) {\n    const a = epAnimate.call(this, anim.keyframes, anim.options);\n    if (callback) a.onfinish = () => callback(this, a);\n    return this;\n}\n\nep.animateUpdate = function(update, exit, entrance) {\n    this.animate(exit, () => {\n        update(this);\n        this.animate(entrance);\n    });\n\n    return this;\n}\n\nep.styleVar = function(name, value) {\n    this.style.setProperty(`--${name}`, value);\n    return this;\n}\n\nep.component = function (methods) {\n    this.component = methods;\n    return this;\n}\n\nconst fpAppend = fp.append;\nfp.append = function(...children) {\n    fpAppend.apply(this, children);\n    return this;\n}\n\nfp.appendTo = function(parent) {\n    parent.appendChild(this);\n    return this;\n}\n\ntp.text = function(text) {\n    this.nodeValue = text;\n    return this;\n}\n"
  },
  {
    "path": "internal/glance/static/js/todo.js",
    "content": "import { elem, fragment } from \"./templating.js\";\nimport { animateReposition } from \"./animations.js\";\nimport { clamp, Vec2, toggleableEvents, throttledDebounce } from \"./utils.js\";\n\nconst trashIconSvg = `<svg fill=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\">\n  <path fill-rule=\"evenodd\" d=\"M5 3.25V4H2.75a.75.75 0 0 0 0 1.5h.3l.815 8.15A1.5 1.5 0 0 0 5.357 15h5.285a1.5 1.5 0 0 0 1.493-1.35l.815-8.15h.3a.75.75 0 0 0 0-1.5H11v-.75A2.25 2.25 0 0 0 8.75 1h-1.5A2.25 2.25 0 0 0 5 3.25Zm2.25-.75a.75.75 0 0 0-.75.75V4h3v-.75a.75.75 0 0 0-.75-.75h-1.5ZM6.05 6a.75.75 0 0 1 .787.713l.275 5.5a.75.75 0 0 1-1.498.075l-.275-5.5A.75.75 0 0 1 6.05 6Zm3.9 0a.75.75 0 0 1 .712.787l-.275 5.5a.75.75 0 0 1-1.498-.075l.275-5.5a.75.75 0 0 1 .786-.711Z\" clip-rule=\"evenodd\" />\n</svg>`;\n\nexport default function(element) {\n    element.swapWith(\n        Todo(element.dataset.todoId)\n    )\n}\n\nfunction itemAnim(height, entrance = true) {\n    const visible = { height: height + \"px\", opacity: 1 };\n    const hidden  = { height: \"0\", opacity: 0, padding: \"0\" };\n\n    return {\n        keyframes: [\n            entrance ? hidden : visible,\n            entrance ? visible : hidden\n        ],\n        options: { duration: 200, easing: \"ease\" }\n    }\n}\n\nfunction inputMarginAnim(entrance = true) {\n    const amount = \"1.5rem\";\n\n    return {\n        keyframes: [\n            { marginBottom: entrance ? \"0px\" : amount },\n            { marginBottom: entrance ? amount : \"0\" }\n        ],\n        options: { duration: 200, easing: \"ease\", fill: \"forwards\" }\n    }\n}\n\nfunction loadFromLocalStorage(id) {\n    return JSON.parse(localStorage.getItem(`todo-${id}`) || \"[]\");\n}\n\nfunction saveToLocalStorage(id, data) {\n    localStorage.setItem(`todo-${id}`, JSON.stringify(data));\n}\n\nfunction Item(unserialize = {}, onUpdate, onDelete, onEscape, onDragStart) {\n    let item, input, inputArea;\n\n    const serializeable = {\n        text: unserialize.text || \"\",\n        checked: unserialize.checked || false\n    };\n\n    item = elem().classes(\"todo-item\", \"flex\", \"gap-10\", \"items-center\").append(\n        elem(\"input\")\n            .classes(\"todo-item-checkbox\", \"shrink-0\")\n            .styles({ marginTop: \"-0.1rem\" })\n            .attrs({ type: \"checkbox\" })\n            .on(\"change\", (e) => {\n                serializeable.checked = e.target.checked;\n                onUpdate();\n            })\n            .tap(self => self.checked = serializeable.checked),\n\n        input = autoScalingTextarea(textarea => inputArea = textarea\n            .classes(\"todo-item-text\")\n            .attrs({\n                placeholder: \"empty task\",\n                spellcheck: \"false\"\n            })\n            .on(\"keydown\", (e) => {\n                if (e.key === \"Enter\") {\n                    e.preventDefault();\n                } else if (e.key === \"Escape\") {\n                    e.preventDefault();\n                    onEscape();\n                }\n            })\n            .on(\"input\", () => {\n                serializeable.text = inputArea.value;\n                onUpdate();\n            })\n        ).classes(\"min-width-0\", \"grow\").append(\n            elem()\n                .classes(\"todo-item-drag-handle\")\n                .on(\"mousedown\", (e) => onDragStart(e, item))\n        ),\n\n        elem(\"button\")\n            .classes(\"todo-item-delete\", \"shrink-0\")\n            .html(trashIconSvg)\n            .on(\"click\", () => onDelete(item))\n    );\n\n    input.component.setValue(serializeable.text);\n    return item.component({\n        focusInput: () => inputArea.focus(),\n        serialize: () => serializeable\n    });\n}\n\nfunction Todo(id) {\n    let items, input, inputArea, inputContainer, lastAddedItem;\n    let queuedForRemoval = 0;\n    let reorderable;\n    let isDragging = false;\n\n    const onDragEnd = () => isDragging = false;\n    const onDragStart = (event, element) => {\n        isDragging = true;\n        reorderable.component.onDragStart(event, element);\n    };\n\n    const saveItems = () => {\n        if (isDragging) return;\n\n        saveToLocalStorage(\n            id, items.children.map(item => item.component.serialize())\n        );\n    };\n\n    const onItemRepositioned = () => saveItems();\n    const debouncedOnItemUpdate = throttledDebounce(saveItems, 10, 1000);\n\n    const onItemDelete = (item) => {\n        if (lastAddedItem === item) lastAddedItem = null;\n        const height = item.clientHeight;\n        queuedForRemoval++;\n        item.animate(itemAnim(height, false), () => {\n            item.remove();\n            queuedForRemoval--;\n            saveItems();\n        });\n\n        if (items.children.length - queuedForRemoval === 0)\n            inputContainer.animate(inputMarginAnim(false));\n    };\n\n    const newItem = (data) => Item(\n        data,\n        debouncedOnItemUpdate,\n        onItemDelete,\n        () => inputArea.focus(),\n        onDragStart\n    );\n\n    const addNewItem = (itemText, prepend) => {\n        const totalItemsBeforeAppending = items.children.length;\n        const item = lastAddedItem = newItem({ text: itemText });\n\n        prepend ? items.prepend(item) : items.append(item);\n        saveItems();\n        const height = item.clientHeight;\n        item.animate(itemAnim(height));\n\n        if (totalItemsBeforeAppending === 0)\n            inputContainer.animate(inputMarginAnim());\n    };\n\n    const handleInputKeyDown = (e) => {\n        switch (e.key) {\n            case \"Enter\":\n                e.preventDefault();\n                const value = e.target.value.trim();\n                if (value === \"\") return;\n                addNewItem(value, e.ctrlKey);\n                input.component.setValue(\"\");\n                break;\n            case \"Escape\":\n                e.target.blur();\n                break;\n            case \"ArrowDown\":\n                if (!lastAddedItem) return;\n                e.preventDefault();\n                lastAddedItem.component.focusInput();\n                break;\n        }\n    };\n\n    items = elem()\n        .classes(\"todo-items\")\n        .append(\n            ...loadFromLocalStorage(id).map(data => newItem(data))\n        );\n\n    return fragment().append(\n        inputContainer = elem()\n            .classes(\"todo-input\", \"flex\", \"gap-10\", \"items-center\")\n            .classesIf(items.children.length > 0, \"margin-bottom-15\")\n            .styles({ paddingRight: \"2.5rem\" })\n            .append(\n                elem().classes(\"todo-plus-icon\", \"shrink-0\"),\n                input = autoScalingTextarea(textarea => inputArea = textarea\n                    .on(\"keydown\", handleInputKeyDown)\n                    .attrs({\n                        placeholder: \"Add a task\",\n                        spellcheck: \"false\"\n                    })\n                ).classes(\"grow\", \"min-width-0\")\n            ),\n\n        reorderable = verticallyReorderable(items, onItemRepositioned, onDragEnd),\n    );\n}\n\n\n// See https://css-tricks.com/the-cleanest-trick-for-autogrowing-textareas/\nexport function autoScalingTextarea(yieldTextarea = null) {\n    let textarea, mimic;\n\n    const updateMimic = (newValue) => mimic.text(newValue + ' ');\n    const container = elem().classes(\"auto-scaling-textarea-container\").append(\n        textarea = elem(\"textarea\")\n            .classes(\"auto-scaling-textarea\")\n            .on(\"input\", () => updateMimic(textarea.value)),\n        mimic = elem().classes(\"auto-scaling-textarea-mimic\")\n    )\n\n    if (typeof yieldTextarea === \"function\") yieldTextarea(textarea);\n\n    return container.component({ setValue: (newValue) => {\n        textarea.value = newValue;\n        updateMimic(newValue);\n    }});\n}\n\nexport function verticallyReorderable(itemsContainer, onItemRepositioned, onDragEnd) {\n    const classToAddToDraggedItem = \"is-being-dragged\";\n\n    const currentlyBeingDragged = {\n        element: null,\n        initialIndex: null,\n        clientOffset: Vec2.new(),\n    };\n\n    const decoy = {\n        element: null,\n        currentIndex: null,\n    };\n\n    const draggableContainer = {\n        element: null,\n        initialRect: null,\n    };\n\n    const lastClientPos = Vec2.new();\n    let initialScrollY = null;\n    let addDocumentEvents, removeDocumentEvents;\n\n    const handleReposition = (event) => {\n        if (currentlyBeingDragged.element == null) return;\n\n        if (event.clientY !== undefined && event.clientX !== undefined)\n            lastClientPos.setFromEvent(event);\n\n        const client = lastClientPos;\n        const container = draggableContainer;\n        const item = currentlyBeingDragged;\n\n        const scrollOffset = window.scrollY - initialScrollY;\n        const offsetY = client.y - container.initialRect.y - item.clientOffset.y + scrollOffset;\n        const offsetX = client.x - container.initialRect.x - item.clientOffset.x;\n\n        const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n        const viewportWidth = window.innerWidth - scrollbarWidth;\n\n        const confinedX = clamp(\n            offsetX,\n            -container.initialRect.x,\n            viewportWidth - container.initialRect.x - container.initialRect.width\n        );\n\n        container.element.styles({\n            transform: `translate(${confinedX}px, ${offsetY}px)`,\n        });\n\n        const containerTop = client.y - item.clientOffset.y;\n        const containerBottom = client.y + container.initialRect.height - item.clientOffset.y;\n\n        let swapWithLast = true;\n        let swapWithIndex = null;\n\n        for (let i = 0; i < itemsContainer.children.length; i++) {\n            const childRect = itemsContainer.children[i].getBoundingClientRect();\n            const topThreshold = childRect.top + childRect.height * .6;\n            const bottomThreshold = childRect.top + childRect.height * .4;\n\n            if (containerBottom > topThreshold) {\n                if (containerTop < bottomThreshold && i != decoy.currentIndex) {\n                    swapWithIndex = i;\n                    swapWithLast = false;\n                    break;\n                }\n                continue;\n            };\n\n            swapWithLast = false;\n\n            if (i == decoy.currentIndex || i-1 == decoy.currentIndex) break;\n            swapWithIndex = (i < decoy.currentIndex) ? i : i-1;\n            break;\n        }\n\n        const lastItemIndex = itemsContainer.children.length - 1;\n\n        if (swapWithLast && decoy.currentIndex != lastItemIndex)\n            swapWithIndex = lastItemIndex;\n\n        if (swapWithIndex === null)\n            return;\n\n        const diff = swapWithIndex - decoy.currentIndex;\n        if (Math.abs(diff) > 1) {\n            swapWithIndex = decoy.currentIndex + Math.sign(diff);\n        }\n\n        const siblingToSwapWith = itemsContainer.children[swapWithIndex];\n\n        if (siblingToSwapWith.isCurrentlyAnimating) return;\n\n        const animateDecoy = animateReposition(decoy.element);\n        const animateChild = animateReposition(\n            siblingToSwapWith,\n            () => {\n                siblingToSwapWith.isCurrentlyAnimating = false;\n                handleReposition({\n                    clientX: client.x,\n                    clientY: client.y,\n                });\n            }\n        );\n\n        siblingToSwapWith.isCurrentlyAnimating = true;\n\n        if (swapWithIndex > decoy.currentIndex)\n            decoy.element.before(siblingToSwapWith);\n         else\n            decoy.element.after(siblingToSwapWith);\n\n        decoy.currentIndex = itemsContainer.children.indexOf(decoy.element);\n\n        animateDecoy();\n        animateChild();\n    }\n\n    const handleRelease = (event) => {\n        if (event.buttons != 0) return;\n\n        removeDocumentEvents();\n        const item = currentlyBeingDragged;\n        const element = item.element;\n        element.styles({ pointerEvents: \"none\" });\n        const animate = animateReposition(element, () => {\n            item.element = null;\n            element\n                .clearClasses(classToAddToDraggedItem)\n                .clearStyles(\"pointer-events\");\n\n            if (typeof onDragEnd === \"function\") onDragEnd(element);\n\n            if (item.initialIndex != decoy.currentIndex && typeof onItemRepositioned === \"function\")\n                onItemRepositioned(element, item.initialIndex, decoy.currentIndex);\n        });\n\n        decoy.element.swapWith(element);\n        draggableContainer.element.append(decoy.element);\n        draggableContainer.element.clearStyles(\"transform\", \"width\");\n\n        item.element = null;\n        decoy.element.remove();\n\n        animate();\n    }\n\n    const preventDefault = (event) => {\n        event.preventDefault();\n    };\n\n    const handleGrab = (event, element) => {\n        if (currentlyBeingDragged.element != null) return;\n\n        event.preventDefault();\n\n        const item = currentlyBeingDragged;\n        if (item.element != null) return;\n\n        addDocumentEvents();\n        initialScrollY = window.scrollY;\n        const client = lastClientPos.setFromEvent(event);\n        const elementRect = element.getBoundingClientRect();\n\n        item.element = element;\n        item.initialIndex = decoy.currentIndex = itemsContainer.children.indexOf(element);\n        item.clientOffset.set(client.x - elementRect.x, client.y - elementRect.y);\n\n        // We use getComputedStyle here to get width and height because .clientWidth and .clientHeight\n        // return integers and not the real float values, which can cause the decoy to be off by a pixel\n        const elementStyle = getComputedStyle(element);\n        const initialWidth = elementStyle.width;\n\n        decoy.element = elem().classes(\"drag-and-drop-decoy\").styles({\n            height: elementStyle.height,\n            width: initialWidth,\n        });\n\n        const container = draggableContainer;\n\n        element.swapWith(decoy.element);\n        container.element.append(element);\n        element.classes(classToAddToDraggedItem);\n\n        decoy.element.animate({\n            keyframes: [{ transform: \"scale(.9)\", opacity: 0, offset: 0 }],\n            options: { duration: 300, easing: \"ease\" }\n        })\n\n        container.element.styles({ width: initialWidth, transform: \"none\" });\n        container.initialRect = container.element.getBoundingClientRect();\n\n        const offsetY = elementRect.y - container.initialRect.y;\n        const offsetX = elementRect.x - container.initialRect.x;\n\n        container.element.styles({ transform: `translate(${offsetX}px, ${offsetY}px)` });\n    }\n\n    [addDocumentEvents, removeDocumentEvents] = toggleableEvents(document, {\n        \"mousemove\": handleReposition,\n        \"scroll\": handleReposition,\n        \"mousedown\": preventDefault,\n        \"contextmenu\": preventDefault,\n        \"mouseup\": handleRelease,\n    });\n\n    return elem().classes(\"drag-and-drop-container\").append(\n        itemsContainer,\n        draggableContainer.element = elem().classes(\"drag-and-drop-draggable\")\n    ).component({\n        onDragStart: handleGrab\n    });\n}\n"
  },
  {
    "path": "internal/glance/static/js/utils.js",
    "content": "export function throttledDebounce(callback, maxDebounceTimes, debounceDelay) {\n    let debounceTimeout;\n    let timesDebounced = 0;\n\n    return function () {\n        if (timesDebounced == maxDebounceTimes) {\n            clearTimeout(debounceTimeout);\n            timesDebounced = 0;\n            callback();\n            return;\n        }\n\n        clearTimeout(debounceTimeout);\n        timesDebounced++;\n\n        debounceTimeout = setTimeout(() => {\n            timesDebounced = 0;\n            callback();\n        }, debounceDelay);\n    };\n};\n\nexport function isElementVisible(element) {\n    return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);\n}\n\nexport function clamp(value, min, max) {\n    return Math.min(Math.max(value, min), max);\n}\n\n// NOTE: inconsistent behavior between browsers when it comes to\n// whether the newly opened tab gets focused or not, potentially\n// depending on the event that this function is called from\nexport function openURLInNewTab(url, focus = true) {\n    const newWindow = window.open(url, '_blank', 'noopener,noreferrer');\n\n    if (focus && newWindow != null) newWindow.focus();\n}\n\n\nexport class Vec2 {\n    constructor(x, y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    static new(x = 0, y = 0) {\n        return new Vec2(x, y);\n    }\n\n    static fromEvent(event) {\n        return new Vec2(event.clientX, event.clientY);\n    }\n\n    setFromEvent(event) {\n        this.x = event.clientX;\n        this.y = event.clientY;\n        return this;\n    }\n\n    set(x, y) {\n        this.x = x;\n        this.y = y;\n        return this;\n    }\n}\n\nexport function toggleableEvents(element, eventToHandlerMap) {\n    return [\n        () => {\n            for (const [event, handler] of Object.entries(eventToHandlerMap)) {\n                element.addEventListener(event, handler);\n            }\n        },\n        () => {\n            for (const [event, handler] of Object.entries(eventToHandlerMap)) {\n                element.removeEventListener(event, handler);\n            }\n        }\n    ];\n}\n"
  },
  {
    "path": "internal/glance/templates/bookmarks.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"dynamic-columns list-gap-24 list-with-separator\">\n    {{- range .Groups }}\n    <div class=\"bookmarks-group\"{{ if .Color }} style=\"--bookmarks-group-color: {{ .Color.String | safeCSS }}\"{{ end }}>\n        {{- if ne .Title \"\" }}\n        <div class=\"bookmarks-group-title size-h3 margin-bottom-3\">{{ .Title }}</div>\n        {{- end }}\n        <ul class=\"list list-gap-2\">\n        {{- range .Links }}\n        <li>\n            <div class=\"flex items-center gap-10\">\n                {{- if ne \"\" .Icon.URL }}\n                <div class=\"bookmarks-icon-container\">\n                    <img class=\"bookmarks-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}\" src=\"{{ .Icon.URL }}\" alt=\"\" loading=\"lazy\">\n                </div>\n                {{- end }}\n                <a href=\"{{ .URL | safeURL }}\" class=\"bookmarks-link {{ if .HideArrow }}bookmarks-link-no-arrow {{ end }}color-highlight size-h4\" {{ if .Target }}target=\"{{ .Target }}\"{{ end }} rel=\"noreferrer\">{{ .Title }}</a>\n            </div>\n            {{- if .Description }}\n            <div class=\"margin-bottom-5\">{{ .Description }}</div>\n            {{- end }}\n        </li>\n        {{- end }}\n        </ul>\n    </div>\n    {{- end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/calendar.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"widget-small-content-bounds\">\n    <div class=\"calendar\" data-first-day-of-week=\"{{ .FirstDay }}\"></div>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/change-detection.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .ChangeDetections }}\n    <li>\n        <a class=\"size-h4 block text-truncate color-highlight\" href=\"{{ .URL }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n        <ul class=\"list-horizontal-text\">\n            <li {{ dynamicRelativeTimeAttrs .LastChanged }}></li>\n            <li class=\"shrink min-width-0\"><a class=\"visited-indicator\" href=\"{{ .DiffURL }}\" target=\"_blank\" rel=\"noreferrer\">diff:{{ .PreviousHash }}</a></li>\n        </ul>\n    </li>\n    {{ else }}\n    <li>No watches configured</li>\n    {{ end}}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/clock.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"clock\" data-hour-format=\"{{ .HourFormat }}\">\n    <div class=\"flex justify-between items-center\" data-local-time>\n        <div>\n            <div class=\"color-highlight size-h1\" data-date></div>\n            <div data-year></div>\n        </div>\n        <div class=\"text-right\">\n            <div class=\"clock-time size-h1\" data-time></div>\n            <div data-weekday></div>\n        </div>\n    </div>\n    {{ if gt (len .Timezones) 0 }}\n    <hr class=\"margin-block-10\">\n    <ul class=\"list list-gap-4\">\n        {{ range .Timezones }}\n        <li class=\"flex items-center gap-15\" data-time-in-zone=\"{{ .Timezone }}\">\n            <div class=\"grow min-width-0\">\n                <div class=\"text-truncate\">{{ if ne .Label \"\" }}{{ .Label }}{{ else }}{{ .Timezone }}{{ end }}</div>\n            </div>\n            <div class=\"color-subdue\" data-time-diff></div>\n            <div class=\"size-h4 clock-time shrink-0 text-right\" data-time></div>\n        </li>\n        {{ end }}\n    </ul>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/custom-api.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}{{ if .Frameless }}widget-content-frameless{{ end }}{{ end }}\n\n{{ define \"widget-content\" }}\n{{ .CompiledHTML }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/dns-stats.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"widget-small-content-bounds dns-stats\">\n    <div class=\"flex text-center justify-between dns-stats-totals\">\n        <div>\n            <div class=\"color-highlight size-h3\">{{ .Stats.TotalQueries | formatNumber }}</div>\n            <div class=\"size-h6\">QUERIES</div>\n        </div>\n        <div>\n            <div class=\"color-highlight size-h3\">{{ .Stats.BlockedPercent }}%</div>\n            <div class=\"size-h6\">BLOCKED</div>\n        </div>\n        {{ if gt .Stats.ResponseTime 0 }}\n        <div>\n            <div class=\"color-highlight size-h3\">{{ .Stats.ResponseTime | formatNumber }}ms</div>\n            <div class=\"size-h6\">LATENCY</div>\n        </div>\n        {{ else }}\n        <div class=\"cursor-help\" data-popover-type=\"text\" data-popover-text=\"Total number of blocked domains from all adlists\" data-popover-max-width=\"200px\" data-popover-text-align=\"center\">\n            <div class=\"color-highlight size-h3\">{{ .Stats.DomainsBlocked | formatApproxNumber }}</div>\n            <div class=\"size-h6\">DOMAINS</div>\n        </div>\n        {{ end }}\n    </div>\n\n    {{ $showGraph := not (or .HideGraph (eq (len .Stats.Series) 0)) }}\n    {{ if $showGraph }}\n    <div class=\"dns-stats-graph margin-top-15\">\n        <div class=\"dns-stats-graph-gridlines-container\">\n            <svg class=\"dns-stats-graph-gridlines\" shape-rendering=\"crispEdges\" viewBox=\"0 0 1 100\" preserveAspectRatio=\"none\">\n                <g stroke=\"var(--color-graph-gridlines)\" stroke-width=\"1\">\n                    <line x1=\"0\" y1=\"1\" x2=\"1\" y2=\"1\" vector-effect=\"non-scaling-stroke\" />\n                    <line x1=\"0\" y1=\"25\" x2=\"1\" y2=\"25\" vector-effect=\"non-scaling-stroke\" />\n                    <line x1=\"0\" y1=\"50\" x2=\"1\" y2=\"50\" vector-effect=\"non-scaling-stroke\" />\n                    <line x1=\"0\" y1=\"75\" x2=\"1\" y2=\"75\" vector-effect=\"non-scaling-stroke\" />\n                    <line x1=\"0\" y1=\"99\" x2=\"1\" y2=\"99\" vector-effect=\"non-scaling-stroke\" stroke=\"var(--color-progress-bar-border)\"/>\n                </g>\n            </svg>\n        </div>\n\n        <div class=\"dns-stats-graph-columns\">\n            {{ range $i, $column := .Stats.Series }}\n            <div class=\"dns-stats-graph-column\" data-popover-type=\"html\" data-popover-position=\"above\" data-popover-show-delay=\"500\">\n                <div data-popover-html>\n                    <div class=\"flex text-center justify-between gap-25\">\n                        <div>\n                            <div class=\"color-highlight size-h3\">{{ $column.Queries | formatNumber }}</div>\n                            <div class=\"size-h6\">QUERIES</div>\n                        </div>\n                        <div>\n                            <div class=\"color-highlight size-h3\">{{ $column.PercentBlocked }}%</div>\n                            <div class=\"size-h6\">BLOCKED</div>\n                        </div>\n                    </div>\n                </div>\n                {{ if gt $column.PercentTotal 0}}\n                <div class=\"dns-stats-graph-bar\" style=\"--bar-height: {{ $column.PercentTotal }}\">\n                    {{ if ne $column.Queries $column.Blocked }}\n                        <div class=\"queries\"></div>\n                    {{ end }}\n                    {{ if gt $column.PercentBlocked 0 }}\n                        <div class=\"blocked\" style=\"--percent: {{ $column.PercentBlocked }}%\"></div>\n                    {{ end }}\n                </div>\n                {{ end }}\n                <div class=\"dns-stats-graph-time\">{{ index $.TimeLabels $i }}</div>\n            </div>\n            {{ end }}\n        </div>\n    </div>\n    {{ end }}\n\n    {{ if and (not .HideTopDomains) .Stats.TopBlockedDomains }}\n    <details class=\"details {{ if $showGraph }}margin-top-40{{ else }}margin-top-15{{ end }}\">\n        <summary class=\"summary\">Top blocked domains</summary>\n        <ul class=\"list list-gap-4 list-with-transition size-h5\">\n            {{ range .Stats.TopBlockedDomains }}\n            <li class=\"flex justify-between gap-10\">\n                <div class=\"text-truncate rtl\">{{ .Domain }}</div>\n                <div class=\"text-right\" style=\"width: 4rem;\"><span class=\"color-highlight\">{{ .PercentBlocked }}</span>%</div>\n            </li>\n            {{ end }}\n        </ul>\n    </details>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/docker-containers.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{- define \"widget-content\" }}\n<ul class=\"dynamic-columns list-gap-20 list-with-separator\">\n    {{- range .Containers }}\n    <li class=\"docker-container flex items-center gap-15\">\n        <div class=\"shrink-0\" data-popover-type=\"html\" data-popover-position=\"above\" data-popover-offset=\"0.25\" data-popover-margin=\"0.1rem\" data-popover-max-width=\"400px\" aria-hidden=\"true\">\n            <img class=\"docker-container-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}\" src=\"{{ .Icon.URL }}\" alt=\"\" loading=\"lazy\">\n            <div data-popover-html>\n                <div class=\"color-highlight text-truncate block\">{{ .Image }}</div>\n                <div>{{ .StateText }}</div>\n                {{- if .Children }}\n                <ul class=\"list list-gap-4 margin-top-10\">\n                    {{- range .Children }}\n                    <li class=\"flex gap-7 items-center\">\n                        <div class=\"margin-bottom-3\">{{ template \"state-icon\" .StateIcon }}</div>\n                        <div class=\"color-highlight\">{{ .Name }} <span class=\"size-h5 color-base\">{{ .StateText }}</span></div>\n                    </li>\n                    {{- end }}\n                </ul>\n                {{- end }}\n            </div>\n        </div>\n\n        <div class=\"min-width-0 grow\">\n            {{- if .URL }}\n            <a href=\"{{ .URL | safeURL }}\" class=\"color-highlight size-title-dynamic block text-truncate\" {{ if not .SameTab }}target=\"_blank\"{{ end }} rel=\"noreferrer\">{{ .Name }}</a>\n            {{- else }}\n            <div class=\"color-highlight text-truncate size-title-dynamic\">{{ .Name }}</div>\n            {{- end }}\n            {{- if .Description }}\n            <div class=\"text-truncate\">{{ .Description }}</div>\n            {{- end }}\n        </div>\n\n        <div class=\"margin-left-auto shrink-0\" data-popover-type=\"text\" data-popover-position=\"above\" data-popover-text=\"{{ .State }}\" aria-label=\"{{ .State }}\">\n        {{ template \"state-icon\" .StateIcon }}\n        </div>\n\n        <div class=\"visually-hidden\" aria-label=\"{{ .StateText }}\"></div>\n    </li>\n    {{- else }}\n    <div class=\"text-center\">No containers available to show.</div>\n    {{- end }}\n</ul>\n{{- end }}\n\n{{- define \"state-icon\" }}\n{{- if eq . \"ok\" }}\n<svg class=\"docker-container-status-icon\" fill=\"var(--color-positive)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n    <path fill-rule=\"evenodd\" d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z\" clip-rule=\"evenodd\" />\n</svg>\n{{- else if eq . \"warn\" }}\n<svg class=\"docker-container-status-icon\" fill=\"var(--color-negative)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n    <path fill-rule=\"evenodd\" d=\"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z\" clip-rule=\"evenodd\" />\n</svg>\n{{- else if eq . \"paused\" }}\n<svg class=\"docker-container-status-icon\" fill=\"var(--color-text-base)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n    <path fill-rule=\"evenodd\" d=\"M2 10a8 8 0 1 1 16 0 8 8 0 0 1-16 0Zm5-2.25A.75.75 0 0 1 7.75 7h.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1-.75-.75v-4.5Zm4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1-.75-.75v-4.5Z\" clip-rule=\"evenodd\" />\n</svg>\n{{- else }}\n<svg class=\"docker-container-status-icon\" fill=\"var(--color-text-base)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n    <path fill-rule=\"evenodd\" d=\"M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0ZM8.94 6.94a.75.75 0 1 1-1.061-1.061 3 3 0 1 1 2.871 5.026v.345a.75.75 0 0 1-1.5 0v-.5c0-.72.57-1.172 1.081-1.287A1.5 1.5 0 1 0 8.94 6.94ZM10 15a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z\" clip-rule=\"evenodd\" />\n</svg>\n{{- end }}\n{{- end }}\n"
  },
  {
    "path": "internal/glance/templates/document.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" id=\"top\" data-theme=\"{{ .Request.Theme.Key }}\" data-scheme=\"{{ if .Request.Theme.Light }}light{{ else }}dark{{ end }}\">\n<head>\n    {{ block \"document-head-before\" . }}{{ end }}\n    <script>\n    if (navigator.platform === 'iPhone') document.documentElement.classList.add('ios');\n    const pageData = {\n        /*{{ if .Page }}*/slug: \"{{ .Page.Slug }}\",/*{{ end }}*/\n        baseURL: \"{{ .App.Config.Server.BaseURL }}\",\n        theme: \"{{ .Request.Theme.Key }}\",\n    };\n    </script>\n    <title>{{ block \"document-title\" . }}{{ end }}</title>\n    <meta charset=\"UTF-8\">\n    <meta name=\"color-scheme\" content=\"dark\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, viewport-fit=cover\">\n    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n    <meta name=\"mobile-web-app-capable\" content=\"yes\">\n    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">\n    <meta name=\"apple-mobile-web-app-title\" content=\"{{ .App.Config.Branding.AppName }}\">\n    <meta name=\"theme-color\" content=\"{{ .Request.Theme.BackgroundColorAsHex }}\">\n    <link rel=\"apple-touch-icon\" sizes=\"512x512\" href='{{ .App.Config.Branding.AppIconURL }}'>\n    <link rel=\"manifest\" href='{{ .App.VersionedAssetPath \"manifest.json\" }}'>\n    <link rel=\"icon\" type=\"{{ .App.Config.Branding.FaviconType }}\" href=\"{{ .App.Config.Branding.FaviconURL }}\" />\n    <link rel=\"stylesheet\" href='{{ .App.StaticAssetPath \"css/bundle.css\" }}'>\n    <style id=\"theme-style\">{{ .Request.Theme.CSS }}</style>\n    {{ if .App.Config.Theme.CustomCSSFile }}<link rel=\"stylesheet\" href=\"{{ .App.Config.Theme.CustomCSSFile }}?v={{ .App.CreatedAt.Unix }}\">{{ end }}\n    {{ block \"document-head-after\" . }}{{ end }}\n    {{ if .App.Config.Document.Head }}{{ .App.Config.Document.Head }}{{ end }}\n</head>\n<body>\n{{ template \"document-body\" . }}\n</body>\n</html>\n"
  },
  {
    "path": "internal/glance/templates/extension.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}{{ if .Extension.Frameless }}widget-content-frameless{{ end }}{{ end }}\n\n{{ define \"widget-content\" }}\n{{ .Extension.Content }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/footer.html",
    "content": "{{ if not .App.Config.Branding.HideFooter }}\n<footer class=\"footer flex items-center flex-column\">\n{{ if eq \"\" .App.Config.Branding.CustomFooter }}\n    <div>\n        <a class=\"size-h3\" href=\"https://github.com/glanceapp/glance\" target=\"_blank\" rel=\"noreferrer\">Glance</a> {{ if ne \"dev\" .App.Version }}<a class=\"visited-indicator\" title=\"Release notes\" href=\"https://github.com/glanceapp/glance/releases/tag/{{ .App.Version }}\" target=\"_blank\" rel=\"noreferrer\">{{ .App.Version }}</a>{{ else }}({{ .App.Version }}){{ end }}\n    </div>\n{{ else }}\n    {{ .App.Config.Branding.CustomFooter }}\n{{ end }}\n</footer>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/forum-posts.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{- define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{- range .Posts }}\n    <li>\n        <div class=\"flex gap-10 row-reverse-on-mobile thumbnail-parent\">\n            {{- if $.ShowThumbnails }}\n            {{- if .IsCrosspost }}\n            <svg class=\"forum-post-list-thumbnail hide-on-mobile\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"-9 -8 40 40\" stroke-width=\"1.5\" stroke=\"var(--color-text-subdue)\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M7.5 21 3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5\" />\n            </svg>\n            {{- else if .ThumbnailUrl }}\n            <img class=\"forum-post-list-thumbnail thumbnail\" src=\"{{ .ThumbnailUrl }}\" alt=\"\" loading=\"lazy\">\n            {{- else if .TargetUrl }}\n            <svg class=\"forum-post-list-thumbnail hide-on-mobile\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"-9 -8 40 40\" stroke-width=\"1.5\" stroke=\"var(--color-text-subdue)\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244\" />\n            </svg>\n            {{- else }}\n            <svg class=\"forum-post-list-thumbnail hide-on-mobile\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"-9 -8 40 40\" stroke-width=\"1.5\" stroke=\"var(--color-text-subdue)\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 0 1 .865-.501 48.172 48.172 0 0 0 3.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0 0 12 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018Z\" />\n            </svg>\n            {{- end }}\n            {{- end }}\n            <div class=\"grow min-width-0\">\n                <a href=\"{{ .DiscussionUrl | safeURL }}\" class=\"size-title-dynamic color-primary-if-not-visited\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n                {{- if .Tags }}\n                <div class=\"inline-block forum-post-tags-container\">\n                    <ul class=\"attachments\">\n                    {{- range .Tags }}\n                    <li>{{ . }}</li>\n                    {{- end }}\n                    </ul>\n                </div>\n                {{- end }}\n                <ul class=\"list-horizontal-text flex-nowrap text-compact\">\n                    <li {{ dynamicRelativeTimeAttrs .TimePosted }}></li>\n                    <li class=\"shrink-0\">{{ .Score | formatApproxNumber }} points</li>\n                    <li class=\"shrink-0{{ if .TargetUrl | safeURL }} forum-post-autohide{{ end }}\">{{ .CommentCount | formatApproxNumber }} comments</li>\n                    {{- if .TargetUrl }}\n                    <li class=\"min-width-0\"><a class=\"visited-indicator text-truncate block\" href=\"{{ .TargetUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .TargetUrlDomain }}</a></li>\n                    {{- end }}\n                </ul>\n            </div>\n        </div>\n    </li>\n    {{- end }}\n</ul>\n{{- end }}\n"
  },
  {
    "path": "internal/glance/templates/group.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"widget-group-header\">\n    <div class=\"widget-header gap-20\" role=\"tablist\">\n        {{- range $i, $widget := .Widgets }}\n        <button class=\"widget-group-title{{ if eq $i 0 }} widget-group-title-current{{ end }}\"{{ if ne \"\" .TitleURL }} data-title-url=\"{{ .TitleURL }}\"{{ end }} aria-selected=\"{{ if eq $i 0 }}true{{ else }}false{{ end }}\" arial-level=\"2\" role=\"tab\" aria-controls=\"widget-{{ .GetID }}-tabpanel-{{ $i }}\" id=\"widget-{{ .GetID }}-tab-{{ $i }}\">{{ $widget.Title }}</button>\n        {{- end }}\n    </div>\n</div>\n\n<div class=\"widget-group-contents\">\n{{- range $i, $widget := .Widgets }}\n    <div class=\"widget-group-content{{ if eq $i 0 }} widget-group-content-current{{ end }}\" id=\"widget-{{ .GetID }}-tabpanel-{{ $i }}\" role=\"tabpanel\" aria-labelledby=\"widget-{{ .GetID }}-tab-{{ $i }}\" aria-hidden=\"{{ if eq $i 0 }}false{{ else }}true{{ end }}\">\n        {{- .Render -}}\n    </div>\n{{- end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/iframe.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<iframe src=\"{{ .Source }}\" width=\"100%\" height=\"{{ .Height }}px\" frameborder=\"0\"></iframe>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/login.html",
    "content": "{{- template \"document.html\" . }}\n\n{{- define \"document-title\" }}Login{{ end }}\n\n{{- define \"document-head-before\" }}\n<link rel=\"preload\" href='{{ .App.StaticAssetPath \"js/templating.js\" }}' as=\"script\"/>\n<link rel=\"prefetch\" href='{{ .App.StaticAssetPath \"js/page.js\" }}'/>\n{{- end }}\n\n{{- define \"document-head-after\" }}\n<link rel=\"stylesheet\" href='{{ .App.StaticAssetPath \"css/login.css\" }}'>\n<script type=\"module\" src='{{ .App.StaticAssetPath \"js/login.js\" }}'></script>\n{{- end }}\n\n{{- define \"document-body\" }}\n<div class=\"flex flex-column body-content\">\n    <div class=\"flex grow items-center justify-center\" style=\"padding-bottom: 5rem\">\n        <h1 class=\"visually-hidden\">Login</h1>\n        <main id=\"login-container\" class=\"grow login-bounds\" style=\"display: none;\">\n            <div class=\"animate-entrance\">\n                <label class=\"form-label widget-header\" for=\"username\">Username</label>\n                <div class=\"form-input widget-content-frame padding-inline-widget flex gap-10 items-center\">\n                    <svg class=\"form-input-icon\" fill=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n                        <path d=\"M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z\" />\n                    </svg>\n                    <input type=\"text\" id=\"username\" class=\"input\" placeholder=\"Enter your username\" autocomplete=\"off\">\n                </div>\n            </div>\n\n            <div class=\"animate-entrance\">\n                <label class=\"form-label widget-header margin-top-20\" for=\"password\">Password</label>\n                <div class=\"form-input widget-content-frame padding-inline-widget flex gap-10 items-center\">\n                    <svg class=\"form-input-icon\" fill=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" aria-hidden=\"true\">\n                        <path fill-rule=\"evenodd\" d=\"M8 7a5 5 0 1 1 3.61 4.804l-1.903 1.903A1 1 0 0 1 9 14H8v1a1 1 0 0 1-1 1H6v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-2a1 1 0 0 1 .293-.707L8.196 8.39A5.002 5.002 0 0 1 8 7Zm5-3a.75.75 0 0 0 0 1.5A1.5 1.5 0 0 1 14.5 7 .75.75 0 0 0 16 7a3 3 0 0 0-3-3Z\" clip-rule=\"evenodd\" />\n                    </svg>\n                    <input type=\"password\" id=\"password\" class=\"input\" placeholder=\"********\" autocomplete=\"off\">\n                    <button class=\"toggle-password-visibility\" id=\"toggle-password-visibility\" tabindex=\"-1\"></button>\n                </div>\n            </div>\n\n            <div class=\"login-error-message\" id=\"error-message\"></div>\n\n            <button class=\"login-button animate-entrance\" id=\"login-button\">\n                <div>LOGIN</div>\n                <svg stroke=\"currentColor\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" aria-hidden=\"true\">\n                    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3\" />\n                </svg>\n            </button>\n        </main>\n    </div>\n    {{ template \"footer.html\" . }}\n</div>\n{{- end }}\n"
  },
  {
    "path": "internal/glance/templates/manifest.json",
    "content": "{\n    \"name\": \"{{ .App.Config.Branding.AppName }}\",\n    \"display\": \"standalone\",\n    \"background_color\": \"{{ .App.Config.Branding.AppBackgroundColor }}\",\n    \"theme_color\": \"{{ .App.Config.Branding.AppBackgroundColor }}\",\n    \"scope\": \"/\",\n    \"start_url\": \"/\",\n    \"icons\": [\n        {\n            \"src\": \"{{ .App.Config.Branding.AppIconURL }}\",\n            \"type\": \"image/png\",\n            \"sizes\": \"512x512\"\n        }\n    ]\n}\n"
  },
  {
    "path": "internal/glance/templates/markets.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"dynamic-columns list-gap-20 list-with-separator\">\n    {{ range .Markets }}\n    <div class=\"flex items-center gap-15\">\n        <div class=\"min-width-0\">\n            <a{{ if ne \"\" .SymbolLink }} href=\"{{ .SymbolLink }}\" target=\"_blank\" rel=\"noreferrer\"{{ end }} class=\"color-highlight size-h3 block text-truncate\">{{ .Symbol }}</a>\n            <div class=\"text-truncate\">{{ .Name }}</div>\n        </div>\n\n        <a class=\"market-chart\" {{ if ne \"\" .ChartLink }} href=\"{{ .ChartLink }}\" target=\"_blank\" rel=\"noreferrer\"{{ end }}>\n            <svg class=\"market-chart shrink-0\" viewBox=\"0 0 100 50\">\n                <polyline fill=\"none\" stroke=\"var(--color-text-subdue)\" stroke-linejoin=\"round\" stroke-width=\"1.5px\" points=\"{{ .SvgChartPoints }}\" vector-effect=\"non-scaling-stroke\"></polyline>\n            </svg>\n        </a>\n\n        <div class=\"market-values shrink-0\">\n            <div class=\"size-h3 text-right {{ if eq .PercentChange 0.0 }}{{ else if gt .PercentChange 0.0 }}color-positive{{ else }}color-negative{{ end }}\">{{ printf \"%+.2f\" .PercentChange }}%</div>\n            <div class=\"text-right\">{{ .Currency }}{{ .Price | formatPriceWithPrecision .PriceHint }}</div>\n        </div>\n    </div>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/monitor-compact.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n{{ if not (and .ShowFailingOnly (not .HasFailing)) }}\n<ul class=\"dynamic-columns list-gap-8\">\n    {{ range .Sites }}\n    {{ if and $.ShowFailingOnly (eq .StatusStyle \"ok\" ) }}{{ continue }}{{ end }}\n    <div class=\"flex items-center gap-12\">\n        {{ template \"site\" . }}\n    </div>\n    {{ end }}\n</ul>\n{{ else }}\n<div class=\"flex items-center justify-center gap-10 padding-block-5\">\n    <p>All sites are online</p>\n    <svg class=\"shrink-0\" style=\"width: 1.7rem;\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"var(--color-positive)\">\n        <path fill-rule=\"evenodd\" d=\"M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ end }}\n{{ end }}\n\n{{ define \"site\" }}\n<a class=\"size-title-dynamic color-highlight text-truncate block grow\" href=\"{{ .URL | safeURL }}\" {{ if not .SameTab }}target=\"_blank\"{{ end }} rel=\"noreferrer\">{{ .Title }}</a>\n{{ if not .Status.TimedOut }}<div>{{ .Status.ResponseTime.Milliseconds | formatNumber }}ms</div>{{ end }}\n{{ if eq .StatusStyle \"ok\" }}\n<div class=\"monitor-site-status-icon-compact\" title=\"{{ .Status.Code }}\">\n    <svg fill=\"var(--color-positive)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\">\n        <path fill-rule=\"evenodd\" d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ else }}\n<div class=\"monitor-site-status-icon-compact\" title=\"{{ if .Status.Error }}{{ .Status.Error }}{{ else }}{{ .Status.Code }}{{ end }}\">\n    <svg fill=\"var(--color-negative)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\">\n        <path fill-rule=\"evenodd\" d=\"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ end }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/monitor.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n{{ if not (and .ShowFailingOnly (not .HasFailing)) }}\n<ul class=\"dynamic-columns list-gap-20 list-with-separator\">\n    {{ range .Sites }}\n    {{ if and $.ShowFailingOnly (eq .StatusStyle \"ok\" ) }} {{ continue }} {{ end }}\n    <div class=\"monitor-site flex items-center gap-15\">\n        {{ template \"site\" . }}\n    </div>\n    {{ end }}\n</ul>\n{{ else }}\n<div class=\"flex items-center justify-center gap-10 padding-block-5\">\n    <p>All sites are online</p>\n    <svg class=\"shrink-0\" style=\"width: 1.7rem;\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"var(--color-positive)\">\n        <path fill-rule=\"evenodd\" d=\"M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ end }}\n{{ end }}\n\n{{ define \"site\" }}\n{{ if .Icon.URL }}\n<img class=\"monitor-site-icon{{ if .Icon.AutoInvert }} flat-icon{{ end }}\" src=\"{{ .Icon.URL }}\" alt=\"\" loading=\"lazy\">\n{{ end }}\n<div class=\"grow min-width-0\">\n    <a class=\"size-h3 color-highlight text-truncate block\" href=\"{{ .URL | safeURL }}\" {{ if not .SameTab }}target=\"_blank\"{{ end }} rel=\"noreferrer\">{{ .Title }}</a>\n    <ul class=\"list-horizontal-text\">\n        {{ if not .Status.Error }}\n        <li title=\"{{ .Status.Code }}\">{{ .StatusText }}</li>\n        <li>{{ .Status.ResponseTime.Milliseconds | formatNumber }}ms</li>\n        {{ else if .Status.TimedOut }}\n        <li class=\"color-negative\">Timed Out</li>\n        {{ else }}\n        <li class=\"color-negative\" title=\"{{ .Status.Error }}\">ERROR</li>\n        {{ end }}\n    </ul>\n</div>\n{{ if eq .StatusStyle \"ok\" }}\n<div class=\"monitor-site-status-icon\">\n    <svg fill=\"var(--color-positive)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\">\n        <path fill-rule=\"evenodd\" d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16Zm3.857-9.809a.75.75 0 0 0-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 1 0-1.06 1.061l2.5 2.5a.75.75 0 0 0 1.137-.089l4-5.5Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ else }}\n<div class=\"monitor-site-status-icon\">\n    <svg fill=\"var(--color-negative)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\">\n        <path fill-rule=\"evenodd\" d=\"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495ZM10 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 10 5Zm0 9a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z\" clip-rule=\"evenodd\" />\n    </svg>\n</div>\n{{ end }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/old-calendar.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"widget-small-content-bounds\">\n    <div class=\"flex justify-between items-center\">\n        <div class=\"color-highlight size-h1\">{{ .Calendar.CurrentMonthName }}</div>\n        <ul class=\"list-horizontal-text color-highlight size-h4\">\n            <li>Week {{ .Calendar.CurrentWeekNumber }}</li>\n            <li>{{ .Calendar.CurrentYear }}</li>\n        </ul>\n    </div>\n\n    <div class=\"flex flex-wrap size-h6 margin-top-10 color-subdue\">\n        {{ if .StartSunday }}\n            <div class=\"old-calendar-day\">Su</div>\n        {{ end }}\n        <div class=\"old-calendar-day\">Mo</div>\n        <div class=\"old-calendar-day\">Tu</div>\n        <div class=\"old-calendar-day\">We</div>\n        <div class=\"old-calendar-day\">Th</div>\n        <div class=\"old-calendar-day\">Fr</div>\n        <div class=\"old-calendar-day\">Sa</div>\n        {{ if not .StartSunday }}\n            <div class=\"old-calendar-day\">Su</div>\n        {{ end }}\n    </div>\n\n    <div class=\"flex flex-wrap\">\n        {{ range .Calendar.Days }}\n        <div class=\"old-calendar-day{{ if eq . $.Calendar.CurrentDay }} old-calendar-day-today{{ end }}\">{{ . }}</div>\n        {{ end }}\n    </div>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/page-content.html",
    "content": "{{ if .Page.ShowMobileHeader }}\n<div class=\"mobile-reachability-header\">{{ .Page.Title }}</div>\n{{ end }}\n\n{{ if .Page.HeadWidgets }}\n<div class=\"head-widgets\">\n    {{- range .Page.HeadWidgets }}\n    {{- .Render }}\n    {{- end }}\n</div>\n{{ end }}\n\n<div class=\"page-columns\">\n{{- range .Page.Columns }}\n    <div class=\"page-column page-column-{{ .Size }}\">\n        {{- range .Widgets }}\n        {{- .Render }}\n        {{- end }}\n    </div>\n{{- end }}\n</div>\n"
  },
  {
    "path": "internal/glance/templates/page.html",
    "content": "{{ template \"document.html\" . }}\n\n{{ define \"document-title\" }}{{ .Page.Title }}{{ end }}\n\n{{ define \"document-head-after\" }}\n<script type=\"module\" src='{{ .App.StaticAssetPath \"js/page.js\" }}'></script>\n{{ end }}\n\n{{ define \"navigation-links\" }}\n{{ range .App.Config.Pages }}\n<a href=\"{{ $.App.Config.Server.BaseURL }}/{{ .Slug }}\" class=\"nav-item{{ if eq .Slug $.Page.Slug }} nav-item-current{{ end }}\"{{ if eq .Slug $.Page.Slug }} aria-current=\"page\"{{ end }}>{{ .Title }}</a>\n{{ end }}\n{{ end }}\n\n{{ define \"document-body\" }}\n<div class=\"flex flex-column body-content\">\n    {{ if not .Page.HideDesktopNavigation }}\n    <div class=\"header-container content-bounds{{ if .Page.DesktopNavigationWidth }} content-bounds-{{ .Page.DesktopNavigationWidth }} {{ end }}\">\n        <div class=\"header flex padding-inline-widget widget-content-frame\">\n            <div class=\"logo\" aria-hidden=\"true\">\n                {{- if .App.Config.Branding.LogoURL }}\n                <img src=\"{{ .App.Config.Branding.LogoURL }}\" alt=\"\">\n                {{- else if .App.Config.Branding.LogoText }}\n                {{- .App.Config.Branding.LogoText }}\n                {{- else }}\n                <svg style=\"max-height: 2rem;\" width=\"100%\" viewBox=\"0 0 108 108\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n                    <rect fill=\"var(--color-text-subdue)\" width=\"50\" height=\"108\" rx=\"6.875\" />\n                    <path fill=\"var(--color-primary)\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M64.875 0C61.078 0 58 3.07804 58 6.875V43.125C58 46.922 61.078 50 64.875 50H101.125C104.922 50 108 46.922 108 43.125V6.875C108 3.07804 104.922 0 101.125 0H64.875ZM75.7545 11L71.3078 15.6814H85.2233C85.9209 15.6814 86.5835 15.6633 87.2113 15.627C87.839 15.5544 88.3273 15.4093 88.6761 15.1915L70 34.5706L73.4004 38L91.8149 18.7843C91.6056 19.1835 91.4487 19.7097 91.3441 20.3629C91.2743 20.9798 91.2394 21.5968 91.2394 22.2137V37.1835L96 32.2843V11H75.7545Z\"/>\n                    <rect fill=\"var(--color-text-base)\" x=\"58\" y=\"58\" width=\"50\" height=\"50\" rx=\"6.875\" />\n                </svg>\n                {{- end }}\n            </div>\n            <nav class=\"nav flex grow hide-scrollbars\">\n                {{ template \"navigation-links\" . }}\n            </nav>\n            {{ if not .App.Config.Theme.DisablePicker }}\n            <div class=\"theme-picker self-center\" data-popover-type=\"html\" data-popover-position=\"below\" data-popover-show-delay=\"0\">\n                <div class=\"current-theme-preview\">\n                    {{ .Request.Theme.PreviewHTML }}\n                </div>\n                <div data-popover-html>\n                    <div class=\"theme-choices\"></div>\n                </div>\n            </div>\n            {{ end }}\n            {{- if .App.RequiresAuth }}\n            <a class=\"block self-center\" href=\"{{ .App.Config.Server.BaseURL }}/logout\" title=\"Logout\">\n                <svg class=\"logout-button\" stroke=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15m3 0 3-3m0 0-3-3m3 3H9\" />\n                </svg>\n            </a>\n            {{- end }}\n        </div>\n    </div>\n    {{ end }}\n\n    <div class=\"mobile-navigation\">\n        <div class=\"mobile-navigation-icons\">\n            <a class=\"mobile-navigation-label\" href=\"#top\">↑</a>\n            {{ range $i, $column := .Page.Columns }}\n            <label class=\"mobile-navigation-label\"><input type=\"radio\" class=\"mobile-navigation-input\" name=\"column\" value=\"{{ $i }}\" autocomplete=\"off\"{{ if eq $i $.Page.PrimaryColumnIndex }} checked{{ end }}><div class=\"mobile-navigation-pill\"></div></label>\n            {{ end }}\n            <label class=\"mobile-navigation-label\"><input type=\"checkbox\" class=\"mobile-navigation-page-links-input\" autocomplete=\"on\"><div class=\"hamburger-icon\"></div></label>\n        </div>\n\n        <div class=\"mobile-navigation-page-links hide-scrollbars\">\n            {{ template \"navigation-links\" . }}\n        </div>\n\n        <div class=\"mobile-navigation-actions flex flex-column margin-block-10\">\n            {{ if not .App.Config.Theme.DisablePicker }}\n            <div class=\"theme-picker flex justify-between items-center\" data-popover-type=\"html\" data-popover-position=\"above\" data-popover-show-delay=\"0\" data-popover-hide-delay=\"100\" data-popover-anchor=\".current-theme-preview\" data-popover-trigger=\"click\">\n                <div data-popover-html>\n                    <div class=\"theme-choices\">\n                        {{ .App.Config.Theme.PreviewHTML }}\n                        {{ range $_, $preset := .App.Config.Theme.Presets.Items }}\n                        {{ $preset.PreviewHTML }}\n                        {{ end }}\n                    </div>\n                </div>\n\n                <div class=\"size-h3 pointer-events-none select-none\">Change theme</div>\n\n                <div class=\"flex gap-15 items-center pointer-events-none\">\n                    <div class=\"current-theme-preview\">\n                        {{ .Request.Theme.PreviewHTML }}\n                    </div>\n                    <svg class=\"ui-icon\" stroke=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                        <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M4.098 19.902a3.75 3.75 0 0 0 5.304 0l6.401-6.402M6.75 21A3.75 3.75 0 0 1 3 17.25V4.125C3 3.504 3.504 3 4.125 3h5.25c.621 0 1.125.504 1.125 1.125v4.072M6.75 21a3.75 3.75 0 0 0 3.75-3.75V8.197M6.75 21h13.125c.621 0 1.125-.504 1.125-1.125v-5.25c0-.621-.504-1.125-1.125-1.125h-4.072M10.5 8.197l2.88-2.88c.438-.439 1.15-.439 1.59 0l3.712 3.713c.44.44.44 1.152 0 1.59l-2.879 2.88M6.75 17.25h.008v.008H6.75v-.008Z\" />\n                    </svg>\n                </div>\n            </div>\n            {{ end }}\n\n            {{ if .App.RequiresAuth }}\n            <a href=\"{{ .App.Config.Server.BaseURL }}/logout\" class=\"flex justify-between items-center\">\n                <div class=\"size-h3\">Logout</div>\n                <svg class=\"ui-icon\" stroke=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 9V5.25A2.25 2.25 0 0 0 13.5 3h-6a2.25 2.25 0 0 0-2.25 2.25v13.5A2.25 2.25 0 0 0 7.5 21h6a2.25 2.25 0 0 0 2.25-2.25V15m3 0 3-3m0 0-3-3m3 3H9\" />\n                </svg>\n            </a>\n            {{ end }}\n        </div>\n    </div>\n\n    <div class=\"content-bounds grow{{ if .Page.Width }} content-bounds-{{ .Page.Width }}{{ end }}\">\n        <main class=\"page{{ if .Page.CenterVertically }} center-vertically{{ end }}\" id=\"page\" aria-live=\"polite\" aria-busy=\"true\">\n            <h1 class=\"visually-hidden\">{{ .Page.Title }}</h1>\n            <div class=\"page-content\" id=\"page-content\"></div>\n            <div class=\"page-loading-container\">\n                <div class=\"visually-hidden\">Loading</div>\n                <div class=\"loading-icon\" aria-hidden=\"true\"></div>\n            </div>\n        </main>\n    </div>\n\n    {{ template \"footer.html\" . }}\n    <div class=\"mobile-navigation-offset\"></div>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/reddit-horizontal-cards.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"carousel-container\">\n    <div class=\"cards-horizontal carousel-items-container\">\n        {{ range .Posts }}\n        <div class=\"card widget-content-frame relative\">\n            {{ if ne \"\" .ThumbnailUrl }}\n            <div class=\"reddit-card-thumbnail-container\">\n                <img class=\"reddit-card-thumbnail\" loading=\"lazy\" src=\"{{ .ThumbnailUrl }}\" alt=\"\">\n            </div>\n            {{ end }}\n            <div class=\"padding-widget flex flex-column grow relative\">\n                {{ if ne \"\" .TargetUrl }}\n                <a class=\"color-highlight size-h5 text-truncate visited-indicator\" href=\"{{ .TargetUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .TargetUrlDomain }}</a>\n                {{ else }}\n                <div class=\"color-highlight size-h5 text-truncate\">/r/{{ $.Subreddit }}</div>\n                {{ end }}\n                <a href=\"{{ .DiscussionUrl }}\" class=\"text-truncate-3-lines color-primary-if-not-visited margin-top-7 margin-bottom-auto\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n                <ul class=\"list-horizontal-text margin-top-7\">\n                    <li {{ dynamicRelativeTimeAttrs .TimePosted }}></li>\n                    <li>{{ .Score | formatApproxNumber }} points</li>\n                </ul>\n            </div>\n        </div>\n        {{ end }}\n    </div>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/reddit-vertical-cards.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"cards-vertical\">\n    {{ range .Posts }}\n    <div class=\"widget-content-frame relative\">\n        {{ if ne \"\" .ThumbnailUrl }}\n        <div class=\"reddit-card-thumbnail-container\">\n            <img class=\"reddit-card-thumbnail\" loading=\"lazy\" src=\"{{ .ThumbnailUrl }}\" alt=\"\">\n        </div>\n        {{ end }}\n        <div class=\"padding-widget relative\">\n            {{ if ne \"\" .TargetUrl }}\n            <a class=\"color-highlight size-h5 text-truncate visited-indicator block\" href=\"{{ .TargetUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .TargetUrlDomain }}</a>\n            {{ else }}\n            <div class=\"color-highlight size-h5 text-truncate\">/r/{{ $.Subreddit }}</div>\n            {{ end }}\n            <a href=\"{{ .DiscussionUrl }}\" class=\"text-truncate-3-lines color-primary-if-not-visited margin-top-7\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n            <ul class=\"list-horizontal-text margin-top-7\">\n                <li {{ dynamicRelativeTimeAttrs .TimePosted }}></li>\n                <li>{{ .Score | formatApproxNumber }} points</li>\n            </ul>\n        </div>\n    </div>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/releases.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-10 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .Releases }}\n    <li>\n        <div class=\"flex items-center gap-10\">\n            <a class=\"size-h4 block text-truncate color-primary-if-not-visited\" href=\"{{ .NotesUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Name }}</a>\n            {{ if $.ShowSourceIcon }}\n            <img class=\"flat-icon release-source-icon\" src=\"{{ .SourceIconURL }}\" alt=\"\" loading=\"lazy\">\n            {{ end }}\n        </div>\n        <ul class=\"list-horizontal-text\">\n            <li {{ dynamicRelativeTimeAttrs .TimeReleased }}></li>\n            <li>{{ .Version }}</li>\n            {{ if gt .Downvotes 3 }}\n            <li>{{ .Downvotes | formatNumber }} ⚠</li>\n            {{ end }}\n        </ul>\n    </li>\n    {{ end }}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/repository.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<a class=\"size-h4 color-highlight\" href=\"https://github.com/{{ $.Repository.Name }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Repository.Name }}</a>\n<ul class=\"list-horizontal-text\">\n    <li>{{ .Repository.Stars | formatNumber }} stars</li>\n    <li>{{ .Repository.Forks | formatNumber }} forks</li>\n</ul>\n\n{{ if gt (len .Repository.Commits) 0 }}\n<hr class=\"margin-block-8\">\n<a class=\"text-compact\" href=\"https://github.com/{{ $.Repository.Name }}/commits\" target=\"_blank\" rel=\"noreferrer\">Last {{ .CommitsLimit }} commits</a>\n<div class=\"flex gap-7 size-h5 size-base-on-mobile margin-top-3\">\n    <ul class=\"list list-gap-2\">\n        {{ range .Repository.Commits }}\n        <li {{ dynamicRelativeTimeAttrs .CreatedAt }}></li>\n        {{ end }}\n    </ul>\n    <ul class=\"list list-gap-2 min-width-0\">\n        {{ range .Repository.Commits }}\n        <li><a class=\"color-primary-if-not-visited text-truncate block\" title=\"{{ .Author }}\" target=\"_blank\" rel=\"noreferrer\" href=\"https://github.com/{{ $.Repository.Name }}/commit/{{ .Sha }}\">{{ .Message }}</a></li>\n        {{ end }}\n    </ul>\n</div>\n{{ end }}\n\n{{ if gt (len .Repository.PullRequests) 0 }}\n<hr class=\"margin-block-8\">\n<a class=\"text-compact\" href=\"https://github.com/{{ $.Repository.Name }}/pulls\" target=\"_blank\" rel=\"noreferrer\">Open pull requests ({{ .Repository.OpenPullRequests | formatNumber }} total)</a>\n<div class=\"flex gap-7 size-h5 size-base-on-mobile margin-top-3\">\n    <ul class=\"list list-gap-2\">\n        {{ range .Repository.PullRequests }}\n        <li {{ dynamicRelativeTimeAttrs .CreatedAt }}></li>\n        {{ end }}\n    </ul>\n    <ul class=\"list list-gap-2 min-width-0\">\n        {{ range .Repository.PullRequests }}\n        <li><a class=\"color-primary-if-not-visited text-truncate block\" target=\"_blank\" rel=\"noreferrer\" href=\"https://github.com/{{ $.Repository.Name }}/pull/{{ .Number }}\">{{ .Title }}</a></li>\n        {{ end }}\n    </ul>\n</div>\n{{ end }}\n\n{{ if gt (len .Repository.Issues) 0 }}\n<hr class=\"margin-block-10\">\n<a class=\"text-compact\" href=\"https://github.com/{{ $.Repository.Name }}/issues\" target=\"_blank\" rel=\"noreferrer\">Open issues ({{ .Repository.OpenIssues | formatNumber }} total)</a>\n<div class=\"flex gap-7 size-h5 size-base-on-mobile margin-top-3\">\n    <ul class=\"list list-gap-2\">\n        {{ range .Repository.Issues }}\n        <li {{ dynamicRelativeTimeAttrs .CreatedAt }}></li>\n        {{ end }}\n    </ul>\n    <ul class=\"list list-gap-2 min-width-0\">\n        {{ range .Repository.Issues }}\n        <li><a class=\"color-primary-if-not-visited text-truncate block\" target=\"_blank\" rel=\"noreferrer\" href=\"https://github.com/{{ $.Repository.Name }}/issues/{{ .Number }}\">{{ .Title }}</a></li>\n        {{ end }}\n    </ul>\n</div>\n{{ end }}\n\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/rss-detailed-list.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-24 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .Items }}\n    <li class=\"flex gap-15 items-start row-reverse-on-mobile thumbnail-parent\">\n        <div class=\"thumbnail-container rss-detailed-thumbnail\">\n            {{ if ne \"\" .ImageURL }}\n            <img class=\"thumbnail\" loading=\"lazy\" src=\"{{ .ImageURL }}\" alt=\"\">\n            {{ else }}\n            <svg class=\"scale-half hide-on-mobile\" stroke=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\" />\n            </svg>\n            {{ end }}\n        </div>\n        <div class=\"grow min-width-0\">\n            <a class=\"size-h3 color-primary-if-not-visited\" href=\"{{ .Link }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n            <ul class=\"list-horizontal-text flex-nowrap\">\n                <li {{ dynamicRelativeTimeAttrs .PublishedAt }}></li>\n                <li class=\"min-width-0\">\n                    <a class=\"block text-truncate\" href=\"{{ .ChannelURL }}\" target=\"_blank\" rel=\"noreferrer\">{{ .ChannelName }}</a>\n                </li>\n            </ul>\n            {{ if ne \"\" .Description }}\n            <p class=\"rss-detailed-description text-truncate-2-lines margin-top-10\">{{ .Description }}</p>\n            {{ end }}\n            {{ if gt (len .Categories) 0 }}\n            <ul class=\"attachments margin-top-10\">\n            {{ range .Categories }}\n                <li>{{ . }}</li>\n            {{ end }}\n            </ul>\n            {{ end }}\n        </div>\n    </li>\n    {{ else }}\n    <li>{{ .NoItemsMessage }}</li>\n    {{ end }}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/rss-horizontal-cards-2.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n{{ if gt (len .Items) 0 }}\n<div class=\"carousel-container\">\n    <div class=\"cards-horizontal carousel-items-container\"{{ if ne 0.0 .CardHeight }} style=\"--rss-card-height: {{ .CardHeight }}rem;\"{{ end }}>\n        {{ range .Items }}\n        <div class=\"card rss-card-2 widget-content-frame thumbnail-parent\">\n            {{ if ne \"\" .ImageURL }}\n            <img class=\"rss-card-2-image thumbnail\" loading=\"lazy\" src=\"{{ .ImageURL }}\" alt=\"\">\n            {{ else }}\n            <svg class=\"rss-card-2-image\" style=\"transform: scale(0.35) translateY(-25%)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" stroke=\"var(--color-text-subdue)\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\" />\n            </svg>\n            {{ end }}\n            <div class=\"rss-card-2-content padding-inline-widget\">\n                <a href=\"{{ .Link }}\" class=\"block text-truncate color-primary-if-not-visited\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n                <ul class=\"list-horizontal-text flex-nowrap margin-top-5\">\n                    <li class=\"shrink-0\" {{ dynamicRelativeTimeAttrs .PublishedAt }}></li>\n                    <li class=\"min-width-0 text-truncate\">{{ .ChannelName }}</li>\n                </ul>\n            </div>\n        </div>\n        {{ end }}\n    </div>\n</div>\n{{ else }}\n<div class=\"widget-content-frame padding-widget\">{{ .NoItemsMessage }}</div>\n{{ end }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/rss-horizontal-cards.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n{{ if gt (len .Items) 0 }}\n<div class=\"carousel-container\">\n    <div class=\"cards-horizontal carousel-items-container\"{{ if ne 0.0 .ThumbnailHeight }} style=\"--rss-thumbnail-height: {{ .ThumbnailHeight }}rem;\"{{ end }}>\n        {{ range .Items }}\n        <div class=\"card widget-content-frame thumbnail-parent\">\n            {{ if ne \"\" .ImageURL }}\n            <img class=\"rss-card-image thumbnail\" loading=\"lazy\" src=\"{{ .ImageURL }}\" alt=\"\">\n            {{ else }}\n            <svg class=\"rss-card-image\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" stroke=\"var(--color-text-subdue)\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z\" />\n            </svg>\n            {{ end }}\n            <div class=\"margin-bottom-widget padding-inline-widget flex flex-column grow\">\n                <a href=\"{{ .Link }}\" class=\"text-truncate-3-lines color-primary-if-not-visited margin-top-10 margin-bottom-auto\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n                <ul class=\"list-horizontal-text flex-nowrap margin-top-7\">\n                    <li class=\"shrink-0\" {{ dynamicRelativeTimeAttrs .PublishedAt }}></li>\n                    <li class=\"min-width-0 text-truncate\">{{ .ChannelName }}</li>\n                </ul>\n            </div>\n        </div>\n        {{ end }}\n    </div>\n</div>\n{{ else }}\n<div class=\"widget-content-frame padding-widget\">{{ .NoItemsMessage }}</div>\n{{ end }}\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/rss-list.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container{{ if .SingleLineTitles }} single-line-titles{{ end }}\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .Items }}\n    <li>\n        <a class=\"title size-title-dynamic color-primary-if-not-visited\" href=\"{{ .Link }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n        <ul class=\"list-horizontal-text flex-nowrap\">\n            <li {{ dynamicRelativeTimeAttrs .PublishedAt }}></li>\n            <li class=\"min-width-0\">\n                <a class=\"block text-truncate\" href=\"{{ .ChannelURL }}\" target=\"_blank\" rel=\"noreferrer\">{{ .ChannelName }}</a>\n            </li>\n        </ul>\n    </li>\n    {{ else }}\n    <li>{{ .NoItemsMessage }}</li>\n    {{ end }}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/search.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"search widget-content-frame padding-inline-widget flex gap-15 items-center\" data-default-search-url=\"{{ .SearchEngine }}\" data-new-tab=\"{{ .NewTab }}\" data-target=\"{{ .Target }}\">\n    <div class=\"search-bangs\">\n        {{ range .Bangs }}\n        <input type=\"hidden\" data-shortcut=\"{{ .Shortcut }}\" data-title=\"{{ .Title }}\" data-url=\"{{ .URL }}\">\n        {{ end }}\n    </div>\n\n    <div class=\"search-icon-container\">\n        <svg class=\"search-icon\" stroke=\"var(--color-text-subdue)\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n            <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z\" />\n        </svg>\n    </div>\n\n    <input class=\"search-input\" type=\"text\" placeholder=\"{{ .Placeholder }}\" autocomplete=\"off\"{{ if .Autofocus }} autofocus{{ end }}>\n\n    <div class=\"search-bang\"></div>\n    <kbd class=\"hide-on-mobile\" title=\"Press [S] to focus the search input\">S</kbd>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/server-stats.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{- define \"widget-content\" }}\n{{- range .Servers }}\n<div class=\"server\">\n    <div class=\"server-info\">\n        <div class=\"server-details\">\n            <div class=\"server-name color-highlight size-h3\">{{ if .Name }}{{ .Name }}{{ else }}{{ .Info.Hostname }}{{ end }}</div>\n            <div>\n                {{- if .IsReachable }}\n                    {{ if .Info.HostInfoIsAvailable }}<span {{ dynamicRelativeTimeAttrs .Info.BootTime }}></span>{{ else }}unknown{{ end }} uptime\n                {{- else }}\n                    unreachable\n                {{- end }}\n            </div>\n        </div>\n        <div class=\"shrink-0\"{{ if .IsReachable }} data-popover-type=\"html\" data-popover-margin=\"0.2rem\" data-popover-max-width=\"400px\"{{ end }}>\n            {{- if .IsReachable }}\n            <div data-popover-html>\n                <div class=\"size-h5 text-compact\">PLATFORM</div>\n                <div class=\"color-highlight\">{{ if .Info.HostInfoIsAvailable }}{{ .Info.Platform }}{{ else }}Unknown{{ end }}</div>\n            </div>\n            {{- end }}\n            <svg class=\"server-icon\" stroke=\"var(--color-{{ if .IsReachable }}positive{{ else }}negative{{ end }})\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M21.75 17.25v-.228a4.5 4.5 0 0 0-.12-1.03l-2.268-9.64a3.375 3.375 0 0 0-3.285-2.602H7.923a3.375 3.375 0 0 0-3.285 2.602l-2.268 9.64a4.5 4.5 0 0 0-.12 1.03v.228m19.5 0a3 3 0 0 1-3 3H5.25a3 3 0 0 1-3-3m19.5 0a3 3 0 0 0-3-3H5.25a3 3 0 0 0-3 3m16.5 0h.008v.008h-.008v-.008Zm-3 0h.008v.008h-.008v-.008Z\" />\n            </svg>\n        </div>\n    </div>\n    <div class=\"server-stats\">\n        <div class=\"flex-1{{ if not .Info.CPU.LoadIsAvailable }} server-stat-unavailable{{ end }}\">\n            <div class=\"flex items-end size-h5\">\n                <div>CPU</div>\n                {{- if and .Info.CPU.TemperatureIsAvailable (ge .Info.CPU.TemperatureC 80) }}\n                <svg class=\"server-spicy-cpu-icon\" fill=\"var(--color-negative)\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\" >\n                    <path fill-rule=\"evenodd\" d=\"M8.074.945A4.993 4.993 0 0 0 6 5v.032c.004.6.114 1.176.311 1.709.16.428-.204.91-.61.7a5.023 5.023 0 0 1-1.868-1.677c-.202-.304-.648-.363-.848-.058a6 6 0 1 0 8.017-1.901l-.004-.007a4.98 4.98 0 0 1-2.18-2.574c-.116-.31-.477-.472-.744-.28Zm.78 6.178a3.001 3.001 0 1 1-3.473 4.341c-.205-.365.215-.694.62-.59a4.008 4.008 0 0 0 1.873.03c.288-.065.413-.386.321-.666A3.997 3.997 0 0 1 8 8.999c0-.585.126-1.14.351-1.641a.42.42 0 0 1 .503-.235Z\" clip-rule=\"evenodd\" />\n                </svg>\n                {{- end }}\n                <div class=\"color-highlight margin-left-auto text-very-compact\">{{ if .Info.CPU.LoadIsAvailable }}{{ .Info.CPU.Load1Percent }} <span class=\"color-base\">%</span>{{ else }}n/a{{ end }}</div>\n            </div>\n            <div{{ if .Info.CPU.LoadIsAvailable }} data-popover-type=\"html\"{{ end }}>\n                {{- if .Info.CPU.LoadIsAvailable }}\n                <div data-popover-html>\n                    <div class=\"flex\">\n                        <div class=\"size-h5\">1M AVG</div>\n                        <div class=\"value-separator\"></div>\n                        <div class=\"color-highlight text-very-compact\">{{ .Info.CPU.Load1Percent }} <span class=\"color-base size-h5\">%</span></div>\n                    </div>\n                    <div class=\"flex margin-top-3\">\n                        <div class=\"size-h5\">15M AVG</div>\n                        <div class=\"value-separator\"></div>\n                        <div class=\"color-highlight text-very-compact\">{{ .Info.CPU.Load15Percent }} <span class=\"color-base size-h5\">%</span></div>\n                    </div>\n                    {{- if .Info.CPU.TemperatureIsAvailable }}\n                    <div class=\"flex margin-top-3\">\n                        <div class=\"size-h5\">TEMP C</div>\n                        <div class=\"value-separator\"></div>\n                        <div class=\"color-highlight text-very-compact\">{{ .Info.CPU.TemperatureC }} <span class=\"color-base size-h5\">°</span></div>\n                    </div>\n                    {{- end }}\n                </div>\n                {{- end }}\n                <div class=\"progress-bar progress-bar-combined\">\n                    {{- if .Info.CPU.LoadIsAvailable }}\n                    <div class=\"progress-value{{ if ge .Info.CPU.Load1Percent 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ .Info.CPU.Load1Percent }}\"></div>\n                    <div class=\"progress-value{{ if ge .Info.CPU.Load15Percent 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ .Info.CPU.Load15Percent }}\"></div>\n                    {{- end }}\n                </div>\n            </div>\n        </div>\n        <div class=\"flex-1{{ if not .Info.Memory.IsAvailable }} server-stat-unavailable{{ end }}\">\n            <div class=\"flex justify-between items-end size-h5\">\n                <div>RAM</div>\n                <div class=\"color-highlight text-very-compact\">{{ if .Info.Memory.IsAvailable }}{{ .Info.Memory.UsedPercent }} <span class=\"color-base\">%</span>{{ else }}n/a{{ end }}</div>\n            </div>\n            <div{{ if .Info.Memory.IsAvailable }} data-popover-type=\"html\"{{ end }}>\n                {{- if .Info.Memory.IsAvailable }}\n                <div data-popover-html>\n                    <div class=\"flex\">\n                        <div class=\"size-h5\">RAM</div>\n                        <div class=\"value-separator\"></div>\n                        <div class=\"color-highlight text-very-compact\">\n                            {{ .Info.Memory.UsedMB | formatServerMegabytes }} <span class=\"color-base size-h5\">/</span> {{ .Info.Memory.TotalMB | formatServerMegabytes }}\n                        </div>\n                    </div>\n                    {{- if and (not .HideSwap) .Info.Memory.SwapIsAvailable }}\n                    <div class=\"flex margin-top-3\">\n                        <div class=\"size-h5\">SWAP</div>\n                        <div class=\"value-separator\"></div>\n                        <div class=\"color-highlight text-very-compact\">\n                            {{ .Info.Memory.SwapUsedMB | formatServerMegabytes }} <span class=\"color-base size-h5\">/</span> {{ .Info.Memory.SwapTotalMB | formatServerMegabytes }}\n                        </div>\n                    </div>\n                    {{- end }}\n                </div>\n                {{- end }}\n                <div class=\"progress-bar progress-bar-combined\">\n                    {{- if .Info.Memory.IsAvailable }}\n                    <div class=\"progress-value{{ if ge .Info.Memory.UsedPercent 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ .Info.Memory.UsedPercent }}\"></div>\n                    {{- if and (not .HideSwap) .Info.Memory.SwapIsAvailable }}\n                    <div class=\"progress-value{{ if ge .Info.Memory.SwapUsedPercent 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ .Info.Memory.SwapUsedPercent }}\"></div>\n                    {{- end }}\n                    {{- end }}\n                </div>\n            </div>\n        </div>\n        <div class=\"flex-1{{ if not .Info.Mountpoints }} server-stat-unavailable{{ end }}\">\n            <div class=\"flex justify-between items-end size-h5\">\n                <div>DISK</div>\n                <div class=\"color-highlight text-very-compact\">{{ if .Info.Mountpoints }}{{ (index .Info.Mountpoints 0).UsedPercent }} <span class=\"color-base\">%</span>{{ else }}n/a{{ end }}</div>\n            </div>\n            <div{{ if .Info.Mountpoints }} data-popover-type=\"html\"{{ end }}>\n                {{- if .Info.Mountpoints }}\n                <div data-popover-html>\n                    <ul class=\"list list-gap-2\">\n                        {{- range .Info.Mountpoints }}\n                        <li class=\"flex\">\n                            <div class=\"size-h5\">{{ if .Name }}{{ .Name }}{{ else }}{{ .Path }}{{ end }}</div>\n                            <div class=\"value-separator\"></div>\n                            <div class=\"color-highlight text-very-compact\">\n                                {{ .UsedMB | formatServerMegabytes }} <span class=\"color-base size-h5\">/</span> {{ .TotalMB | formatServerMegabytes }}\n                            </div>\n                        </li>\n                        {{- end }}\n                    </ul>\n                </div>\n                {{- end }}\n                <div class=\"progress-bar progress-bar-combined\">\n                    {{- if .Info.Mountpoints }}\n                    <div class=\"progress-value{{ if ge ((index .Info.Mountpoints 0).UsedPercent) 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ (index .Info.Mountpoints 0).UsedPercent }}\"></div>\n                    {{- if ge (len .Info.Mountpoints) 2 }}\n                    <div class=\"progress-value{{ if ge ((index .Info.Mountpoints 1).UsedPercent) 85 }} progress-value-notice{{ end }}\" style=\"--percent: {{ (index .Info.Mountpoints 1).UsedPercent }}\"></div>\n                    {{- end }}\n                    {{- end }}\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n{{- end }}\n{{- end }}\n"
  },
  {
    "path": "internal/glance/templates/split-column.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"masonry\" data-max-columns=\"{{ .MaxColumns }}\">\n{{ range .Widgets }}\n    {{ .Render }}\n{{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/theme-preset-preview.html",
    "content": "{{- $background := \"hsl(240, 8%, 9%)\" | safeCSS }}\n{{- $primary := \"hsl(43, 50%, 70%)\" | safeCSS  }}\n{{- $positive := \"hsl(43, 50%, 70%)\" | safeCSS }}\n{{- $negative := \"hsl(0, 70%, 70%)\" | safeCSS }}\n{{- if .BackgroundColor }}{{ $background = .BackgroundColor.String | safeCSS }}{{ end }}\n{{- if .PrimaryColor }}\n    {{- $primary = .PrimaryColor.String | safeCSS }}\n    {{- if not .PositiveColor }}\n        {{- $positive = $primary }}\n    {{- else }}\n        {{- $positive = .PositiveColor.String | safeCSS }}\n    {{- end }}\n{{- end }}\n{{- if .NegativeColor }}{{ $negative = .NegativeColor.String | safeCSS }}{{ end }}\n<button class=\"theme-preset{{ if .Light }} theme-preset-light{{ end }}\" style=\"--color: {{ $background }}\" data-key=\"{{ .Key }}\">\n    <div class=\"theme-color\" style=\"--color: {{ $primary }}\"></div>\n    <div class=\"theme-color\" style=\"--color: {{ $positive }}\"></div>\n    <div class=\"theme-color\" style=\"--color: {{ $negative }}\"></div>\n</button>\n"
  },
  {
    "path": "internal/glance/templates/theme-style.gotmpl",
    "content": ":root {\n    {{ if .BackgroundColor }}\n    --bgh: {{ .BackgroundColor.H }};\n    --bgs: {{ .BackgroundColor.S }}%;\n    --bgl: {{ .BackgroundColor.L }}%;\n    {{ end }}\n    {{ if ne 0.0 .ContrastMultiplier }}--cm: {{ .ContrastMultiplier }};{{ end }}\n    {{ if ne 0.0 .TextSaturationMultiplier }}--tsm: {{ .TextSaturationMultiplier }};{{ end }}\n    {{ if .PrimaryColor }}--color-primary: {{ .PrimaryColor.String | safeCSS }};{{ end }}\n    {{ if .PositiveColor }}--color-positive: {{ .PositiveColor.String | safeCSS }};{{ end }}\n    {{ if .NegativeColor }}--color-negative: {{ .NegativeColor.String | safeCSS }};{{ end }}\n}\n"
  },
  {
    "path": "internal/glance/templates/todo.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"todo\" data-todo-id=\"{{ .TodoID }}\"></div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/twitch-channels.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .Channels }}\n    <li>\n        <div class=\"{{ if .IsLive }}twitch-channel-live {{ end }}flex gap-10 items-start thumbnail-parent\">\n            <div class=\"twitch-channel-avatar-container\"{{ if .IsLive }} data-popover-type=\"html\" data-popover-position=\"above\" data-popover-margin=\"0.15rem\" data-popover-offset=\"0.2\"{{ end }}>\n                {{ if .IsLive }}\n                <div data-popover-html>\n                    <img class=\"twitch-stream-preview\" src=\"https://static-cdn.jtvnw.net/previews-ttv/live_user_{{ .Login }}-440x248.jpg\" loading=\"lazy\" alt=\"\">\n                    <p class=\"margin-top-10 color-highlight text-truncate-3-lines\">{{ .StreamTitle }}</p>\n                </div>\n                {{ end }}\n                {{ if .Exists }}\n                <a href=\"https://twitch.tv/{{ .Login }}\" target=\"_blank\" rel=\"noreferrer\">\n                    <img class=\"twitch-channel-avatar thumbnail\" src=\"{{ .AvatarUrl }}\" alt=\"\" loading=\"lazy\">\n                </a>\n                {{ else }}\n                <svg class=\"twitch-channel-avatar thumbnail\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\" stroke=\"currentColor\">\n                    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z\" />\n                </svg>\n                {{ end }}\n            </div>\n            <div class=\"min-width-0\">\n                <a href=\"https://twitch.tv/{{ .Login }}\" class=\"size-h3{{ if .IsLive }} color-highlight{{ end }} block text-truncate\" target=\"_blank\" rel=\"noreferrer\">{{ .Name }}</a>\n                {{ if .Exists }}\n                    {{ if .IsLive }}\n                        {{ if .Category }}\n                            <a class=\"text-truncate block\" href=\"https://www.twitch.tv/directory/category/{{ .CategorySlug }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Category }}</a>\n                        {{ end }}\n                    <ul class=\"list-horizontal-text\">\n                        <li {{ dynamicRelativeTimeAttrs .LiveSince }}></li>\n                        <li>{{ .ViewersCount | formatApproxNumber }} viewers</li>\n                    </ul>\n                    {{ else }}\n                    <div>Offline</div>\n                    {{ end }}\n                {{ else }}\n                <div class=\"color-negative\">Not found</div>\n                {{ end }}\n            </div>\n        </div>\n    </li>\n    {{ end }}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/twitch-games-list.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{ range .Categories }}\n    <li class=\"twitch-category thumbnail-parent\">\n        <div class=\"flex gap-10 items-start\">\n            <img class=\"twitch-category-thumbnail thumbnail\" loading=\"lazy\" src=\"{{ .AvatarUrl }}\" alt=\"\">\n            <div class=\"min-width-0\">\n                <a class=\"size-h3 color-highlight text-truncate block\" href=\"https://www.twitch.tv/directory/category/{{ .Slug }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Name }}</a>\n                <ul class=\"list-horizontal-text\">\n                    <li>{{ .ViewersCount | formatApproxNumber }} viewers</li>\n                    {{ if .IsNew }}\n                    <li class=\"color-primary\">NEW</li>\n                    {{ end }}\n                </ul>\n                <ul class=\"list-horizontal-text flex-nowrap\">\n                    {{ range $i, $tag := .Tags }}\n                        {{ if eq $i 0 }}\n                        <li class=\"shrink-0\">{{ $tag.Name }}</li>\n                        {{ else }}\n                        <li class=\"text-truncate min-width-0\">{{ $tag.Name }}</li>\n                        {{ end }}\n                    {{ end }}\n                </ul>\n            </div>\n        </div>\n    </li>\n    {{ end }}\n</ul>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/v0.7-update-notice-page.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <link rel=\"stylesheet\" href=\"static/main.css\">\n    <title>Update notice</title>\n    <style>\n        body {\n            display: flex;\n            align-items: center;\n            justify-content: center;\n        }\n\n        .content-bounds {\n            max-width: 700px;\n            margin-top: -10rem;\n        }\n\n        .comfy-line-height {\n            line-height: 1.9;\n        }\n    </style>\n</head>\n<body>\n\n<div class=\"content-bounds color-paragraph\">\n    <p class=\"uppercase size-h5 color-negative padding-inline-widget\">UPDATE NOTICE</p>\n    <div class=\"widget-content-frame margin-top-10 padding-widget\">\n        <p class=\"comfy-line-height\">\n            The default location of glance.yml in the Docker image has\n            changed since v0.7.0, please see the <a class=\"color-primary\" href=\"https://github.com/glanceapp/glance/blob/main/docs/v0.7.0-upgrade.md\" target=\"_blank\">migration guide</a>\n            for instructions or visit the <a class=\"color-primary\" href=\"https://github.com/glanceapp/glance/releases/tag/v0.7.0\" target=\"_blank\">release notes</a>\n            to find out more about why this change was necessary. Sorry for the inconvenience.\n        </p>\n\n        <p class=\"margin-top-15 color-base\">Migration should take around 5 minutes.</p>\n    </div>\n</div>\n\n</body>\n</html>\n"
  },
  {
    "path": "internal/glance/templates/video-card-contents.html",
    "content": "{{ define \"video-card-contents\" }}\n<img class=\"video-thumbnail thumbnail\" loading=\"lazy\" src=\"{{ .ThumbnailUrl }}\" alt=\"\">\n<div class=\"margin-top-10 margin-bottom-widget flex flex-column grow padding-inline-widget\">\n    <a class=\"text-truncate-2-lines margin-bottom-auto color-primary-if-not-visited\" href=\"{{ .Url | safeURL }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n    <ul class=\"list-horizontal-text flex-nowrap margin-top-7\">\n        <li class=\"shrink-0\" {{ dynamicRelativeTimeAttrs .TimePosted }}></li>\n        <li class=\"min-width-0\">\n            <a class=\"block text-truncate\" href=\"{{ .AuthorUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Author }}</a>\n        </li>\n    </ul>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/videos-grid.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"cards-grid collapsible-container\" data-collapse-after-rows=\"{{ .CollapseAfterRows }}\">\n    {{ range .Videos }}\n    <div class=\"card widget-content-frame thumbnail-parent\">\n        {{ template \"video-card-contents\" . }}\n    </div>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/videos-vertical-list.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{- define \"widget-content\" }}\n<ul class=\"list list-gap-14 collapsible-container\" data-collapse-after=\"{{ .CollapseAfter }}\">\n    {{- range .Videos }}\n    <li class=\"flex thumbnail-parent gap-10 items-center\">\n        <img class=\"video-horizontal-list-thumbnail thumbnail\" loading=\"lazy\" src=\"{{ .ThumbnailUrl }}\" alt=\"\">\n        <div class=\"min-width-0\">\n            <a class=\"block text-truncate color-primary-if-not-visited\" href=\"{{ .Url | safeURL }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Title }}</a>\n            <ul class=\"list-horizontal-text flex-nowrap\">\n                <li class=\"shrink-0\" {{ dynamicRelativeTimeAttrs .TimePosted }}></li>\n                <li class=\"min-width-0\">\n                    <a class=\"block text-truncate\" href=\"{{ .AuthorUrl }}\" target=\"_blank\" rel=\"noreferrer\">{{ .Author }}</a>\n                </li>\n            </ul>\n        </div>\n    </li>\n    {{- end }}\n</ul>\n{{- end }}\n"
  },
  {
    "path": "internal/glance/templates/videos.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content-classes\" }}widget-content-frameless{{ end }}\n\n{{ define \"widget-content\" }}\n<div class=\"carousel-container\">\n    <div class=\"cards-horizontal carousel-items-container\">\n        {{ range .Videos }}\n        <div class=\"card widget-content-frame thumbnail-parent\">\n            {{ template \"video-card-contents\" . }}\n        </div>\n        {{ end }}\n    </div>\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/weather.html",
    "content": "{{ template \"widget-base.html\" . }}\n\n{{ define \"widget-content\" }}\n<div class=\"widget-small-content-bounds\">\n    <div class=\"size-h2 color-highlight text-center\">{{ .Weather.WeatherCodeAsString }}</div>\n    <div class=\"size-h4 text-center\">Feels like {{ .Weather.ApparentTemperature }}°{{ if eq .Units \"metric\" }}C{{ else }}F{{ end }}</div>\n\n    <div class=\"weather-columns flex margin-top-15 justify-center\">\n        {{ range $i, $column := .Weather.Columns }}\n        <div class=\"weather-column{{ if eq $i $.Weather.CurrentColumn }} weather-column-current{{ end }}\">\n            {{ if $column.HasPrecipitation }}\n            <div class=\"weather-column-rain\"></div>\n            {{ end }}\n            {{ if and (ge $i $.Weather.SunriseColumn) (le $i $.Weather.SunsetColumn ) }}\n            <div class=\"weather-column-daylight{{ if eq $i $.Weather.SunriseColumn }} weather-column-daylight-sunrise{{ else if eq $i $.Weather.SunsetColumn }} weather-column-daylight-sunset{{ end }}\"></div>\n            {{ end }}\n            <div class=\"weather-column-value{{ if lt $column.Temperature 0 }} weather-column-value-negative{{ end }}\">{{ $column.Temperature | absInt }}</div>\n            <div class=\"weather-bar\" style='--weather-bar-height: {{ printf \"%.2f\" $column.Scale }}'></div>\n            <div class=\"weather-column-time\">{{ index $.TimeLabels $i }}</div>\n        </div>\n        {{ end }}\n    </div>\n\n    {{ if not .HideLocation }}\n    <div class=\"flex items-center justify-center margin-top-15 gap-7 size-h5\">\n        <div class=\"location-icon\"></div>\n        <div class=\"text-truncate\">{{ .Place.Name }},{{ if .ShowAreaName }} {{ .Place.Area }},{{ end }} {{ .Place.Country }}</div>\n    </div>\n    {{ end }}\n</div>\n{{ end }}\n"
  },
  {
    "path": "internal/glance/templates/widget-base.html",
    "content": "<div class=\"widget widget-type-{{ .GetType }}{{ if .CSSClass }} {{ .CSSClass }}{{ end }}\">\n    {{- if not .HideHeader }}\n    <div class=\"widget-header\">\n        {{- if ne \"\" .TitleURL }}\n        <h2><a href=\"{{ .TitleURL | safeURL }}\" target=\"_blank\" rel=\"noreferrer\" class=\"uppercase\">{{ .Title }}</a></h2>\n        {{- else }}\n        <h2 class=\"uppercase\">{{ .Title }}</h2>\n        {{- end }}\n        {{- if .IsWIP }}\n        <div data-popover-type=\"html\" data-popover-position=\"above\">\n            <div data-popover-html>\n                <p class=\"size-h5\">WORK IN PROGRESS</p>\n                <p class=\"margin-block-10 color-paragraph\">This widget is still in development, certain features may not work as expected or may change drastically.</p>\n                <a class=\"color-primary visited-indicator\" href=\"https://github.com/glanceapp/glance/issues\" target=\"_blank\" rel=\"noreferrer\">Report issue</a>\n            </div>\n            <svg class=\"widget-beta-icon cursor-help\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" fill=\"currentColor\">\n                <path fill-rule=\"evenodd\" d=\"M19 5.5a4.5 4.5 0 0 1-4.791 4.49c-.873-.055-1.808.128-2.368.8l-6.024 7.23a2.724 2.724 0 1 1-3.837-3.837L9.21 8.16c.672-.56.855-1.495.8-2.368a4.5 4.5 0 0 1 5.873-4.575c.324.105.39.51.15.752L13.34 4.66a.455.455 0 0 0-.11.494 3.01 3.01 0 0 0 1.617 1.617c.17.07.363.02.493-.111l2.692-2.692c.241-.241.647-.174.752.15.14.435.216.9.216 1.382ZM4 17a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z\" clip-rule=\"evenodd\" />\n            </svg>\n        </div>\n        {{- end }}\n        {{- if and .Error .ContentAvailable }}\n        <div class=\"notice-icon notice-icon-major\" title=\"{{ .Error }}\"></div>\n        {{- else if .Notice }}\n        <div class=\"notice-icon notice-icon-minor\" title=\"{{ .Notice }}\"></div>\n        {{- end }}\n    </div>\n    {{- end }}\n    <div class=\"widget-content{{ if .ContentAvailable }} {{ block \"widget-content-classes\" . }}{{ end }}{{ end }}\">\n        {{- if .ContentAvailable }}\n        {{ block \"widget-content\" . }}{{ end }}\n        {{- else }}\n            <div class=\"widget-error-header\">\n                <div class=\"color-negative size-h3\">ERROR</div>\n                <svg class=\"widget-error-icon\" xmlns=\"http://www.w3.org/2000/svg\" fill=\"none\" viewBox=\"0 0 24 24\" stroke-width=\"1.5\">\n                    <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z\" />\n                </svg>\n            </div>\n            <p class=\"break-all\">{{ if .Error }}{{ .Error }}{{ else }}No error information provided{{ end }}</p>\n        {{- end}}\n    </div>\n</div>\n"
  },
  {
    "path": "internal/glance/templates.go",
    "content": "package glance\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"math\"\n\t\"strconv\"\n\n\t\"golang.org/x/text/language\"\n\t\"golang.org/x/text/message\"\n)\n\nvar intl = message.NewPrinter(language.English)\n\nvar globalTemplateFunctions = template.FuncMap{\n\t\"formatApproxNumber\": formatApproxNumber,\n\t\"formatNumber\":       intl.Sprint,\n\t\"safeCSS\": func(str string) template.CSS {\n\t\treturn template.CSS(str)\n\t},\n\t\"safeURL\": func(str string) template.URL {\n\t\treturn template.URL(str)\n\t},\n\t\"safeHTML\": func(str string) template.HTML {\n\t\treturn template.HTML(str)\n\t},\n\t\"absInt\": func(i int) int {\n\t\treturn int(math.Abs(float64(i)))\n\t},\n\t\"formatPrice\": func(price float64) string {\n\t\treturn intl.Sprintf(\"%.2f\", price)\n\t},\n\t\"formatPriceWithPrecision\": func(precision int, price float64) string {\n\t\treturn intl.Sprintf(\"%.\"+strconv.Itoa(precision)+\"f\", price)\n\t},\n\t\"dynamicRelativeTimeAttrs\": dynamicRelativeTimeAttrs,\n\t\"formatServerMegabytes\": func(mb uint64) template.HTML {\n\t\tvar value string\n\t\tvar label string\n\n\t\tif mb < 1_000 {\n\t\t\tvalue = strconv.FormatUint(mb, 10)\n\t\t\tlabel = \"MB\"\n\t\t} else if mb < 1_000_000 {\n\t\t\tif mb < 10_000 {\n\t\t\t\tvalue = fmt.Sprintf(\"%.1f\", float64(mb)/1_000)\n\t\t\t} else {\n\t\t\t\tvalue = strconv.FormatUint(mb/1_000, 10)\n\t\t\t}\n\n\t\t\tlabel = \"GB\"\n\t\t} else {\n\t\t\tvalue = fmt.Sprintf(\"%.1f\", float64(mb)/1_000_000)\n\t\t\tlabel = \"TB\"\n\t\t}\n\n\t\treturn template.HTML(value + ` <span class=\"color-base size-h5\">` + label + `</span>`)\n\t},\n}\n\nfunc mustParseTemplate(primary string, dependencies ...string) *template.Template {\n\tt, err := template.New(primary).\n\t\tFuncs(globalTemplateFunctions).\n\t\tParseFS(templateFS, append([]string{primary}, dependencies...)...)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn t\n}\n\nfunc formatApproxNumber(count int) string {\n\tif count < 1_000 {\n\t\treturn strconv.Itoa(count)\n\t}\n\n\tif count < 10_000 {\n\t\treturn strconv.FormatFloat(float64(count)/1_000, 'f', 1, 64) + \"k\"\n\t}\n\n\tif count < 1_000_000 {\n\t\treturn strconv.Itoa(count/1_000) + \"k\"\n\t}\n\n\treturn strconv.FormatFloat(float64(count)/1_000_000, 'f', 1, 64) + \"m\"\n}\n\nfunc dynamicRelativeTimeAttrs(t interface{ Unix() int64 }) template.HTMLAttr {\n\treturn template.HTMLAttr(`data-dynamic-relative-time=\"` + strconv.FormatInt(t.Unix(), 10) + `\"`)\n}\n"
  },
  {
    "path": "internal/glance/theme.go",
    "content": "package glance\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"time\"\n)\n\nvar (\n\tthemeStyleTemplate         = mustParseTemplate(\"theme-style.gotmpl\")\n\tthemePresetPreviewTemplate = mustParseTemplate(\"theme-preset-preview.html\")\n)\n\nfunc (a *application) handleThemeChangeRequest(w http.ResponseWriter, r *http.Request) {\n\tthemeKey := r.PathValue(\"key\")\n\n\tproperties, exists := a.Config.Theme.Presets.Get(themeKey)\n\tif !exists && themeKey != \"default\" {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif themeKey == \"default\" {\n\t\tproperties = &a.Config.Theme.themeProperties\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName:     \"theme\",\n\t\tValue:    themeKey,\n\t\tPath:     a.Config.Server.BaseURL + \"/\",\n\t\tSameSite: http.SameSiteLaxMode,\n\t\tExpires:  time.Now().Add(2 * 365 * 24 * time.Hour),\n\t})\n\n\tw.Header().Set(\"Content-Type\", \"text/css\")\n\tw.Header().Set(\"X-Scheme\", ternary(properties.Light, \"light\", \"dark\"))\n\tw.Write([]byte(properties.CSS))\n}\n\ntype themeProperties struct {\n\tBackgroundColor          *hslColorField `yaml:\"background-color\"`\n\tPrimaryColor             *hslColorField `yaml:\"primary-color\"`\n\tPositiveColor            *hslColorField `yaml:\"positive-color\"`\n\tNegativeColor            *hslColorField `yaml:\"negative-color\"`\n\tLight                    bool           `yaml:\"light\"`\n\tContrastMultiplier       float32        `yaml:\"contrast-multiplier\"`\n\tTextSaturationMultiplier float32        `yaml:\"text-saturation-multiplier\"`\n\n\tKey                  string        `yaml:\"-\"`\n\tCSS                  template.CSS  `yaml:\"-\"`\n\tPreviewHTML          template.HTML `yaml:\"-\"`\n\tBackgroundColorAsHex string        `yaml:\"-\"`\n}\n\nfunc (t *themeProperties) init() error {\n\tcss, err := executeTemplateToString(themeStyleTemplate, t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"compiling theme style: %v\", err)\n\t}\n\tt.CSS = template.CSS(whitespaceAtBeginningOfLinePattern.ReplaceAllString(css, \"\"))\n\n\tpreviewHTML, err := executeTemplateToString(themePresetPreviewTemplate, t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"compiling theme preview: %v\", err)\n\t}\n\tt.PreviewHTML = template.HTML(previewHTML)\n\n\tif t.BackgroundColor != nil {\n\t\tt.BackgroundColorAsHex = t.BackgroundColor.ToHex()\n\t} else {\n\t\tt.BackgroundColorAsHex = \"#151519\"\n\t}\n\n\treturn nil\n}\n\nfunc (t1 *themeProperties) SameAs(t2 *themeProperties) bool {\n\tif t1 == nil && t2 == nil {\n\t\treturn true\n\t}\n\tif t1 == nil || t2 == nil {\n\t\treturn false\n\t}\n\tif t1.Light != t2.Light {\n\t\treturn false\n\t}\n\tif t1.ContrastMultiplier != t2.ContrastMultiplier {\n\t\treturn false\n\t}\n\tif t1.TextSaturationMultiplier != t2.TextSaturationMultiplier {\n\t\treturn false\n\t}\n\tif !t1.BackgroundColor.SameAs(t2.BackgroundColor) {\n\t\treturn false\n\t}\n\tif !t1.PrimaryColor.SameAs(t2.PrimaryColor) {\n\t\treturn false\n\t}\n\tif !t1.PositiveColor.SameAs(t2.PositiveColor) {\n\t\treturn false\n\t}\n\tif !t1.NegativeColor.SameAs(t2.NegativeColor) {\n\t\treturn false\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "internal/glance/utils.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"math\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar sequentialWhitespacePattern = regexp.MustCompile(`\\s+`)\nvar whitespaceAtBeginningOfLinePattern = regexp.MustCompile(`(?m)^\\s+`)\n\nfunc percentChange(current, previous float64) float64 {\n\tif previous == 0 {\n\t\tif current == 0 {\n\t\t\treturn 0 // 0% change if both are 0\n\t\t}\n\t\treturn 100 // 100% increase if going from 0 to something\n\t}\n\n\treturn (current/previous - 1) * 100\n}\n\nfunc extractDomainFromUrl(u string) string {\n\tif u == \"\" {\n\t\treturn \"\"\n\t}\n\n\tparsed, err := url.Parse(u)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimPrefix(strings.ToLower(parsed.Host), \"www.\")\n}\n\nfunc svgPolylineCoordsFromYValues(width float64, height float64, values []float64) string {\n\tif len(values) < 2 {\n\t\treturn \"\"\n\t}\n\n\tverticalPadding := height * 0.02\n\theight -= verticalPadding * 2\n\tcoordinates := make([]string, len(values))\n\tdistanceBetweenPoints := width / float64(len(values)-1)\n\tmin := slices.Min(values)\n\tmax := slices.Max(values)\n\n\tfor i := range values {\n\t\tcoordinates[i] = fmt.Sprintf(\n\t\t\t\"%.2f,%.2f\",\n\t\t\tfloat64(i)*distanceBetweenPoints,\n\t\t\t((max-values[i])/(max-min))*height+verticalPadding,\n\t\t)\n\t}\n\n\treturn strings.Join(coordinates, \" \")\n}\n\nfunc maybeCopySliceWithoutZeroValues[T int | float64](values []T) []T {\n\tif len(values) == 0 {\n\t\treturn values\n\t}\n\n\tfor i := range values {\n\t\tif values[i] != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tc := make([]T, 0, len(values)-1)\n\n\t\tfor i := range values {\n\t\t\tif values[i] != 0 {\n\t\t\t\tc = append(c, values[i])\n\t\t\t}\n\t\t}\n\n\t\treturn c\n\t}\n\n\treturn values\n}\n\nvar urlSchemePattern = regexp.MustCompile(`^[a-z]+:\\/\\/`)\n\nfunc stripURLScheme(url string) string {\n\treturn urlSchemePattern.ReplaceAllString(url, \"\")\n}\n\nfunc isRunningInsideDockerContainer() bool {\n\t_, err := os.Stat(\"/.dockerenv\")\n\treturn err == nil\n}\n\nfunc prefixStringLines(prefix string, s string) string {\n\tlines := strings.Split(s, \"\\n\")\n\n\tfor i, line := range lines {\n\t\tlines[i] = prefix + line\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc limitStringLength(s string, max int) (string, bool) {\n\tasRunes := []rune(s)\n\n\tif len(asRunes) > max {\n\t\treturn string(asRunes[:max]), true\n\t}\n\n\treturn s, false\n}\n\nfunc parseRFC3339Time(t string) time.Time {\n\tparsed, err := time.Parse(time.RFC3339, t)\n\tif err != nil {\n\t\treturn time.Now()\n\t}\n\n\treturn parsed\n}\n\nfunc normalizeVersionFormat(version string) string {\n\tversion = strings.ToLower(strings.TrimSpace(version))\n\n\tif len(version) > 0 && version[0] != 'v' {\n\t\treturn \"v\" + version\n\t}\n\n\treturn version\n}\n\nfunc titleToSlug(s string) string {\n\ts = strings.ToLower(s)\n\ts = sequentialWhitespacePattern.ReplaceAllString(s, \"-\")\n\ts = strings.Trim(s, \"-\")\n\n\treturn s\n}\n\nfunc fileServerWithCache(fs http.FileSystem, cacheDuration time.Duration) http.Handler {\n\tserver := http.FileServer(fs)\n\tcacheControlValue := fmt.Sprintf(\"public, max-age=%d\", int(cacheDuration.Seconds()))\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// TODO: fix always setting cache control even if the file doesn't exist\n\t\tw.Header().Set(\"Cache-Control\", cacheControlValue)\n\t\tserver.ServeHTTP(w, r)\n\t})\n}\n\nfunc executeTemplateToString(t *template.Template, data any) (string, error) {\n\tvar b bytes.Buffer\n\terr := t.Execute(&b, data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"executing template: %w\", err)\n\t}\n\n\treturn b.String(), nil\n}\n\nfunc stringToBool(s string) bool {\n\treturn s == \"true\" || s == \"yes\"\n}\n\nfunc itemAtIndexOrDefault[T any](items []T, index int, def T) T {\n\tif index >= len(items) {\n\t\treturn def\n\t}\n\n\treturn items[index]\n}\n\nfunc ternary[T any](condition bool, a, b T) T {\n\tif condition {\n\t\treturn a\n\t}\n\n\treturn b\n}\n\n// Having compile time errors about unused variables is cool and all, but I don't want to\n// have to constantly comment out my code while I'm working on it and testing things out\nfunc ItsUsedTrustMeBro(...any) {}\n\nfunc hslToHex(h, s, l float64) string {\n\ts /= 100.0\n\tl /= 100.0\n\n\tvar r, g, b float64\n\n\tif s == 0 {\n\t\tr, g, b = l, l, l\n\t} else {\n\t\thueToRgb := func(p, q, t float64) float64 {\n\t\t\tif t < 0 {\n\t\t\t\tt += 1\n\t\t\t}\n\t\t\tif t > 1 {\n\t\t\t\tt -= 1\n\t\t\t}\n\t\t\tif t < 1.0/6.0 {\n\t\t\t\treturn p + (q-p)*6.0*t\n\t\t\t}\n\t\t\tif t < 1.0/2.0 {\n\t\t\t\treturn q\n\t\t\t}\n\t\t\tif t < 2.0/3.0 {\n\t\t\t\treturn p + (q-p)*(2.0/3.0-t)*6.0\n\t\t\t}\n\t\t\treturn p\n\t\t}\n\n\t\tq := 0.0\n\t\tif l < 0.5 {\n\t\t\tq = l * (1 + s)\n\t\t} else {\n\t\t\tq = l + s - l*s\n\t\t}\n\n\t\tp := 2*l - q\n\n\t\th /= 360.0\n\n\t\tr = hueToRgb(p, q, h+1.0/3.0)\n\t\tg = hueToRgb(p, q, h)\n\t\tb = hueToRgb(p, q, h-1.0/3.0)\n\t}\n\n\tir := int(math.Round(r * 255.0))\n\tig := int(math.Round(g * 255.0))\n\tib := int(math.Round(b * 255.0))\n\n\tir = int(math.Max(0, math.Min(255, float64(ir))))\n\tig = int(math.Max(0, math.Min(255, float64(ig))))\n\tib = int(math.Max(0, math.Min(255, float64(ib))))\n\n\treturn fmt.Sprintf(\"#%02x%02x%02x\", ir, ig, ib)\n}\n"
  },
  {
    "path": "internal/glance/widget-bookmarks.go",
    "content": "package glance\n\nimport (\n\t\"html/template\"\n)\n\nvar bookmarksWidgetTemplate = mustParseTemplate(\"bookmarks.html\", \"widget-base.html\")\n\ntype bookmarksWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tcachedHTML template.HTML `yaml:\"-\"`\n\tGroups     []struct {\n\t\tTitle     string         `yaml:\"title\"`\n\t\tColor     *hslColorField `yaml:\"color\"`\n\t\tSameTab   bool           `yaml:\"same-tab\"`\n\t\tHideArrow bool           `yaml:\"hide-arrow\"`\n\t\tTarget    string         `yaml:\"target\"`\n\t\tLinks     []struct {\n\t\t\tTitle       string          `yaml:\"title\"`\n\t\t\tURL         string          `yaml:\"url\"`\n\t\t\tDescription string          `yaml:\"description\"`\n\t\t\tIcon        customIconField `yaml:\"icon\"`\n\t\t\t// we need a pointer to bool to know whether a value was provided,\n\t\t\t// however there's no way to dereference a pointer in a template so\n\t\t\t// {{ if not .SameTab }} would return true for any non-nil pointer\n\t\t\t// which leaves us with no way of checking if the value is true or\n\t\t\t// false, hence the duplicated fields below\n\t\t\tSameTabRaw   *bool  `yaml:\"same-tab\"`\n\t\t\tSameTab      bool   `yaml:\"-\"`\n\t\t\tHideArrowRaw *bool  `yaml:\"hide-arrow\"`\n\t\t\tHideArrow    bool   `yaml:\"-\"`\n\t\t\tTarget       string `yaml:\"target\"`\n\t\t} `yaml:\"links\"`\n\t} `yaml:\"groups\"`\n}\n\nfunc (widget *bookmarksWidget) initialize() error {\n\twidget.withTitle(\"Bookmarks\").withError(nil)\n\n\tfor g := range widget.Groups {\n\t\tgroup := &widget.Groups[g]\n\t\tfor l := range group.Links {\n\t\t\tlink := &group.Links[l]\n\t\t\tif link.SameTabRaw == nil {\n\t\t\t\tlink.SameTab = group.SameTab\n\t\t\t} else {\n\t\t\t\tlink.SameTab = *link.SameTabRaw\n\t\t\t}\n\n\t\t\tif link.HideArrowRaw == nil {\n\t\t\t\tlink.HideArrow = group.HideArrow\n\t\t\t} else {\n\t\t\t\tlink.HideArrow = *link.HideArrowRaw\n\t\t\t}\n\n\t\t\tif link.Target == \"\" {\n\t\t\t\tif group.Target != \"\" {\n\t\t\t\t\tlink.Target = group.Target\n\t\t\t\t} else {\n\t\t\t\t\tif link.SameTab {\n\t\t\t\t\t\tlink.Target = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlink.Target = \"_blank\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\twidget.cachedHTML = widget.renderTemplate(widget, bookmarksWidgetTemplate)\n\n\treturn nil\n}\n\nfunc (widget *bookmarksWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-calendar.go",
    "content": "package glance\n\nimport (\n\t\"errors\"\n\t\"html/template\"\n\t\"time\"\n)\n\nvar calendarWidgetTemplate = mustParseTemplate(\"calendar.html\", \"widget-base.html\")\n\nvar calendarWeekdaysToInt = map[string]time.Weekday{\n\t\"sunday\":    time.Sunday,\n\t\"monday\":    time.Monday,\n\t\"tuesday\":   time.Tuesday,\n\t\"wednesday\": time.Wednesday,\n\t\"thursday\":  time.Thursday,\n\t\"friday\":    time.Friday,\n\t\"saturday\":  time.Saturday,\n}\n\ntype calendarWidget struct {\n\twidgetBase     `yaml:\",inline\"`\n\tFirstDayOfWeek string        `yaml:\"first-day-of-week\"`\n\tFirstDay       int           `yaml:\"-\"`\n\tcachedHTML     template.HTML `yaml:\"-\"`\n}\n\nfunc (widget *calendarWidget) initialize() error {\n\twidget.withTitle(\"Calendar\").withError(nil)\n\n\tif widget.FirstDayOfWeek == \"\" {\n\t\twidget.FirstDayOfWeek = \"monday\"\n\t} else if _, ok := calendarWeekdaysToInt[widget.FirstDayOfWeek]; !ok {\n\t\treturn errors.New(\"invalid first day of week\")\n\t}\n\n\twidget.FirstDay = int(calendarWeekdaysToInt[widget.FirstDayOfWeek])\n\twidget.cachedHTML = widget.renderTemplate(widget, calendarWidgetTemplate)\n\n\treturn nil\n}\n\nfunc (widget *calendarWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-changedetection.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar changeDetectionWidgetTemplate = mustParseTemplate(\"change-detection.html\", \"widget-base.html\")\n\ntype changeDetectionWidget struct {\n\twidgetBase       `yaml:\",inline\"`\n\tChangeDetections changeDetectionWatchList `yaml:\"-\"`\n\tWatchUUIDs       []string                 `yaml:\"watches\"`\n\tInstanceURL      string                   `yaml:\"instance-url\"`\n\tToken            string                   `yaml:\"token\"`\n\tLimit            int                      `yaml:\"limit\"`\n\tCollapseAfter    int                      `yaml:\"collapse-after\"`\n}\n\nfunc (widget *changeDetectionWidget) initialize() error {\n\twidget.withTitle(\"Change Detection\").withCacheDuration(1 * time.Hour)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 10\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\tif widget.InstanceURL == \"\" {\n\t\twidget.InstanceURL = \"https://www.changedetection.io\"\n\t}\n\n\treturn nil\n}\n\nfunc (widget *changeDetectionWidget) update(ctx context.Context) {\n\tif len(widget.WatchUUIDs) == 0 {\n\t\tuuids, err := fetchWatchUUIDsFromChangeDetection(widget.InstanceURL, string(widget.Token))\n\n\t\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\t\treturn\n\t\t}\n\n\t\twidget.WatchUUIDs = uuids\n\t}\n\n\twatches, err := fetchWatchesFromChangeDetection(widget.InstanceURL, widget.WatchUUIDs, string(widget.Token))\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif len(watches) > widget.Limit {\n\t\twatches = watches[:widget.Limit]\n\t}\n\n\twidget.ChangeDetections = watches\n}\n\nfunc (widget *changeDetectionWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, changeDetectionWidgetTemplate)\n}\n\ntype changeDetectionWatch struct {\n\tTitle        string\n\tURL          string\n\tLastChanged  time.Time\n\tDiffURL      string\n\tPreviousHash string\n}\n\ntype changeDetectionWatchList []changeDetectionWatch\n\nfunc (r changeDetectionWatchList) sortByNewest() changeDetectionWatchList {\n\tsort.Slice(r, func(i, j int) bool {\n\t\treturn r[i].LastChanged.After(r[j].LastChanged)\n\t})\n\n\treturn r\n}\n\ntype changeDetectionResponseJson struct {\n\tTitle        string `json:\"title\"`\n\tURL          string `json:\"url\"`\n\tLastChanged  int64  `json:\"last_changed\"`\n\tDateCreated  int64  `json:\"date_created\"`\n\tPreviousHash string `json:\"previous_md5\"`\n}\n\nfunc fetchWatchUUIDsFromChangeDetection(instanceURL string, token string) ([]string, error) {\n\trequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/api/v1/watch\", instanceURL), nil)\n\n\tif token != \"\" {\n\t\trequest.Header.Add(\"x-api-key\", token)\n\t}\n\n\tuuidsMap, err := decodeJsonFromRequest[map[string]struct{}](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not fetch list of watch UUIDs: %v\", err)\n\t}\n\n\tuuids := make([]string, 0, len(uuidsMap))\n\n\tfor uuid := range uuidsMap {\n\t\tuuids = append(uuids, uuid)\n\t}\n\n\treturn uuids, nil\n}\n\nfunc fetchWatchesFromChangeDetection(instanceURL string, requestedWatchIDs []string, token string) (changeDetectionWatchList, error) {\n\twatches := make(changeDetectionWatchList, 0, len(requestedWatchIDs))\n\n\tif len(requestedWatchIDs) == 0 {\n\t\treturn watches, nil\n\t}\n\n\trequests := make([]*http.Request, len(requestedWatchIDs))\n\n\tfor i, repository := range requestedWatchIDs {\n\t\trequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"%s/api/v1/watch/%s\", instanceURL, repository), nil)\n\n\t\tif token != \"\" {\n\t\t\trequest.Header.Add(\"x-api-key\", token)\n\t\t}\n\n\t\trequests[i] = request\n\t}\n\n\ttask := decodeJsonFromRequestTask[changeDetectionResponseJson](defaultHTTPClient)\n\tjob := newJob(task, requests).withWorkers(15)\n\tresponses, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar failed int\n\n\tfor i := range responses {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to fetch or parse change detection watch\", \"url\", requests[i].URL, \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\twatchJson := responses[i]\n\n\t\twatch := changeDetectionWatch{\n\t\t\tURL:     watchJson.URL,\n\t\t\tDiffURL: fmt.Sprintf(\"%s/diff/%s?from_version=%d\", instanceURL, requestedWatchIDs[i], watchJson.LastChanged-1),\n\t\t}\n\n\t\tif watchJson.LastChanged == 0 {\n\t\t\twatch.LastChanged = time.Unix(watchJson.DateCreated, 0)\n\t\t} else {\n\t\t\twatch.LastChanged = time.Unix(watchJson.LastChanged, 0)\n\t\t}\n\n\t\tif watchJson.Title != \"\" {\n\t\t\twatch.Title = watchJson.Title\n\t\t} else {\n\t\t\twatch.Title = strings.TrimPrefix(strings.Trim(stripURLScheme(watchJson.URL), \"/\"), \"www.\")\n\t\t}\n\n\t\tif watchJson.PreviousHash != \"\" {\n\t\t\tvar hashLength = 8\n\n\t\t\tif len(watchJson.PreviousHash) < hashLength {\n\t\t\t\thashLength = len(watchJson.PreviousHash)\n\t\t\t}\n\n\t\t\twatch.PreviousHash = watchJson.PreviousHash[0:hashLength]\n\t\t}\n\n\t\twatches = append(watches, watch)\n\t}\n\n\tif len(watches) == 0 {\n\t\treturn nil, errNoContent\n\t}\n\n\twatches.sortByNewest()\n\n\tif failed > 0 {\n\t\treturn watches, fmt.Errorf(\"%w: could not get %d watches\", errPartialContent, failed)\n\t}\n\n\treturn watches, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-clock.go",
    "content": "package glance\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"time\"\n)\n\nvar clockWidgetTemplate = mustParseTemplate(\"clock.html\", \"widget-base.html\")\n\ntype clockWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tcachedHTML template.HTML `yaml:\"-\"`\n\tHourFormat string        `yaml:\"hour-format\"`\n\tTimezones  []struct {\n\t\tTimezone string `yaml:\"timezone\"`\n\t\tLabel    string `yaml:\"label\"`\n\t} `yaml:\"timezones\"`\n}\n\nfunc (widget *clockWidget) initialize() error {\n\twidget.withTitle(\"Clock\").withError(nil)\n\n\tif widget.HourFormat == \"\" {\n\t\twidget.HourFormat = \"24h\"\n\t} else if widget.HourFormat != \"12h\" && widget.HourFormat != \"24h\" {\n\t\treturn errors.New(\"hour-format must be either 12h or 24h\")\n\t}\n\n\tfor t := range widget.Timezones {\n\t\tif widget.Timezones[t].Timezone == \"\" {\n\t\t\treturn errors.New(\"missing timezone value\")\n\t\t}\n\n\t\tif _, err := time.LoadLocation(widget.Timezones[t].Timezone); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid timezone '%s': %v\", widget.Timezones[t].Timezone, err)\n\t\t}\n\t}\n\n\twidget.cachedHTML = widget.renderTemplate(widget, clockWidgetTemplate)\n\n\treturn nil\n}\n\nfunc (widget *clockWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-container.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype containerWidgetBase struct {\n\tWidgets widgets `yaml:\"widgets\"`\n}\n\nfunc (widget *containerWidgetBase) _initializeWidgets() error {\n\tfor i := range widget.Widgets {\n\t\tif err := widget.Widgets[i].initialize(); err != nil {\n\t\t\treturn formatWidgetInitError(err, widget.Widgets[i])\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (widget *containerWidgetBase) _update(ctx context.Context) {\n\tvar wg sync.WaitGroup\n\tnow := time.Now()\n\n\tfor w := range widget.Widgets {\n\t\twidget := widget.Widgets[w]\n\n\t\tif !widget.requiresUpdate(&now) {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twidget.update(ctx)\n\t\t}()\n\t}\n\n\twg.Wait()\n}\n\nfunc (widget *containerWidgetBase) _setProviders(providers *widgetProviders) {\n\tfor i := range widget.Widgets {\n\t\twidget.Widgets[i].setProviders(providers)\n\t}\n}\n\nfunc (widget *containerWidgetBase) _requiresUpdate(now *time.Time) bool {\n\tfor i := range widget.Widgets {\n\t\tif widget.Widgets[i].requiresUpdate(now) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n"
  },
  {
    "path": "internal/glance/widget-custom-api.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"io\"\n\t\"log/slog\"\n\t\"math\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/tidwall/gjson\"\n)\n\nvar customAPIWidgetTemplate = mustParseTemplate(\"custom-api.html\", \"widget-base.html\")\n\n// Needs to be exported for the YAML unmarshaler to work\ntype CustomAPIRequest struct {\n\tURL                string               `yaml:\"url\"`\n\tAllowInsecure      bool                 `yaml:\"allow-insecure\"`\n\tHeaders            map[string]string    `yaml:\"headers\"`\n\tParameters         queryParametersField `yaml:\"parameters\"`\n\tMethod             string               `yaml:\"method\"`\n\tBodyType           string               `yaml:\"body-type\"`\n\tBody               any                  `yaml:\"body\"`\n\tSkipJSONValidation bool                 `yaml:\"skip-json-validation\"`\n\tbodyReader         io.ReadSeeker        `yaml:\"-\"`\n\thttpRequest        *http.Request        `yaml:\"-\"`\n}\n\ntype customAPIWidget struct {\n\twidgetBase        `yaml:\",inline\"`\n\t*CustomAPIRequest `yaml:\",inline\"`             // the primary request\n\tSubrequests       map[string]*CustomAPIRequest `yaml:\"subrequests\"`\n\tOptions           customAPIOptions             `yaml:\"options\"`\n\tTemplate          string                       `yaml:\"template\"`\n\tFrameless         bool                         `yaml:\"frameless\"`\n\tcompiledTemplate  *template.Template           `yaml:\"-\"`\n\tCompiledHTML      template.HTML                `yaml:\"-\"`\n}\n\nfunc (widget *customAPIWidget) initialize() error {\n\twidget.withTitle(\"Custom API\").withCacheDuration(1 * time.Hour)\n\n\tif err := widget.CustomAPIRequest.initialize(); err != nil {\n\t\treturn fmt.Errorf(\"initializing primary request: %v\", err)\n\t}\n\n\tfor key := range widget.Subrequests {\n\t\tif err := widget.Subrequests[key].initialize(); err != nil {\n\t\t\treturn fmt.Errorf(\"initializing subrequest %q: %v\", key, err)\n\t\t}\n\t}\n\n\tif widget.Template == \"\" {\n\t\treturn errors.New(\"template is required\")\n\t}\n\n\tcompiledTemplate, err := template.New(\"\").Funcs(customAPITemplateFuncs).Parse(widget.Template)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template: %w\", err)\n\t}\n\n\twidget.compiledTemplate = compiledTemplate\n\n\treturn nil\n}\n\nfunc (widget *customAPIWidget) update(ctx context.Context) {\n\tcompiledHTML, err := fetchAndRenderCustomAPIRequest(\n\t\twidget.CustomAPIRequest, widget.Subrequests, widget.Options, widget.compiledTemplate,\n\t)\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\twidget.CompiledHTML = compiledHTML\n}\n\nfunc (widget *customAPIWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, customAPIWidgetTemplate)\n}\n\ntype customAPIOptions map[string]any\n\nfunc (o *customAPIOptions) StringOr(key, defaultValue string) string {\n\treturn customAPIGetOptionOrDefault(*o, key, defaultValue)\n}\n\nfunc (o *customAPIOptions) IntOr(key string, defaultValue int) int {\n\treturn customAPIGetOptionOrDefault(*o, key, defaultValue)\n}\n\nfunc (o *customAPIOptions) FloatOr(key string, defaultValue float64) float64 {\n\treturn customAPIGetOptionOrDefault(*o, key, defaultValue)\n}\n\nfunc (o *customAPIOptions) BoolOr(key string, defaultValue bool) bool {\n\treturn customAPIGetOptionOrDefault(*o, key, defaultValue)\n}\n\nfunc (o *customAPIOptions) JSON(key string) string {\n\tvalue, exists := (*o)[key]\n\tif !exists {\n\t\tpanic(fmt.Sprintf(\"key %q does not exist in options\", key))\n\t}\n\n\tencoded, err := json.Marshal(value)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"marshaling %s: %v\", key, err))\n\t}\n\n\treturn string(encoded)\n}\n\nfunc customAPIGetOptionOrDefault[T any](o customAPIOptions, key string, defaultValue T) T {\n\tif value, exists := o[key]; exists {\n\t\tif typedValue, ok := value.(T); ok {\n\t\t\treturn typedValue\n\t\t}\n\t}\n\treturn defaultValue\n}\n\nfunc (req *CustomAPIRequest) initialize() error {\n\tif req == nil || req.URL == \"\" {\n\t\treturn nil\n\t}\n\n\tif req.Body != nil {\n\t\tif req.Method == \"\" {\n\t\t\treq.Method = http.MethodPost\n\t\t}\n\n\t\tif req.BodyType == \"\" {\n\t\t\treq.BodyType = \"json\"\n\t\t}\n\n\t\tif req.BodyType != \"json\" && req.BodyType != \"string\" {\n\t\t\treturn errors.New(\"invalid body type, must be either 'json' or 'string'\")\n\t\t}\n\n\t\tswitch req.BodyType {\n\t\tcase \"json\":\n\t\t\tencoded, err := json.Marshal(req.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"marshaling body: %v\", err)\n\t\t\t}\n\n\t\t\treq.bodyReader = bytes.NewReader(encoded)\n\t\tcase \"string\":\n\t\t\tbodyAsString, ok := req.Body.(string)\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"body must be a string when body-type is 'string'\")\n\t\t\t}\n\n\t\t\treq.bodyReader = strings.NewReader(bodyAsString)\n\t\t}\n\n\t} else if req.Method == \"\" {\n\t\treq.Method = http.MethodGet\n\t}\n\n\thttpReq, err := http.NewRequest(strings.ToUpper(req.Method), req.URL, req.bodyReader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(req.Parameters) > 0 {\n\t\thttpReq.URL.RawQuery = req.Parameters.toQueryString()\n\t}\n\n\tif req.BodyType == \"json\" {\n\t\thttpReq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tfor key, value := range req.Headers {\n\t\thttpReq.Header.Add(key, value)\n\t}\n\n\treq.httpRequest = httpReq\n\n\treturn nil\n}\n\ntype customAPIResponseData struct {\n\tJSON     decoratedGJSONResult\n\tResponse *http.Response\n}\n\ntype customAPITemplateData struct {\n\t*customAPIResponseData\n\tsubrequests map[string]*customAPIResponseData\n\tOptions     customAPIOptions\n}\n\nfunc (data *customAPITemplateData) JSONLines() []decoratedGJSONResult {\n\tresult := make([]decoratedGJSONResult, 0, 5)\n\n\tgjson.ForEachLine(data.JSON.Raw, func(line gjson.Result) bool {\n\t\tresult = append(result, decoratedGJSONResult{line})\n\t\treturn true\n\t})\n\n\treturn result\n}\n\nfunc (data *customAPITemplateData) Subrequest(key string) *customAPIResponseData {\n\treq, exists := data.subrequests[key]\n\tif !exists {\n\t\t// We have to panic here since there's nothing sensible we can return and the\n\t\t// lack of an error would cause requested data to return zero values which\n\t\t// would be confusing from the user's perspective. Go's template module\n\t\t// handles recovering from panics and will return the panic message as an\n\t\t// error during template execution.\n\t\tpanic(fmt.Sprintf(\"subrequest with key %q has not been defined\", key))\n\t}\n\n\treturn req\n}\n\nfunc fetchCustomAPIResponse(ctx context.Context, req *CustomAPIRequest) (*customAPIResponseData, error) {\n\tif req == nil || req.URL == \"\" {\n\t\treturn &customAPIResponseData{\n\t\t\tJSON:     decoratedGJSONResult{gjson.Result{}},\n\t\t\tResponse: &http.Response{},\n\t\t}, nil\n\t}\n\n\tif req.bodyReader != nil {\n\t\treq.bodyReader.Seek(0, io.SeekStart)\n\t}\n\n\tclient := ternary(req.AllowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)\n\tresp, err := client.Do(req.httpRequest.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody := strings.TrimSpace(string(bodyBytes))\n\n\tif !req.SkipJSONValidation && body != \"\" && !gjson.Valid(body) {\n\t\tif 200 <= resp.StatusCode && resp.StatusCode < 300 {\n\t\t\ttruncatedBody, isTruncated := limitStringLength(body, 100)\n\t\t\tif isTruncated {\n\t\t\t\ttruncatedBody += \"... <truncated>\"\n\t\t\t}\n\n\t\t\tslog.Error(\"Invalid response JSON in custom API widget\", \"url\", req.httpRequest.URL.String(), \"body\", truncatedBody)\n\t\t\treturn nil, errors.New(\"invalid response JSON\")\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"%d %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\n\t}\n\n\treturn &customAPIResponseData{\n\t\tJSON:     decoratedGJSONResult{gjson.Parse(body)},\n\t\tResponse: resp,\n\t}, nil\n}\n\nfunc fetchAndRenderCustomAPIRequest(\n\tprimaryReq *CustomAPIRequest,\n\tsubReqs map[string]*CustomAPIRequest,\n\toptions customAPIOptions,\n\ttmpl *template.Template,\n) (template.HTML, error) {\n\tvar primaryData *customAPIResponseData\n\tsubData := make(map[string]*customAPIResponseData, len(subReqs))\n\tvar err error\n\n\tif len(subReqs) == 0 {\n\t\t// If there are no subrequests, we can fetch the primary request in a much simpler way\n\t\tprimaryData, err = fetchCustomAPIResponse(context.Background(), primaryReq)\n\t} else {\n\t\t// If there are subrequests, we need to fetch them concurrently\n\t\t// and cancel all requests if any of them fail. There's probably\n\t\t// a more elegant way to do this, but this works for now.\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tdefer cancel()\n\n\t\tvar wg sync.WaitGroup\n\t\tvar mu sync.Mutex // protects subData and err\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tvar localErr error\n\t\t\tprimaryData, localErr = fetchCustomAPIResponse(ctx, primaryReq)\n\t\t\tmu.Lock()\n\t\t\tif localErr != nil && err == nil {\n\t\t\t\terr = localErr\n\t\t\t\tcancel()\n\t\t\t}\n\t\t\tmu.Unlock()\n\t\t}()\n\n\t\tfor key, req := range subReqs {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tvar localErr error\n\t\t\t\tvar data *customAPIResponseData\n\t\t\t\tdata, localErr = fetchCustomAPIResponse(ctx, req)\n\t\t\t\tmu.Lock()\n\t\t\t\tif localErr == nil {\n\t\t\t\t\tsubData[key] = data\n\t\t\t\t} else if err == nil {\n\t\t\t\t\terr = localErr\n\t\t\t\t\tcancel()\n\t\t\t\t}\n\t\t\t\tmu.Unlock()\n\t\t\t}()\n\t\t}\n\n\t\twg.Wait()\n\t}\n\n\temptyBody := template.HTML(\"\")\n\n\tif err != nil {\n\t\treturn emptyBody, err\n\t}\n\n\tdata := customAPITemplateData{\n\t\tcustomAPIResponseData: primaryData,\n\t\tsubrequests:           subData,\n\t\tOptions:               options,\n\t}\n\n\tvar templateBuffer bytes.Buffer\n\terr = tmpl.Execute(&templateBuffer, &data)\n\tif err != nil {\n\t\treturn emptyBody, err\n\t}\n\n\treturn template.HTML(templateBuffer.String()), nil\n}\n\ntype decoratedGJSONResult struct {\n\tgjson.Result\n}\n\nfunc gJsonResultArrayToDecoratedResultArray(results []gjson.Result) []decoratedGJSONResult {\n\tdecoratedResults := make([]decoratedGJSONResult, len(results))\n\n\tfor i, result := range results {\n\t\tdecoratedResults[i] = decoratedGJSONResult{result}\n\t}\n\n\treturn decoratedResults\n}\n\nfunc (r *decoratedGJSONResult) Exists(key string) bool {\n\treturn r.Result.Get(key).Exists()\n}\n\nfunc (r *decoratedGJSONResult) Array(key string) []decoratedGJSONResult {\n\tif key == \"\" {\n\t\treturn gJsonResultArrayToDecoratedResultArray(r.Result.Array())\n\t}\n\n\treturn gJsonResultArrayToDecoratedResultArray(r.Result.Get(key).Array())\n}\n\nfunc (r *decoratedGJSONResult) String(key string) string {\n\tif key == \"\" {\n\t\treturn r.Result.String()\n\t}\n\n\treturn r.Result.Get(key).String()\n}\n\nfunc (r *decoratedGJSONResult) Int(key string) int {\n\tif key == \"\" {\n\t\treturn int(r.Result.Int())\n\t}\n\n\treturn int(r.Result.Get(key).Int())\n}\n\nfunc (r *decoratedGJSONResult) Float(key string) float64 {\n\tif key == \"\" {\n\t\treturn r.Result.Float()\n\t}\n\n\treturn r.Result.Get(key).Float()\n}\n\nfunc (r *decoratedGJSONResult) Bool(key string) bool {\n\tif key == \"\" {\n\t\treturn r.Result.Bool()\n\t}\n\n\treturn r.Result.Get(key).Bool()\n}\n\nfunc (r *decoratedGJSONResult) Get(key string) *decoratedGJSONResult {\n\treturn &decoratedGJSONResult{r.Result.Get(key)}\n}\n\nfunc customAPIDoMathOp[T int | float64](a, b T, op string) T {\n\tswitch op {\n\tcase \"add\":\n\t\treturn a + b\n\tcase \"sub\":\n\t\treturn a - b\n\tcase \"mul\":\n\t\treturn a * b\n\tcase \"div\":\n\t\tif b == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn a / b\n\t}\n\treturn 0\n}\n\nvar customAPITemplateFuncs = func() template.FuncMap {\n\tvar regexpCacheMu sync.Mutex\n\tvar regexpCache = make(map[string]*regexp.Regexp)\n\n\tgetCachedRegexp := func(pattern string) *regexp.Regexp {\n\t\tregexpCacheMu.Lock()\n\t\tdefer regexpCacheMu.Unlock()\n\n\t\tregex, exists := regexpCache[pattern]\n\t\tif !exists {\n\t\t\tregex = regexp.MustCompile(pattern)\n\t\t\tregexpCache[pattern] = regex\n\t\t}\n\n\t\treturn regex\n\t}\n\n\tdoMathOpWithAny := func(a, b any, op string) any {\n\t\tswitch at := a.(type) {\n\t\tcase int:\n\t\t\tswitch bt := b.(type) {\n\t\t\tcase int:\n\t\t\t\treturn customAPIDoMathOp(at, bt, op)\n\t\t\tcase float64:\n\t\t\t\treturn customAPIDoMathOp(float64(at), bt, op)\n\t\t\tdefault:\n\t\t\t\treturn math.NaN()\n\t\t\t}\n\t\tcase float64:\n\t\t\tswitch bt := b.(type) {\n\t\t\tcase int:\n\t\t\t\treturn customAPIDoMathOp(at, float64(bt), op)\n\t\t\tcase float64:\n\t\t\t\treturn customAPIDoMathOp(at, bt, op)\n\t\t\tdefault:\n\t\t\t\treturn math.NaN()\n\t\t\t}\n\t\tdefault:\n\t\t\treturn math.NaN()\n\t\t}\n\t}\n\n\tfuncs := template.FuncMap{\n\t\t\"toFloat\": func(a int) float64 {\n\t\t\treturn float64(a)\n\t\t},\n\t\t\"toInt\": func(a float64) int {\n\t\t\treturn int(a)\n\t\t},\n\t\t\"add\": func(a, b any) any {\n\t\t\treturn doMathOpWithAny(a, b, \"add\")\n\t\t},\n\t\t\"sub\": func(a, b any) any {\n\t\t\treturn doMathOpWithAny(a, b, \"sub\")\n\t\t},\n\t\t\"mul\": func(a, b any) any {\n\t\t\treturn doMathOpWithAny(a, b, \"mul\")\n\t\t},\n\t\t\"div\": func(a, b any) any {\n\t\t\treturn doMathOpWithAny(a, b, \"div\")\n\t\t},\n\t\t\"mod\": func(a, b int) int {\n\t\t\tif b == 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\treturn a % b\n\t\t},\n\t\t\"now\": func() time.Time {\n\t\t\treturn time.Now()\n\t\t},\n\t\t\"offsetNow\": func(offset string) time.Time {\n\t\t\td, err := time.ParseDuration(offset)\n\t\t\tif err != nil {\n\t\t\t\treturn time.Now()\n\t\t\t}\n\t\t\treturn time.Now().Add(d)\n\t\t},\n\t\t\"duration\": func(str string) time.Duration {\n\t\t\td, err := time.ParseDuration(str)\n\t\t\tif err != nil {\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\t\treturn d\n\t\t},\n\t\t\"parseTime\": func(layout, value string) time.Time {\n\t\t\treturn customAPIFuncParseTimeInLocation(layout, value, time.UTC)\n\t\t},\n\t\t\"formatTime\": customAPIFuncFormatTime,\n\t\t\"parseLocalTime\": func(layout, value string) time.Time {\n\t\t\treturn customAPIFuncParseTimeInLocation(layout, value, time.Local)\n\t\t},\n\t\t\"toRelativeTime\": dynamicRelativeTimeAttrs,\n\t\t\"parseRelativeTime\": func(layout, value string) template.HTMLAttr {\n\t\t\t// Shorthand to do both of the above with a single function call\n\t\t\treturn dynamicRelativeTimeAttrs(customAPIFuncParseTimeInLocation(layout, value, time.UTC))\n\t\t},\n\t\t\"startOfDay\": func(t time.Time) time.Time {\n\t\t\treturn time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())\n\t\t},\n\t\t\"endOfDay\": func(t time.Time) time.Time {\n\t\t\treturn time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())\n\t\t},\n\t\t// The reason we flip the parameter order is so that you can chain multiple calls together like this:\n\t\t// {{ .JSON.String \"foo\" | trimPrefix \"bar\" | doSomethingElse }}\n\t\t// instead of doing this:\n\t\t// {{ trimPrefix (.JSON.String \"foo\") \"bar\" | doSomethingElse }}\n\t\t// since the piped value gets passed as the last argument to the function.\n\t\t\"trimPrefix\": func(prefix, s string) string {\n\t\t\treturn strings.TrimPrefix(s, prefix)\n\t\t},\n\t\t\"trimSuffix\": func(suffix, s string) string {\n\t\t\treturn strings.TrimSuffix(s, suffix)\n\t\t},\n\t\t\"trimSpace\": strings.TrimSpace,\n\t\t\"replaceAll\": func(old, new, s string) string {\n\t\t\treturn strings.ReplaceAll(s, old, new)\n\t\t},\n\t\t\"replaceMatches\": func(pattern, replacement, s string) string {\n\t\t\tif s == \"\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\n\t\t\treturn getCachedRegexp(pattern).ReplaceAllString(s, replacement)\n\t\t},\n\t\t\"findMatch\": func(pattern, s string) string {\n\t\t\tif s == \"\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\n\t\t\treturn getCachedRegexp(pattern).FindString(s)\n\t\t},\n\t\t\"findSubmatch\": func(pattern, s string) string {\n\t\t\tif s == \"\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\n\t\t\tregex := getCachedRegexp(pattern)\n\t\t\treturn itemAtIndexOrDefault(regex.FindStringSubmatch(s), 1, \"\")\n\t\t},\n\t\t\"percentChange\": percentChange,\n\t\t\"sortByString\": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {\n\t\t\tsort.Slice(results, func(a, b int) bool {\n\t\t\t\tif order == \"asc\" {\n\t\t\t\t\treturn results[a].String(key) < results[b].String(key)\n\t\t\t\t}\n\n\t\t\t\treturn results[a].String(key) > results[b].String(key)\n\t\t\t})\n\n\t\t\treturn results\n\t\t},\n\t\t\"sortByInt\": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {\n\t\t\tsort.Slice(results, func(a, b int) bool {\n\t\t\t\tif order == \"asc\" {\n\t\t\t\t\treturn results[a].Int(key) < results[b].Int(key)\n\t\t\t\t}\n\n\t\t\t\treturn results[a].Int(key) > results[b].Int(key)\n\t\t\t})\n\n\t\t\treturn results\n\t\t},\n\t\t\"sortByFloat\": func(key, order string, results []decoratedGJSONResult) []decoratedGJSONResult {\n\t\t\tsort.Slice(results, func(a, b int) bool {\n\t\t\t\tif order == \"asc\" {\n\t\t\t\t\treturn results[a].Float(key) < results[b].Float(key)\n\t\t\t\t}\n\n\t\t\t\treturn results[a].Float(key) > results[b].Float(key)\n\t\t\t})\n\n\t\t\treturn results\n\t\t},\n\t\t\"sortByTime\": func(key, layout, order string, results []decoratedGJSONResult) []decoratedGJSONResult {\n\t\t\tsort.Slice(results, func(a, b int) bool {\n\t\t\t\ttimeA := customAPIFuncParseTimeInLocation(layout, results[a].String(key), time.UTC)\n\t\t\t\ttimeB := customAPIFuncParseTimeInLocation(layout, results[b].String(key), time.UTC)\n\n\t\t\t\tif order == \"asc\" {\n\t\t\t\t\treturn timeA.Before(timeB)\n\t\t\t\t}\n\n\t\t\t\treturn timeA.After(timeB)\n\t\t\t})\n\n\t\t\treturn results\n\t\t},\n\t\t\"concat\": func(items ...string) string {\n\t\t\treturn strings.Join(items, \"\")\n\t\t},\n\t\t\"unique\": func(key string, results []decoratedGJSONResult) []decoratedGJSONResult {\n\t\t\tseen := make(map[string]struct{})\n\t\t\tout := make([]decoratedGJSONResult, 0, len(results))\n\t\t\tfor _, result := range results {\n\t\t\t\tval := result.String(key)\n\t\t\t\tif _, ok := seen[val]; !ok {\n\t\t\t\t\tseen[val] = struct{}{}\n\t\t\t\t\tout = append(out, result)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out\n\t\t},\n\t\t\"newRequest\": func(url string) *CustomAPIRequest {\n\t\t\treturn &CustomAPIRequest{\n\t\t\t\tURL: url,\n\t\t\t}\n\t\t},\n\t\t\"withHeader\": func(key, value string, req *CustomAPIRequest) *CustomAPIRequest {\n\t\t\tif req.Headers == nil {\n\t\t\t\treq.Headers = make(map[string]string)\n\t\t\t}\n\t\t\treq.Headers[key] = value\n\t\t\treturn req\n\t\t},\n\t\t\"withParameter\": func(key, value string, req *CustomAPIRequest) *CustomAPIRequest {\n\t\t\tif req.Parameters == nil {\n\t\t\t\treq.Parameters = make(queryParametersField)\n\t\t\t}\n\t\t\treq.Parameters[key] = append(req.Parameters[key], value)\n\t\t\treturn req\n\t\t},\n\t\t\"withStringBody\": func(body string, req *CustomAPIRequest) *CustomAPIRequest {\n\t\t\treq.Body = body\n\t\t\treq.BodyType = \"string\"\n\t\t\treturn req\n\t\t},\n\t\t\"getResponse\": func(req *CustomAPIRequest) *customAPIResponseData {\n\t\t\terr := req.initialize()\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"initializing request: %v\", err))\n\t\t\t}\n\n\t\t\tdata, err := fetchCustomAPIResponse(context.Background(), req)\n\t\t\tif err != nil {\n\t\t\t\tslog.Error(\"Could not fetch response within custom API template\", \"error\", err)\n\t\t\t\treturn &customAPIResponseData{\n\t\t\t\t\tJSON: decoratedGJSONResult{gjson.Result{}},\n\t\t\t\t\tResponse: &http.Response{\n\t\t\t\t\t\tStatus: err.Error(),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn data\n\t\t},\n\t}\n\n\tfor key, value := range globalTemplateFunctions {\n\t\tif _, exists := funcs[key]; !exists {\n\t\t\tfuncs[key] = value\n\t\t}\n\t}\n\n\treturn funcs\n}()\n\nfunc customAPIFuncFormatTime(layout string, t time.Time) string {\n\tswitch strings.ToLower(layout) {\n\tcase \"unix\":\n\t\treturn strconv.FormatInt(t.Unix(), 10)\n\tcase \"rfc3339\":\n\t\tlayout = time.RFC3339\n\tcase \"rfc3339nano\":\n\t\tlayout = time.RFC3339Nano\n\tcase \"datetime\":\n\t\tlayout = time.DateTime\n\tcase \"dateonly\":\n\t\tlayout = time.DateOnly\n\t}\n\n\treturn t.Format(layout)\n}\n\nfunc customAPIFuncParseTimeInLocation(layout, value string, loc *time.Location) time.Time {\n\tswitch strings.ToLower(layout) {\n\tcase \"unix\":\n\t\tasInt, err := strconv.ParseInt(value, 10, 64)\n\t\tif err != nil {\n\t\t\treturn time.Unix(0, 0)\n\t\t}\n\n\t\treturn time.Unix(asInt, 0)\n\tcase \"rfc3339\":\n\t\tlayout = time.RFC3339\n\tcase \"rfc3339nano\":\n\t\tlayout = time.RFC3339Nano\n\tcase \"datetime\":\n\t\tlayout = time.DateTime\n\tcase \"dateonly\":\n\t\tlayout = time.DateOnly\n\t}\n\n\tparsed, err := time.ParseInLocation(layout, value, loc)\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\treturn parsed\n}\n"
  },
  {
    "path": "internal/glance/widget-dns-stats.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar dnsStatsWidgetTemplate = mustParseTemplate(\"dns-stats.html\", \"widget-base.html\")\n\nconst (\n\tdnsStatsBars            = 8\n\tdnsStatsHoursSpan       = 24\n\tdnsStatsHoursPerBar int = dnsStatsHoursSpan / dnsStatsBars\n)\n\ntype dnsStatsWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\n\tTimeLabels      [8]string `yaml:\"-\"`\n\tStats           *dnsStats `yaml:\"-\"`\n\tpiholeSessionID string    `yaml:\"-\"`\n\n\tHourFormat     string `yaml:\"hour-format\"`\n\tHideGraph      bool   `yaml:\"hide-graph\"`\n\tHideTopDomains bool   `yaml:\"hide-top-domains\"`\n\tService        string `yaml:\"service\"`\n\tAllowInsecure  bool   `yaml:\"allow-insecure\"`\n\tURL            string `yaml:\"url\"`\n\tToken          string `yaml:\"token\"`\n\tUsername       string `yaml:\"username\"`\n\tPassword       string `yaml:\"password\"`\n}\n\nconst (\n\tdnsServiceAdguard    = \"adguard\"\n\tdnsServicePihole     = \"pihole\"\n\tdnsServiceTechnitium = \"technitium\"\n\tdnsServicePiholeV6   = \"pihole-v6\"\n)\n\nfunc makeDNSWidgetTimeLabels(format string) [8]string {\n\tnow := time.Now()\n\tvar labels [dnsStatsBars]string\n\n\tfor h := dnsStatsHoursSpan; h > 0; h -= dnsStatsHoursPerBar {\n\t\tlabels[7-(h/3-1)] = strings.ToLower(now.Add(-time.Duration(h) * time.Hour).Format(format))\n\t}\n\n\treturn labels\n}\n\nfunc (widget *dnsStatsWidget) initialize() error {\n\ttitleURL := strings.TrimRight(widget.URL, \"/\")\n\tswitch widget.Service {\n\tcase dnsServicePihole, dnsServicePiholeV6:\n\t\ttitleURL = titleURL + \"/admin\"\n\t}\n\n\twidget.\n\t\twithTitle(\"DNS Stats\").\n\t\twithTitleURL(titleURL).\n\t\twithCacheDuration(10 * time.Minute)\n\n\tswitch widget.Service {\n\tcase dnsServiceAdguard:\n\tcase dnsServicePiholeV6:\n\tcase dnsServicePihole:\n\tcase dnsServiceTechnitium:\n\tdefault:\n\t\treturn fmt.Errorf(\"service must be one of: %s, %s, %s, %s\", dnsServiceAdguard, dnsServicePihole, dnsServicePiholeV6, dnsServiceTechnitium)\n\t}\n\n\treturn nil\n}\n\nfunc (widget *dnsStatsWidget) update(ctx context.Context) {\n\tvar stats *dnsStats\n\tvar err error\n\n\tswitch widget.Service {\n\tcase dnsServiceAdguard:\n\t\tstats, err = fetchAdguardStats(widget.URL, widget.AllowInsecure, widget.Username, widget.Password, widget.HideGraph)\n\tcase dnsServicePihole:\n\t\tstats, err = fetchPihole5Stats(widget.URL, widget.AllowInsecure, widget.Token, widget.HideGraph)\n\tcase dnsServiceTechnitium:\n\t\tstats, err = fetchTechnitiumStats(widget.URL, widget.AllowInsecure, widget.Token, widget.HideGraph)\n\tcase dnsServicePiholeV6:\n\t\tvar newSessionID string\n\t\tstats, newSessionID, err = fetchPiholeStats(\n\t\t\twidget.URL,\n\t\t\twidget.AllowInsecure,\n\t\t\twidget.Password,\n\t\t\twidget.piholeSessionID,\n\t\t\t!widget.HideGraph,\n\t\t\t!widget.HideTopDomains,\n\t\t)\n\t\tif err == nil {\n\t\t\twidget.piholeSessionID = newSessionID\n\t\t}\n\t}\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif widget.HourFormat == \"24h\" {\n\t\twidget.TimeLabels = makeDNSWidgetTimeLabels(\"15:00\")\n\t} else {\n\t\twidget.TimeLabels = makeDNSWidgetTimeLabels(\"3PM\")\n\t}\n\n\twidget.Stats = stats\n}\n\nfunc (widget *dnsStatsWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, dnsStatsWidgetTemplate)\n}\n\ntype dnsStats struct {\n\tTotalQueries      int\n\tBlockedQueries    int // we don't actually use this anywhere in templates, maybe remove it later?\n\tBlockedPercent    int\n\tResponseTime      int\n\tDomainsBlocked    int\n\tSeries            [dnsStatsBars]dnsStatsSeries\n\tTopBlockedDomains []dnsStatsBlockedDomain\n}\n\ntype dnsStatsSeries struct {\n\tQueries        int\n\tBlocked        int\n\tPercentTotal   int\n\tPercentBlocked int\n}\n\ntype dnsStatsBlockedDomain struct {\n\tDomain         string\n\tPercentBlocked int\n}\n\ntype adguardStatsResponse struct {\n\tTotalQueries      int              `json:\"num_dns_queries\"`\n\tQueriesSeries     []int            `json:\"dns_queries\"`\n\tBlockedQueries    int              `json:\"num_blocked_filtering\"`\n\tBlockedSeries     []int            `json:\"blocked_filtering\"`\n\tResponseTime      float64          `json:\"avg_processing_time\"`\n\tTopBlockedDomains []map[string]int `json:\"top_blocked_domains\"`\n}\n\nfunc fetchAdguardStats(instanceURL string, allowInsecure bool, username, password string, noGraph bool) (*dnsStats, error) {\n\trequestURL := strings.TrimRight(instanceURL, \"/\") + \"/control/stats\"\n\n\trequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest.SetBasicAuth(username, password)\n\n\tvar client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)\n\tresponseJson, err := decodeJsonFromRequest[adguardStatsResponse](client, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar topBlockedDomainsCount = min(len(responseJson.TopBlockedDomains), 5)\n\n\tstats := &dnsStats{\n\t\tTotalQueries:      responseJson.TotalQueries,\n\t\tBlockedQueries:    responseJson.BlockedQueries,\n\t\tResponseTime:      int(responseJson.ResponseTime * 1000),\n\t\tTopBlockedDomains: make([]dnsStatsBlockedDomain, 0, topBlockedDomainsCount),\n\t}\n\n\tif stats.TotalQueries <= 0 {\n\t\treturn stats, nil\n\t}\n\n\tstats.BlockedPercent = int(float64(responseJson.BlockedQueries) / float64(responseJson.TotalQueries) * 100)\n\n\tfor i := range topBlockedDomainsCount {\n\t\tdomain := responseJson.TopBlockedDomains[i]\n\t\tvar firstDomain string\n\n\t\tfor k := range domain {\n\t\t\tfirstDomain = k\n\t\t\tbreak\n\t\t}\n\n\t\tif firstDomain == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tstats.TopBlockedDomains = append(stats.TopBlockedDomains, dnsStatsBlockedDomain{\n\t\t\tDomain: firstDomain,\n\t\t})\n\n\t\tif stats.BlockedQueries > 0 {\n\t\t\tstats.TopBlockedDomains[i].PercentBlocked = int(float64(domain[firstDomain]) / float64(responseJson.BlockedQueries) * 100)\n\t\t}\n\t}\n\n\tif noGraph {\n\t\treturn stats, nil\n\t}\n\n\tqueriesSeries := responseJson.QueriesSeries\n\tblockedSeries := responseJson.BlockedSeries\n\n\tif len(queriesSeries) > dnsStatsHoursSpan {\n\t\tqueriesSeries = queriesSeries[len(queriesSeries)-dnsStatsHoursSpan:]\n\t} else if len(queriesSeries) < dnsStatsHoursSpan {\n\t\tqueriesSeries = append(make([]int, dnsStatsHoursSpan-len(queriesSeries)), queriesSeries...)\n\t}\n\n\tif len(blockedSeries) > dnsStatsHoursSpan {\n\t\tblockedSeries = blockedSeries[len(blockedSeries)-dnsStatsHoursSpan:]\n\t} else if len(blockedSeries) < dnsStatsHoursSpan {\n\t\tblockedSeries = append(make([]int, dnsStatsHoursSpan-len(blockedSeries)), blockedSeries...)\n\t}\n\n\tmaxQueriesInSeries := 0\n\n\tfor i := range dnsStatsBars {\n\t\tqueries := 0\n\t\tblocked := 0\n\n\t\tfor j := range dnsStatsHoursPerBar {\n\t\t\tqueries += queriesSeries[i*dnsStatsHoursPerBar+j]\n\t\t\tblocked += blockedSeries[i*dnsStatsHoursPerBar+j]\n\t\t}\n\n\t\tstats.Series[i] = dnsStatsSeries{\n\t\t\tQueries: queries,\n\t\t\tBlocked: blocked,\n\t\t}\n\n\t\tif queries > 0 {\n\t\t\tstats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100)\n\t\t}\n\n\t\tif queries > maxQueriesInSeries {\n\t\t\tmaxQueriesInSeries = queries\n\t\t}\n\t}\n\n\tfor i := range dnsStatsBars {\n\t\tstats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)\n\t}\n\n\treturn stats, nil\n}\n\n// Legacy Pi-hole stats response (before v6)\ntype pihole5StatsResponse struct {\n\tTotalQueries      int                      `json:\"dns_queries_today\"`\n\tQueriesSeries     pihole5QueriesSeries     `json:\"domains_over_time\"`\n\tBlockedQueries    int                      `json:\"ads_blocked_today\"`\n\tBlockedSeries     map[int64]int            `json:\"ads_over_time\"`\n\tBlockedPercentage float64                  `json:\"ads_percentage_today\"`\n\tTopBlockedDomains pihole5TopBlockedDomains `json:\"top_ads\"`\n\tDomainsBlocked    int                      `json:\"domains_being_blocked\"`\n}\n\n// If the user has query logging disabled it's possible for domains_over_time to be returned as an\n// empty array rather than a map which will prevent unmashalling the rest of the data so we use\n// custom unmarshal behavior to fallback to an empty map.\n// See https://github.com/glanceapp/glance/issues/289\ntype pihole5QueriesSeries map[int64]int\n\nfunc (p *pihole5QueriesSeries) UnmarshalJSON(data []byte) error {\n\ttemp := make(map[int64]int)\n\n\terr := json.Unmarshal(data, &temp)\n\tif err != nil {\n\t\t*p = make(pihole5QueriesSeries)\n\t} else {\n\t\t*p = temp\n\t}\n\n\treturn nil\n}\n\n// If user has some level of privacy enabled on Pihole, `json:\"top_ads\"` is an empty array\n// Use custom unmarshal behavior to avoid not getting the rest of the valid data when unmarshalling\ntype pihole5TopBlockedDomains map[string]int\n\nfunc (p *pihole5TopBlockedDomains) UnmarshalJSON(data []byte) error {\n\t// NOTE: do not change to piholeTopBlockedDomains type here or it will cause a stack overflow\n\t// because of the UnmarshalJSON method getting called recursively\n\ttemp := make(map[string]int)\n\n\terr := json.Unmarshal(data, &temp)\n\tif err != nil {\n\t\t*p = make(pihole5TopBlockedDomains)\n\t} else {\n\t\t*p = temp\n\t}\n\n\treturn nil\n}\n\nfunc fetchPihole5Stats(instanceURL string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) {\n\tif token == \"\" {\n\t\treturn nil, errors.New(\"missing API token\")\n\t}\n\n\trequestURL := strings.TrimRight(instanceURL, \"/\") +\n\t\t\"/admin/api.php?summaryRaw&topItems&overTimeData10mins&auth=\" + token\n\n\trequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)\n\tresponseJson, err := decodeJsonFromRequest[pihole5StatsResponse](client, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstats := &dnsStats{\n\t\tTotalQueries:   responseJson.TotalQueries,\n\t\tBlockedQueries: responseJson.BlockedQueries,\n\t\tBlockedPercent: int(responseJson.BlockedPercentage),\n\t\tDomainsBlocked: responseJson.DomainsBlocked,\n\t}\n\n\tif len(responseJson.TopBlockedDomains) > 0 {\n\t\tdomains := make([]dnsStatsBlockedDomain, 0, len(responseJson.TopBlockedDomains))\n\n\t\tfor domain, count := range responseJson.TopBlockedDomains {\n\t\t\tdomains = append(domains, dnsStatsBlockedDomain{\n\t\t\t\tDomain:         domain,\n\t\t\t\tPercentBlocked: int(float64(count) / float64(responseJson.BlockedQueries) * 100),\n\t\t\t})\n\t\t}\n\n\t\tsort.Slice(domains, func(a, b int) bool {\n\t\t\treturn domains[a].PercentBlocked > domains[b].PercentBlocked\n\t\t})\n\n\t\tstats.TopBlockedDomains = domains[:min(len(domains), 5)]\n\t}\n\n\tif noGraph {\n\t\treturn stats, nil\n\t}\n\n\t// Pihole _should_ return data for the last 24 hours in a 10 minute interval, 6*24 = 144\n\tif len(responseJson.QueriesSeries) != 144 || len(responseJson.BlockedSeries) != 144 {\n\t\tslog.Warn(\n\t\t\t\"DNS stats for pihole: did not get expected 144 data points\",\n\t\t\t\"len(queries)\", len(responseJson.QueriesSeries),\n\t\t\t\"len(blocked)\", len(responseJson.BlockedSeries),\n\t\t)\n\t\treturn stats, nil\n\t}\n\n\tvar lowestTimestamp int64 = 0\n\tfor timestamp := range responseJson.QueriesSeries {\n\t\tif lowestTimestamp == 0 || timestamp < lowestTimestamp {\n\t\t\tlowestTimestamp = timestamp\n\t\t}\n\t}\n\n\tmaxQueriesInSeries := 0\n\n\tfor i := range dnsStatsBars {\n\t\tqueries := 0\n\t\tblocked := 0\n\n\t\tfor j := range 18 {\n\t\t\tindex := lowestTimestamp + int64(i*10800+j*600)\n\n\t\t\tqueries += responseJson.QueriesSeries[index]\n\t\t\tblocked += responseJson.BlockedSeries[index]\n\t\t}\n\n\t\tif queries > maxQueriesInSeries {\n\t\t\tmaxQueriesInSeries = queries\n\t\t}\n\n\t\tstats.Series[i] = dnsStatsSeries{\n\t\t\tQueries: queries,\n\t\t\tBlocked: blocked,\n\t\t}\n\n\t\tif queries > 0 {\n\t\t\tstats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100)\n\t\t}\n\t}\n\n\tfor i := range dnsStatsBars {\n\t\tstats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)\n\t}\n\n\treturn stats, nil\n}\n\nfunc fetchPiholeStats(\n\tinstanceURL string,\n\tallowInsecure bool,\n\tpassword string,\n\tsessionID string,\n\tincludeGraph bool,\n\tincludeTopDomains bool,\n) (*dnsStats, string, error) {\n\tinstanceURL = strings.TrimRight(instanceURL, \"/\")\n\tvar client = ternary(allowInsecure, defaultInsecureHTTPClient, defaultHTTPClient)\n\n\tfetchNewSessionID := func() error {\n\t\tnewSessionID, err := fetchPiholeSessionID(instanceURL, client, password)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsessionID = newSessionID\n\t\treturn nil\n\t}\n\n\tif sessionID == \"\" {\n\t\tif err := fetchNewSessionID(); err != nil {\n\t\t\tslog.Error(\"Failed to fetch Pihole v6 session ID\", \"error\", err)\n\t\t\treturn nil, \"\", fmt.Errorf(\"fetching session ID: %v\", err)\n\t\t}\n\t} else {\n\t\tisValid, err := checkPiholeSessionIDIsValid(instanceURL, client, sessionID)\n\t\tif err != nil {\n\t\t\tslog.Error(\"Failed to check Pihole v6 session ID validity\", \"error\", err)\n\t\t\treturn nil, \"\", fmt.Errorf(\"checking session ID: %v\", err)\n\t\t}\n\n\t\tif !isValid {\n\t\t\tif err := fetchNewSessionID(); err != nil {\n\t\t\t\tslog.Error(\"Failed to renew Pihole v6 session ID\", \"error\", err)\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"renewing session ID: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\ttype statsResponseJson struct {\n\t\tQueries struct {\n\t\t\tTotal          int     `json:\"total\"`\n\t\t\tBlocked        int     `json:\"blocked\"`\n\t\t\tPercentBlocked float64 `json:\"percent_blocked\"`\n\t\t} `json:\"queries\"`\n\t\tGravity struct {\n\t\t\tDomainsBlocked int `json:\"domains_being_blocked\"`\n\t\t} `json:\"gravity\"`\n\t}\n\n\tstatsRequest, _ := http.NewRequestWithContext(ctx, \"GET\", instanceURL+\"/api/stats/summary\", nil)\n\tstatsRequest.Header.Set(\"x-ftl-sid\", sessionID)\n\n\tvar statsResponse statsResponseJson\n\tvar statsErr error\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tstatsResponse, statsErr = decodeJsonFromRequest[statsResponseJson](client, statsRequest)\n\t\tif statsErr != nil {\n\t\t\tcancel()\n\t\t}\n\t}()\n\n\ttype seriesResponseJson struct {\n\t\tHistory []struct {\n\t\t\tTimestamp int64 `json:\"timestamp\"`\n\t\t\tTotal     int   `json:\"total\"`\n\t\t\tBlocked   int   `json:\"blocked\"`\n\t\t} `json:\"history\"`\n\t}\n\n\tvar seriesResponse seriesResponseJson\n\tvar seriesErr error\n\n\tif includeGraph {\n\t\tseriesRequest, _ := http.NewRequestWithContext(ctx, \"GET\", instanceURL+\"/api/history\", nil)\n\t\tseriesRequest.Header.Set(\"x-ftl-sid\", sessionID)\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tseriesResponse, seriesErr = decodeJsonFromRequest[seriesResponseJson](client, seriesRequest)\n\t\t}()\n\t}\n\n\ttype topDomainsResponseJson struct {\n\t\tDomains []struct {\n\t\t\tDomain string `json:\"domain\"`\n\t\t\tCount  int    `json:\"count\"`\n\t\t} `json:\"domains\"`\n\t\tTotalQueries   int     `json:\"total_queries\"`\n\t\tBlockedQueries int     `json:\"blocked_queries\"`\n\t\tTook           float64 `json:\"took\"`\n\t}\n\n\tvar topDomainsResponse topDomainsResponseJson\n\tvar topDomainsErr error\n\n\tif includeTopDomains {\n\t\ttopDomainsRequest, _ := http.NewRequestWithContext(ctx, \"GET\", instanceURL+\"/api/stats/top_domains?blocked=true\", nil)\n\t\ttopDomainsRequest.Header.Set(\"x-ftl-sid\", sessionID)\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\ttopDomainsResponse, topDomainsErr = decodeJsonFromRequest[topDomainsResponseJson](client, topDomainsRequest)\n\t\t}()\n\t}\n\n\twg.Wait()\n\tpartialContent := false\n\n\tif statsErr != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"fetching stats: %v\", statsErr)\n\t}\n\n\tif includeGraph && seriesErr != nil {\n\t\tslog.Error(\"Failed to fetch Pihole v6 graph data\", \"error\", seriesErr)\n\t\tpartialContent = true\n\t}\n\n\tif includeTopDomains && topDomainsErr != nil {\n\t\tslog.Error(\"Failed to fetch Pihole v6 top domains\", \"error\", topDomainsErr)\n\t\tpartialContent = true\n\t}\n\n\tstats := &dnsStats{\n\t\tTotalQueries:   statsResponse.Queries.Total,\n\t\tBlockedQueries: statsResponse.Queries.Blocked,\n\t\tBlockedPercent: int(statsResponse.Queries.PercentBlocked),\n\t\tDomainsBlocked: statsResponse.Gravity.DomainsBlocked,\n\t}\n\n\tif includeGraph && seriesErr == nil {\n\t\tif len(seriesResponse.History) != 145 {\n\t\t\tslog.Error(\n\t\t\t\t\"Pihole v6 graph data has unexpected length\",\n\t\t\t\t\"length\", len(seriesResponse.History),\n\t\t\t\t\"expected\", 145,\n\t\t\t)\n\t\t\tpartialContent = true\n\t\t} else {\n\t\t\t// The API from v5 used to return 144 data points, but v6 returns 145.\n\t\t\t// We only show data from the last 24 hours hours, Pihole returns data\n\t\t\t// points in a 10 minute interval, 24*(60/10) = 144. Why is there an extra\n\t\t\t// data point? I don't know, but we'll just ignore the first one since it's\n\t\t\t// the oldest data point.\n\t\t\thistory := seriesResponse.History[1:]\n\n\t\t\tconst interval = 10\n\t\t\tconst dataPointsPerBar = dnsStatsHoursPerBar * (60 / interval)\n\n\t\t\tmaxQueriesInSeries := 0\n\n\t\t\tfor i := range dnsStatsBars {\n\t\t\t\tqueries := 0\n\t\t\t\tblocked := 0\n\t\t\t\tfor j := range dataPointsPerBar {\n\t\t\t\t\tindex := i*dataPointsPerBar + j\n\t\t\t\t\tqueries += history[index].Total\n\t\t\t\t\tblocked += history[index].Blocked\n\t\t\t\t}\n\t\t\t\tif queries > maxQueriesInSeries {\n\t\t\t\t\tmaxQueriesInSeries = queries\n\t\t\t\t}\n\t\t\t\tstats.Series[i] = dnsStatsSeries{\n\t\t\t\t\tQueries: queries,\n\t\t\t\t\tBlocked: blocked,\n\t\t\t\t}\n\t\t\t\tif queries > 0 {\n\t\t\t\t\tstats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor i := range dnsStatsBars {\n\t\t\t\tstats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)\n\t\t\t}\n\t\t}\n\t}\n\n\tif includeTopDomains && topDomainsErr == nil && len(topDomainsResponse.Domains) > 0 {\n\t\tdomains := make([]dnsStatsBlockedDomain, 0, len(topDomainsResponse.Domains))\n\t\tfor i := range topDomainsResponse.Domains {\n\t\t\td := &topDomainsResponse.Domains[i]\n\t\t\tdomains = append(domains, dnsStatsBlockedDomain{\n\t\t\t\tDomain:         d.Domain,\n\t\t\t\tPercentBlocked: int(float64(d.Count) / float64(statsResponse.Queries.Blocked) * 100),\n\t\t\t})\n\t\t}\n\n\t\tsort.Slice(domains, func(a, b int) bool {\n\t\t\treturn domains[a].PercentBlocked > domains[b].PercentBlocked\n\t\t})\n\t\tstats.TopBlockedDomains = domains[:min(len(domains), 5)]\n\t}\n\n\treturn stats, sessionID, ternary(partialContent, errPartialContent, nil)\n}\n\nfunc fetchPiholeSessionID(instanceURL string, client *http.Client, password string) (string, error) {\n\trequestBody := []byte(`{\"password\":\"` + password + `\"}`)\n\n\trequest, err := http.NewRequest(\"POST\", instanceURL+\"/api/auth\", bytes.NewBuffer(requestBody))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"creating authentication request: %v\", err)\n\t}\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"sending authentication request: %v\", err)\n\t}\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"reading authentication response: %v\", err)\n\t}\n\n\tvar jsonResponse struct {\n\t\tSession struct {\n\t\t\tSID     string `json:\"sid\"`\n\t\t\tMessage string `json:\"message\"`\n\t\t} `json:\"session\"`\n\t}\n\n\tif err := json.Unmarshal(body, &jsonResponse); err != nil {\n\t\treturn \"\", fmt.Errorf(\"parsing authentication response: %v\", err)\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"authentication request returned status %s with message '%s'\",\n\t\t\tresponse.Status, jsonResponse.Session.Message,\n\t\t)\n\t}\n\n\tif jsonResponse.Session.SID == \"\" {\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"authentication response returned empty session ID, status code %d, message '%s'\",\n\t\t\tresponse.StatusCode, jsonResponse.Session.Message,\n\t\t)\n\t}\n\n\treturn jsonResponse.Session.SID, nil\n}\n\nfunc checkPiholeSessionIDIsValid(instanceURL string, client *http.Client, sessionID string) (bool, error) {\n\trequest, err := http.NewRequest(\"GET\", instanceURL+\"/api/auth\", nil)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"creating session ID check request: %v\", err)\n\t}\n\trequest.Header.Set(\"x-ftl-sid\", sessionID)\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusOK && response.StatusCode != http.StatusUnauthorized {\n\t\treturn false, fmt.Errorf(\"session ID check request returned status %s\", response.Status)\n\t}\n\n\treturn response.StatusCode == http.StatusOK, nil\n}\n\ntype technitiumStatsResponse struct {\n\tResponse struct {\n\t\tStats struct {\n\t\t\tTotalQueries   int `json:\"totalQueries\"`\n\t\t\tBlockedQueries int `json:\"totalBlocked\"`\n\t\t\tBlockedZones   int `json:\"blockedZones\"`\n\t\t\tBlockListZones int `json:\"blockListZones\"`\n\t\t} `json:\"stats\"`\n\t\tMainChartData struct {\n\t\t\tDatasets []struct {\n\t\t\t\tLabel string `json:\"label\"`\n\t\t\t\tData  []int  `json:\"data\"`\n\t\t\t} `json:\"datasets\"`\n\t\t} `json:\"mainChartData\"`\n\t\tTopBlockedDomains []struct {\n\t\t\tDomain string `json:\"name\"`\n\t\t\tCount  int    `json:\"hits\"`\n\t\t}\n\t} `json:\"response\"`\n}\n\nfunc fetchTechnitiumStats(instanceUrl string, allowInsecure bool, token string, noGraph bool) (*dnsStats, error) {\n\tif token == \"\" {\n\t\treturn nil, errors.New(\"missing API token\")\n\t}\n\n\trequestURL := strings.TrimRight(instanceUrl, \"/\") + \"/api/dashboard/stats/get?token=\" + token + \"&type=LastDay\"\n\n\trequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar client requestDoer\n\tif !allowInsecure {\n\t\tclient = defaultHTTPClient\n\t} else {\n\t\tclient = defaultInsecureHTTPClient\n\t}\n\n\tresponseJson, err := decodeJsonFromRequest[technitiumStatsResponse](client, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar topBlockedDomainsCount = min(len(responseJson.Response.TopBlockedDomains), 5)\n\n\tstats := &dnsStats{\n\t\tTotalQueries:      responseJson.Response.Stats.TotalQueries,\n\t\tBlockedQueries:    responseJson.Response.Stats.BlockedQueries,\n\t\tTopBlockedDomains: make([]dnsStatsBlockedDomain, 0, topBlockedDomainsCount),\n\t\tDomainsBlocked:    responseJson.Response.Stats.BlockedZones + responseJson.Response.Stats.BlockListZones,\n\t}\n\n\tif stats.TotalQueries <= 0 {\n\t\treturn stats, nil\n\t}\n\n\tstats.BlockedPercent = int(float64(responseJson.Response.Stats.BlockedQueries) / float64(responseJson.Response.Stats.TotalQueries) * 100)\n\n\tfor i := 0; i < topBlockedDomainsCount; i++ {\n\t\tdomain := responseJson.Response.TopBlockedDomains[i]\n\t\tfirstDomain := domain.Domain\n\n\t\tif firstDomain == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tstats.TopBlockedDomains = append(stats.TopBlockedDomains, dnsStatsBlockedDomain{\n\t\t\tDomain: firstDomain,\n\t\t})\n\n\t\tif stats.BlockedQueries > 0 {\n\t\t\tstats.TopBlockedDomains[i].PercentBlocked = int(float64(domain.Count) / float64(responseJson.Response.Stats.BlockedQueries) * 100)\n\t\t}\n\t}\n\n\tif noGraph {\n\t\treturn stats, nil\n\t}\n\n\tvar queriesSeries, blockedSeries []int\n\n\tfor _, label := range responseJson.Response.MainChartData.Datasets {\n\t\tswitch label.Label {\n\t\tcase \"Total\":\n\t\t\tqueriesSeries = label.Data\n\t\tcase \"Blocked\":\n\t\t\tblockedSeries = label.Data\n\t\t}\n\t}\n\n\tif len(queriesSeries) > dnsStatsHoursSpan {\n\t\tqueriesSeries = queriesSeries[len(queriesSeries)-dnsStatsHoursSpan:]\n\t} else if len(queriesSeries) < dnsStatsHoursSpan {\n\t\tqueriesSeries = append(make([]int, dnsStatsHoursSpan-len(queriesSeries)), queriesSeries...)\n\t}\n\n\tif len(blockedSeries) > dnsStatsHoursSpan {\n\t\tblockedSeries = blockedSeries[len(blockedSeries)-dnsStatsHoursSpan:]\n\t} else if len(blockedSeries) < dnsStatsHoursSpan {\n\t\tblockedSeries = append(make([]int, dnsStatsHoursSpan-len(blockedSeries)), blockedSeries...)\n\t}\n\n\tmaxQueriesInSeries := 0\n\n\tfor i := 0; i < dnsStatsBars; i++ {\n\t\tqueries := 0\n\t\tblocked := 0\n\n\t\tfor j := 0; j < dnsStatsHoursPerBar; j++ {\n\t\t\tqueries += queriesSeries[i*dnsStatsHoursPerBar+j]\n\t\t\tblocked += blockedSeries[i*dnsStatsHoursPerBar+j]\n\t\t}\n\n\t\tstats.Series[i] = dnsStatsSeries{\n\t\t\tQueries: queries,\n\t\t\tBlocked: blocked,\n\t\t}\n\n\t\tif queries > 0 {\n\t\t\tstats.Series[i].PercentBlocked = int(float64(blocked) / float64(queries) * 100)\n\t\t}\n\n\t\tif queries > maxQueriesInSeries {\n\t\t\tmaxQueriesInSeries = queries\n\t\t}\n\t}\n\n\tfor i := 0; i < dnsStatsBars; i++ {\n\t\tstats.Series[i].PercentTotal = int(float64(stats.Series[i].Queries) / float64(maxQueriesInSeries) * 100)\n\t}\n\n\treturn stats, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-docker-containers.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar dockerContainersWidgetTemplate = mustParseTemplate(\"docker-containers.html\", \"widget-base.html\")\n\ntype dockerContainersWidget struct {\n\twidgetBase           `yaml:\",inline\"`\n\tHideByDefault        bool                         `yaml:\"hide-by-default\"`\n\tRunningOnly          bool                         `yaml:\"running-only\"`\n\tCategory             string                       `yaml:\"category\"`\n\tSockPath             string                       `yaml:\"sock-path\"`\n\tFormatContainerNames bool                         `yaml:\"format-container-names\"`\n\tContainers           dockerContainerList          `yaml:\"-\"`\n\tLabelOverrides       map[string]map[string]string `yaml:\"containers\"`\n}\n\nfunc (widget *dockerContainersWidget) initialize() error {\n\twidget.withTitle(\"Docker Containers\").withCacheDuration(1 * time.Minute)\n\n\tif widget.SockPath == \"\" {\n\t\twidget.SockPath = \"/var/run/docker.sock\"\n\t}\n\n\treturn nil\n}\n\nfunc (widget *dockerContainersWidget) update(ctx context.Context) {\n\tcontainers, err := fetchDockerContainers(\n\t\twidget.SockPath,\n\t\twidget.HideByDefault,\n\t\twidget.Category,\n\t\twidget.RunningOnly,\n\t\twidget.FormatContainerNames,\n\t\twidget.LabelOverrides,\n\t)\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tcontainers.sortByStateIconThenTitle()\n\twidget.Containers = containers\n}\n\nfunc (widget *dockerContainersWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, dockerContainersWidgetTemplate)\n}\n\nconst (\n\tdockerContainerLabelHide        = \"glance.hide\"\n\tdockerContainerLabelName        = \"glance.name\"\n\tdockerContainerLabelURL         = \"glance.url\"\n\tdockerContainerLabelDescription = \"glance.description\"\n\tdockerContainerLabelSameTab     = \"glance.same-tab\"\n\tdockerContainerLabelIcon        = \"glance.icon\"\n\tdockerContainerLabelID          = \"glance.id\"\n\tdockerContainerLabelParent      = \"glance.parent\"\n\tdockerContainerLabelCategory    = \"glance.category\"\n)\n\nconst (\n\tdockerContainerStateIconOK     = \"ok\"\n\tdockerContainerStateIconPaused = \"paused\"\n\tdockerContainerStateIconWarn   = \"warn\"\n\tdockerContainerStateIconOther  = \"other\"\n)\n\nvar dockerContainerStateIconPriorities = map[string]int{\n\tdockerContainerStateIconWarn:   0,\n\tdockerContainerStateIconOther:  1,\n\tdockerContainerStateIconPaused: 2,\n\tdockerContainerStateIconOK:     3,\n}\n\ntype dockerContainerJsonResponse struct {\n\tNames  []string              `json:\"Names\"`\n\tImage  string                `json:\"Image\"`\n\tState  string                `json:\"State\"`\n\tStatus string                `json:\"Status\"`\n\tLabels dockerContainerLabels `json:\"Labels\"`\n}\n\ntype dockerContainerLabels map[string]string\n\nfunc (l *dockerContainerLabels) getOrDefault(label, def string) string {\n\tif l == nil {\n\t\treturn def\n\t}\n\n\tv, ok := (*l)[label]\n\tif !ok {\n\t\treturn def\n\t}\n\n\tif v == \"\" {\n\t\treturn def\n\t}\n\n\treturn v\n}\n\ntype dockerContainer struct {\n\tName        string\n\tURL         string\n\tSameTab     bool\n\tImage       string\n\tState       string\n\tStateText   string\n\tStateIcon   string\n\tDescription string\n\tIcon        customIconField\n\tChildren    dockerContainerList\n}\n\ntype dockerContainerList []dockerContainer\n\nfunc (containers dockerContainerList) sortByStateIconThenTitle() {\n\tp := &dockerContainerStateIconPriorities\n\n\tsort.SliceStable(containers, func(a, b int) bool {\n\t\tif containers[a].StateIcon != containers[b].StateIcon {\n\t\t\treturn (*p)[containers[a].StateIcon] < (*p)[containers[b].StateIcon]\n\t\t}\n\n\t\treturn strings.ToLower(containers[a].Name) < strings.ToLower(containers[b].Name)\n\t})\n}\n\nfunc dockerContainerStateToStateIcon(state string) string {\n\tswitch state {\n\tcase \"running\":\n\t\treturn dockerContainerStateIconOK\n\tcase \"paused\":\n\t\treturn dockerContainerStateIconPaused\n\tcase \"exited\", \"unhealthy\", \"dead\":\n\t\treturn dockerContainerStateIconWarn\n\tdefault:\n\t\treturn dockerContainerStateIconOther\n\t}\n}\n\nfunc fetchDockerContainers(\n\tsocketPath string,\n\thideByDefault bool,\n\tcategory string,\n\trunningOnly bool,\n\tformatNames bool,\n\tlabelOverrides map[string]map[string]string,\n) (dockerContainerList, error) {\n\tcontainers, err := fetchDockerContainersFromSource(socketPath, category, runningOnly, labelOverrides)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching containers: %w\", err)\n\t}\n\n\tcontainers, children := groupDockerContainerChildren(containers, hideByDefault)\n\tdockerContainers := make(dockerContainerList, 0, len(containers))\n\n\tfor i := range containers {\n\t\tcontainer := &containers[i]\n\n\t\tdc := dockerContainer{\n\t\t\tName:        deriveDockerContainerName(container, formatNames),\n\t\t\tURL:         container.Labels.getOrDefault(dockerContainerLabelURL, \"\"),\n\t\t\tDescription: container.Labels.getOrDefault(dockerContainerLabelDescription, \"\"),\n\t\t\tSameTab:     stringToBool(container.Labels.getOrDefault(dockerContainerLabelSameTab, \"false\")),\n\t\t\tImage:       container.Image,\n\t\t\tState:       strings.ToLower(container.State),\n\t\t\tStateText:   strings.ToLower(container.Status),\n\t\t\tIcon:        newCustomIconField(container.Labels.getOrDefault(dockerContainerLabelIcon, \"si:docker\")),\n\t\t}\n\n\t\tif idValue := container.Labels.getOrDefault(dockerContainerLabelID, \"\"); idValue != \"\" {\n\t\t\tif children, ok := children[idValue]; ok {\n\t\t\t\tfor i := range children {\n\t\t\t\t\tchild := &children[i]\n\t\t\t\t\tdc.Children = append(dc.Children, dockerContainer{\n\t\t\t\t\t\tName:      deriveDockerContainerName(child, formatNames),\n\t\t\t\t\t\tStateText: child.Status,\n\t\t\t\t\t\tStateIcon: dockerContainerStateToStateIcon(strings.ToLower(child.State)),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdc.Children.sortByStateIconThenTitle()\n\n\t\tstateIconSupersededByChild := false\n\t\tfor i := range dc.Children {\n\t\t\tif dc.Children[i].StateIcon == dockerContainerStateIconWarn {\n\t\t\t\tdc.StateIcon = dockerContainerStateIconWarn\n\t\t\t\tstateIconSupersededByChild = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !stateIconSupersededByChild {\n\t\t\tdc.StateIcon = dockerContainerStateToStateIcon(dc.State)\n\t\t}\n\n\t\tdockerContainers = append(dockerContainers, dc)\n\t}\n\n\treturn dockerContainers, nil\n}\n\nfunc deriveDockerContainerName(container *dockerContainerJsonResponse, formatNames bool) string {\n\tif v := container.Labels.getOrDefault(dockerContainerLabelName, \"\"); v != \"\" {\n\t\treturn v\n\t}\n\n\tif len(container.Names) == 0 || container.Names[0] == \"\" {\n\t\treturn \"n/a\"\n\t}\n\n\tname := strings.TrimLeft(container.Names[0], \"/\")\n\n\tif formatNames {\n\t\tname = strings.ReplaceAll(name, \"_\", \" \")\n\t\tname = strings.ReplaceAll(name, \"-\", \" \")\n\n\t\twords := strings.Split(name, \" \")\n\t\tfor i := range words {\n\t\t\tif len(words[i]) > 0 {\n\t\t\t\twords[i] = strings.ToUpper(words[i][:1]) + words[i][1:]\n\t\t\t}\n\t\t}\n\t\tname = strings.Join(words, \" \")\n\t}\n\n\treturn name\n}\n\nfunc groupDockerContainerChildren(\n\tcontainers []dockerContainerJsonResponse,\n\thideByDefault bool,\n) (\n\t[]dockerContainerJsonResponse,\n\tmap[string][]dockerContainerJsonResponse,\n) {\n\tparents := make([]dockerContainerJsonResponse, 0, len(containers))\n\tchildren := make(map[string][]dockerContainerJsonResponse)\n\n\tfor i := range containers {\n\t\tcontainer := &containers[i]\n\n\t\tif isDockerContainerHidden(container, hideByDefault) {\n\t\t\tcontinue\n\t\t}\n\n\t\tisParent := container.Labels.getOrDefault(dockerContainerLabelID, \"\") != \"\"\n\t\tparent := container.Labels.getOrDefault(dockerContainerLabelParent, \"\")\n\n\t\tif !isParent && parent != \"\" {\n\t\t\tchildren[parent] = append(children[parent], *container)\n\t\t} else {\n\t\t\tparents = append(parents, *container)\n\t\t}\n\t}\n\n\treturn parents, children\n}\n\nfunc isDockerContainerHidden(container *dockerContainerJsonResponse, hideByDefault bool) bool {\n\tif v := container.Labels.getOrDefault(dockerContainerLabelHide, \"\"); v != \"\" {\n\t\treturn stringToBool(v)\n\t}\n\n\treturn hideByDefault\n}\n\n\nfunc fetchDockerContainersFromSource(\n\tsource string,\n\tcategory string,\n\trunningOnly bool,\n\tlabelOverrides map[string]map[string]string,\n) ([]dockerContainerJsonResponse, error) {\n\tvar hostname string\n\n\tvar client *http.Client\n\tif strings.HasPrefix(source, \"tcp://\") || strings.HasPrefix(source, \"http://\") {\n\t\tclient = &http.Client{}\n\t\tparsed, err := url.Parse(source)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing URL: %w\", err)\n\t\t}\n\n\t\tport := parsed.Port()\n\t\tif port == \"\" {\n\t\t\tport = \"80\"\n\t\t}\n\n\t\thostname = parsed.Hostname() + \":\" + port\n\t} else {\n\t\thostname = \"docker\"\n\t\tclient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\t\treturn net.Dial(\"unix\", source)\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\n\tfetchAll := ternary(runningOnly, \"false\", \"true\")\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\trequest, err := http.NewRequestWithContext(ctx, \"GET\", \"http://\"+hostname+\"/containers/json?all=\"+fetchAll, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating request: %w\", err)\n\t}\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sending request to socket: %w\", err)\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"non-200 response status: %s\", response.Status)\n\t}\n\n\tvar containers []dockerContainerJsonResponse\n\tif err := json.NewDecoder(response.Body).Decode(&containers); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding response: %w\", err)\n\t}\n\n\tfor i := range containers {\n\t\tcontainer := &containers[i]\n\t\tname := strings.TrimLeft(itemAtIndexOrDefault(container.Names, 0, \"\"), \"/\")\n\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\toverrides, ok := labelOverrides[name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif container.Labels == nil {\n\t\t\tcontainer.Labels = make(dockerContainerLabels)\n\t\t}\n\n\t\tfor label, value := range overrides {\n\t\t\tcontainer.Labels[\"glance.\"+label] = value\n\t\t}\n\t}\n\n\t// We have to filter here instead of using the `filters` parameter of Docker's API\n\t// because the user may define a category override within their config\n\tif category != \"\" {\n\t\tfiltered := make([]dockerContainerJsonResponse, 0, len(containers))\n\n\t\tfor i := range containers {\n\t\t\tcontainer := &containers[i]\n\n\t\t\tif container.Labels.getOrDefault(dockerContainerLabelCategory, \"\") == category {\n\t\t\t\tfiltered = append(filtered, *container)\n\t\t\t}\n\t\t}\n\n\t\tcontainers = filtered\n\t}\n\n\treturn containers, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-extension.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\"\n\t\"html/template\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"time\"\n)\n\nvar extensionWidgetTemplate = mustParseTemplate(\"extension.html\", \"widget-base.html\")\n\nconst extensionWidgetDefaultTitle = \"Extension\"\n\ntype extensionWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tURL                 string               `yaml:\"url\"`\n\tFallbackContentType string               `yaml:\"fallback-content-type\"`\n\tParameters          queryParametersField `yaml:\"parameters\"`\n\tHeaders             map[string]string    `yaml:\"headers\"`\n\tAllowHtml           bool                 `yaml:\"allow-potentially-dangerous-html\"`\n\tExtension           extension            `yaml:\"-\"`\n\tcachedHTML          template.HTML        `yaml:\"-\"`\n}\n\nfunc (widget *extensionWidget) initialize() error {\n\twidget.withTitle(extensionWidgetDefaultTitle).withCacheDuration(time.Minute * 30)\n\n\tif widget.URL == \"\" {\n\t\treturn errors.New(\"URL is required\")\n\t}\n\n\tif _, err := url.Parse(widget.URL); err != nil {\n\t\treturn fmt.Errorf(\"parsing URL: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (widget *extensionWidget) update(ctx context.Context) {\n\textension, err := fetchExtension(extensionRequestOptions{\n\t\tURL:                 widget.URL,\n\t\tFallbackContentType: widget.FallbackContentType,\n\t\tParameters:          widget.Parameters,\n\t\tHeaders:             widget.Headers,\n\t\tAllowHtml:           widget.AllowHtml,\n\t})\n\n\twidget.canContinueUpdateAfterHandlingErr(err)\n\n\twidget.Extension = extension\n\n\tif widget.Title == extensionWidgetDefaultTitle && extension.Title != \"\" {\n\t\twidget.Title = extension.Title\n\t}\n\n\tif widget.TitleURL == \"\" && extension.TitleURL != \"\" {\n\t\twidget.TitleURL = extension.TitleURL\n\t}\n\n\twidget.cachedHTML = widget.renderTemplate(widget, extensionWidgetTemplate)\n}\n\nfunc (widget *extensionWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n\ntype extensionType int\n\nconst (\n\textensionContentHTML extensionType = iota\n\textensionContentUnknown\n)\n\nvar extensionStringToType = map[string]extensionType{\n\t\"html\": extensionContentHTML,\n}\n\nconst (\n\textensionHeaderTitle            = \"Widget-Title\"\n\textensionHeaderTitleURL         = \"Widget-Title-URL\"\n\textensionHeaderContentType      = \"Widget-Content-Type\"\n\textensionHeaderContentFrameless = \"Widget-Content-Frameless\"\n)\n\ntype extensionRequestOptions struct {\n\tURL                 string               `yaml:\"url\"`\n\tFallbackContentType string               `yaml:\"fallback-content-type\"`\n\tParameters          queryParametersField `yaml:\"parameters\"`\n\tHeaders             map[string]string    `yaml:\"headers\"`\n\tAllowHtml           bool                 `yaml:\"allow-potentially-dangerous-html\"`\n}\n\ntype extension struct {\n\tTitle     string\n\tTitleURL  string\n\tContent   template.HTML\n\tFrameless bool\n}\n\nfunc convertExtensionContent(options extensionRequestOptions, content []byte, contentType extensionType) template.HTML {\n\tswitch contentType {\n\tcase extensionContentHTML:\n\t\tif options.AllowHtml {\n\t\t\treturn template.HTML(content)\n\t\t}\n\n\t\tfallthrough\n\tdefault:\n\t\treturn template.HTML(\"<pre>\" + html.EscapeString(string(content)) + \"</pre>\")\n\t}\n}\n\nfunc fetchExtension(options extensionRequestOptions) (extension, error) {\n\trequest, _ := http.NewRequest(\"GET\", options.URL, nil)\n\tif len(options.Parameters) > 0 {\n\t\trequest.URL.RawQuery = options.Parameters.toQueryString()\n\t}\n\n\tfor key, value := range options.Headers {\n\t\trequest.Header.Add(key, value)\n\t}\n\n\tresponse, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\tslog.Error(\"Failed fetching extension\", \"url\", options.URL, \"error\", err)\n\t\treturn extension{}, fmt.Errorf(\"%w: request failed: %w\", errNoContent, err)\n\t}\n\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\tslog.Error(\"Failed reading response body of extension\", \"url\", options.URL, \"error\", err)\n\t\treturn extension{}, fmt.Errorf(\"%w: could not read body: %w\", errNoContent, err)\n\t}\n\n\textension := extension{}\n\n\tif response.Header.Get(extensionHeaderTitle) == \"\" {\n\t\textension.Title = \"Extension\"\n\t} else {\n\t\textension.Title = response.Header.Get(extensionHeaderTitle)\n\t}\n\n\tif response.Header.Get(extensionHeaderTitleURL) != \"\" {\n\t\textension.TitleURL = response.Header.Get(extensionHeaderTitleURL)\n\t}\n\n\tcontentType, ok := extensionStringToType[response.Header.Get(extensionHeaderContentType)]\n\n\tif !ok {\n\t\tcontentType, ok = extensionStringToType[options.FallbackContentType]\n\n\t\tif !ok {\n\t\t\tcontentType = extensionContentUnknown\n\t\t}\n\t}\n\n\tif stringToBool(response.Header.Get(extensionHeaderContentFrameless)) {\n\t\textension.Frameless = true\n\t}\n\n\textension.Content = convertExtensionContent(options, body, contentType)\n\n\treturn extension, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-group.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"html/template\"\n\t\"time\"\n)\n\nvar groupWidgetTemplate = mustParseTemplate(\"group.html\", \"widget-base.html\")\n\ntype groupWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tcontainerWidgetBase `yaml:\",inline\"`\n}\n\nfunc (widget *groupWidget) initialize() error {\n\twidget.withError(nil)\n\twidget.HideHeader = true\n\n\tfor i := range widget.Widgets {\n\t\twidget.Widgets[i].setHideHeader(true)\n\n\t\tif widget.Widgets[i].GetType() == \"group\" {\n\t\t\treturn errors.New(\"nested groups are not supported\")\n\t\t} else if widget.Widgets[i].GetType() == \"split-column\" {\n\t\t\treturn errors.New(\"split columns inside of groups are not supported\")\n\t\t}\n\t}\n\n\tif err := widget.containerWidgetBase._initializeWidgets(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (widget *groupWidget) update(ctx context.Context) {\n\twidget.containerWidgetBase._update(ctx)\n}\n\nfunc (widget *groupWidget) setProviders(providers *widgetProviders) {\n\twidget.containerWidgetBase._setProviders(providers)\n}\n\nfunc (widget *groupWidget) requiresUpdate(now *time.Time) bool {\n\treturn widget.containerWidgetBase._requiresUpdate(now)\n}\n\nfunc (widget *groupWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, groupWidgetTemplate)\n}\n"
  },
  {
    "path": "internal/glance/widget-hacker-news.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype hackerNewsWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tPosts               forumPostList `yaml:\"-\"`\n\tLimit               int           `yaml:\"limit\"`\n\tSortBy              string        `yaml:\"sort-by\"`\n\tExtraSortBy         string        `yaml:\"extra-sort-by\"`\n\tCollapseAfter       int           `yaml:\"collapse-after\"`\n\tCommentsUrlTemplate string        `yaml:\"comments-url-template\"`\n\tShowThumbnails      bool          `yaml:\"-\"`\n}\n\nfunc (widget *hackerNewsWidget) initialize() error {\n\twidget.\n\t\twithTitle(\"Hacker News\").\n\t\twithTitleURL(\"https://news.ycombinator.com/\").\n\t\twithCacheDuration(30 * time.Minute)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 15\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\tif widget.SortBy != \"top\" && widget.SortBy != \"new\" && widget.SortBy != \"best\" {\n\t\twidget.SortBy = \"top\"\n\t}\n\n\treturn nil\n}\n\nfunc (widget *hackerNewsWidget) update(ctx context.Context) {\n\tposts, err := fetchHackerNewsPosts(widget.SortBy, 40, widget.CommentsUrlTemplate)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif widget.ExtraSortBy == \"engagement\" {\n\t\tposts.calculateEngagement()\n\t\tposts.sortByEngagement()\n\t}\n\n\tif widget.Limit < len(posts) {\n\t\tposts = posts[:widget.Limit]\n\t}\n\n\twidget.Posts = posts\n}\n\nfunc (widget *hackerNewsWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, forumPostsTemplate)\n}\n\ntype hackerNewsPostResponseJson struct {\n\tId           int    `json:\"id\"`\n\tScore        int    `json:\"score\"`\n\tTitle        string `json:\"title\"`\n\tTargetUrl    string `json:\"url,omitempty\"`\n\tCommentCount int    `json:\"descendants\"`\n\tTimePosted   int64  `json:\"time\"`\n}\n\nfunc fetchHackerNewsPostIds(sort string) ([]int, error) {\n\trequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://hacker-news.firebaseio.com/v0/%sstories.json\", sort), nil)\n\tresponse, err := decodeJsonFromRequest[[]int](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: could not fetch list of post IDs\", errNoContent)\n\t}\n\n\treturn response, nil\n}\n\nfunc fetchHackerNewsPostsFromIds(postIds []int, commentsUrlTemplate string) (forumPostList, error) {\n\trequests := make([]*http.Request, len(postIds))\n\n\tfor i, id := range postIds {\n\t\trequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://hacker-news.firebaseio.com/v0/item/%d.json\", id), nil)\n\t\trequests[i] = request\n\t}\n\n\ttask := decodeJsonFromRequestTask[hackerNewsPostResponseJson](defaultHTTPClient)\n\tjob := newJob(task, requests).withWorkers(30)\n\tresults, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tposts := make(forumPostList, 0, len(postIds))\n\n\tfor i := range results {\n\t\tif errs[i] != nil {\n\t\t\tslog.Error(\"Failed to fetch or parse hacker news post\", \"error\", errs[i], \"url\", requests[i].URL)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar commentsUrl string\n\n\t\tif commentsUrlTemplate == \"\" {\n\t\t\tcommentsUrl = \"https://news.ycombinator.com/item?id=\" + strconv.Itoa(results[i].Id)\n\t\t} else {\n\t\t\tcommentsUrl = strings.ReplaceAll(commentsUrlTemplate, \"{POST-ID}\", strconv.Itoa(results[i].Id))\n\t\t}\n\n\t\tposts = append(posts, forumPost{\n\t\t\tTitle:           results[i].Title,\n\t\t\tDiscussionUrl:   commentsUrl,\n\t\t\tTargetUrl:       results[i].TargetUrl,\n\t\t\tTargetUrlDomain: extractDomainFromUrl(results[i].TargetUrl),\n\t\t\tCommentCount:    results[i].CommentCount,\n\t\t\tScore:           results[i].Score,\n\t\t\tTimePosted:      time.Unix(results[i].TimePosted, 0),\n\t\t})\n\t}\n\n\tif len(posts) == 0 {\n\t\treturn nil, errNoContent\n\t}\n\n\tif len(posts) != len(postIds) {\n\t\treturn posts, fmt.Errorf(\"%w could not fetch some hacker news posts\", errPartialContent)\n\t}\n\n\treturn posts, nil\n}\n\nfunc fetchHackerNewsPosts(sort string, limit int, commentsUrlTemplate string) (forumPostList, error) {\n\tpostIds, err := fetchHackerNewsPostIds(sort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(postIds) > limit {\n\t\tpostIds = postIds[:limit]\n\t}\n\n\treturn fetchHackerNewsPostsFromIds(postIds, commentsUrlTemplate)\n}\n"
  },
  {
    "path": "internal/glance/widget-html.go",
    "content": "package glance\n\nimport (\n\t\"html/template\"\n)\n\ntype htmlWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tSource     template.HTML `yaml:\"source\"`\n}\n\nfunc (widget *htmlWidget) initialize() error {\n\twidget.withTitle(\"\").withError(nil)\n\n\treturn nil\n}\n\nfunc (widget *htmlWidget) Render() template.HTML {\n\treturn widget.Source\n}\n"
  },
  {
    "path": "internal/glance/widget-iframe.go",
    "content": "package glance\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/url\"\n)\n\nvar iframeWidgetTemplate = mustParseTemplate(\"iframe.html\", \"widget-base.html\")\n\ntype iframeWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tcachedHTML template.HTML `yaml:\"-\"`\n\tSource     string        `yaml:\"source\"`\n\tHeight     int           `yaml:\"height\"`\n}\n\nfunc (widget *iframeWidget) initialize() error {\n\twidget.withTitle(\"IFrame\").withError(nil)\n\n\tif widget.Source == \"\" {\n\t\treturn errors.New(\"source is required\")\n\t}\n\n\tif _, err := url.Parse(widget.Source); err != nil {\n\t\treturn fmt.Errorf(\"parsing URL: %v\", err)\n\t}\n\n\tif widget.Height == 50 {\n\t\twidget.Height = 300\n\t} else if widget.Height < 50 {\n\t\twidget.Height = 50\n\t}\n\n\twidget.cachedHTML = widget.renderTemplate(widget, iframeWidgetTemplate)\n\n\treturn nil\n}\n\nfunc (widget *iframeWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-lobsters.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype lobstersWidget struct {\n\twidgetBase     `yaml:\",inline\"`\n\tPosts          forumPostList `yaml:\"-\"`\n\tInstanceURL    string        `yaml:\"instance-url\"`\n\tCustomURL      string        `yaml:\"custom-url\"`\n\tLimit          int           `yaml:\"limit\"`\n\tCollapseAfter  int           `yaml:\"collapse-after\"`\n\tSortBy         string        `yaml:\"sort-by\"`\n\tTags           []string      `yaml:\"tags\"`\n\tShowThumbnails bool          `yaml:\"-\"`\n}\n\nfunc (widget *lobstersWidget) initialize() error {\n\twidget.withTitle(\"Lobsters\").withCacheDuration(time.Hour)\n\n\tif widget.InstanceURL == \"\" {\n\t\twidget.withTitleURL(\"https://lobste.rs\")\n\t} else {\n\t\twidget.withTitleURL(widget.InstanceURL)\n\t}\n\n\tif widget.SortBy == \"\" || (widget.SortBy != \"hot\" && widget.SortBy != \"new\") {\n\t\twidget.SortBy = \"hot\"\n\t}\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 15\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\treturn nil\n}\n\nfunc (widget *lobstersWidget) update(ctx context.Context) {\n\tposts, err := fetchLobstersPosts(widget.CustomURL, widget.InstanceURL, widget.SortBy, widget.Tags)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif widget.Limit < len(posts) {\n\t\tposts = posts[:widget.Limit]\n\t}\n\n\twidget.Posts = posts\n}\n\nfunc (widget *lobstersWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, forumPostsTemplate)\n}\n\ntype lobstersPostResponseJson struct {\n\tCreatedAt    string   `json:\"created_at\"`\n\tTitle        string   `json:\"title\"`\n\tURL          string   `json:\"url\"`\n\tScore        int      `json:\"score\"`\n\tCommentCount int      `json:\"comment_count\"`\n\tCommentsURL  string   `json:\"comments_url\"`\n\tTags         []string `json:\"tags\"`\n}\n\ntype lobstersFeedResponseJson []lobstersPostResponseJson\n\nfunc fetchLobstersPostsFromFeed(feedUrl string) (forumPostList, error) {\n\trequest, err := http.NewRequest(\"GET\", feedUrl, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfeed, err := decodeJsonFromRequest[lobstersFeedResponseJson](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tposts := make(forumPostList, 0, len(feed))\n\n\tfor i := range feed {\n\t\tcreatedAt, _ := time.Parse(time.RFC3339, feed[i].CreatedAt)\n\n\t\tposts = append(posts, forumPost{\n\t\t\tTitle:           feed[i].Title,\n\t\t\tDiscussionUrl:   feed[i].CommentsURL,\n\t\t\tTargetUrl:       feed[i].URL,\n\t\t\tTargetUrlDomain: extractDomainFromUrl(feed[i].URL),\n\t\t\tCommentCount:    feed[i].CommentCount,\n\t\t\tScore:           feed[i].Score,\n\t\t\tTimePosted:      createdAt,\n\t\t\tTags:            feed[i].Tags,\n\t\t})\n\t}\n\n\tif len(posts) == 0 {\n\t\treturn nil, errNoContent\n\t}\n\n\treturn posts, nil\n}\n\nfunc fetchLobstersPosts(customURL string, instanceURL string, sortBy string, tags []string) (forumPostList, error) {\n\tvar feedUrl string\n\n\tif customURL != \"\" {\n\t\tfeedUrl = customURL\n\t} else {\n\t\tif instanceURL != \"\" {\n\t\t\tinstanceURL = strings.TrimRight(instanceURL, \"/\") + \"/\"\n\t\t} else {\n\t\t\tinstanceURL = \"https://lobste.rs/\"\n\t\t}\n\n\t\tif sortBy == \"hot\" {\n\t\t\tsortBy = \"hottest\"\n\t\t} else if sortBy == \"new\" {\n\t\t\tsortBy = \"newest\"\n\t\t}\n\n\t\tif len(tags) == 0 {\n\t\t\tfeedUrl = instanceURL + sortBy + \".json\"\n\t\t} else {\n\t\t\ttags := strings.Join(tags, \",\")\n\t\t\tfeedUrl = instanceURL + \"t/\" + tags + \".json\"\n\t\t}\n\t}\n\n\tposts, err := fetchLobstersPostsFromFeed(feedUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn posts, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-markets.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"math\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar marketsWidgetTemplate = mustParseTemplate(\"markets.html\", \"widget-base.html\")\n\ntype marketsWidget struct {\n\twidgetBase         `yaml:\",inline\"`\n\tStocksRequests     []marketRequest `yaml:\"stocks\"`\n\tMarketRequests     []marketRequest `yaml:\"markets\"`\n\tChartLinkTemplate  string          `yaml:\"chart-link-template\"`\n\tSymbolLinkTemplate string          `yaml:\"symbol-link-template\"`\n\tSort               string          `yaml:\"sort-by\"`\n\tMarkets            marketList      `yaml:\"-\"`\n}\n\nfunc (widget *marketsWidget) initialize() error {\n\twidget.withTitle(\"Markets\").withCacheDuration(time.Hour)\n\n\t// legacy support, remove in v0.10.0\n\tif len(widget.MarketRequests) == 0 {\n\t\twidget.MarketRequests = widget.StocksRequests\n\t}\n\n\tfor i := range widget.MarketRequests {\n\t\tm := &widget.MarketRequests[i]\n\n\t\tif widget.ChartLinkTemplate != \"\" && m.ChartLink == \"\" {\n\t\t\tm.ChartLink = strings.ReplaceAll(widget.ChartLinkTemplate, \"{SYMBOL}\", m.Symbol)\n\t\t}\n\n\t\tif widget.SymbolLinkTemplate != \"\" && m.SymbolLink == \"\" {\n\t\t\tm.SymbolLink = strings.ReplaceAll(widget.SymbolLinkTemplate, \"{SYMBOL}\", m.Symbol)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (widget *marketsWidget) update(ctx context.Context) {\n\tmarkets, err := fetchMarketsDataFromYahoo(widget.MarketRequests)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif widget.Sort == \"absolute-change\" {\n\t\tmarkets.sortByAbsChange()\n\t} else if widget.Sort == \"change\" {\n\t\tmarkets.sortByChange()\n\t}\n\n\twidget.Markets = markets\n}\n\nfunc (widget *marketsWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, marketsWidgetTemplate)\n}\n\ntype marketRequest struct {\n\tCustomName string `yaml:\"name\"`\n\tSymbol     string `yaml:\"symbol\"`\n\tChartLink  string `yaml:\"chart-link\"`\n\tSymbolLink string `yaml:\"symbol-link\"`\n}\n\ntype market struct {\n\tmarketRequest\n\tName           string\n\tCurrency       string\n\tPrice          float64\n\tPriceHint      int\n\tPercentChange  float64\n\tSvgChartPoints string\n}\n\ntype marketList []market\n\nfunc (t marketList) sortByAbsChange() {\n\tsort.Slice(t, func(i, j int) bool {\n\t\treturn math.Abs(t[i].PercentChange) > math.Abs(t[j].PercentChange)\n\t})\n}\n\nfunc (t marketList) sortByChange() {\n\tsort.Slice(t, func(i, j int) bool {\n\t\treturn t[i].PercentChange > t[j].PercentChange\n\t})\n}\n\ntype marketResponseJson struct {\n\tChart struct {\n\t\tResult []struct {\n\t\t\tMeta struct {\n\t\t\t\tCurrency           string  `json:\"currency\"`\n\t\t\t\tSymbol             string  `json:\"symbol\"`\n\t\t\t\tRegularMarketPrice float64 `json:\"regularMarketPrice\"`\n\t\t\t\tChartPreviousClose float64 `json:\"chartPreviousClose\"`\n\t\t\t\tShortName          string  `json:\"shortName\"`\n\t\t\t\tPriceHint          int     `json:\"priceHint\"`\n\t\t\t} `json:\"meta\"`\n\t\t\tIndicators struct {\n\t\t\t\tQuote []struct {\n\t\t\t\t\tClose []float64 `json:\"close,omitempty\"`\n\t\t\t\t} `json:\"quote\"`\n\t\t\t} `json:\"indicators\"`\n\t\t} `json:\"result\"`\n\t} `json:\"chart\"`\n}\n\n// TODO: allow changing chart time frame\nconst marketChartDays = 21\n\nfunc fetchMarketsDataFromYahoo(marketRequests []marketRequest) (marketList, error) {\n\trequests := make([]*http.Request, 0, len(marketRequests))\n\n\tfor i := range marketRequests {\n\t\trequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://query1.finance.yahoo.com/v8/finance/chart/%s?range=1mo&interval=1d\", marketRequests[i].Symbol), nil)\n\t\tsetBrowserUserAgentHeader(request)\n\t\trequests = append(requests, request)\n\t}\n\n\tjob := newJob(decodeJsonFromRequestTask[marketResponseJson](defaultHTTPClient), requests)\n\tresponses, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errNoContent, err)\n\t}\n\n\tmarkets := make(marketList, 0, len(responses))\n\tvar failed int\n\n\tfor i := range responses {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to fetch market data\", \"symbol\", marketRequests[i].Symbol, \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\tresponse := responses[i]\n\n\t\tif len(response.Chart.Result) == 0 {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Market response contains no data\", \"symbol\", marketRequests[i].Symbol)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := &response.Chart.Result[0]\n\t\tprices := result.Indicators.Quote[0].Close\n\n\t\tif len(prices) > marketChartDays {\n\t\t\tprices = prices[len(prices)-marketChartDays:]\n\t\t}\n\n\t\tprevious := result.Meta.RegularMarketPrice\n\n\t\tif len(prices) >= 2 && prices[len(prices)-2] != 0 {\n\t\t\tprevious = prices[len(prices)-2]\n\t\t}\n\n\t\tpoints := svgPolylineCoordsFromYValues(100, 50, maybeCopySliceWithoutZeroValues(prices))\n\n\t\tcurrency, exists := currencyToSymbol[strings.ToUpper(result.Meta.Currency)]\n\t\tif !exists {\n\t\t\tcurrency = result.Meta.Currency\n\t\t}\n\n\t\tmarkets = append(markets, market{\n\t\t\tmarketRequest: marketRequests[i],\n\t\t\tPrice:         result.Meta.RegularMarketPrice,\n\t\t\tCurrency:      currency,\n\t\t\tPriceHint:     result.Meta.PriceHint,\n\t\t\tName: ternary(marketRequests[i].CustomName == \"\",\n\t\t\t\tresult.Meta.ShortName,\n\t\t\t\tmarketRequests[i].CustomName,\n\t\t\t),\n\t\t\tPercentChange: percentChange(\n\t\t\t\tresult.Meta.RegularMarketPrice,\n\t\t\t\tprevious,\n\t\t\t),\n\t\t\tSvgChartPoints: points,\n\t\t})\n\t}\n\n\tif len(markets) == 0 {\n\t\treturn nil, errNoContent\n\t}\n\n\tif failed > 0 {\n\t\treturn markets, fmt.Errorf(\"%w: could not fetch data for %d market(s)\", errPartialContent, failed)\n\t}\n\n\treturn markets, nil\n}\n\nvar currencyToSymbol = map[string]string{\n\t\"USD\": \"$\",\n\t\"EUR\": \"€\",\n\t\"JPY\": \"¥\",\n\t\"CAD\": \"C$\",\n\t\"AUD\": \"A$\",\n\t\"GBP\": \"£\",\n\t\"CHF\": \"Fr\",\n\t\"NZD\": \"N$\",\n\t\"INR\": \"₹\",\n\t\"BRL\": \"R$\",\n\t\"RUB\": \"₽\",\n\t\"TRY\": \"₺\",\n\t\"ZAR\": \"R\",\n\t\"CNY\": \"¥\",\n\t\"KRW\": \"₩\",\n\t\"HKD\": \"HK$\",\n\t\"SGD\": \"S$\",\n\t\"SEK\": \"kr\",\n\t\"NOK\": \"kr\",\n\t\"DKK\": \"kr\",\n\t\"PLN\": \"zł\",\n\t\"PHP\": \"₱\",\n}\n"
  },
  {
    "path": "internal/glance/widget-monitor.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"slices\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tmonitorWidgetTemplate        = mustParseTemplate(\"monitor.html\", \"widget-base.html\")\n\tmonitorWidgetCompactTemplate = mustParseTemplate(\"monitor-compact.html\", \"widget-base.html\")\n)\n\ntype monitorWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tSites      []struct {\n\t\t*SiteStatusRequest `yaml:\",inline\"`\n\t\tStatus             *siteStatus     `yaml:\"-\"`\n\t\tURL                string          `yaml:\"-\"`\n\t\tErrorURL           string          `yaml:\"error-url\"`\n\t\tTitle              string          `yaml:\"title\"`\n\t\tIcon               customIconField `yaml:\"icon\"`\n\t\tSameTab            bool            `yaml:\"same-tab\"`\n\t\tStatusText         string          `yaml:\"-\"`\n\t\tStatusStyle        string          `yaml:\"-\"`\n\t\tAltStatusCodes     []int           `yaml:\"alt-status-codes\"`\n\t} `yaml:\"sites\"`\n\tStyle           string `yaml:\"style\"`\n\tShowFailingOnly bool   `yaml:\"show-failing-only\"`\n\tHasFailing      bool   `yaml:\"-\"`\n}\n\nfunc (widget *monitorWidget) initialize() error {\n\twidget.withTitle(\"Monitor\").withCacheDuration(5 * time.Minute)\n\n\treturn nil\n}\n\nfunc (widget *monitorWidget) update(ctx context.Context) {\n\trequests := make([]*SiteStatusRequest, len(widget.Sites))\n\n\tfor i := range widget.Sites {\n\t\trequests[i] = widget.Sites[i].SiteStatusRequest\n\t}\n\n\tstatuses, err := fetchStatusForSites(requests)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\twidget.HasFailing = false\n\n\tfor i := range widget.Sites {\n\t\tsite := &widget.Sites[i]\n\t\tstatus := &statuses[i]\n\t\tsite.Status = status\n\n\t\tif !slices.Contains(site.AltStatusCodes, status.Code) && (status.Code >= 400 || status.Error != nil) {\n\t\t\twidget.HasFailing = true\n\t\t}\n\n\t\tif status.Error != nil && site.ErrorURL != \"\" {\n\t\t\tsite.URL = site.ErrorURL\n\t\t} else {\n\t\t\tsite.URL = site.DefaultURL\n\t\t}\n\n\t\tsite.StatusText = statusCodeToText(status.Code, site.AltStatusCodes)\n\t\tsite.StatusStyle = statusCodeToStyle(status.Code, site.AltStatusCodes)\n\t}\n}\n\nfunc (widget *monitorWidget) Render() template.HTML {\n\tif widget.Style == \"compact\" {\n\t\treturn widget.renderTemplate(widget, monitorWidgetCompactTemplate)\n\t}\n\n\treturn widget.renderTemplate(widget, monitorWidgetTemplate)\n}\n\nfunc statusCodeToText(status int, altStatusCodes []int) string {\n\tif status == 200 || slices.Contains(altStatusCodes, status) {\n\t\treturn \"OK\"\n\t}\n\tif status == 404 {\n\t\treturn \"Not Found\"\n\t}\n\tif status == 403 {\n\t\treturn \"Forbidden\"\n\t}\n\tif status == 401 {\n\t\treturn \"Unauthorized\"\n\t}\n\tif status >= 500 {\n\t\treturn \"Server Error\"\n\t}\n\tif status >= 400 {\n\t\treturn \"Client Error\"\n\t}\n\n\treturn strconv.Itoa(status)\n}\n\nfunc statusCodeToStyle(status int, altStatusCodes []int) string {\n\tif status == 200 || slices.Contains(altStatusCodes, status) {\n\t\treturn \"ok\"\n\t}\n\n\treturn \"error\"\n}\n\ntype SiteStatusRequest struct {\n\tDefaultURL    string        `yaml:\"url\"`\n\tCheckURL      string        `yaml:\"check-url\"`\n\tAllowInsecure bool          `yaml:\"allow-insecure\"`\n\tTimeout       durationField `yaml:\"timeout\"`\n\tBasicAuth     struct {\n\t\tUsername string `yaml:\"username\"`\n\t\tPassword string `yaml:\"password\"`\n\t} `yaml:\"basic-auth\"`\n}\n\ntype siteStatus struct {\n\tCode         int\n\tTimedOut     bool\n\tResponseTime time.Duration\n\tError        error\n}\n\nfunc fetchSiteStatusTask(statusRequest *SiteStatusRequest) (siteStatus, error) {\n\tvar url string\n\tif statusRequest.CheckURL != \"\" {\n\t\turl = statusRequest.CheckURL\n\t} else {\n\t\turl = statusRequest.DefaultURL\n\t}\n\n\ttimeout := ternary(statusRequest.Timeout > 0, time.Duration(statusRequest.Timeout), 3*time.Second)\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\trequest, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn siteStatus{\n\t\t\tError: err,\n\t\t}, nil\n\t}\n\n\tif statusRequest.BasicAuth.Username != \"\" || statusRequest.BasicAuth.Password != \"\" {\n\t\trequest.SetBasicAuth(statusRequest.BasicAuth.Username, statusRequest.BasicAuth.Password)\n\t}\n\n\trequestSentAt := time.Now()\n\tvar response *http.Response\n\n\tif !statusRequest.AllowInsecure {\n\t\tresponse, err = defaultHTTPClient.Do(request)\n\t} else {\n\t\tresponse, err = defaultInsecureHTTPClient.Do(request)\n\t}\n\n\tstatus := siteStatus{ResponseTime: time.Since(requestSentAt)}\n\n\tif err != nil {\n\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\tstatus.TimedOut = true\n\t\t}\n\n\t\tstatus.Error = err\n\t\treturn status, nil\n\t}\n\n\tdefer response.Body.Close()\n\n\tstatus.Code = response.StatusCode\n\n\treturn status, nil\n}\n\nfunc fetchStatusForSites(requests []*SiteStatusRequest) ([]siteStatus, error) {\n\tjob := newJob(fetchSiteStatusTask, requests).withWorkers(20)\n\tresults, _, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn results, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-old-calendar.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"html/template\"\n\t\"time\"\n)\n\nvar oldCalendarWidgetTemplate = mustParseTemplate(\"old-calendar.html\", \"widget-base.html\")\n\ntype oldCalendarWidget struct {\n\twidgetBase  `yaml:\",inline\"`\n\tCalendar    *calendar\n\tStartSunday bool `yaml:\"start-sunday\"`\n}\n\nfunc (widget *oldCalendarWidget) initialize() error {\n\twidget.withTitle(\"Calendar\").withCacheOnTheHour()\n\n\treturn nil\n}\n\nfunc (widget *oldCalendarWidget) update(ctx context.Context) {\n\twidget.Calendar = newCalendar(time.Now(), widget.StartSunday)\n\twidget.withError(nil).scheduleNextUpdate()\n}\n\nfunc (widget *oldCalendarWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, oldCalendarWidgetTemplate)\n}\n\ntype calendar struct {\n\tCurrentDay        int\n\tCurrentWeekNumber int\n\tCurrentMonthName  string\n\tCurrentYear       int\n\tDays              []int\n}\n\n// TODO: very inflexible, refactor to allow more customizability\n// TODO: allow changing between showing the previous and next week and the entire month\nfunc newCalendar(now time.Time, startSunday bool) *calendar {\n\tyear, week := now.ISOWeek()\n\tweekday := now.Weekday()\n\tif !startSunday {\n\t\tweekday = (weekday + 6) % 7 // Shift Monday to 0\n\t}\n\n\tcurrentMonthDays := daysInMonth(now.Month(), year)\n\n\tvar previousMonthDays int\n\n\tif previousMonthNumber := now.Month() - 1; previousMonthNumber < 1 {\n\t\tpreviousMonthDays = daysInMonth(12, year-1)\n\t} else {\n\t\tpreviousMonthDays = daysInMonth(previousMonthNumber, year)\n\t}\n\n\tstartDaysFrom := now.Day() - int(weekday) - 7\n\n\tdays := make([]int, 21)\n\n\tfor i := 0; i < 21; i++ {\n\t\tday := startDaysFrom + i\n\n\t\tif day < 1 {\n\t\t\tday = previousMonthDays + day\n\t\t} else if day > currentMonthDays {\n\t\t\tday = day - currentMonthDays\n\t\t}\n\n\t\tdays[i] = day\n\t}\n\n\treturn &calendar{\n\t\tCurrentDay:        now.Day(),\n\t\tCurrentWeekNumber: week,\n\t\tCurrentMonthName:  now.Month().String(),\n\t\tCurrentYear:       year,\n\t\tDays:              days,\n\t}\n}\n\nfunc daysInMonth(m time.Month, year int) int {\n\treturn time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()\n}\n"
  },
  {
    "path": "internal/glance/widget-reddit.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tredditWidgetHorizontalCardsTemplate = mustParseTemplate(\"reddit-horizontal-cards.html\", \"widget-base.html\")\n\tredditWidgetVerticalCardsTemplate   = mustParseTemplate(\"reddit-vertical-cards.html\", \"widget-base.html\")\n)\n\ntype redditWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tPosts               forumPostList     `yaml:\"-\"`\n\tSubreddit           string            `yaml:\"subreddit\"`\n\tProxy               proxyOptionsField `yaml:\"proxy\"`\n\tStyle               string            `yaml:\"style\"`\n\tShowThumbnails      bool              `yaml:\"show-thumbnails\"`\n\tShowFlairs          bool              `yaml:\"show-flairs\"`\n\tSortBy              string            `yaml:\"sort-by\"`\n\tTopPeriod           string            `yaml:\"top-period\"`\n\tSearch              string            `yaml:\"search\"`\n\tExtraSortBy         string            `yaml:\"extra-sort-by\"`\n\tCommentsURLTemplate string            `yaml:\"comments-url-template\"`\n\tLimit               int               `yaml:\"limit\"`\n\tCollapseAfter       int               `yaml:\"collapse-after\"`\n\tRequestURLTemplate  string            `yaml:\"request-url-template\"`\n\n\tAppAuth struct {\n\t\tName   string `yaml:\"name\"`\n\t\tID     string `yaml:\"id\"`\n\t\tSecret string `yaml:\"secret\"`\n\n\t\tenabled        bool\n\t\taccessToken    string\n\t\ttokenExpiresAt time.Time\n\t} `yaml:\"app-auth\"`\n}\n\nfunc (widget *redditWidget) initialize() error {\n\tif widget.Subreddit == \"\" {\n\t\treturn errors.New(\"subreddit is required\")\n\t}\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 15\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\ts := widget.SortBy\n\tif s != \"hot\" && s != \"new\" && s != \"top\" && s != \"rising\" {\n\t\twidget.SortBy = \"hot\"\n\t}\n\n\tp := widget.TopPeriod\n\tif p != \"hour\" && p != \"day\" && p != \"week\" && p != \"month\" && p != \"year\" && p != \"all\" {\n\t\twidget.TopPeriod = \"day\"\n\t}\n\n\tif widget.RequestURLTemplate != \"\" {\n\t\tif !strings.Contains(widget.RequestURLTemplate, \"{REQUEST-URL}\") {\n\t\t\treturn errors.New(\"no `{REQUEST-URL}` placeholder specified\")\n\t\t}\n\t}\n\n\ta := &widget.AppAuth\n\tif a.Name != \"\" || a.ID != \"\" || a.Secret != \"\" {\n\t\tif a.Name == \"\" || a.ID == \"\" || a.Secret == \"\" {\n\t\t\treturn errors.New(\"application name, client ID and client secret are required\")\n\t\t}\n\t\ta.enabled = true\n\t}\n\n\twidget.\n\t\twithTitle(\"r/\" + widget.Subreddit).\n\t\twithTitleURL(\"https://www.reddit.com/r/\" + widget.Subreddit + \"/\").\n\t\twithCacheDuration(30 * time.Minute)\n\n\treturn nil\n}\n\nfunc (widget *redditWidget) update(ctx context.Context) {\n\tposts, err := widget.fetchSubredditPosts()\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif len(posts) > widget.Limit {\n\t\tposts = posts[:widget.Limit]\n\t}\n\n\tif widget.ExtraSortBy == \"engagement\" {\n\t\tposts.calculateEngagement()\n\t\tposts.sortByEngagement()\n\t}\n\n\twidget.Posts = posts\n}\n\nfunc (widget *redditWidget) Render() template.HTML {\n\tif widget.Style == \"horizontal-cards\" {\n\t\treturn widget.renderTemplate(widget, redditWidgetHorizontalCardsTemplate)\n\t}\n\n\tif widget.Style == \"vertical-cards\" {\n\t\treturn widget.renderTemplate(widget, redditWidgetVerticalCardsTemplate)\n\t}\n\n\treturn widget.renderTemplate(widget, forumPostsTemplate)\n\n}\n\ntype subredditResponseJson struct {\n\tData struct {\n\t\tChildren []struct {\n\t\t\tData struct {\n\t\t\t\tId            string  `json:\"id\"`\n\t\t\t\tTitle         string  `json:\"title\"`\n\t\t\t\tUpvotes       int     `json:\"ups\"`\n\t\t\t\tUrl           string  `json:\"url\"`\n\t\t\t\tTime          float64 `json:\"created\"`\n\t\t\t\tCommentsCount int     `json:\"num_comments\"`\n\t\t\t\tDomain        string  `json:\"domain\"`\n\t\t\t\tPermalink     string  `json:\"permalink\"`\n\t\t\t\tStickied      bool    `json:\"stickied\"`\n\t\t\t\tPinned        bool    `json:\"pinned\"`\n\t\t\t\tIsSelf        bool    `json:\"is_self\"`\n\t\t\t\tThumbnail     string  `json:\"thumbnail\"`\n\t\t\t\tFlair         string  `json:\"link_flair_text\"`\n\t\t\t\tParentList    []struct {\n\t\t\t\t\tId        string `json:\"id\"`\n\t\t\t\t\tSubreddit string `json:\"subreddit\"`\n\t\t\t\t\tPermalink string `json:\"permalink\"`\n\t\t\t\t} `json:\"crosspost_parent_list\"`\n\t\t\t} `json:\"data\"`\n\t\t} `json:\"children\"`\n\t} `json:\"data\"`\n}\n\nfunc (widget *redditWidget) parseCustomCommentsURL(subreddit, postId, postPath string) string {\n\ttemplate := strings.ReplaceAll(widget.CommentsURLTemplate, \"{SUBREDDIT}\", subreddit)\n\ttemplate = strings.ReplaceAll(template, \"{POST-ID}\", postId)\n\ttemplate = strings.ReplaceAll(template, \"{POST-PATH}\", strings.TrimLeft(postPath, \"/\"))\n\n\treturn template\n}\n\nfunc (widget *redditWidget) fetchSubredditPosts() (forumPostList, error) {\n\tvar client requestDoer = defaultHTTPClient\n\tvar baseURL string\n\tvar requestURL string\n\tvar headers http.Header\n\tquery := url.Values{}\n\tapp := &widget.AppAuth\n\n\tif !app.enabled {\n\t\tbaseURL = \"https://www.reddit.com\"\n\t\theaders = http.Header{\n\t\t\t\"User-Agent\": []string{getBrowserUserAgentHeader()},\n\t\t}\n\t} else {\n\t\tbaseURL = \"https://oauth.reddit.com\"\n\n\t\tif app.accessToken == \"\" || time.Now().Add(time.Minute).After(app.tokenExpiresAt) {\n\t\t\tif err := widget.fetchNewAppAccessToken(); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"fetching new app access token: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\theaders = http.Header{\n\t\t\t\"Authorization\": []string{\"Bearer \" + app.accessToken},\n\t\t\t\"User-Agent\":    []string{app.Name + \"/1.0\"},\n\t\t}\n\t}\n\n\tif widget.Limit > 25 {\n\t\tquery.Set(\"limit\", strconv.Itoa(widget.Limit))\n\t}\n\n\tif widget.Search != \"\" {\n\t\tquery.Set(\"q\", widget.Search+\" subreddit:\"+widget.Subreddit)\n\t\tquery.Set(\"sort\", widget.SortBy)\n\t\trequestURL = fmt.Sprintf(\"%s/search.json?%s\", baseURL, query.Encode())\n\t} else {\n\t\tif widget.SortBy == \"top\" {\n\t\t\tquery.Set(\"t\", widget.TopPeriod)\n\t\t}\n\t\trequestURL = fmt.Sprintf(\"%s/r/%s/%s.json?%s\", baseURL, widget.Subreddit, widget.SortBy, query.Encode())\n\t}\n\n\tif widget.RequestURLTemplate != \"\" {\n\t\trequestURL = strings.ReplaceAll(widget.RequestURLTemplate, \"{REQUEST-URL}\", requestURL)\n\t} else if widget.Proxy.client != nil {\n\t\tclient = widget.Proxy.client\n\t}\n\n\trequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.Header = headers\n\n\tresponseJson, err := decodeJsonFromRequest[subredditResponseJson](client, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(responseJson.Data.Children) == 0 {\n\t\treturn nil, fmt.Errorf(\"no posts found\")\n\t}\n\n\tposts := make(forumPostList, 0, len(responseJson.Data.Children))\n\n\tfor i := range responseJson.Data.Children {\n\t\tpost := &responseJson.Data.Children[i].Data\n\n\t\tif post.Stickied || post.Pinned {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar commentsUrl string\n\n\t\tif widget.CommentsURLTemplate == \"\" {\n\t\t\tcommentsUrl = \"https://www.reddit.com\" + post.Permalink\n\t\t} else {\n\t\t\tcommentsUrl = widget.parseCustomCommentsURL(widget.Subreddit, post.Id, post.Permalink)\n\t\t}\n\n\t\tforumPost := forumPost{\n\t\t\tTitle:           html.UnescapeString(post.Title),\n\t\t\tDiscussionUrl:   commentsUrl,\n\t\t\tTargetUrlDomain: post.Domain,\n\t\t\tCommentCount:    post.CommentsCount,\n\t\t\tScore:           post.Upvotes,\n\t\t\tTimePosted:      time.Unix(int64(post.Time), 0),\n\t\t}\n\n\t\tif post.Thumbnail != \"\" && post.Thumbnail != \"self\" && post.Thumbnail != \"default\" && post.Thumbnail != \"nsfw\" {\n\t\t\tforumPost.ThumbnailUrl = html.UnescapeString(post.Thumbnail)\n\t\t}\n\n\t\tif !post.IsSelf {\n\t\t\tforumPost.TargetUrl = post.Url\n\t\t}\n\n\t\tif widget.ShowFlairs && post.Flair != \"\" {\n\t\t\tforumPost.Tags = append(forumPost.Tags, post.Flair)\n\t\t}\n\n\t\tif len(post.ParentList) > 0 {\n\t\t\tforumPost.IsCrosspost = true\n\t\t\tforumPost.TargetUrlDomain = \"r/\" + post.ParentList[0].Subreddit\n\n\t\t\tif widget.CommentsURLTemplate == \"\" {\n\t\t\t\tforumPost.TargetUrl = \"https://www.reddit.com\" + post.ParentList[0].Permalink\n\t\t\t} else {\n\t\t\t\tforumPost.TargetUrl = widget.parseCustomCommentsURL(\n\t\t\t\t\tpost.ParentList[0].Subreddit,\n\t\t\t\t\tpost.ParentList[0].Id,\n\t\t\t\t\tpost.ParentList[0].Permalink,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tposts = append(posts, forumPost)\n\t}\n\n\treturn posts, nil\n}\n\nfunc (widget *redditWidget) fetchNewAppAccessToken() error {\n\tbody := strings.NewReader(\"grant_type=client_credentials\")\n\treq, err := http.NewRequest(\"POST\", \"https://www.reddit.com/api/v1/access_token\", body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating request for app access token: %v\", err)\n\t}\n\n\tapp := &widget.AppAuth\n\treq.SetBasicAuth(app.ID, app.Secret)\n\treq.Header.Add(\"User-Agent\", app.Name+\"/1.0\")\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\ttype tokenResponse struct {\n\t\tAccessToken string `json:\"access_token\"`\n\t\tExpiresIn   int    `json:\"expires_in\"`\n\t}\n\n\tclient := ternary(widget.Proxy.client != nil, widget.Proxy.client, defaultHTTPClient)\n\tresponse, err := decodeJsonFromRequest[tokenResponse](client, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapp.accessToken = response.AccessToken\n\tapp.tokenExpiresAt = time.Now().Add(time.Duration(response.ExpiresIn) * time.Second)\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/glance/widget-releases.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nvar releasesWidgetTemplate = mustParseTemplate(\"releases.html\", \"widget-base.html\")\n\ntype releasesWidget struct {\n\twidgetBase     `yaml:\",inline\"`\n\tReleases       appReleaseList    `yaml:\"-\"`\n\tRepositories   []*releaseRequest `yaml:\"repositories\"`\n\tToken          string            `yaml:\"token\"`\n\tGitLabToken    string            `yaml:\"gitlab-token\"`\n\tLimit          int               `yaml:\"limit\"`\n\tCollapseAfter  int               `yaml:\"collapse-after\"`\n\tShowSourceIcon bool              `yaml:\"show-source-icon\"`\n}\n\nfunc (widget *releasesWidget) initialize() error {\n\twidget.withTitle(\"Releases\").withCacheDuration(2 * time.Hour)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 10\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\tfor i := range widget.Repositories {\n\t\tr := widget.Repositories[i]\n\n\t\tif r.source == releaseSourceGithub && widget.Token != \"\" {\n\t\t\tr.token = &widget.Token\n\t\t} else if r.source == releaseSourceGitlab && widget.GitLabToken != \"\" {\n\t\t\tr.token = &widget.GitLabToken\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (widget *releasesWidget) update(ctx context.Context) {\n\treleases, err := fetchLatestReleases(widget.Repositories)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif len(releases) > widget.Limit {\n\t\treleases = releases[:widget.Limit]\n\t}\n\n\tfor i := range releases {\n\t\treleases[i].SourceIconURL = widget.Providers.assetResolver(\"icons/\" + string(releases[i].Source) + \".svg\")\n\t}\n\n\twidget.Releases = releases\n}\n\nfunc (widget *releasesWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, releasesWidgetTemplate)\n}\n\ntype releaseSource string\n\nconst (\n\treleaseSourceCodeberg  releaseSource = \"codeberg\"\n\treleaseSourceGithub    releaseSource = \"github\"\n\treleaseSourceGitlab    releaseSource = \"gitlab\"\n\treleaseSourceDockerHub releaseSource = \"dockerhub\"\n)\n\ntype appRelease struct {\n\tSource        releaseSource\n\tSourceIconURL string\n\tName          string\n\tVersion       string\n\tNotesUrl      string\n\tTimeReleased  time.Time\n\tDownvotes     int\n}\n\ntype appReleaseList []appRelease\n\nfunc (r appReleaseList) sortByNewest() appReleaseList {\n\tsort.Slice(r, func(i, j int) bool {\n\t\treturn r[i].TimeReleased.After(r[j].TimeReleased)\n\t})\n\n\treturn r\n}\n\ntype releaseRequest struct {\n\tIncludePreleases bool   `yaml:\"include-prereleases\"`\n\tRepository       string `yaml:\"repository\"`\n\n\tsource releaseSource\n\ttoken  *string\n}\n\nfunc (r *releaseRequest) UnmarshalYAML(node *yaml.Node) error {\n\ttype releaseRequestAlias releaseRequest\n\talias := (*releaseRequestAlias)(r)\n\tvar repository string\n\n\tif err := node.Decode(&repository); err != nil {\n\t\tif err := node.Decode(alias); err != nil {\n\t\t\treturn fmt.Errorf(\"could not umarshal repository into string or struct: %v\", err)\n\t\t}\n\t}\n\n\tif r.Repository == \"\" {\n\t\tif repository == \"\" {\n\t\t\treturn errors.New(\"repository is required\")\n\t\t} else {\n\t\t\tr.Repository = repository\n\t\t}\n\t}\n\n\tparts := strings.SplitN(repository, \":\", 2)\n\tif len(parts) == 1 {\n\t\tr.source = releaseSourceGithub\n\t} else if len(parts) == 2 {\n\t\tr.Repository = parts[1]\n\n\t\tswitch parts[0] {\n\t\tcase string(releaseSourceGithub):\n\t\t\tr.source = releaseSourceGithub\n\t\tcase string(releaseSourceGitlab):\n\t\t\tr.source = releaseSourceGitlab\n\t\tcase string(releaseSourceDockerHub):\n\t\t\tr.source = releaseSourceDockerHub\n\t\tcase string(releaseSourceCodeberg):\n\t\t\tr.source = releaseSourceCodeberg\n\t\tdefault:\n\t\t\treturn errors.New(\"invalid source\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc fetchLatestReleases(requests []*releaseRequest) (appReleaseList, error) {\n\tjob := newJob(fetchLatestReleaseTask, requests).withWorkers(20)\n\tresults, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar failed int\n\n\treleases := make(appReleaseList, 0, len(requests))\n\n\tfor i := range results {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to fetch release\", \"source\", requests[i].source, \"repository\", requests[i].Repository, \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\treleases = append(releases, *results[i])\n\t}\n\n\tif failed == len(requests) {\n\t\treturn nil, errNoContent\n\t}\n\n\treleases.sortByNewest()\n\n\tif failed > 0 {\n\t\treturn releases, fmt.Errorf(\"%w: could not get %d releases\", errPartialContent, failed)\n\t}\n\n\treturn releases, nil\n}\n\nfunc fetchLatestReleaseTask(request *releaseRequest) (*appRelease, error) {\n\tswitch request.source {\n\tcase releaseSourceCodeberg:\n\t\treturn fetchLatestCodebergRelease(request)\n\tcase releaseSourceGithub:\n\t\treturn fetchLatestGithubRelease(request)\n\tcase releaseSourceGitlab:\n\t\treturn fetchLatestGitLabRelease(request)\n\tcase releaseSourceDockerHub:\n\t\treturn fetchLatestDockerHubRelease(request)\n\t}\n\n\treturn nil, errors.New(\"unsupported source\")\n}\n\ntype githubReleaseResponseJson struct {\n\tTagName     string `json:\"tag_name\"`\n\tPublishedAt string `json:\"published_at\"`\n\tHtmlUrl     string `json:\"html_url\"`\n\tReactions   struct {\n\t\tDownvotes int `json:\"-1\"`\n\t} `json:\"reactions\"`\n}\n\nfunc fetchLatestGithubRelease(request *releaseRequest) (*appRelease, error) {\n\tvar requestURL string\n\tif !request.IncludePreleases {\n\t\trequestURL = fmt.Sprintf(\"https://api.github.com/repos/%s/releases/latest\", request.Repository)\n\t} else {\n\t\trequestURL = fmt.Sprintf(\"https://api.github.com/repos/%s/releases\", request.Repository)\n\t}\n\n\thttpRequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif request.token != nil {\n\t\thttpRequest.Header.Add(\"Authorization\", \"Bearer \"+(*request.token))\n\t}\n\n\tvar response githubReleaseResponseJson\n\n\tif !request.IncludePreleases {\n\t\tresponse, err = decodeJsonFromRequest[githubReleaseResponseJson](defaultHTTPClient, httpRequest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tresponses, err := decodeJsonFromRequest[[]githubReleaseResponseJson](defaultHTTPClient, httpRequest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(responses) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no releases found for repository %s\", request.Repository)\n\t\t}\n\n\t\tresponse = responses[0]\n\t}\n\n\treturn &appRelease{\n\t\tSource:       releaseSourceGithub,\n\t\tName:         request.Repository,\n\t\tVersion:      normalizeVersionFormat(response.TagName),\n\t\tNotesUrl:     response.HtmlUrl,\n\t\tTimeReleased: parseRFC3339Time(response.PublishedAt),\n\t\tDownvotes:    response.Reactions.Downvotes,\n\t}, nil\n}\n\ntype dockerHubRepositoryTagsResponse struct {\n\tResults []dockerHubRepositoryTagResponse `json:\"results\"`\n}\n\ntype dockerHubRepositoryTagResponse struct {\n\tName       string `json:\"name\"`\n\tLastPushed string `json:\"tag_last_pushed\"`\n}\n\nconst dockerHubOfficialRepoTagURLFormat = \"https://hub.docker.com/_/%s/tags?name=%s\"\nconst dockerHubRepoTagURLFormat = \"https://hub.docker.com/r/%s/tags?name=%s\"\nconst dockerHubTagsURLFormat = \"https://hub.docker.com/v2/namespaces/%s/repositories/%s/tags\"\nconst dockerHubSpecificTagURLFormat = \"https://hub.docker.com/v2/namespaces/%s/repositories/%s/tags/%s\"\n\nfunc fetchLatestDockerHubRelease(request *releaseRequest) (*appRelease, error) {\n\tnameParts := strings.Split(request.Repository, \"/\")\n\n\tif len(nameParts) > 2 {\n\t\treturn nil, fmt.Errorf(\"invalid repository name: %s\", request.Repository)\n\t} else if len(nameParts) == 1 {\n\t\tnameParts = []string{\"library\", nameParts[0]}\n\t}\n\n\ttagParts := strings.SplitN(nameParts[1], \":\", 2)\n\tvar requestURL string\n\n\tif len(tagParts) == 2 {\n\t\trequestURL = fmt.Sprintf(dockerHubSpecificTagURLFormat, nameParts[0], tagParts[0], tagParts[1])\n\t} else {\n\t\trequestURL = fmt.Sprintf(dockerHubTagsURLFormat, nameParts[0], nameParts[1])\n\t}\n\n\thttpRequest, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif request.token != nil {\n\t\thttpRequest.Header.Add(\"Authorization\", \"Bearer \"+(*request.token))\n\t}\n\n\tvar tag *dockerHubRepositoryTagResponse\n\n\tif len(tagParts) == 1 {\n\t\tresponse, err := decodeJsonFromRequest[dockerHubRepositoryTagsResponse](defaultHTTPClient, httpRequest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(response.Results) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no tags found for repository: %s\", request.Repository)\n\t\t}\n\n\t\ttag = &response.Results[0]\n\t} else {\n\t\tresponse, err := decodeJsonFromRequest[dockerHubRepositoryTagResponse](defaultHTTPClient, httpRequest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttag = &response\n\t}\n\n\tvar repo string\n\tvar displayName string\n\tvar notesURL string\n\n\tif len(tagParts) == 1 {\n\t\trepo = nameParts[1]\n\t} else {\n\t\trepo = tagParts[0]\n\t}\n\n\tif nameParts[0] == \"library\" {\n\t\tdisplayName = repo\n\t\tnotesURL = fmt.Sprintf(dockerHubOfficialRepoTagURLFormat, repo, tag.Name)\n\t} else {\n\t\tdisplayName = nameParts[0] + \"/\" + repo\n\t\tnotesURL = fmt.Sprintf(dockerHubRepoTagURLFormat, displayName, tag.Name)\n\t}\n\n\treturn &appRelease{\n\t\tSource:       releaseSourceDockerHub,\n\t\tNotesUrl:     notesURL,\n\t\tName:         displayName,\n\t\tVersion:      tag.Name,\n\t\tTimeReleased: parseRFC3339Time(tag.LastPushed),\n\t}, nil\n}\n\ntype gitlabReleaseResponseJson struct {\n\tTagName    string `json:\"tag_name\"`\n\tReleasedAt string `json:\"released_at\"`\n\tLinks      struct {\n\t\tSelf string `json:\"self\"`\n\t} `json:\"_links\"`\n}\n\nfunc fetchLatestGitLabRelease(request *releaseRequest) (*appRelease, error) {\n\thttpRequest, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\n\t\t\t\"https://gitlab.com/api/v4/projects/%s/releases/permalink/latest\",\n\t\t\turl.QueryEscape(request.Repository),\n\t\t),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif request.token != nil {\n\t\thttpRequest.Header.Add(\"PRIVATE-TOKEN\", *request.token)\n\t}\n\n\tresponse, err := decodeJsonFromRequest[gitlabReleaseResponseJson](defaultHTTPClient, httpRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &appRelease{\n\t\tSource:       releaseSourceGitlab,\n\t\tName:         request.Repository,\n\t\tVersion:      normalizeVersionFormat(response.TagName),\n\t\tNotesUrl:     response.Links.Self,\n\t\tTimeReleased: parseRFC3339Time(response.ReleasedAt),\n\t}, nil\n}\n\ntype codebergReleaseResponseJson struct {\n\tTagName     string `json:\"tag_name\"`\n\tPublishedAt string `json:\"published_at\"`\n\tHtmlUrl     string `json:\"html_url\"`\n}\n\nfunc fetchLatestCodebergRelease(request *releaseRequest) (*appRelease, error) {\n\thttpRequest, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\n\t\t\t\"https://codeberg.org/api/v1/repos/%s/releases/latest\",\n\t\t\trequest.Repository,\n\t\t),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := decodeJsonFromRequest[codebergReleaseResponseJson](defaultHTTPClient, httpRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &appRelease{\n\t\tSource:       releaseSourceCodeberg,\n\t\tName:         request.Repository,\n\t\tVersion:      normalizeVersionFormat(response.TagName),\n\t\tNotesUrl:     response.HtmlUrl,\n\t\tTimeReleased: parseRFC3339Time(response.PublishedAt),\n\t}, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-repository.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar repositoryWidgetTemplate = mustParseTemplate(\"repository.html\", \"widget-base.html\")\n\ntype repositoryWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tRequestedRepository string     `yaml:\"repository\"`\n\tToken               string     `yaml:\"token\"`\n\tPullRequestsLimit   int        `yaml:\"pull-requests-limit\"`\n\tIssuesLimit         int        `yaml:\"issues-limit\"`\n\tCommitsLimit        int        `yaml:\"commits-limit\"`\n\tRepository          repository `yaml:\"-\"`\n}\n\nfunc (widget *repositoryWidget) initialize() error {\n\twidget.withTitle(\"Repository\").withCacheDuration(1 * time.Hour)\n\n\tif widget.PullRequestsLimit == 0 || widget.PullRequestsLimit < -1 {\n\t\twidget.PullRequestsLimit = 3\n\t}\n\n\tif widget.IssuesLimit == 0 || widget.IssuesLimit < -1 {\n\t\twidget.IssuesLimit = 3\n\t}\n\n\tif widget.CommitsLimit == 0 || widget.CommitsLimit < -1 {\n\t\twidget.CommitsLimit = -1\n\t}\n\n\treturn nil\n}\n\nfunc (widget *repositoryWidget) update(ctx context.Context) {\n\tdetails, err := fetchRepositoryDetailsFromGithub(\n\t\twidget.RequestedRepository,\n\t\tstring(widget.Token),\n\t\twidget.PullRequestsLimit,\n\t\twidget.IssuesLimit,\n\t\twidget.CommitsLimit,\n\t)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\twidget.Repository = details\n}\n\nfunc (widget *repositoryWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, repositoryWidgetTemplate)\n}\n\ntype repository struct {\n\tName             string\n\tStars            int\n\tForks            int\n\tOpenPullRequests int\n\tPullRequests     []githubTicket\n\tOpenIssues       int\n\tIssues           []githubTicket\n\tLastCommits      int\n\tCommits          []githubCommitDetails\n}\n\ntype githubTicket struct {\n\tNumber    int\n\tCreatedAt time.Time\n\tTitle     string\n}\n\ntype githubCommitDetails struct {\n\tSha       string\n\tAuthor    string\n\tCreatedAt time.Time\n\tMessage   string\n}\n\ntype githubRepositoryResponseJson struct {\n\tName  string `json:\"full_name\"`\n\tStars int    `json:\"stargazers_count\"`\n\tForks int    `json:\"forks_count\"`\n}\n\ntype githubTicketResponseJson struct {\n\tCount   int `json:\"total_count\"`\n\tTickets []struct {\n\t\tNumber    int    `json:\"number\"`\n\t\tCreatedAt string `json:\"created_at\"`\n\t\tTitle     string `json:\"title\"`\n\t} `json:\"items\"`\n}\n\ntype gitHubCommitResponseJson struct {\n\tSha    string `json:\"sha\"`\n\tCommit struct {\n\t\tAuthor struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tDate string `json:\"date\"`\n\t\t} `json:\"author\"`\n\t\tMessage string `json:\"message\"`\n\t} `json:\"commit\"`\n}\n\nfunc fetchRepositoryDetailsFromGithub(repo string, token string, maxPRs int, maxIssues int, maxCommits int) (repository, error) {\n\trepositoryRequest, err := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.github.com/repos/%s\", repo), nil)\n\tif err != nil {\n\t\treturn repository{}, fmt.Errorf(\"%w: could not create request with repository: %v\", errNoContent, err)\n\t}\n\n\tPRsRequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.github.com/search/issues?q=is:pr+is:open+repo:%s&per_page=%d\", repo, maxPRs), nil)\n\tissuesRequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.github.com/search/issues?q=is:issue+is:open+repo:%s&per_page=%d\", repo, maxIssues), nil)\n\tCommitsRequest, _ := http.NewRequest(\"GET\", fmt.Sprintf(\"https://api.github.com/repos/%s/commits?per_page=%d\", repo, maxCommits), nil)\n\n\tif token != \"\" {\n\t\ttoken = fmt.Sprintf(\"Bearer %s\", token)\n\t\trepositoryRequest.Header.Add(\"Authorization\", token)\n\t\tPRsRequest.Header.Add(\"Authorization\", token)\n\t\tissuesRequest.Header.Add(\"Authorization\", token)\n\t\tCommitsRequest.Header.Add(\"Authorization\", token)\n\t}\n\n\tvar repositoryResponse githubRepositoryResponseJson\n\tvar detailsErr error\n\tvar PRsResponse githubTicketResponseJson\n\tvar PRsErr error\n\tvar issuesResponse githubTicketResponseJson\n\tvar issuesErr error\n\tvar commitsResponse []gitHubCommitResponseJson\n\tvar CommitsErr error\n\tvar wg sync.WaitGroup\n\n\twg.Add(1)\n\tgo (func() {\n\t\tdefer wg.Done()\n\t\trepositoryResponse, detailsErr = decodeJsonFromRequest[githubRepositoryResponseJson](defaultHTTPClient, repositoryRequest)\n\t})()\n\n\tif maxPRs > 0 {\n\t\twg.Add(1)\n\t\tgo (func() {\n\t\t\tdefer wg.Done()\n\t\t\tPRsResponse, PRsErr = decodeJsonFromRequest[githubTicketResponseJson](defaultHTTPClient, PRsRequest)\n\t\t})()\n\t}\n\n\tif maxIssues > 0 {\n\t\twg.Add(1)\n\t\tgo (func() {\n\t\t\tdefer wg.Done()\n\t\t\tissuesResponse, issuesErr = decodeJsonFromRequest[githubTicketResponseJson](defaultHTTPClient, issuesRequest)\n\t\t})()\n\t}\n\n\tif maxCommits > 0 {\n\t\twg.Add(1)\n\t\tgo (func() {\n\t\t\tdefer wg.Done()\n\t\t\tcommitsResponse, CommitsErr = decodeJsonFromRequest[[]gitHubCommitResponseJson](defaultHTTPClient, CommitsRequest)\n\t\t})()\n\t}\n\n\twg.Wait()\n\n\tif detailsErr != nil {\n\t\treturn repository{}, fmt.Errorf(\"%w: could not get repository details: %s\", errNoContent, detailsErr)\n\t}\n\n\tdetails := repository{\n\t\tName:         repositoryResponse.Name,\n\t\tStars:        repositoryResponse.Stars,\n\t\tForks:        repositoryResponse.Forks,\n\t\tPullRequests: make([]githubTicket, 0, len(PRsResponse.Tickets)),\n\t\tIssues:       make([]githubTicket, 0, len(issuesResponse.Tickets)),\n\t\tCommits:      make([]githubCommitDetails, 0, len(commitsResponse)),\n\t}\n\n\terr = nil\n\n\tif maxPRs > 0 {\n\t\tif PRsErr != nil {\n\t\t\terr = fmt.Errorf(\"%w: could not get PRs: %s\", errPartialContent, PRsErr)\n\t\t} else {\n\t\t\tdetails.OpenPullRequests = PRsResponse.Count\n\n\t\t\tfor i := range PRsResponse.Tickets {\n\t\t\t\tdetails.PullRequests = append(details.PullRequests, githubTicket{\n\t\t\t\t\tNumber:    PRsResponse.Tickets[i].Number,\n\t\t\t\t\tCreatedAt: parseRFC3339Time(PRsResponse.Tickets[i].CreatedAt),\n\t\t\t\t\tTitle:     PRsResponse.Tickets[i].Title,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif maxIssues > 0 {\n\t\tif issuesErr != nil {\n\t\t\t// TODO: fix, overwriting the previous error\n\t\t\terr = fmt.Errorf(\"%w: could not get issues: %s\", errPartialContent, issuesErr)\n\t\t} else {\n\t\t\tdetails.OpenIssues = issuesResponse.Count\n\n\t\t\tfor i := range issuesResponse.Tickets {\n\t\t\t\tdetails.Issues = append(details.Issues, githubTicket{\n\t\t\t\t\tNumber:    issuesResponse.Tickets[i].Number,\n\t\t\t\t\tCreatedAt: parseRFC3339Time(issuesResponse.Tickets[i].CreatedAt),\n\t\t\t\t\tTitle:     issuesResponse.Tickets[i].Title,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif maxCommits > 0 {\n\t\tif CommitsErr != nil {\n\t\t\terr = fmt.Errorf(\"%w: could not get commits: %s\", errPartialContent, CommitsErr)\n\t\t} else {\n\t\t\tfor i := range commitsResponse {\n\t\t\t\tdetails.Commits = append(details.Commits, githubCommitDetails{\n\t\t\t\t\tSha:       commitsResponse[i].Sha,\n\t\t\t\t\tAuthor:    commitsResponse[i].Commit.Author.Name,\n\t\t\t\t\tCreatedAt: parseRFC3339Time(commitsResponse[i].Commit.Author.Date),\n\t\t\t\t\tMessage:   strings.SplitN(commitsResponse[i].Commit.Message, \"\\n\\n\", 2)[0],\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn details, err\n}\n"
  },
  {
    "path": "internal/glance/widget-rss.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html\"\n\t\"html/template\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/mmcdole/gofeed\"\n\tgofeedext \"github.com/mmcdole/gofeed/extensions\"\n)\n\nvar (\n\trssWidgetTemplate                 = mustParseTemplate(\"rss-list.html\", \"widget-base.html\")\n\trssWidgetDetailedListTemplate     = mustParseTemplate(\"rss-detailed-list.html\", \"widget-base.html\")\n\trssWidgetHorizontalCardsTemplate  = mustParseTemplate(\"rss-horizontal-cards.html\", \"widget-base.html\")\n\trssWidgetHorizontalCards2Template = mustParseTemplate(\"rss-horizontal-cards-2.html\", \"widget-base.html\")\n)\n\nvar feedParser = gofeed.NewParser()\n\ntype rssWidget struct {\n\twidgetBase       `yaml:\",inline\"`\n\tFeedRequests     []rssFeedRequest `yaml:\"feeds\"`\n\tStyle            string           `yaml:\"style\"`\n\tThumbnailHeight  float64          `yaml:\"thumbnail-height\"`\n\tCardHeight       float64          `yaml:\"card-height\"`\n\tLimit            int              `yaml:\"limit\"`\n\tCollapseAfter    int              `yaml:\"collapse-after\"`\n\tSingleLineTitles bool             `yaml:\"single-line-titles\"`\n\tPreserveOrder    bool             `yaml:\"preserve-order\"`\n\n\tItems          rssFeedItemList `yaml:\"-\"`\n\tNoItemsMessage string          `yaml:\"-\"`\n\n\tcachedFeedsMutex sync.Mutex\n\tcachedFeeds      map[string]*cachedRSSFeed `yaml:\"-\"`\n}\n\nfunc (widget *rssWidget) initialize() error {\n\twidget.withTitle(\"RSS Feed\").withCacheDuration(2 * time.Hour)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 25\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\tif widget.ThumbnailHeight < 0 {\n\t\twidget.ThumbnailHeight = 0\n\t}\n\n\tif widget.CardHeight < 0 {\n\t\twidget.CardHeight = 0\n\t}\n\n\tif widget.Style == \"detailed-list\" {\n\t\tfor i := range widget.FeedRequests {\n\t\t\twidget.FeedRequests[i].IsDetailed = true\n\t\t}\n\t}\n\n\twidget.NoItemsMessage = \"No items were returned from the feeds.\"\n\twidget.cachedFeeds = make(map[string]*cachedRSSFeed)\n\n\treturn nil\n}\n\nfunc (widget *rssWidget) update(ctx context.Context) {\n\titems, err := widget.fetchItemsFromFeeds()\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif !widget.PreserveOrder {\n\t\titems.sortByNewest()\n\t}\n\n\tif len(items) > widget.Limit {\n\t\titems = items[:widget.Limit]\n\t}\n\n\twidget.Items = items\n}\n\nfunc (widget *rssWidget) Render() template.HTML {\n\tif widget.Style == \"horizontal-cards\" {\n\t\treturn widget.renderTemplate(widget, rssWidgetHorizontalCardsTemplate)\n\t}\n\n\tif widget.Style == \"horizontal-cards-2\" {\n\t\treturn widget.renderTemplate(widget, rssWidgetHorizontalCards2Template)\n\t}\n\n\tif widget.Style == \"detailed-list\" {\n\t\treturn widget.renderTemplate(widget, rssWidgetDetailedListTemplate)\n\t}\n\n\treturn widget.renderTemplate(widget, rssWidgetTemplate)\n}\n\ntype cachedRSSFeed struct {\n\tetag         string\n\tlastModified string\n\titems        []rssFeedItem\n}\n\ntype rssFeedItem struct {\n\tChannelName string\n\tChannelURL  string\n\tTitle       string\n\tLink        string\n\tImageURL    string\n\tCategories  []string\n\tDescription string\n\tPublishedAt time.Time\n}\n\ntype rssFeedRequest struct {\n\tURL             string            `yaml:\"url\"`\n\tTitle           string            `yaml:\"title\"`\n\tHideCategories  bool              `yaml:\"hide-categories\"`\n\tHideDescription bool              `yaml:\"hide-description\"`\n\tLimit           int               `yaml:\"limit\"`\n\tItemLinkPrefix  string            `yaml:\"item-link-prefix\"`\n\tHeaders         map[string]string `yaml:\"headers\"`\n\tIsDetailed      bool              `yaml:\"-\"`\n}\n\ntype rssFeedItemList []rssFeedItem\n\nfunc (f rssFeedItemList) sortByNewest() rssFeedItemList {\n\tsort.Slice(f, func(i, j int) bool {\n\t\treturn f[i].PublishedAt.After(f[j].PublishedAt)\n\t})\n\n\treturn f\n}\n\nfunc (widget *rssWidget) fetchItemsFromFeeds() (rssFeedItemList, error) {\n\trequests := widget.FeedRequests\n\n\tjob := newJob(widget.fetchItemsFromFeedTask, requests).withWorkers(30)\n\tfeeds, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errNoContent, err)\n\t}\n\n\tfailed := 0\n\tentries := make(rssFeedItemList, 0, len(feeds)*10)\n\tseen := make(map[string]struct{})\n\n\tfor i := range feeds {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to get RSS feed\", \"url\", requests[i].URL, \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, item := range feeds[i] {\n\t\t\tif _, exists := seen[item.Link]; exists {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tentries = append(entries, item)\n\t\t\tseen[item.Link] = struct{}{}\n\t\t}\n\t}\n\n\tif failed == len(requests) {\n\t\treturn nil, errNoContent\n\t}\n\n\tif failed > 0 {\n\t\treturn entries, fmt.Errorf(\"%w: missing %d RSS feeds\", errPartialContent, failed)\n\t}\n\n\treturn entries, nil\n}\n\nfunc (widget *rssWidget) fetchItemsFromFeedTask(request rssFeedRequest) ([]rssFeedItem, error) {\n\treq, err := http.NewRequest(\"GET\", request.URL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"User-Agent\", glanceUserAgentString)\n\n\twidget.cachedFeedsMutex.Lock()\n\tcache, isCached := widget.cachedFeeds[request.URL]\n\tif isCached {\n\t\tif cache.etag != \"\" {\n\t\t\treq.Header.Add(\"If-None-Match\", cache.etag)\n\t\t}\n\t\tif cache.lastModified != \"\" {\n\t\t\treq.Header.Add(\"If-Modified-Since\", cache.lastModified)\n\t\t}\n\t}\n\twidget.cachedFeedsMutex.Unlock()\n\n\tfor key, value := range request.Headers {\n\t\treq.Header.Set(key, value)\n\t}\n\n\tresp, err := defaultHTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == http.StatusNotModified && isCached {\n\t\treturn cache.items, nil\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"unexpected status code %d from %s\", resp.StatusCode, request.URL)\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfeed, err := feedParser.ParseString(string(body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif request.Limit > 0 && len(feed.Items) > request.Limit {\n\t\tfeed.Items = feed.Items[:request.Limit]\n\t}\n\n\titems := make(rssFeedItemList, 0, len(feed.Items))\n\n\tfor i := range feed.Items {\n\t\titem := feed.Items[i]\n\n\t\trssItem := rssFeedItem{\n\t\t\tChannelURL: feed.Link,\n\t\t}\n\n\t\tif request.ItemLinkPrefix != \"\" {\n\t\t\trssItem.Link = request.ItemLinkPrefix + item.Link\n\t\t} else if strings.HasPrefix(item.Link, \"http://\") || strings.HasPrefix(item.Link, \"https://\") {\n\t\t\trssItem.Link = item.Link\n\t\t} else {\n\t\t\tparsedUrl, err := url.Parse(feed.Link)\n\t\t\tif err != nil {\n\t\t\t\tparsedUrl, err = url.Parse(request.URL)\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\tvar link string\n\n\t\t\t\tif len(item.Link) > 0 && item.Link[0] == '/' {\n\t\t\t\t\tlink = item.Link\n\t\t\t\t} else {\n\t\t\t\t\tlink = \"/\" + item.Link\n\t\t\t\t}\n\n\t\t\t\trssItem.Link = parsedUrl.Scheme + \"://\" + parsedUrl.Host + link\n\t\t\t}\n\t\t}\n\n\t\tif item.Title != \"\" {\n\t\t\trssItem.Title = html.UnescapeString(item.Title)\n\t\t} else {\n\t\t\trssItem.Title = shortenFeedDescriptionLen(item.Description, 100)\n\t\t}\n\n\t\tif request.IsDetailed {\n\t\t\tif !request.HideDescription && item.Description != \"\" && item.Title != \"\" {\n\t\t\t\trssItem.Description = shortenFeedDescriptionLen(item.Description, 200)\n\t\t\t}\n\n\t\t\tif !request.HideCategories {\n\t\t\t\tvar categories = make([]string, 0, 6)\n\n\t\t\t\tfor _, category := range item.Categories {\n\t\t\t\t\tif len(categories) == 6 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(category) == 0 || len(category) > 30 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tcategories = append(categories, category)\n\t\t\t\t}\n\n\t\t\t\trssItem.Categories = categories\n\t\t\t}\n\t\t}\n\n\t\tif request.Title != \"\" {\n\t\t\trssItem.ChannelName = request.Title\n\t\t} else {\n\t\t\trssItem.ChannelName = feed.Title\n\t\t}\n\n\t\tif item.Image != nil {\n\t\t\trssItem.ImageURL = item.Image.URL\n\t\t} else if url := findThumbnailInItemExtensions(item); url != \"\" {\n\t\t\trssItem.ImageURL = url\n\t\t} else if feed.Image != nil {\n\t\t\tif len(feed.Image.URL) > 0 && feed.Image.URL[0] == '/' {\n\t\t\t\trssItem.ImageURL = strings.TrimRight(feed.Link, \"/\") + feed.Image.URL\n\t\t\t} else {\n\t\t\t\trssItem.ImageURL = feed.Image.URL\n\t\t\t}\n\t\t}\n\n\t\tif item.PublishedParsed != nil {\n\t\t\trssItem.PublishedAt = *item.PublishedParsed\n\t\t} else {\n\t\t\trssItem.PublishedAt = time.Now()\n\t\t}\n\n\t\titems = append(items, rssItem)\n\t}\n\n\tif resp.Header.Get(\"ETag\") != \"\" || resp.Header.Get(\"Last-Modified\") != \"\" {\n\t\twidget.cachedFeedsMutex.Lock()\n\t\twidget.cachedFeeds[request.URL] = &cachedRSSFeed{\n\t\t\tetag:         resp.Header.Get(\"ETag\"),\n\t\t\tlastModified: resp.Header.Get(\"Last-Modified\"),\n\t\t\titems:        items,\n\t\t}\n\t\twidget.cachedFeedsMutex.Unlock()\n\t}\n\n\treturn items, nil\n}\n\nfunc findThumbnailInItemExtensions(item *gofeed.Item) string {\n\tmedia, ok := item.Extensions[\"media\"]\n\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\treturn recursiveFindThumbnailInExtensions(media)\n}\n\nfunc recursiveFindThumbnailInExtensions(extensions map[string][]gofeedext.Extension) string {\n\tfor _, exts := range extensions {\n\t\tfor _, ext := range exts {\n\t\t\tif ext.Name == \"thumbnail\" || ext.Name == \"image\" {\n\t\t\t\tif url, ok := ext.Attrs[\"url\"]; ok {\n\t\t\t\t\treturn url\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ext.Children != nil {\n\t\t\t\tif url := recursiveFindThumbnailInExtensions(ext.Children); url != \"\" {\n\t\t\t\t\treturn url\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nvar htmlTagsWithAttributesPattern = regexp.MustCompile(`<\\/?[a-zA-Z0-9-]+ *(?:[a-zA-Z-]+=(?:\"|').*?(?:\"|') ?)* *\\/?>`)\n\nfunc sanitizeFeedDescription(description string) string {\n\tif description == \"\" {\n\t\treturn \"\"\n\t}\n\n\tdescription = strings.ReplaceAll(description, \"\\n\", \" \")\n\tdescription = htmlTagsWithAttributesPattern.ReplaceAllString(description, \"\")\n\tdescription = sequentialWhitespacePattern.ReplaceAllString(description, \" \")\n\tdescription = strings.TrimSpace(description)\n\tdescription = html.UnescapeString(description)\n\n\treturn description\n}\n\nfunc shortenFeedDescriptionLen(description string, maxLen int) string {\n\tdescription, _ = limitStringLength(description, 1000)\n\tdescription = sanitizeFeedDescription(description)\n\tdescription, limited := limitStringLength(description, maxLen)\n\n\tif limited {\n\t\tdescription += \"…\"\n\t}\n\n\treturn description\n}\n"
  },
  {
    "path": "internal/glance/widget-search.go",
    "content": "package glance\n\nimport (\n\t\"fmt\"\n\t\"html/template\"\n\t\"strings\"\n)\n\nvar searchWidgetTemplate = mustParseTemplate(\"search.html\", \"widget-base.html\")\n\ntype SearchBang struct {\n\tTitle    string\n\tShortcut string\n\tURL      string\n}\n\ntype searchWidget struct {\n\twidgetBase   `yaml:\",inline\"`\n\tcachedHTML   template.HTML `yaml:\"-\"`\n\tSearchEngine string        `yaml:\"search-engine\"`\n\tBangs        []SearchBang  `yaml:\"bangs\"`\n\tNewTab       bool          `yaml:\"new-tab\"`\n\tTarget       string        `yaml:\"target\"`\n\tAutofocus    bool          `yaml:\"autofocus\"`\n\tPlaceholder  string        `yaml:\"placeholder\"`\n}\n\nfunc convertSearchUrl(url string) string {\n\t// Go's template is being stubborn and continues to escape the curlies in the\n\t// URL regardless of what the type of the variable is so this is my way around it\n\treturn strings.ReplaceAll(url, \"{QUERY}\", \"!QUERY!\")\n}\n\nvar searchEngines = map[string]string{\n\t\"duckduckgo\": \"https://duckduckgo.com/?q={QUERY}\",\n\t\"google\":     \"https://www.google.com/search?q={QUERY}\",\n\t\"bing\":       \"https://www.bing.com/search?q={QUERY}\",\n\t\"perplexity\": \"https://www.perplexity.ai/search?q={QUERY}\",\n\t\"kagi\": \"https://kagi.com/search?q={QUERY}\",\n\t\"startpage\": \"https://www.startpage.com/search?q={QUERY}\",\n}\n\nfunc (widget *searchWidget) initialize() error {\n\twidget.withTitle(\"Search\").withError(nil)\n\n\tif widget.SearchEngine == \"\" {\n\t\twidget.SearchEngine = \"duckduckgo\"\n\t}\n\n\tif widget.Placeholder == \"\" {\n\t\twidget.Placeholder = \"Type here to search…\"\n\t}\n\n\tif url, ok := searchEngines[widget.SearchEngine]; ok {\n\t\twidget.SearchEngine = url\n\t}\n\n\twidget.SearchEngine = convertSearchUrl(widget.SearchEngine)\n\n\tfor i := range widget.Bangs {\n\t\tif widget.Bangs[i].Shortcut == \"\" {\n\t\t\treturn fmt.Errorf(\"search bang #%d has no shortcut\", i+1)\n\t\t}\n\n\t\tif widget.Bangs[i].URL == \"\" {\n\t\t\treturn fmt.Errorf(\"search bang #%d has no URL\", i+1)\n\t\t}\n\n\t\twidget.Bangs[i].URL = convertSearchUrl(widget.Bangs[i].URL)\n\t}\n\n\twidget.cachedHTML = widget.renderTemplate(widget, searchWidgetTemplate)\n\treturn nil\n}\n\nfunc (widget *searchWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-server-stats.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/glanceapp/glance/pkg/sysinfo\"\n)\n\nvar serverStatsWidgetTemplate = mustParseTemplate(\"server-stats.html\", \"widget-base.html\")\n\ntype serverStatsWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tServers    []serverStatsRequest `yaml:\"servers\"`\n}\n\nfunc (widget *serverStatsWidget) initialize() error {\n\twidget.withTitle(\"Server Stats\").withCacheDuration(15 * time.Second)\n\twidget.widgetBase.WIP = true\n\n\tif len(widget.Servers) == 0 {\n\t\twidget.Servers = []serverStatsRequest{{Type: \"local\"}}\n\t}\n\n\tfor i := range widget.Servers {\n\t\twidget.Servers[i].URL = strings.TrimRight(widget.Servers[i].URL, \"/\")\n\n\t\tif widget.Servers[i].Timeout == 0 {\n\t\t\twidget.Servers[i].Timeout = durationField(3 * time.Second)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (widget *serverStatsWidget) update(context.Context) {\n\t// Refactor later, most of it may change depending on feedback\n\tvar wg sync.WaitGroup\n\n\tfor i := range widget.Servers {\n\t\tserv := &widget.Servers[i]\n\n\t\tif serv.Type == \"local\" {\n\t\t\tinfo, errs := sysinfo.Collect(serv.SystemInfoRequest)\n\n\t\t\tif len(errs) > 0 {\n\t\t\t\tfor i := range errs {\n\t\t\t\t\tslog.Warn(\"Getting system info: \" + errs[i].Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tserv.IsReachable = true\n\t\t\tserv.Info = info\n\t\t} else {\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tinfo, err := fetchRemoteServerInfo(serv)\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Warn(\"Getting remote system info: \" + err.Error())\n\t\t\t\t\tserv.IsReachable = false\n\t\t\t\t\tserv.Info = &sysinfo.SystemInfo{\n\t\t\t\t\t\tHostname: \"Unnamed server #\" + strconv.Itoa(i+1),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tserv.IsReachable = true\n\t\t\t\t\tserv.Info = info\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\twg.Wait()\n\twidget.withError(nil).scheduleNextUpdate()\n}\n\nfunc (widget *serverStatsWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, serverStatsWidgetTemplate)\n}\n\ntype serverStatsRequest struct {\n\t*sysinfo.SystemInfoRequest `yaml:\",inline\"`\n\tInfo                       *sysinfo.SystemInfo `yaml:\"-\"`\n\tIsReachable                bool                `yaml:\"-\"`\n\tStatusText                 string              `yaml:\"-\"`\n\tName                       string              `yaml:\"name\"`\n\tHideSwap                   bool                `yaml:\"hide-swap\"`\n\tType                       string              `yaml:\"type\"`\n\tURL                        string              `yaml:\"url\"`\n\tToken                      string              `yaml:\"token\"`\n\tTimeout                    durationField       `yaml:\"timeout\"`\n\t// Support for other agents\n\t// Provider                   string              `yaml:\"provider\"`\n}\n\nfunc fetchRemoteServerInfo(infoReq *serverStatsRequest) (*sysinfo.SystemInfo, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(infoReq.Timeout))\n\tdefer cancel()\n\n\trequest, _ := http.NewRequestWithContext(ctx, \"GET\", infoReq.URL+\"/api/sysinfo/all\", nil)\n\tif infoReq.Token != \"\" {\n\t\trequest.Header.Set(\"Authorization\", \"Bearer \"+infoReq.Token)\n\t}\n\n\tinfo, err := decodeJsonFromRequest[*sysinfo.SystemInfo](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn info, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-shared.go",
    "content": "package glance\n\nimport (\n\t\"math\"\n\t\"sort\"\n\t\"time\"\n)\n\nconst twitchGqlEndpoint = \"https://gql.twitch.tv/gql\"\nconst twitchGqlClientId = \"kimne78kx3ncx6brgo4mv6wki5h1ko\"\n\nvar forumPostsTemplate = mustParseTemplate(\"forum-posts.html\", \"widget-base.html\")\n\ntype forumPost struct {\n\tTitle           string\n\tDiscussionUrl   string\n\tTargetUrl       string\n\tTargetUrlDomain string\n\tThumbnailUrl    string\n\tCommentCount    int\n\tScore           int\n\tEngagement      float64\n\tTimePosted      time.Time\n\tTags            []string\n\tIsCrosspost     bool\n}\n\ntype forumPostList []forumPost\n\nconst depreciatePostsOlderThanHours = 7\nconst maxDepreciation = 0.9\nconst maxDepreciationAfterHours = 24\n\nfunc (p forumPostList) calculateEngagement() {\n\tvar totalComments int\n\tvar totalScore int\n\n\tfor i := range p {\n\t\ttotalComments += p[i].CommentCount\n\t\ttotalScore += p[i].Score\n\t}\n\n\tnumberOfPosts := float64(len(p))\n\taverageComments := float64(totalComments) / numberOfPosts\n\taverageScore := float64(totalScore) / numberOfPosts\n\n\tfor i := range p {\n\t\tp[i].Engagement = (float64(p[i].CommentCount)/averageComments + float64(p[i].Score)/averageScore) / 2\n\n\t\telapsed := time.Since(p[i].TimePosted)\n\n\t\tif elapsed < time.Hour*depreciatePostsOlderThanHours {\n\t\t\tcontinue\n\t\t}\n\n\t\tp[i].Engagement *= 1.0 - (math.Max(elapsed.Hours()-depreciatePostsOlderThanHours, maxDepreciationAfterHours)/maxDepreciationAfterHours)*maxDepreciation\n\t}\n}\n\nfunc (p forumPostList) sortByEngagement() {\n\tsort.Slice(p, func(i, j int) bool {\n\t\treturn p[i].Engagement > p[j].Engagement\n\t})\n}\n"
  },
  {
    "path": "internal/glance/widget-split-column.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"html/template\"\n\t\"time\"\n)\n\nvar splitColumnWidgetTemplate = mustParseTemplate(\"split-column.html\", \"widget-base.html\")\n\ntype splitColumnWidget struct {\n\twidgetBase          `yaml:\",inline\"`\n\tcontainerWidgetBase `yaml:\",inline\"`\n\tMaxColumns          int `yaml:\"max-columns\"`\n}\n\nfunc (widget *splitColumnWidget) initialize() error {\n\twidget.withError(nil).withTitle(\"Split Column\").setHideHeader(true)\n\n\tif err := widget.containerWidgetBase._initializeWidgets(); err != nil {\n\t\treturn err\n\t}\n\n\tif widget.MaxColumns < 2 {\n\t\twidget.MaxColumns = 2\n\t}\n\n\treturn nil\n}\n\nfunc (widget *splitColumnWidget) update(ctx context.Context) {\n\twidget.containerWidgetBase._update(ctx)\n}\n\nfunc (widget *splitColumnWidget) setProviders(providers *widgetProviders) {\n\twidget.containerWidgetBase._setProviders(providers)\n}\n\nfunc (widget *splitColumnWidget) requiresUpdate(now *time.Time) bool {\n\treturn widget.containerWidgetBase._requiresUpdate(now)\n}\n\nfunc (widget *splitColumnWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, splitColumnWidgetTemplate)\n}\n"
  },
  {
    "path": "internal/glance/widget-todo.go",
    "content": "package glance\n\nimport (\n\t\"html/template\"\n)\n\nvar todoWidgetTemplate = mustParseTemplate(\"todo.html\", \"widget-base.html\")\n\ntype todoWidget struct {\n\twidgetBase `yaml:\",inline\"`\n\tcachedHTML template.HTML `yaml:\"-\"`\n\tTodoID     string        `yaml:\"id\"`\n}\n\nfunc (widget *todoWidget) initialize() error {\n\twidget.withTitle(\"To-do\").withError(nil)\n\n\twidget.cachedHTML = widget.renderTemplate(widget, todoWidgetTemplate)\n\treturn nil\n}\n\nfunc (widget *todoWidget) Render() template.HTML {\n\treturn widget.cachedHTML\n}\n"
  },
  {
    "path": "internal/glance/widget-twitch-channels.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar twitchChannelsWidgetTemplate = mustParseTemplate(\"twitch-channels.html\", \"widget-base.html\")\n\ntype twitchChannelsWidget struct {\n\twidgetBase      `yaml:\",inline\"`\n\tChannelsRequest []string        `yaml:\"channels\"`\n\tChannels        []twitchChannel `yaml:\"-\"`\n\tCollapseAfter   int             `yaml:\"collapse-after\"`\n\tSortBy          string          `yaml:\"sort-by\"`\n}\n\nfunc (widget *twitchChannelsWidget) initialize() error {\n\twidget.\n\t\twithTitle(\"Twitch Channels\").\n\t\twithTitleURL(\"https://www.twitch.tv/directory/following\").\n\t\twithCacheDuration(time.Minute * 10)\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\tif widget.SortBy != \"viewers\" && widget.SortBy != \"live\" {\n\t\twidget.SortBy = \"viewers\"\n\t}\n\n\treturn nil\n}\n\nfunc (widget *twitchChannelsWidget) update(ctx context.Context) {\n\tchannels, err := fetchChannelsFromTwitch(widget.ChannelsRequest)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif widget.SortBy == \"viewers\" {\n\t\tchannels.sortByViewers()\n\t} else if widget.SortBy == \"live\" {\n\t\tchannels.sortByLive()\n\t}\n\n\twidget.Channels = channels\n}\n\nfunc (widget *twitchChannelsWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, twitchChannelsWidgetTemplate)\n}\n\ntype twitchChannel struct {\n\tLogin        string\n\tExists       bool\n\tName         string\n\tStreamTitle  string\n\tAvatarUrl    string\n\tIsLive       bool\n\tLiveSince    time.Time\n\tCategory     string\n\tCategorySlug string\n\tViewersCount int\n}\n\ntype twitchChannelList []twitchChannel\n\nfunc (channels twitchChannelList) sortByViewers() {\n\tsort.Slice(channels, func(i, j int) bool {\n\t\treturn channels[i].ViewersCount > channels[j].ViewersCount\n\t})\n}\n\nfunc (channels twitchChannelList) sortByLive() {\n\tsort.SliceStable(channels, func(i, j int) bool {\n\t\treturn channels[i].IsLive && !channels[j].IsLive\n\t})\n}\n\ntype twitchOperationResponse struct {\n\tData       json.RawMessage\n\tExtensions struct {\n\t\tOperationName string `json:\"operationName\"`\n\t}\n}\n\ntype twitchChannelShellOperationResponse struct {\n\tUserOrError struct {\n\t\tType            string `json:\"__typename\"`\n\t\tDisplayName     string `json:\"displayName\"`\n\t\tProfileImageUrl string `json:\"profileImageURL\"`\n\t\tStream          *struct {\n\t\t\tViewersCount int `json:\"viewersCount\"`\n\t\t}\n\t} `json:\"userOrError\"`\n}\n\ntype twitchStreamMetadataOperationResponse struct {\n\tUserOrNull *struct {\n\t\tStream *struct {\n\t\t\tStartedAt string `json:\"createdAt\"`\n\t\t\tGame      *struct {\n\t\t\t\tSlug string `json:\"slug\"`\n\t\t\t\tName string `json:\"name\"`\n\t\t\t} `json:\"game\"`\n\t\t} `json:\"stream\"`\n\t\tLastBroadcast *struct {\n\t\t\tTitle string `json:\"title\"`\n\t\t}\n\t} `json:\"user\"`\n}\n\nconst twitchChannelStatusOperationRequestBody = `[\n{\"operationName\":\"ChannelShell\",\"variables\":{\"login\":\"%s\"},\"extensions\":{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe\"}}},\n{\"operationName\":\"StreamMetadata\",\"variables\":{\"channelLogin\":\"%s\"},\"extensions\":{\"persistedQuery\":{\"version\":1,\"sha256Hash\":\"676ee2f834ede42eb4514cdb432b3134fefc12590080c9a2c9bb44a2a4a63266\"}}}\n]`\n\n// TODO: rework\n// The operations for multiple channels can all be sent in a single request\n// rather than sending a separate request for each channel. Need to figure out\n// what the limit is for max operations per request and batch operations in\n// multiple requests if number of channels exceeds allowed limit.\n\nfunc fetchChannelFromTwitchTask(channel string) (twitchChannel, error) {\n\tresult := twitchChannel{\n\t\tLogin: strings.ToLower(channel),\n\t}\n\n\treader := strings.NewReader(fmt.Sprintf(twitchChannelStatusOperationRequestBody, channel, channel))\n\trequest, _ := http.NewRequest(\"POST\", twitchGqlEndpoint, reader)\n\trequest.Header.Add(\"Client-ID\", twitchGqlClientId)\n\n\tresponse, err := decodeJsonFromRequest[[]twitchOperationResponse](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tif len(response) != 2 {\n\t\treturn result, fmt.Errorf(\"expected 2 operation responses, got %d\", len(response))\n\t}\n\n\tvar channelShell twitchChannelShellOperationResponse\n\tvar streamMetadata twitchStreamMetadataOperationResponse\n\n\tfor i := range response {\n\t\tswitch response[i].Extensions.OperationName {\n\t\tcase \"ChannelShell\":\n\t\t\tif err = json.Unmarshal(response[i].Data, &channelShell); err != nil {\n\t\t\t\treturn result, fmt.Errorf(\"unmarshalling channel shell: %w\", err)\n\t\t\t}\n\t\tcase \"StreamMetadata\":\n\t\t\tif err = json.Unmarshal(response[i].Data, &streamMetadata); err != nil {\n\t\t\t\treturn result, fmt.Errorf(\"unmarshalling stream metadata: %w\", err)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn result, fmt.Errorf(\"unknown operation name: %s\", response[i].Extensions.OperationName)\n\t\t}\n\t}\n\n\tif channelShell.UserOrError.Type != \"User\" {\n\t\tresult.Name = result.Login\n\t\treturn result, nil\n\t}\n\n\tresult.Exists = true\n\tresult.Name = channelShell.UserOrError.DisplayName\n\tresult.AvatarUrl = channelShell.UserOrError.ProfileImageUrl\n\n\tif channelShell.UserOrError.Stream != nil {\n\t\tresult.IsLive = true\n\t\tresult.ViewersCount = channelShell.UserOrError.Stream.ViewersCount\n\n\t\tif streamMetadata.UserOrNull != nil && streamMetadata.UserOrNull.Stream != nil {\n\t\t\tif streamMetadata.UserOrNull.LastBroadcast != nil {\n\t\t\t\tresult.StreamTitle = streamMetadata.UserOrNull.LastBroadcast.Title\n\t\t\t}\n\n\t\t\tif streamMetadata.UserOrNull.Stream.Game != nil {\n\t\t\t\tresult.Category = streamMetadata.UserOrNull.Stream.Game.Name\n\t\t\t\tresult.CategorySlug = streamMetadata.UserOrNull.Stream.Game.Slug\n\t\t\t}\n\t\t\tstartedAt, err := time.Parse(\"2006-01-02T15:04:05Z\", streamMetadata.UserOrNull.Stream.StartedAt)\n\n\t\t\tif err == nil {\n\t\t\t\tresult.LiveSince = startedAt\n\t\t\t} else {\n\t\t\t\tslog.Warn(\"Failed to parse Twitch stream started at\", \"error\", err, \"started_at\", streamMetadata.UserOrNull.Stream.StartedAt)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// This prevents live channels with 0 viewers from being\n\t\t// incorrectly sorted lower than offline channels\n\t\tresult.ViewersCount = -1\n\t}\n\n\treturn result, nil\n}\n\nfunc fetchChannelsFromTwitch(channelLogins []string) (twitchChannelList, error) {\n\tresult := make(twitchChannelList, 0, len(channelLogins))\n\n\tjob := newJob(fetchChannelFromTwitchTask, channelLogins).withWorkers(10)\n\tchannels, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tvar failed int\n\n\tfor i := range channels {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to fetch Twitch channel\", \"channel\", channelLogins[i], \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, channels[i])\n\t}\n\n\tif failed == len(channelLogins) {\n\t\treturn result, errNoContent\n\t}\n\n\tif failed > 0 {\n\t\treturn result, fmt.Errorf(\"%w: failed to fetch %d channels\", errPartialContent, failed)\n\t}\n\n\treturn result, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-twitch-top-games.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar twitchGamesWidgetTemplate = mustParseTemplate(\"twitch-games-list.html\", \"widget-base.html\")\n\ntype twitchGamesWidget struct {\n\twidgetBase    `yaml:\",inline\"`\n\tCategories    []twitchCategory `yaml:\"-\"`\n\tExclude       []string         `yaml:\"exclude\"`\n\tLimit         int              `yaml:\"limit\"`\n\tCollapseAfter int              `yaml:\"collapse-after\"`\n}\n\nfunc (widget *twitchGamesWidget) initialize() error {\n\twidget.\n\t\twithTitle(\"Top games on Twitch\").\n\t\twithTitleURL(\"https://www.twitch.tv/directory?sort=VIEWER_COUNT\").\n\t\twithCacheDuration(time.Minute * 10)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 10\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 5\n\t}\n\n\treturn nil\n}\n\nfunc (widget *twitchGamesWidget) update(ctx context.Context) {\n\tcategories, err := fetchTopGamesFromTwitch(widget.Exclude, widget.Limit)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\twidget.Categories = categories\n}\n\nfunc (widget *twitchGamesWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, twitchGamesWidgetTemplate)\n}\n\ntype twitchCategory struct {\n\tSlug         string `json:\"slug\"`\n\tName         string `json:\"name\"`\n\tAvatarUrl    string `json:\"avatarURL\"`\n\tViewersCount int    `json:\"viewersCount\"`\n\tTags         []struct {\n\t\tName string `json:\"tagName\"`\n\t} `json:\"tags\"`\n\tGameReleaseDate string `json:\"originalReleaseDate\"`\n\tIsNew           bool   `json:\"-\"`\n}\n\ntype twitchDirectoriesOperationResponse struct {\n\tData struct {\n\t\tDirectoriesWithTags struct {\n\t\t\tEdges []struct {\n\t\t\t\tNode twitchCategory `json:\"node\"`\n\t\t\t} `json:\"edges\"`\n\t\t} `json:\"directoriesWithTags\"`\n\t} `json:\"data\"`\n}\n\nconst twitchDirectoriesOperationRequestBody = `[\n{\"operationName\": \"BrowsePage_AllDirectories\",\"variables\": {\"limit\": %d,\"options\": {\"sort\": \"VIEWER_COUNT\",\"tags\": []}},\"extensions\": {\"persistedQuery\": {\"version\": 1,\"sha256Hash\": \"2f67f71ba89f3c0ed26a141ec00da1defecb2303595f5cda4298169549783d9e\"}}}\n]`\n\nfunc fetchTopGamesFromTwitch(exclude []string, limit int) ([]twitchCategory, error) {\n\treader := strings.NewReader(fmt.Sprintf(twitchDirectoriesOperationRequestBody, len(exclude)+limit))\n\trequest, _ := http.NewRequest(\"POST\", twitchGqlEndpoint, reader)\n\trequest.Header.Add(\"Client-ID\", twitchGqlClientId)\n\tresponse, err := decodeJsonFromRequest[[]twitchDirectoriesOperationResponse](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(response) == 0 {\n\t\treturn nil, errors.New(\"no categories could be retrieved\")\n\t}\n\n\tedges := (response)[0].Data.DirectoriesWithTags.Edges\n\tcategories := make([]twitchCategory, 0, len(edges))\n\n\tfor i := range edges {\n\t\tif slices.Contains(exclude, edges[i].Node.Slug) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcategory := &edges[i].Node\n\t\tcategory.AvatarUrl = strings.Replace(category.AvatarUrl, \"285x380\", \"144x192\", 1)\n\n\t\tif len(category.Tags) > 2 {\n\t\t\tcategory.Tags = category.Tags[:2]\n\t\t}\n\n\t\tgameReleasedDate, err := time.Parse(\"2006-01-02T15:04:05Z\", category.GameReleaseDate)\n\n\t\tif err == nil {\n\t\t\tif time.Since(gameReleasedDate) < 14*24*time.Hour {\n\t\t\t\tcategory.IsNew = true\n\t\t\t}\n\t\t}\n\n\t\tcategories = append(categories, *category)\n\t}\n\n\tif len(categories) > limit {\n\t\tcategories = categories[:limit]\n\t}\n\n\treturn categories, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-utils.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"encoding/json\"\n\t\"encoding/xml\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/rand/v2\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n)\n\nvar (\n\terrNoContent      = errors.New(\"failed to retrieve any content\")\n\terrPartialContent = errors.New(\"failed to retrieve some of the content\")\n)\n\nconst defaultClientTimeout = 5 * time.Second\n\nvar defaultHTTPClient = &http.Client{\n\tTransport: &http.Transport{\n\t\tMaxIdleConnsPerHost: 10,\n\t\tProxy:               http.ProxyFromEnvironment,\n\t},\n\tTimeout: defaultClientTimeout,\n}\n\nvar defaultInsecureHTTPClient = &http.Client{\n\tTimeout: defaultClientTimeout,\n\tTransport: &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tProxy:           http.ProxyFromEnvironment,\n\t},\n}\n\ntype requestDoer interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\nvar glanceUserAgentString = \"Glance/\" + buildVersion + \" +https://github.com/glanceapp/glance\"\nvar userAgentPersistentVersion atomic.Int32\n\nfunc getBrowserUserAgentHeader() string {\n\tif rand.IntN(2000) == 0 {\n\t\tuserAgentPersistentVersion.Store(rand.Int32N(5))\n\t}\n\n\tversion := strconv.Itoa(130 + int(userAgentPersistentVersion.Load()))\n\treturn \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:\" + version + \".0) Gecko/20100101 Firefox/\" + version + \".0\"\n}\n\nfunc setBrowserUserAgentHeader(request *http.Request) {\n\trequest.Header.Set(\"User-Agent\", getBrowserUserAgentHeader())\n}\n\nfunc decodeJsonFromRequest[T any](client requestDoer, request *http.Request) (T, error) {\n\tvar result T\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\ttruncatedBody, _ := limitStringLength(string(body), 256)\n\n\t\treturn result, fmt.Errorf(\n\t\t\t\"unexpected status code %d from %s, response: %s\",\n\t\t\tresponse.StatusCode,\n\t\t\trequest.URL,\n\t\t\ttruncatedBody,\n\t\t)\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}\n\nfunc decodeJsonFromRequestTask[T any](client requestDoer) func(*http.Request) (T, error) {\n\treturn func(request *http.Request) (T, error) {\n\t\treturn decodeJsonFromRequest[T](client, request)\n\t}\n}\n\n// TODO: tidy up, these are a copy of the above but with a line changed\nfunc decodeXmlFromRequest[T any](client requestDoer, request *http.Request) (T, error) {\n\tvar result T\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer response.Body.Close()\n\n\tbody, err := io.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\ttruncatedBody, _ := limitStringLength(string(body), 256)\n\n\t\treturn result, fmt.Errorf(\n\t\t\t\"unexpected status code %d for %s, response: %s\",\n\t\t\tresponse.StatusCode,\n\t\t\trequest.URL,\n\t\t\ttruncatedBody,\n\t\t)\n\t}\n\n\terr = xml.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}\n\nfunc decodeXmlFromRequestTask[T any](client requestDoer) func(*http.Request) (T, error) {\n\treturn func(request *http.Request) (T, error) {\n\t\treturn decodeXmlFromRequest[T](client, request)\n\t}\n}\n\ntype workerPoolTask[I any, O any] struct {\n\tindex  int\n\tinput  I\n\toutput O\n\terr    error\n}\n\ntype workerPoolJob[I any, O any] struct {\n\tdata    []I\n\tworkers int\n\ttask    func(I) (O, error)\n\tctx     context.Context\n}\n\nconst defaultNumWorkers = 10\n\nfunc (job *workerPoolJob[I, O]) withWorkers(workers int) *workerPoolJob[I, O] {\n\tif workers == 0 {\n\t\tjob.workers = defaultNumWorkers\n\t} else {\n\t\tjob.workers = min(workers, len(job.data))\n\t}\n\n\treturn job\n}\n\n// func (job *workerPoolJob[I, O]) withContext(ctx context.Context) *workerPoolJob[I, O] {\n// \tif ctx != nil {\n// \t\tjob.ctx = ctx\n// \t}\n\n// \treturn job\n// }\n\nfunc newJob[I any, O any](task func(I) (O, error), data []I) *workerPoolJob[I, O] {\n\treturn &workerPoolJob[I, O]{\n\t\tworkers: defaultNumWorkers,\n\t\ttask:    task,\n\t\tdata:    data,\n\t\tctx:     context.Background(),\n\t}\n}\n\nfunc workerPoolDo[I any, O any](job *workerPoolJob[I, O]) ([]O, []error, error) {\n\tresults := make([]O, len(job.data))\n\terrs := make([]error, len(job.data))\n\n\tif len(job.data) == 0 {\n\t\treturn results, errs, nil\n\t}\n\n\tif len(job.data) == 1 {\n\t\tresults[0], errs[0] = job.task(job.data[0])\n\t\treturn results, errs, nil\n\t}\n\n\ttasksQueue := make(chan *workerPoolTask[I, O])\n\tresultsQueue := make(chan *workerPoolTask[I, O])\n\n\tvar wg sync.WaitGroup\n\n\tfor range job.workers {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tfor t := range tasksQueue {\n\t\t\t\tt.output, t.err = job.task(t.input)\n\t\t\t\tresultsQueue <- t\n\t\t\t}\n\t\t}()\n\t}\n\n\tvar err error\n\n\tgo func() {\n\tloop:\n\t\tfor i := range job.data {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\ttasksQueue <- &workerPoolTask[I, O]{\n\t\t\t\t\tindex: i,\n\t\t\t\t\tinput: job.data[i],\n\t\t\t\t}\n\t\t\tcase <-job.ctx.Done():\n\t\t\t\terr = job.ctx.Err()\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\n\t\tclose(tasksQueue)\n\t\twg.Wait()\n\t\tclose(resultsQueue)\n\t}()\n\n\tfor task := range resultsQueue {\n\t\terrs[task.index] = task.err\n\t\tresults[task.index] = task.output\n\t}\n\n\treturn results, errs, err\n}\n"
  },
  {
    "path": "internal/glance/widget-videos.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst videosWidgetPlaylistPrefix = \"playlist:\"\n\nvar (\n\tvideosWidgetTemplate             = mustParseTemplate(\"videos.html\", \"widget-base.html\", \"video-card-contents.html\")\n\tvideosWidgetGridTemplate         = mustParseTemplate(\"videos-grid.html\", \"widget-base.html\", \"video-card-contents.html\")\n\tvideosWidgetVerticalListTemplate = mustParseTemplate(\"videos-vertical-list.html\", \"widget-base.html\")\n)\n\ntype videosWidget struct {\n\twidgetBase        `yaml:\",inline\"`\n\tVideos            videoList `yaml:\"-\"`\n\tVideoUrlTemplate  string    `yaml:\"video-url-template\"`\n\tStyle             string    `yaml:\"style\"`\n\tCollapseAfter     int       `yaml:\"collapse-after\"`\n\tCollapseAfterRows int       `yaml:\"collapse-after-rows\"`\n\tChannels          []string  `yaml:\"channels\"`\n\tPlaylists         []string  `yaml:\"playlists\"`\n\tLimit             int       `yaml:\"limit\"`\n\tIncludeShorts     bool      `yaml:\"include-shorts\"`\n}\n\nfunc (widget *videosWidget) initialize() error {\n\twidget.withTitle(\"Videos\").withCacheDuration(time.Hour)\n\n\tif widget.Limit <= 0 {\n\t\twidget.Limit = 25\n\t}\n\n\tif widget.CollapseAfterRows == 0 || widget.CollapseAfterRows < -1 {\n\t\twidget.CollapseAfterRows = 4\n\t}\n\n\tif widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {\n\t\twidget.CollapseAfter = 7\n\t}\n\n\t// A bit cheeky, but from a user's perspective it makes more sense when channels and\n\t// playlists are separate things rather than specifying a list of channels and some of\n\t// them awkwardly have a \"playlist:\" prefix\n\tif len(widget.Playlists) > 0 {\n\t\tinitialLen := len(widget.Channels)\n\t\twidget.Channels = append(widget.Channels, make([]string, len(widget.Playlists))...)\n\n\t\tfor i := range widget.Playlists {\n\t\t\twidget.Channels[initialLen+i] = videosWidgetPlaylistPrefix + widget.Playlists[i]\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (widget *videosWidget) update(ctx context.Context) {\n\tvideos, err := fetchYoutubeChannelUploads(widget.Channels, widget.VideoUrlTemplate, widget.IncludeShorts)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\tif len(videos) > widget.Limit {\n\t\tvideos = videos[:widget.Limit]\n\t}\n\n\twidget.Videos = videos\n}\n\nfunc (widget *videosWidget) Render() template.HTML {\n\tvar template *template.Template\n\n\tswitch widget.Style {\n\tcase \"grid-cards\":\n\t\ttemplate = videosWidgetGridTemplate\n\tcase \"vertical-list\":\n\t\ttemplate = videosWidgetVerticalListTemplate\n\tdefault:\n\t\ttemplate = videosWidgetTemplate\n\t}\n\n\treturn widget.renderTemplate(widget, template)\n}\n\ntype youtubeFeedResponseXml struct {\n\tChannel     string `xml:\"author>name\"`\n\tChannelLink string `xml:\"author>uri\"`\n\tVideos      []struct {\n\t\tTitle     string `xml:\"title\"`\n\t\tPublished string `xml:\"published\"`\n\t\tLink      struct {\n\t\t\tHref string `xml:\"href,attr\"`\n\t\t} `xml:\"link\"`\n\n\t\tGroup struct {\n\t\t\tThumbnail struct {\n\t\t\t\tUrl string `xml:\"url,attr\"`\n\t\t\t} `xml:\"http://search.yahoo.com/mrss/ thumbnail\"`\n\t\t} `xml:\"http://search.yahoo.com/mrss/ group\"`\n\t} `xml:\"entry\"`\n}\n\nfunc parseYoutubeFeedTime(t string) time.Time {\n\tparsedTime, err := time.Parse(\"2006-01-02T15:04:05-07:00\", t)\n\tif err != nil {\n\t\treturn time.Now()\n\t}\n\n\treturn parsedTime\n}\n\ntype video struct {\n\tThumbnailUrl string\n\tTitle        string\n\tUrl          string\n\tAuthor       string\n\tAuthorUrl    string\n\tTimePosted   time.Time\n}\n\ntype videoList []video\n\nfunc (v videoList) sortByNewest() videoList {\n\tsort.Slice(v, func(i, j int) bool {\n\t\treturn v[i].TimePosted.After(v[j].TimePosted)\n\t})\n\n\treturn v\n}\n\nfunc fetchYoutubeChannelUploads(channelOrPlaylistIDs []string, videoUrlTemplate string, includeShorts bool) (videoList, error) {\n\trequests := make([]*http.Request, 0, len(channelOrPlaylistIDs))\n\n\tfor i := range channelOrPlaylistIDs {\n\t\tvar feedUrl string\n\t\tif strings.HasPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix) {\n\t\t\tfeedUrl = \"https://www.youtube.com/feeds/videos.xml?playlist_id=\" +\n\t\t\t\tstrings.TrimPrefix(channelOrPlaylistIDs[i], videosWidgetPlaylistPrefix)\n\t\t} else if !includeShorts && strings.HasPrefix(channelOrPlaylistIDs[i], \"UC\") {\n\t\t\tplaylistId := strings.Replace(channelOrPlaylistIDs[i], \"UC\", \"UULF\", 1)\n\t\t\tfeedUrl = \"https://www.youtube.com/feeds/videos.xml?playlist_id=\" + playlistId\n\t\t} else {\n\t\t\tfeedUrl = \"https://www.youtube.com/feeds/videos.xml?channel_id=\" + channelOrPlaylistIDs[i]\n\t\t}\n\n\t\trequest, _ := http.NewRequest(\"GET\", feedUrl, nil)\n\t\trequests = append(requests, request)\n\t}\n\n\tjob := newJob(decodeXmlFromRequestTask[youtubeFeedResponseXml](defaultHTTPClient), requests).withWorkers(30)\n\tresponses, errs, err := workerPoolDo(job)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errNoContent, err)\n\t}\n\n\tvideos := make(videoList, 0, len(channelOrPlaylistIDs)*15)\n\tvar failed int\n\n\tfor i := range responses {\n\t\tif errs[i] != nil {\n\t\t\tfailed++\n\t\t\tslog.Error(\"Failed to fetch youtube feed\", \"channel\", channelOrPlaylistIDs[i], \"error\", errs[i])\n\t\t\tcontinue\n\t\t}\n\n\t\tresponse := responses[i]\n\n\t\tfor j := range response.Videos {\n\t\t\tv := &response.Videos[j]\n\t\t\tvar videoUrl string\n\n\t\t\tif videoUrlTemplate == \"\" {\n\t\t\t\tvideoUrl = v.Link.Href\n\t\t\t} else {\n\t\t\t\tparsedUrl, err := url.Parse(v.Link.Href)\n\n\t\t\t\tif err == nil {\n\t\t\t\t\tvideoUrl = strings.ReplaceAll(videoUrlTemplate, \"{VIDEO-ID}\", parsedUrl.Query().Get(\"v\"))\n\t\t\t\t} else {\n\t\t\t\t\tvideoUrl = \"#\"\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvideos = append(videos, video{\n\t\t\t\tThumbnailUrl: v.Group.Thumbnail.Url,\n\t\t\t\tTitle:        v.Title,\n\t\t\t\tUrl:          videoUrl,\n\t\t\t\tAuthor:       response.Channel,\n\t\t\t\tAuthorUrl:    response.ChannelLink + \"/videos\",\n\t\t\t\tTimePosted:   parseYoutubeFeedTime(v.Published),\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(videos) == 0 {\n\t\treturn nil, errNoContent\n\t}\n\n\tvideos.sortByNewest()\n\n\tif failed > 0 {\n\t\treturn videos, fmt.Errorf(\"%w: missing videos from %d channels\", errPartialContent, failed)\n\t}\n\n\treturn videos, nil\n}\n"
  },
  {
    "path": "internal/glance/widget-weather.go",
    "content": "package glance\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"math\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t_ \"time/tzdata\"\n)\n\nvar weatherWidgetTemplate = mustParseTemplate(\"weather.html\", \"widget-base.html\")\n\ntype weatherWidget struct {\n\twidgetBase   `yaml:\",inline\"`\n\tLocation     string                      `yaml:\"location\"`\n\tShowAreaName bool                        `yaml:\"show-area-name\"`\n\tHideLocation bool                        `yaml:\"hide-location\"`\n\tHourFormat   string                      `yaml:\"hour-format\"`\n\tUnits        string                      `yaml:\"units\"`\n\tPlace        *openMeteoPlaceResponseJson `yaml:\"-\"`\n\tWeather      *weather                    `yaml:\"-\"`\n\tTimeLabels   [12]string                  `yaml:\"-\"`\n}\n\nvar timeLabels12h = [12]string{\"2am\", \"4am\", \"6am\", \"8am\", \"10am\", \"12pm\", \"2pm\", \"4pm\", \"6pm\", \"8pm\", \"10pm\", \"12am\"}\nvar 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\"}\n\nfunc (widget *weatherWidget) initialize() error {\n\twidget.withTitle(\"Weather\").withCacheOnTheHour()\n\n\tif widget.Location == \"\" {\n\t\treturn fmt.Errorf(\"location is required\")\n\t}\n\n\tif widget.HourFormat == \"\" || widget.HourFormat == \"12h\" {\n\t\twidget.TimeLabels = timeLabels12h\n\t} else if widget.HourFormat == \"24h\" {\n\t\twidget.TimeLabels = timeLabels24h\n\t} else {\n\t\treturn errors.New(\"hour-format must be either 12h or 24h\")\n\t}\n\n\tif widget.Units == \"\" {\n\t\twidget.Units = \"metric\"\n\t} else if widget.Units != \"metric\" && widget.Units != \"imperial\" {\n\t\treturn errors.New(\"units must be either metric or imperial\")\n\t}\n\n\treturn nil\n}\n\nfunc (widget *weatherWidget) update(ctx context.Context) {\n\tif widget.Place == nil {\n\t\tplace, err := fetchOpenMeteoPlaceFromName(widget.Location)\n\t\tif err != nil {\n\t\t\twidget.withError(err).scheduleEarlyUpdate()\n\t\t\treturn\n\t\t}\n\n\t\twidget.Place = place\n\t}\n\n\tweather, err := fetchWeatherForOpenMeteoPlace(widget.Place, widget.Units)\n\n\tif !widget.canContinueUpdateAfterHandlingErr(err) {\n\t\treturn\n\t}\n\n\twidget.Weather = weather\n}\n\nfunc (widget *weatherWidget) Render() template.HTML {\n\treturn widget.renderTemplate(widget, weatherWidgetTemplate)\n}\n\ntype weather struct {\n\tTemperature         int\n\tApparentTemperature int\n\tWeatherCode         int\n\tCurrentColumn       int\n\tSunriseColumn       int\n\tSunsetColumn        int\n\tColumns             []weatherColumn\n}\n\nfunc (w *weather) WeatherCodeAsString() string {\n\tif weatherCode, ok := weatherCodeTable[w.WeatherCode]; ok {\n\t\treturn weatherCode\n\t}\n\n\treturn \"\"\n}\n\ntype openMeteoPlacesResponseJson struct {\n\tResults []openMeteoPlaceResponseJson\n}\n\ntype openMeteoPlaceResponseJson struct {\n\tName      string\n\tArea      string `json:\"admin1\"`\n\tLatitude  float64\n\tLongitude float64\n\tTimezone  string\n\tCountry   string\n\tlocation  *time.Location\n}\n\ntype openMeteoWeatherResponseJson struct {\n\tDaily struct {\n\t\tSunrise []int64 `json:\"sunrise\"`\n\t\tSunset  []int64 `json:\"sunset\"`\n\t} `json:\"daily\"`\n\n\tHourly struct {\n\t\tTemperature              []float64 `json:\"temperature_2m\"`\n\t\tPrecipitationProbability []int     `json:\"precipitation_probability\"`\n\t} `json:\"hourly\"`\n\n\tCurrent struct {\n\t\tTemperature         float64 `json:\"temperature_2m\"`\n\t\tApparentTemperature float64 `json:\"apparent_temperature\"`\n\t\tWeatherCode         int     `json:\"weather_code\"`\n\t} `json:\"current\"`\n}\n\ntype weatherColumn struct {\n\tTemperature      int\n\tScale            float64\n\tHasPrecipitation bool\n}\n\nvar commonCountryAbbreviations = map[string]string{\n\t\"US\":  \"United States\",\n\t\"USA\": \"United States\",\n\t\"UK\":  \"United Kingdom\",\n}\n\nfunc expandCountryAbbreviations(name string) string {\n\tif expanded, ok := commonCountryAbbreviations[strings.TrimSpace(name)]; ok {\n\t\treturn expanded\n\t}\n\n\treturn name\n}\n\n// Separates the location that Open Meteo accepts from the administrative area\n// which can then be used to filter to the correct place after the list of places\n// has been retrieved. Also expands abbreviations since Open Meteo does not accept\n// country names like \"US\", \"USA\" and \"UK\"\nfunc parsePlaceName(name string) (string, string) {\n\tparts := strings.Split(name, \",\")\n\n\tif len(parts) == 1 {\n\t\treturn name, \"\"\n\t}\n\n\tif len(parts) == 2 {\n\t\treturn parts[0] + \", \" + expandCountryAbbreviations(parts[1]), \"\"\n\t}\n\n\treturn parts[0] + \", \" + expandCountryAbbreviations(parts[2]), strings.TrimSpace(parts[1])\n}\n\nfunc fetchOpenMeteoPlaceFromName(location string) (*openMeteoPlaceResponseJson, error) {\n\tlocation, area := parsePlaceName(location)\n\trequestUrl := fmt.Sprintf(\"https://geocoding-api.open-meteo.com/v1/search?name=%s&count=20&language=en&format=json\", url.QueryEscape(location))\n\trequest, _ := http.NewRequest(\"GET\", requestUrl, nil)\n\tresponseJson, err := decodeJsonFromRequest[openMeteoPlacesResponseJson](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetching places data: %v\", err)\n\t}\n\n\tif len(responseJson.Results) == 0 {\n\t\treturn nil, fmt.Errorf(\"no places found for %s\", location)\n\t}\n\n\tvar place *openMeteoPlaceResponseJson\n\n\tif area != \"\" {\n\t\tarea = strings.ToLower(area)\n\n\t\tfor i := range responseJson.Results {\n\t\t\tif strings.ToLower(responseJson.Results[i].Area) == area {\n\t\t\t\tplace = &responseJson.Results[i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif place == nil {\n\t\t\treturn nil, fmt.Errorf(\"no place found for %s in %s\", location, area)\n\t\t}\n\t} else {\n\t\tplace = &responseJson.Results[0]\n\t}\n\n\tloc, err := time.LoadLocation(place.Timezone)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading location: %v\", err)\n\t}\n\n\tplace.location = loc\n\n\treturn place, nil\n}\n\nfunc fetchWeatherForOpenMeteoPlace(place *openMeteoPlaceResponseJson, units string) (*weather, error) {\n\tquery := url.Values{}\n\tvar temperatureUnit string\n\n\tif units == \"imperial\" {\n\t\ttemperatureUnit = \"fahrenheit\"\n\t} else {\n\t\ttemperatureUnit = \"celsius\"\n\t}\n\n\tquery.Add(\"latitude\", fmt.Sprintf(\"%f\", place.Latitude))\n\tquery.Add(\"longitude\", fmt.Sprintf(\"%f\", place.Longitude))\n\tquery.Add(\"timeformat\", \"unixtime\")\n\tquery.Add(\"timezone\", place.Timezone)\n\tquery.Add(\"forecast_days\", \"1\")\n\tquery.Add(\"current\", \"temperature_2m,apparent_temperature,weather_code\")\n\tquery.Add(\"hourly\", \"temperature_2m,precipitation_probability\")\n\tquery.Add(\"daily\", \"sunrise,sunset\")\n\tquery.Add(\"temperature_unit\", temperatureUnit)\n\n\trequestUrl := \"https://api.open-meteo.com/v1/forecast?\" + query.Encode()\n\trequest, _ := http.NewRequest(\"GET\", requestUrl, nil)\n\tresponseJson, err := decodeJsonFromRequest[openMeteoWeatherResponseJson](defaultHTTPClient, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errNoContent, err)\n\t}\n\n\tnow := time.Now().In(place.location)\n\tbars := make([]weatherColumn, 0, 24)\n\tcurrentBar := now.Hour() / 2\n\tsunriseBar := (time.Unix(int64(responseJson.Daily.Sunrise[0]), 0).In(place.location).Hour()) / 2\n\tsunsetBar := (time.Unix(int64(responseJson.Daily.Sunset[0]), 0).In(place.location).Hour() - 1) / 2\n\n\tif sunsetBar < 0 {\n\t\tsunsetBar = 0\n\t}\n\n\tif len(responseJson.Hourly.Temperature) == 24 {\n\t\ttemperatures := make([]int, 12)\n\t\tprecipitations := make([]bool, 12)\n\n\t\tt := responseJson.Hourly.Temperature\n\t\tp := responseJson.Hourly.PrecipitationProbability\n\n\t\tfor i := 0; i < 24; i += 2 {\n\t\t\tif i/2 == currentBar {\n\t\t\t\ttemperatures[i/2] = int(responseJson.Current.Temperature)\n\t\t\t} else {\n\t\t\t\ttemperatures[i/2] = int(math.Round((t[i] + t[i+1]) / 2))\n\t\t\t}\n\n\t\t\tprecipitations[i/2] = (p[i]+p[i+1])/2 > 75\n\t\t}\n\n\t\tminT := slices.Min(temperatures)\n\t\tmaxT := slices.Max(temperatures)\n\n\t\ttemperaturesRange := float64(maxT - minT)\n\n\t\tfor i := 0; i < 12; i++ {\n\t\t\tbars = append(bars, weatherColumn{\n\t\t\t\tTemperature:      temperatures[i],\n\t\t\t\tHasPrecipitation: precipitations[i],\n\t\t\t})\n\n\t\t\tif temperaturesRange > 0 {\n\t\t\t\tbars[i].Scale = float64(temperatures[i]-minT) / temperaturesRange\n\t\t\t} else {\n\t\t\t\tbars[i].Scale = 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &weather{\n\t\tTemperature:         int(responseJson.Current.Temperature),\n\t\tApparentTemperature: int(responseJson.Current.ApparentTemperature),\n\t\tWeatherCode:         responseJson.Current.WeatherCode,\n\t\tCurrentColumn:       currentBar,\n\t\tSunriseColumn:       sunriseBar,\n\t\tSunsetColumn:        sunsetBar,\n\t\tColumns:             bars,\n\t}, nil\n}\n\nvar weatherCodeTable = map[int]string{\n\t0:  \"Clear Sky\",\n\t1:  \"Mainly Clear\",\n\t2:  \"Partly Cloudy\",\n\t3:  \"Overcast\",\n\t45: \"Fog\",\n\t48: \"Rime Fog\",\n\t51: \"Drizzle\",\n\t53: \"Drizzle\",\n\t55: \"Drizzle\",\n\t56: \"Drizzle\",\n\t57: \"Drizzle\",\n\t61: \"Rain\",\n\t63: \"Moderate Rain\",\n\t65: \"Heavy Rain\",\n\t66: \"Freezing Rain\",\n\t67: \"Freezing Rain\",\n\t71: \"Snow\",\n\t73: \"Moderate Snow\",\n\t75: \"Heavy Snow\",\n\t77: \"Snow Grains\",\n\t80: \"Rain\",\n\t81: \"Moderate Rain\",\n\t82: \"Heavy Rain\",\n\t85: \"Snow\",\n\t86: \"Snow\",\n\t95: \"Thunderstorm\",\n\t96: \"Thunderstorm\",\n\t99: \"Thunderstorm\",\n}\n"
  },
  {
    "path": "internal/glance/widget.go",
    "content": "package glance\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"log/slog\"\n\t\"math\"\n\t\"net/http\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"gopkg.in/yaml.v3\"\n)\n\nvar widgetIDCounter atomic.Uint64\n\nfunc newWidget(widgetType string) (widget, error) {\n\tif widgetType == \"\" {\n\t\treturn nil, errors.New(\"widget 'type' property is empty or not specified\")\n\t}\n\n\tvar w widget\n\n\tswitch widgetType {\n\tcase \"calendar\":\n\t\tw = &calendarWidget{}\n\tcase \"calendar-legacy\":\n\t\tw = &oldCalendarWidget{}\n\tcase \"clock\":\n\t\tw = &clockWidget{}\n\tcase \"weather\":\n\t\tw = &weatherWidget{}\n\tcase \"bookmarks\":\n\t\tw = &bookmarksWidget{}\n\tcase \"iframe\":\n\t\tw = &iframeWidget{}\n\tcase \"html\":\n\t\tw = &htmlWidget{}\n\tcase \"hacker-news\":\n\t\tw = &hackerNewsWidget{}\n\tcase \"releases\":\n\t\tw = &releasesWidget{}\n\tcase \"videos\":\n\t\tw = &videosWidget{}\n\tcase \"markets\", \"stocks\":\n\t\tw = &marketsWidget{}\n\tcase \"reddit\":\n\t\tw = &redditWidget{}\n\tcase \"rss\":\n\t\tw = &rssWidget{}\n\tcase \"monitor\":\n\t\tw = &monitorWidget{}\n\tcase \"twitch-top-games\":\n\t\tw = &twitchGamesWidget{}\n\tcase \"twitch-channels\":\n\t\tw = &twitchChannelsWidget{}\n\tcase \"lobsters\":\n\t\tw = &lobstersWidget{}\n\tcase \"change-detection\":\n\t\tw = &changeDetectionWidget{}\n\tcase \"repository\":\n\t\tw = &repositoryWidget{}\n\tcase \"search\":\n\t\tw = &searchWidget{}\n\tcase \"extension\":\n\t\tw = &extensionWidget{}\n\tcase \"group\":\n\t\tw = &groupWidget{}\n\tcase \"dns-stats\":\n\t\tw = &dnsStatsWidget{}\n\tcase \"split-column\":\n\t\tw = &splitColumnWidget{}\n\tcase \"custom-api\":\n\t\tw = &customAPIWidget{}\n\tcase \"docker-containers\":\n\t\tw = &dockerContainersWidget{}\n\tcase \"server-stats\":\n\t\tw = &serverStatsWidget{}\n\tcase \"to-do\":\n\t\tw = &todoWidget{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown widget type: %s\", widgetType)\n\t}\n\n\tw.setID(widgetIDCounter.Add(1))\n\n\treturn w, nil\n}\n\ntype widgets []widget\n\nfunc (w *widgets) UnmarshalYAML(node *yaml.Node) error {\n\tvar nodes []yaml.Node\n\n\tif err := node.Decode(&nodes); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, node := range nodes {\n\t\tmeta := struct {\n\t\t\tType string `yaml:\"type\"`\n\t\t}{}\n\n\t\tif err := node.Decode(&meta); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twidget, err := newWidget(meta.Type)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %d: %w\", node.Line, err)\n\t\t}\n\n\t\tif err = node.Decode(widget); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t*w = append(*w, widget)\n\t}\n\n\treturn nil\n}\n\ntype widget interface {\n\t// These need to be exported because they get called in templates\n\tRender() template.HTML\n\tGetType() string\n\tGetID() uint64\n\n\tinitialize() error\n\trequiresUpdate(*time.Time) bool\n\tsetProviders(*widgetProviders)\n\tupdate(context.Context)\n\tsetID(uint64)\n\thandleRequest(w http.ResponseWriter, r *http.Request)\n\tsetHideHeader(bool)\n}\n\ntype cacheType int\n\nconst (\n\tcacheTypeInfinite cacheType = iota\n\tcacheTypeDuration\n\tcacheTypeOnTheHour\n)\n\ntype widgetBase struct {\n\tID                  uint64           `yaml:\"-\"`\n\tProviders           *widgetProviders `yaml:\"-\"`\n\tType                string           `yaml:\"type\"`\n\tTitle               string           `yaml:\"title\"`\n\tTitleURL            string           `yaml:\"title-url\"`\n\tHideHeader          bool             `yaml:\"hide-header\"`\n\tCSSClass            string           `yaml:\"css-class\"`\n\tCustomCacheDuration durationField    `yaml:\"cache\"`\n\tContentAvailable    bool             `yaml:\"-\"`\n\tWIP                 bool             `yaml:\"-\"`\n\tError               error            `yaml:\"-\"`\n\tNotice              error            `yaml:\"-\"`\n\ttemplateBuffer      bytes.Buffer     `yaml:\"-\"`\n\tcacheDuration       time.Duration    `yaml:\"-\"`\n\tcacheType           cacheType        `yaml:\"-\"`\n\tnextUpdate          time.Time        `yaml:\"-\"`\n\tupdateRetriedTimes  int              `yaml:\"-\"`\n}\n\ntype widgetProviders struct {\n\tassetResolver func(string) string\n}\n\nfunc (w *widgetBase) requiresUpdate(now *time.Time) bool {\n\tif w.cacheType == cacheTypeInfinite {\n\t\treturn false\n\t}\n\n\tif w.nextUpdate.IsZero() {\n\t\treturn true\n\t}\n\n\treturn now.After(w.nextUpdate)\n}\n\nfunc (w *widgetBase) IsWIP() bool {\n\treturn w.WIP\n}\n\nfunc (w *widgetBase) update(ctx context.Context) {\n\n}\n\nfunc (w *widgetBase) GetID() uint64 {\n\treturn w.ID\n}\n\nfunc (w *widgetBase) setID(id uint64) {\n\tw.ID = id\n}\n\nfunc (w *widgetBase) setHideHeader(value bool) {\n\tw.HideHeader = value\n}\n\nfunc (widget *widgetBase) handleRequest(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"not implemented\", http.StatusNotImplemented)\n}\n\nfunc (w *widgetBase) GetType() string {\n\treturn w.Type\n}\n\nfunc (w *widgetBase) setProviders(providers *widgetProviders) {\n\tw.Providers = providers\n}\n\nfunc (w *widgetBase) renderTemplate(data any, t *template.Template) template.HTML {\n\tw.templateBuffer.Reset()\n\terr := t.Execute(&w.templateBuffer, data)\n\tif err != nil {\n\t\tw.ContentAvailable = false\n\t\tw.Error = err\n\n\t\tslog.Error(\"Failed to render template\", \"error\", err)\n\n\t\t// need to immediately re-render with the error,\n\t\t// otherwise risk breaking the page since the widget\n\t\t// will likely be partially rendered with tags not closed.\n\t\tw.templateBuffer.Reset()\n\t\terr2 := t.Execute(&w.templateBuffer, data)\n\n\t\tif err2 != nil {\n\t\t\tslog.Error(\"Failed to render error within widget\", \"error\", err2, \"initial_error\", err)\n\t\t\tw.templateBuffer.Reset()\n\t\t\t// TODO: add some kind of a generic widget error template when the widget\n\t\t\t// failed to render, and we also failed to re-render the widget with the error\n\t\t}\n\t}\n\n\treturn template.HTML(w.templateBuffer.String())\n}\n\nfunc (w *widgetBase) withTitle(title string) *widgetBase {\n\tif w.Title == \"\" {\n\t\tw.Title = title\n\t}\n\n\treturn w\n}\n\nfunc (w *widgetBase) withTitleURL(titleURL string) *widgetBase {\n\tif w.TitleURL == \"\" {\n\t\tw.TitleURL = titleURL\n\t}\n\n\treturn w\n}\n\nfunc (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase {\n\tw.cacheType = cacheTypeDuration\n\n\tif duration == -1 || w.CustomCacheDuration == 0 {\n\t\tw.cacheDuration = duration\n\t} else {\n\t\tw.cacheDuration = time.Duration(w.CustomCacheDuration)\n\t}\n\n\treturn w\n}\n\nfunc (w *widgetBase) withCacheOnTheHour() *widgetBase {\n\tw.cacheType = cacheTypeOnTheHour\n\n\treturn w\n}\n\nfunc (w *widgetBase) withNotice(err error) *widgetBase {\n\tw.Notice = err\n\n\treturn w\n}\n\nfunc (w *widgetBase) withError(err error) *widgetBase {\n\tif err == nil && !w.ContentAvailable {\n\t\tw.ContentAvailable = true\n\t}\n\n\tw.Error = err\n\n\treturn w\n}\n\nfunc (w *widgetBase) canContinueUpdateAfterHandlingErr(err error) bool {\n\t// TODO: needs covering more edge cases.\n\t// if there's partial content and we update early there's a chance\n\t// the early update returns even less content than the initial update.\n\t// need some kind of mechanism that tells us whether we should update early\n\t// or not depending on the number of things that failed during the initial\n\t// and subsequent update and how they failed - ie whether it was server\n\t// error (like gateway timeout, do retry early) or client error (like\n\t// hitting a rate limit, don't retry early). will require reworking a\n\t// good amount of code in the feed package and probably having a custom\n\t// error type that holds more information because screw wrapping errors.\n\t// alternatively have a resource cache and only refetch the failed resources,\n\t// then rebuild the widget.\n\n\tif err != nil {\n\t\tw.scheduleEarlyUpdate()\n\n\t\tif !errors.Is(err, errPartialContent) {\n\t\t\tw.withError(err)\n\t\t\tw.withNotice(nil)\n\t\t\treturn false\n\t\t}\n\n\t\tw.withError(nil)\n\t\tw.withNotice(err)\n\t\treturn true\n\t}\n\n\tw.withNotice(nil)\n\tw.withError(nil)\n\tw.scheduleNextUpdate()\n\treturn true\n}\n\nfunc (w *widgetBase) getNextUpdateTime() time.Time {\n\tnow := time.Now()\n\n\tif w.cacheType == cacheTypeDuration {\n\t\treturn now.Add(w.cacheDuration)\n\t}\n\n\tif w.cacheType == cacheTypeOnTheHour {\n\t\treturn now.Add(time.Duration(\n\t\t\t((60-now.Minute())*60)-now.Second(),\n\t\t) * time.Second)\n\t}\n\n\treturn time.Time{}\n}\n\nfunc (w *widgetBase) scheduleNextUpdate() *widgetBase {\n\tw.nextUpdate = w.getNextUpdateTime()\n\tw.updateRetriedTimes = 0\n\n\treturn w\n}\n\nfunc (w *widgetBase) scheduleEarlyUpdate() *widgetBase {\n\tw.updateRetriedTimes++\n\n\tif w.updateRetriedTimes > 5 {\n\t\tw.updateRetriedTimes = 5\n\t}\n\n\tnextEarlyUpdate := time.Now().Add(time.Duration(math.Pow(float64(w.updateRetriedTimes), 2)) * time.Minute)\n\tnextUsualUpdate := w.getNextUpdateTime()\n\n\tif nextEarlyUpdate.After(nextUsualUpdate) {\n\t\tw.nextUpdate = nextUsualUpdate\n\t} else {\n\t\tw.nextUpdate = nextEarlyUpdate\n\t}\n\n\treturn w\n}\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"os\"\n\n\t\"github.com/glanceapp/glance/internal/glance\"\n)\n\nfunc main() {\n\tos.Exit(glance.Main())\n}\n"
  },
  {
    "path": "pkg/sysinfo/sysinfo.go",
    "content": "package sysinfo\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/cpu\"\n\t\"github.com/shirou/gopsutil/v4/disk\"\n\t\"github.com/shirou/gopsutil/v4/host\"\n\t\"github.com/shirou/gopsutil/v4/load\"\n\t\"github.com/shirou/gopsutil/v4/mem\"\n\t\"github.com/shirou/gopsutil/v4/sensors\"\n)\n\ntype timestampJSON struct {\n\ttime.Time\n}\n\nfunc (t timestampJSON) MarshalJSON() ([]byte, error) {\n\treturn []byte(strconv.FormatInt(t.Unix(), 10)), nil\n}\n\nfunc (t *timestampJSON) UnmarshalJSON(data []byte) error {\n\ti, err := strconv.ParseInt(string(data), 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.Time = time.Unix(i, 0)\n\treturn nil\n}\n\ntype SystemInfo struct {\n\tHostInfoIsAvailable bool          `json:\"host_info_is_available\"`\n\tBootTime            timestampJSON `json:\"boot_time\"`\n\tHostname            string        `json:\"hostname\"`\n\tPlatform            string        `json:\"platform\"`\n\n\tCPU struct {\n\t\tLoadIsAvailable bool  `json:\"load_is_available\"`\n\t\tLoad1Percent    uint8 `json:\"load1_percent\"`\n\t\tLoad15Percent   uint8 `json:\"load15_percent\"`\n\n\t\tTemperatureIsAvailable bool  `json:\"temperature_is_available\"`\n\t\tTemperatureC           uint8 `json:\"temperature_c\"`\n\t} `json:\"cpu\"`\n\n\tMemory struct {\n\t\tIsAvailable bool   `json:\"memory_is_available\"`\n\t\tTotalMB     uint64 `json:\"total_mb\"`\n\t\tUsedMB      uint64 `json:\"used_mb\"`\n\t\tUsedPercent uint8  `json:\"used_percent\"`\n\n\t\tSwapIsAvailable bool   `json:\"swap_is_available\"`\n\t\tSwapTotalMB     uint64 `json:\"swap_total_mb\"`\n\t\tSwapUsedMB      uint64 `json:\"swap_used_mb\"`\n\t\tSwapUsedPercent uint8  `json:\"swap_used_percent\"`\n\t} `json:\"memory\"`\n\n\tMountpoints []MountpointInfo `json:\"mountpoints\"`\n}\n\ntype MountpointInfo struct {\n\tPath        string `json:\"path\"`\n\tName        string `json:\"name\"`\n\tTotalMB     uint64 `json:\"total_mb\"`\n\tUsedMB      uint64 `json:\"used_mb\"`\n\tUsedPercent uint8  `json:\"used_percent\"`\n}\n\ntype SystemInfoRequest struct {\n\tCPUTempSensor            string                       `yaml:\"cpu-temp-sensor\"`\n\tHideMountpointsByDefault bool                         `yaml:\"hide-mountpoints-by-default\"`\n\tMountpoints              map[string]MointpointRequest `yaml:\"mountpoints\"`\n}\n\ntype MointpointRequest struct {\n\tName string `yaml:\"name\"`\n\tHide *bool  `yaml:\"hide\"`\n}\n\n// Currently caches hostname indefinitely which isn't ideal\n// Potential issue with caching boot time as it may not initially get reported correctly:\n// https://github.com/shirou/gopsutil/issues/842#issuecomment-1908972344\ntype cacheableHostInfo struct {\n\tavailable bool\n\thostname  string\n\tplatform  string\n\tbootTime  timestampJSON\n}\n\nvar cachedHostInfo cacheableHostInfo\n\nfunc getHostInfo() (cacheableHostInfo, error) {\n\tvar err error\n\tinfo := cacheableHostInfo{}\n\n\tinfo.hostname, err = os.Hostname()\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\tinfo.platform, _, _, err = host.PlatformInformation()\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\tbootTime, err := host.BootTime()\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\tinfo.bootTime = timestampJSON{time.Unix(int64(bootTime), 0)}\n\tinfo.available = true\n\n\treturn info, nil\n}\n\nfunc Collect(req *SystemInfoRequest) (*SystemInfo, []error) {\n\tif req == nil {\n\t\treq = &SystemInfoRequest{}\n\t}\n\n\tvar errs []error\n\n\taddErr := func(err error) {\n\t\terrs = append(errs, err)\n\t}\n\n\tinfo := &SystemInfo{\n\t\tMountpoints: []MountpointInfo{},\n\t}\n\n\tapplyCachedHostInfo := func() {\n\t\tinfo.HostInfoIsAvailable = true\n\t\tinfo.BootTime = cachedHostInfo.bootTime\n\t\tinfo.Hostname = cachedHostInfo.hostname\n\t\tinfo.Platform = cachedHostInfo.platform\n\t}\n\n\tif cachedHostInfo.available {\n\t\tapplyCachedHostInfo()\n\t} else {\n\t\thostInfo, err := getHostInfo()\n\t\tif err == nil {\n\t\t\tcachedHostInfo = hostInfo\n\t\t\tapplyCachedHostInfo()\n\t\t} else {\n\t\t\taddErr(fmt.Errorf(\"getting host info: %v\", err))\n\t\t}\n\t}\n\n\tcoreCount, err := cpu.Counts(true)\n\tif err == nil {\n\t\tloadAvg, err := load.Avg()\n\t\tif err == nil {\n\t\t\tinfo.CPU.LoadIsAvailable = true\n\t\t\tif runtime.GOOS == \"windows\" {\n\t\t\t\t// The numbers returned here seem unreliable on Windows. Even with the CPU pegged\n\t\t\t\t// at close to 50% for multiple minutes, load1 is sometimes way under or way over\n\t\t\t\t// with no clear pattern. Dividing by core count gives numbers that are way too\n\t\t\t\t// low so that's likely not necessary as it is with unix.\n\t\t\t\tinfo.CPU.Load1Percent = uint8(math.Min(loadAvg.Load1*100, 100))\n\t\t\t\tinfo.CPU.Load15Percent = uint8(math.Min(loadAvg.Load15*100, 100))\n\t\t\t} else {\n\t\t\t\tinfo.CPU.Load1Percent = uint8(math.Min((loadAvg.Load1/float64(coreCount))*100, 100))\n\t\t\t\tinfo.CPU.Load15Percent = uint8(math.Min((loadAvg.Load15/float64(coreCount))*100, 100))\n\t\t\t}\n\t\t} else {\n\t\t\taddErr(fmt.Errorf(\"getting load avg: %v\", err))\n\t\t}\n\t} else {\n\t\taddErr(fmt.Errorf(\"getting core count: %v\", err))\n\t}\n\n\tmemory, err := mem.VirtualMemory()\n\tif err == nil {\n\t\tinfo.Memory.IsAvailable = true\n\t\tinfo.Memory.TotalMB = memory.Total / 1024 / 1024\n\t\tinfo.Memory.UsedMB = memory.Used / 1024 / 1024\n\t\tinfo.Memory.UsedPercent = uint8(math.Min(memory.UsedPercent, 100))\n\t} else {\n\t\taddErr(fmt.Errorf(\"getting memory info: %v\", err))\n\t}\n\n\tswapMemory, err := mem.SwapMemory()\n\tif err == nil {\n\t\tinfo.Memory.SwapIsAvailable = true\n\t\tinfo.Memory.SwapTotalMB = swapMemory.Total / 1024 / 1024\n\t\tinfo.Memory.SwapUsedMB = swapMemory.Used / 1024 / 1024\n\t\tinfo.Memory.SwapUsedPercent = uint8(math.Min(swapMemory.UsedPercent, 100))\n\t} else {\n\t\taddErr(fmt.Errorf(\"getting swap memory info: %v\", err))\n\t}\n\n\t// currently disabled on Windows because it requires elevated privilidges, otherwise\n\t// keeps returning a single sensor with key \"ACPI\\\\ThermalZone\\\\TZ00_0\" which\n\t// doesn't seem to be the CPU sensor or correspond to anything useful when\n\t// compared against the temperatures Libre Hardware Monitor reports.\n\t// Also disabled on the bsd's because it's not implemented by go-psutil for them\n\tif runtime.GOOS != \"windows\" && runtime.GOOS != \"openbsd\" && runtime.GOOS != \"netbsd\" && runtime.GOOS != \"freebsd\" {\n\t\tsensorReadings, err := sensors.SensorsTemperatures()\n\t\t_, errIsWarning := err.(*sensors.Warnings)\n\t\tif err == nil || errIsWarning {\n\t\t\tif req.CPUTempSensor != \"\" {\n\t\t\t\tfor i := range sensorReadings {\n\t\t\t\t\tif sensorReadings[i].SensorKey == req.CPUTempSensor {\n\t\t\t\t\t\tinfo.CPU.TemperatureIsAvailable = true\n\t\t\t\t\t\tinfo.CPU.TemperatureC = uint8(sensorReadings[i].Temperature)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !info.CPU.TemperatureIsAvailable {\n\t\t\t\t\taddErr(fmt.Errorf(\"CPU temperature sensor %s not found\", req.CPUTempSensor))\n\t\t\t\t}\n\t\t\t} else if cpuTempSensor := inferCPUTempSensor(sensorReadings); cpuTempSensor != nil {\n\t\t\t\tinfo.CPU.TemperatureIsAvailable = true\n\t\t\t\tinfo.CPU.TemperatureC = uint8(cpuTempSensor.Temperature)\n\t\t\t}\n\t\t} else {\n\t\t\taddErr(fmt.Errorf(\"getting sensor readings: %v\", err))\n\t\t}\n\t}\n\n\taddedMountpoints := map[string]struct{}{}\n\taddMountpointInfo := func(requestedPath string, mpReq MointpointRequest) {\n\t\tif _, exists := addedMountpoints[requestedPath]; exists {\n\t\t\treturn\n\t\t}\n\n\t\tisHidden := req.HideMountpointsByDefault\n\t\tif mpReq.Hide != nil {\n\t\t\tisHidden = *mpReq.Hide\n\t\t}\n\t\tif isHidden {\n\t\t\treturn\n\t\t}\n\n\t\tusage, err := disk.Usage(requestedPath)\n\t\tif err == nil {\n\t\t\tmpInfo := MountpointInfo{\n\t\t\t\tPath:        requestedPath,\n\t\t\t\tName:        mpReq.Name,\n\t\t\t\tTotalMB:     usage.Total / 1024 / 1024,\n\t\t\t\tUsedMB:      usage.Used / 1024 / 1024,\n\t\t\t\tUsedPercent: uint8(math.Min(usage.UsedPercent, 100)),\n\t\t\t}\n\n\t\t\tinfo.Mountpoints = append(info.Mountpoints, mpInfo)\n\t\t\taddedMountpoints[requestedPath] = struct{}{}\n\t\t} else {\n\t\t\taddErr(fmt.Errorf(\"getting filesystem usage for %s: %v\", requestedPath, err))\n\t\t}\n\t}\n\n\tif !req.HideMountpointsByDefault {\n\t\tfilesystems, err := disk.Partitions(false)\n\t\tif err == nil {\n\t\t\tfor _, fs := range filesystems {\n\t\t\t\taddMountpointInfo(fs.Mountpoint, req.Mountpoints[fs.Mountpoint])\n\t\t\t}\n\t\t} else {\n\t\t\taddErr(fmt.Errorf(\"getting filesystems: %v\", err))\n\t\t}\n\t}\n\n\tfor mountpoint, mpReq := range req.Mountpoints {\n\t\taddMountpointInfo(mountpoint, mpReq)\n\t}\n\n\tsort.Slice(info.Mountpoints, func(a, b int) bool {\n\t\treturn info.Mountpoints[a].UsedPercent > info.Mountpoints[b].UsedPercent\n\t})\n\n\treturn info, errs\n}\n\nfunc inferCPUTempSensor(sensors []sensors.TemperatureStat) *sensors.TemperatureStat {\n\tfor i := range sensors {\n\t\tswitch sensors[i].SensorKey {\n\t\tcase\n\t\t\t\"coretemp_package_id_0\", // intel / linux\n\t\t\t\"coretemp\",              // intel / linux\n\t\t\t\"k10temp\",               // amd / linux\n\t\t\t\"zenpower\",              // amd / linux\n\t\t\t\"cpu_thermal\":           // raspberry pi / linux\n\t\t\treturn &sensors[i]\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  }
]