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

What if you could see everything at a...

+

Glance

+

InstallConfigurationThemes

+ +![example homepage](docs/images/readme-main-image.png) + +### Features +#### Various widgets +* RSS feeds +* Subreddit posts +* Weather +* Bookmarks +* Latest YouTube videos from specific channels +* Calendar +* Stocks +* iframe +* Twitch channels & top games +* GitHub releases +* Site monitor + +#### Themeable +![multiple color schemes example](docs/images/themes-example.png) + +#### Optimized for mobile devices +![mobile device previews](docs/images/mobile-preview.png) + +#### Fast and lightweight +* Minimal JS, no bloated frameworks +* Very few dependencies +* Single, easily distributed <15mb binary and just as small docker container +* All requests are parallelized, uncached pages usually load within ~1s (depending on internet speed and number of widgets) + +### Configuration +Checkout the [configuration docs](docs/configuration.md) to learn more. A [preconfigured page](docs/configuration.md#preconfigured-page) is also available to get you started quickly. + +### Installation +> [!CAUTION] +> +> The project is under active development, expect things to break every once in a while. + +#### Manual +Checkout the [releases page](https://github.com/glanceapp/glance/releases) for available binaries. You can place the binary inside `/opt/glance/` and have it start with your server via a [systemd service](https://linuxhandbook.com/create-systemd-services/). To specify a different path for the config file use the `--config` option: + +``` +/opt/glance/glance --config /etc/glance.yml +``` + +#### Docker +> [!IMPORTANT] +> +> Make sure you have a valid `glance.yml` file before running the container. + +```console +docker run -d -p 8080:8080 \ + -v ./glance.yml:/app/glance.yml \ + -v /etc/timezone:/etc/timezone:ro \ + -v /etc/localtime:/etc/localtime:ro \ + glanceapp/glance +``` + +Or if you prefer docker compose: + +```yaml +services: + glance: + image: glanceapp/glance + volumes: + - ./glance.yml:/app/glance.yml + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + ports: + - 8080:8080 + restart: unless-stopped +``` + +### Building from source + +Requirements: [Go](https://go.dev/dl/) >= v1.22 + +To build: + +``` +go build . +``` + +To run: + +``` +go run . +``` diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..1f7052a --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,873 @@ +# Configuration + +- [Intro](#intro) +- [Preconfigured page](#preconfigured-page) +- [Server](#server) +- [Theme](#theme) + - [Themes](#themes) +- [Pages & Columns](#pages--columns) +- [Widgets](#widgets) + - [RSS](#rss) + - [Videos](#videos) + - [Hacker News](#hacker-news) + - [Reddit](#reddit) + - [Weather](#weather) + - [Monitor](#monitor) + - [Releases](#releases) + - [Bookmarks](#bookmarks) + - [Calendar](#calendar) + - [Stocks](#stocks) + - [Twitch Channels](#twitch-channels) + - [Twitch Top Games](#twitch-top-games) + - [iframe](#iframe) + +## Intro +Configuration is done via a single YAML file and a server restart is required in order for any changes to take effect. Trying to start the server with an invalid config file will result in an error. + +## Preconfigured page +If you don't want to spend time reading through all the available configuration options and just want something to get you going quickly you can use the following `glance.yml` and make changes as you see fit: + +```yaml +pages: + - name: Home + columns: + - size: small + widgets: + - type: calendar + + - type: rss + limit: 10 + collapse-after: 3 + cache: 3h + feeds: + - url: https://ciechanow.ski/atom.xml + - url: https://www.joshwcomeau.com/rss.xml + title: Josh Comeau + - url: https://samwho.dev/rss.xml + - url: https://awesomekling.github.io/feed.xml + - url: https://ishadeed.com/feed.xml + title: Ahmad Shadeed + + - type: twitch-channels + channels: + - theprimeagen + - cohhcarnage + - christitustech + - blurbs + - asmongold + - jembawls + + - size: full + widgets: + - type: hacker-news + + - type: videos + channels: + - UCR-DXc1voovS8nhAvccRZhg # Jeff Geerling + - UCv6J_jJa8GJqFwQNgNrMuww # ServeTheHome + - UCOk-gHyjcWZNj3Br4oxwh0A # Techno Tim + + - type: reddit + subreddit: selfhosted + + - size: small + widgets: + - type: weather + location: London, United Kingdom + + - type: stocks + stocks: + - symbol: SPY + name: S&P 500 + - symbol: BTC-USD + name: Bitcoin + - symbol: NVDA + name: NVIDIA + - symbol: AAPL + name: Apple + - symbol: MSFT + name: Microsoft + - symbol: GOOGL + name: Google + - symbol: AMD + name: AMD + - symbol: RDDT + name: Reddit +``` + +This will give you a page that looks like the following: + +![](images/preconfigured-page-preview.png) + +Configure the widgets, add more of them, add extra pages, etc. Make it your own! + +## Server +Server configuration is done through a top level `server` property. Example: + +```yaml +server: + port: 8080 + assets-path: /home/user/glance-assets +``` + +### Properties + +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| host | string | no | | +| port | number | no | 8080 | +| assets-path | string | no | | + +#### `host` +The address which the server will listen on. Setting it to `localhost` means that only the machine that the server is running on will be able to access the dashboard. By default it will listen on all interfaces. + +#### `port` +A number between 1 and 65,535, so long as that port isn't already used by anything else. + +#### `assets-path` +The path to a directory that will be served by the server under the `/assets/` path. This is handy for widgets like the Monitor where you have to specify an icon URL and you want to self host all the icons rather than pointing to an external source. + +> [!IMPORTANT] +> +> When installing through docker the path will point to the files inside the container. Don't forget to mount your assets path to the same path inside the container. +> Example: +> +> If your assets are in: +> ``` +> /home/user/glance-assets +> ``` +> +> You should mount: +> ``` +> /home/user/glance-assets:/app/assets +> ``` +> +> And your config should contain: +> ``` +> assets-path: /app/assets +> ``` + +##### Examples + +Say you have a directory `glance-assets` with a file `gitea-icon.png` in it and you specify your assets path like: + +```yaml +assets-path: /home/user/glance-assets +``` + +To be able to point to an asset from your assets path, use the the `/assets/` path like such: + +```yaml +icon: /assets/gitea-icon.png +``` + +## Theme +Theming is done through a top level `theme` property. Values for the colors are in [HSL](https://giggster.com/guide/basics/hue-saturation-lightness/) (hue, saturation, lightness) format. You can use a color picker [like this one](https://hslpicker.com/) to convert colors from other formats to HSL. The values are separated by a space and `%` is not required for any of the numbers. + +Example: + +```yaml +theme: + background-color: 100 20 10 + primary-color: 40 90 40 + contrast-multiplier: 1.1 +``` + +### Themes +If you don't want to spend time configuring your own theme, there are [several available themes](preconfigured-themes.md) which you can simply copy the values for. + +### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| light | bool | no | false | +| background-color | HSL | no | 240 8 9 | +| primary-color | HSL | no | 43 50 70 | +| positive-color | HSL | no | same as `primary-color` | +| negative-color | HSL | no | 0 70 70 | +| contrast-multiplier | number | no | 1 | +| text-saturation-multiplier | number | no | 1 | + +#### `light` +Whether the scheme is light or dark. This does not change the background color, it inverts the text colors so that they look appropriately on a light background. + +#### `background-color` +Color of the page and widgets. + +#### `primary-color` +Color used across the page, largely to indicate unvisited links. + +#### `positive-color` +Used to indicate that something is positive, such as stock price being up, twitch channel being live or a monitored site being online. If not set, the value of `primary-color` will be used. + +#### `negative-color` +Oppposite of `positive-color`. + +#### `contrast-multiplier` +Used to increase or decrease the contrast (in other words visibility) of the text. A value of `1.3` means that the text will be 30% lighter/darker depending on the scheme. Use this if you think that some of the text on the page is too dark and hard to read. Example: + +![difference between 1 and 1.3 contrast](images/contrast-multiplier-example.png) + +#### `text-saturation-multiplier` +Used to increase or decrease the saturation of text, useful when using a custom background color with a high amount of saturation and needing the text to have a more neutral color. `0.5` means that the saturation will be 50% lower and `1.5` means that it'll be 50% higher. + + +## Pages & Columns +![illustration of pages and columns](images/pages-and-columns-illustration.png) + +Using pages and columns is how widgets are organized. Each page contains up to 3 columns and each column can have any number of widgets. + +### Pages +Pages are defined through a top level `pages` property. The page defined first becomes the home page and all pages get automatically added to the navigation bar in the order that they were defined. Example: + +```yaml +pages: + - name: Home + columns: ... + + - name: Videos + columns: ... + + - name: Homelab + columns: ... +``` + +### Properties +| Name | Type | Required | +| ---- | ---- | -------- | +| title | string | yes | +| slug | string | no | +| columns | array | yes | + +#### `title` +The name of the page which gets shown in the navigation bar. + +#### `slug` +The URL friendly version of the title which is used to access the page. For example if the title of the page is "RSS Feeds" you can make the page accessible via `localhost:8080/feeds` by setting the slug to `feeds`. If not defined, it will automatically be generated from the title. + +### Columns +Columns are defined for each page using a `columns` property. There are two types of columns - `full` and `small`, which refers to their width. A small column takes up a fixed amount of width (300px) and a full column takes up the all of the remaining width. You can have up to 3 columns per page and you must have either 1 or 2 full columns. Example: + +```yaml +pages: + - name: Home + columns: + - size: small + widgets: ... + - size: full + widgets: ... + - size: small + widgets: ... +``` + +### Properties +| Name | Type | Required | +| ---- | ---- | -------- | +| size | string | yes | +| widgets | array | no | + +Here are some of the possible column configurations: + +![column configuration small-full-small](images/column-configuration-1.png) + +```yaml +columns: + - size: small + widgets: ... + - size: full + widgets: ... + - size: small + widgets: ... +``` + +![column configuration small-full-small](images/column-configuration-2.png) + +```yaml +columns: + - size: full + widgets: ... + - size: small + widgets: ... +``` + +![column configuration small-full-small](images/column-configuration-3.png) + +```yaml +columns: + - size: full + widgets: ... + - size: full + widgets: ... +``` + +## Widgets +Widgets are defined for each column using a `widgets` property. Example: + +```yaml +pages: + - name: Home + columns: + - size: small + widgets: + - type: weather + location: London, United Kingdom +``` + +> [!NOTE] +> +> Currently not all widgets are designed to fit every column size, however some widgets offer different "styles" that help alleviate this limitation. + +### Shared Properties +| Name | Type | Required | +| ---- | ---- | -------- | +| type | string | yes | +| title | string | no | +| cache | string | no | + +#### `type` +Used to specify the widget. + +#### `title` +The title of the widget. If left blank it will be defined by the widget. + +#### `cache` +How long to keep the fetched data in memory. The value is a string and must be a number followed by one of s, m, h, d. Examples: + +```yaml +cache: 30s # 30 seconds +cache: 5m # 5 minutes +cache: 2h # 2 hours +cache: 1d # 1 day +``` + +> [!NOTE] +> +> Not all widgets can have their cache duration modified. The calendar and weather widgets update on the hour and this cannot be changed. + +### RSS +Display a list of articles from multiple RSS feeds. + +Example: + +```yaml +- type: rss + title: News + style: horizontal-cards + feeds: + - url: https://feeds.bloomberg.com/markets/news.rss + title: Bloomberg + - url: https://moxie.foxbusiness.com/google-publisher/markets.xml + title: Fox Business + - url: https://moxie.foxbusiness.com/google-publisher/technology.xml + title: Fox Business +``` + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| style | string | no | vertical-list | +| feeds | array | yes | +| limit | integer | no | 25 | +| collapse-after | integer | no | 5 | + +##### `style` +Used to change the appearance of the widget. Possible values are `vertical-list` and `horizontal-cards` where the former is intended to be used within a small column and the latter a full column. Below are previews of each style. + +`vertical-list` + +![preview of vertical-list style for RSS widget](images/rss-feed-vertical-list-preview.png) + +`horizontal-cards` + +![preview of horizontal-cards style for RSS widget](images/rss-feed-horizontal-cards-preview.png) + +##### `feeds` +An array of RSS/atom feeds. The title can optionally be changed. + +###### Properties for each feed +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| url | string | yes | | +| title | string | no | the title provided by the feed | + +##### `limit` +The maximum number of articles to show. + +##### `collapse-after` +How many articles are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. + +### Videos +Display a list of the latest videos from specific YouTube channels. + +Example: + +```yaml +- type: videos + channels: + - UCXuqSBlHAE6Xw-yeJA0Tunw + - UCBJycsmduvYEL83R_U4JriQ + - UCHnyfMqiRRG1u-2MsSQLbXA +``` + +Preview: +![](images/videos-widget-preview.png) + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| channels | array | yes | | +| limit | integer | no | 25 | + +##### `channels` +A list of channel IDs. One way of getting the ID of a channel is going to the channel's page and clicking on its description: + +![](images/videos-channel-description-example.png) + +Then scroll down and click on "Share channel", then "Copy channel ID": + +![](images/videos-copy-channel-id-example.png) + +##### `limit` +The maximum number of videos to show. + +### Hacker News +Display a list of posts from [Hacker News](https://news.ycombinator.com/). + +Example: + +```yaml +- type: hacker-news + limit: 15 + collapse-after: 5 +``` + +Preview: +![](images/hacker-news-widget-preview.png) + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| limit | integer | no | 15 | +| collapse-after | integer | no | 5 | + +### Reddit +Display a list of posts from a specific subreddit. + +Example: + +```yaml +- type: reddit + subreddit: technology +``` + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| subreddit | string | yes | | +| style | string | no | vertical-list | +| limit | integer | no | 15 | +| collapse-after | integer | no | 5 | + +##### `subreddit` +The subreddit for which to fetch the posts from. + +##### `style` +Used to change the appearance of the widget. Possible values are `vertical-list`, `horizontal-cards` and `vertical-cards`. The first two were designed for full columns and the last for small columns. + +`vertical-list` + +![](images/reddit-widget-preview.png) + +`horizontal-cards` + +![](images/reddit-widget-horizontal-cards-preview.png) + +`vertical-cards` + +![](images/reddit-widget-vertical-cards-preview.png) + +##### `limit` +The maximum number of posts to show. + +##### `collapse-after` +How many posts are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. Not available when using the `vertical-cards` and `horizontal-cards` styles. + +### Weather +Display weather information for a specific location. The data is provided by https://open-meteo.com/. + +Example: + +```yaml +- type: weather + location: London, United Kingdom +``` + +Preview: + +![](images/weather-widget-preview.png) + +Each bar represents a 2 hour interval. The yellow background represents sunrise and sunset. The blue dots represent the times of the day where there is a high chance for precipitation. You can hover over the bars to view the exact temperature for that time. + +#### Properties + +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| location | string | yes | | +| hide-location | boolean | no | false | + +##### `location` +The name of the city and country to fetch weather information for. Attempting to launch the applcation with an invalid location will result in an error. You can use the [gecoding API page](https://open-meteo.com/en/docs/geocoding-api) to search for your specific location. Glance will use the first result from the list if there are multiple. + +##### `hide-location` +Optionally don't display the location name on the widget. + +### Monitor +Display a list of sites and whether they are reachable (online) or not. This is determined by sending a HEAD request to the specified URL, if the response is 200 then the site is OK. The time it took to receive a response is also shown in milliseconds. + +Example: + +```yaml +- type: monitor + cache: 1m + title: Services + sites: + - title: Jellyfin + url: https://jellyfin.yourdomain.com + icon: /assets/jellyfin-logo.png + - title: Gitea + url: https://gitea.yourdomain.com + icon: /assets/gitea-logo.png + - title: Immich + url: https://immich.yourdomain.com + icon: /assets/immich-logo.png + - title: AdGuard Home + url: https://adguard.yourdomain.com + icon: /assets/adguard-logo.png + - title: Vaultwarden + url: https://vault.yourdomain.com + icon: /assets/vaultwarden-logo.png + +``` + +Preview: + +![](images/monitor-widget-preview.png) + +You can hover over the "ERROR" text to view more information. + +#### Properties + +| Name | Type | Required | +| ---- | ---- | -------- | +| sites | array | yes | | + +##### `sites` + +Properties for each site: + +| Name | Type | Required | +| ---- | ---- | -------- | +| title | string | yes | +| url | string | yes | +| icon | string | no | + +`title` + +The title used to indicate the site. + +`url` + +The URL which will be requested and its response will determine the status of the site. + +`icon` + +Optional URL to an image which will be used as the icon for the site. Can be an external URL or internal via [server configured assets](#assets-path). + +### Releases +Display a list of releases for specific repositories on Github. Draft releases and prereleases will not be shown. + +Example: + +```yaml +- type: releases + repositories: + - immich-app/immich + - go-gitea/gitea + - dani-garcia/vaultwarden + - jellyfin/jellyfin +``` + +Preview: + +![](images/releases-widget-preview.png) + +#### Properties + +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| repositories | array | yes | | +| token | string | no | | +| limit | integer | no | 10 | +| collapse-after | integer | no | 5 | + +##### `repositories` +A list of repositores for which to fetch the latest release for. Only the name/repo is required, not the full URL. + +##### `token` +Without authentication Github allows for up to 60 requests per hour. You can easily exceed this limit and start seeing errors if you're tracking lots of repositories or your cache time is low. To circumvent this you can [create a read only token from your Github account](https://github.com/settings/personal-access-tokens/new) and provide it here. + +You can also specify the value for this token through an ENV variable using the syntax `${GITHUB_TOKEN}` where `GITHUB_TOKEN` is the name of the variable that holds the token. If you've installed Glance through docker you can specify the token in your docker-compose: + +```yaml +services: + glance: + image: glanceapp/glance + environment: + - GITHUB_TOKEN: +``` + +and then use it in your `glance.yml` like this: + +```yaml +- type: releases + token: ${GITHUB_TOKEN} + repositories: ... +``` + +This way you can safely check your `glance.yml` in version control without exposing the token. + +##### `limit` +The maximum number of releases to show. + +#### `collapse-after` +How many releases are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. + +### Bookmarks +Display a list of links which can be grouped. + +Example: + +```yaml +- type: bookmarks + groups: + - links: + - title: Gmail + url: https://mail.google.com/mail/u/0/ + - title: Amazon + url: https://www.amazon.com/ + - title: Github + url: https://github.com/ + - title: Wikipedia + url: https://en.wikipedia.org/ + - title: Entertainment + color: 10 70 50 + links: + - title: Netflix + url: https://www.netflix.com/ + - title: Disney+ + url: https://www.disneyplus.com/ + - title: YouTube + url: https://www.youtube.com/ + - title: Prime Video + url: https://www.primevideo.com/ + - title: Social + color: 200 50 50 + links: + - title: Reddit + url: https://www.reddit.com/ + - title: Twitter + url: https://twitter.com/ + - title: Instagram + url: https://www.instagram.com/ +``` + +Preview: + +![](images/bookmarks-widget-preview.png) + + +#### Properties + +| Name | Type | Required | +| ---- | ---- | -------- | +| groups | array | yes | + +##### `groups` +An array of groups which can optionally have a title and a custom color. + +###### Properties for each group +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| title | string | no | | +| color | HSL | no | the primary theme color | +| links | array | yes | | + +###### Properties for each link +| Name | Type | Required | +| ---- | ---- | -------- | +| title | string | yes | +| url | string | yes | + +### Calendar +Display a calendar. + +Example: + +```yaml +- type: calendar +``` + +Preview: + +![](images/calendar-widget-preview.png) + +> [!NOTE] +> +> There is currently no customizability available for the calendar. Extra features will be added in the future. + +### Stocks +Display a list of stocks, their current value, change for the day and a small 21d chart. Data is taken from Yahoo Finance. + +Example: + +```yaml +- type: stocks + stocks: + - symbol: SPY + name: S&P 500 + - symbol: BTC-USD + name: Bitcoin + - symbol: NVDA + name: NVIDIA + - symbol: AAPL + name: Apple + - symbol: MSFT + name: Microsoft + - symbol: GOOGL + name: Google + - symbol: AMD + name: AMD + - symbol: RDDT + name: Reddit +``` + +Preview: + +![](images/stocks-widget-preview.png) + +#### Properties + +| Name | Type | Required | +| ---- | ---- | -------- | +| stocks | array | yes | + +##### `stocks` +An array of stocks for which to display information about. + +###### Properties for each stock +| Name | Type | Required | +| ---- | ---- | -------- | +| symbol | string | yes | +| name | string | no | + +`symbol` + +The symbol, as seen in Yahoo Finance. + +`name` + +The name that will be displayed under the symbol. + +### Twitch Channels +Display a list of channels from Twitch. + +Example: + +```yaml +- type: twitch-channels + channels: + - jembawls + - giantwaffle + - asmongold + - cohhcarnage + - j_blow + - xQc +``` + +Preview: + +![](images/twitch-channels-widget-preview.png) + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| channels | array | yes | | +| collapse-after | integer | no | 5 | + +##### `channels` +A list of channels to display. + +##### `collapse-after` +How many channels are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. + +### Twitch top games +Display a list of games with the most viewers on Twitch. + +Example: + +```yaml +- type: twitch-top-games + exclude: + - just-chatting + - pools-hot-tubs-and-beaches + - music + - art + - asmr +``` + +Preview: + +![](images/twitch-top-games-widget-preview.png) + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| exclude | array | no | | +| limit | integer | no | 10 | +| collapse-after | integer | no | 5 | + +##### `exclude` +A list of categories that will never be shown. You must provide the slug found by clicking on the category and looking at the URL: + +``` +https://www.twitch.tv/directory/category/grand-theft-auto-v + ^^^^^^^^^^^^^^^^^^ +``` + +##### `limit` +The maximum number of games to show. + +##### `collapse-after` +How many games are visible before the "SHOW MORE" button appears. Set to `-1` to never collapse. + +### iframe +Embed an iframe as a widget. + +Example: + +```yaml +- type: iframe + source: + height: 400 +``` + +#### Properties +| Name | Type | Required | Default | +| ---- | ---- | -------- | ------- | +| source | string | yes | | +| height | integer | no | 300 | + +##### `source` +The source of the iframe. + +##### `height` +The height of the iframe. The minimum allowed height is 50. diff --git a/docs/images/bookmarks-widget-preview.png b/docs/images/bookmarks-widget-preview.png new file mode 100644 index 0000000..4c9535f Binary files /dev/null and b/docs/images/bookmarks-widget-preview.png differ diff --git a/docs/images/calendar-widget-preview.png b/docs/images/calendar-widget-preview.png new file mode 100644 index 0000000..5a161bf Binary files /dev/null and b/docs/images/calendar-widget-preview.png differ diff --git a/docs/images/column-configuration-1.png b/docs/images/column-configuration-1.png new file mode 100644 index 0000000..1abc15b Binary files /dev/null and b/docs/images/column-configuration-1.png differ diff --git a/docs/images/column-configuration-2.png b/docs/images/column-configuration-2.png new file mode 100644 index 0000000..ee3b0b2 Binary files /dev/null and b/docs/images/column-configuration-2.png differ diff --git a/docs/images/column-configuration-3.png b/docs/images/column-configuration-3.png new file mode 100644 index 0000000..131a596 Binary files /dev/null and b/docs/images/column-configuration-3.png differ diff --git a/docs/images/contrast-multiplier-example.png b/docs/images/contrast-multiplier-example.png new file mode 100644 index 0000000..fed488d Binary files /dev/null and b/docs/images/contrast-multiplier-example.png differ diff --git a/docs/images/hacker-news-widget-preview.png b/docs/images/hacker-news-widget-preview.png new file mode 100644 index 0000000..2d87fc9 Binary files /dev/null and b/docs/images/hacker-news-widget-preview.png differ diff --git a/docs/images/mobile-preview.png b/docs/images/mobile-preview.png new file mode 100644 index 0000000..38acdcf Binary files /dev/null and b/docs/images/mobile-preview.png differ diff --git a/docs/images/monitor-widget-preview.png b/docs/images/monitor-widget-preview.png new file mode 100644 index 0000000..5f9594c Binary files /dev/null and b/docs/images/monitor-widget-preview.png differ diff --git a/docs/images/pages-and-columns-illustration.png b/docs/images/pages-and-columns-illustration.png new file mode 100644 index 0000000..75703d7 Binary files /dev/null and b/docs/images/pages-and-columns-illustration.png differ diff --git a/docs/images/preconfigured-page-preview.png b/docs/images/preconfigured-page-preview.png new file mode 100644 index 0000000..0a57c14 Binary files /dev/null and b/docs/images/preconfigured-page-preview.png differ diff --git a/docs/images/readme-main-image.png b/docs/images/readme-main-image.png new file mode 100644 index 0000000..821c35b Binary files /dev/null and b/docs/images/readme-main-image.png differ diff --git a/docs/images/reddit-widget-horizontal-cards-preview.png b/docs/images/reddit-widget-horizontal-cards-preview.png new file mode 100644 index 0000000..64e5dcf Binary files /dev/null and b/docs/images/reddit-widget-horizontal-cards-preview.png differ diff --git a/docs/images/reddit-widget-preview.png b/docs/images/reddit-widget-preview.png new file mode 100644 index 0000000..6a8d3c3 Binary files /dev/null and b/docs/images/reddit-widget-preview.png differ diff --git a/docs/images/reddit-widget-vertical-cards-preview.png b/docs/images/reddit-widget-vertical-cards-preview.png new file mode 100644 index 0000000..db62a2b Binary files /dev/null and b/docs/images/reddit-widget-vertical-cards-preview.png differ diff --git a/docs/images/releases-widget-preview.png b/docs/images/releases-widget-preview.png new file mode 100644 index 0000000..47acfd0 Binary files /dev/null and b/docs/images/releases-widget-preview.png differ diff --git a/docs/images/rss-feed-horizontal-cards-preview.png b/docs/images/rss-feed-horizontal-cards-preview.png new file mode 100644 index 0000000..b7703ea Binary files /dev/null and b/docs/images/rss-feed-horizontal-cards-preview.png differ diff --git a/docs/images/rss-feed-vertical-list-preview.png b/docs/images/rss-feed-vertical-list-preview.png new file mode 100644 index 0000000..7bf5d24 Binary files /dev/null and b/docs/images/rss-feed-vertical-list-preview.png differ diff --git a/docs/images/stocks-widget-preview.png b/docs/images/stocks-widget-preview.png new file mode 100644 index 0000000..283b877 Binary files /dev/null and b/docs/images/stocks-widget-preview.png differ diff --git a/docs/images/themes-example.png b/docs/images/themes-example.png new file mode 100644 index 0000000..e98fc14 Binary files /dev/null and b/docs/images/themes-example.png differ diff --git a/docs/images/themes/camouflage.png b/docs/images/themes/camouflage.png new file mode 100644 index 0000000..dc5cc52 Binary files /dev/null and b/docs/images/themes/camouflage.png differ diff --git a/docs/images/themes/catppuccin.png b/docs/images/themes/catppuccin.png new file mode 100644 index 0000000..3b8b575 Binary files /dev/null and b/docs/images/themes/catppuccin.png differ diff --git a/docs/images/themes/peachy.png b/docs/images/themes/peachy.png new file mode 100644 index 0000000..1bee620 Binary files /dev/null and b/docs/images/themes/peachy.png differ diff --git a/docs/images/themes/teal-city.png b/docs/images/themes/teal-city.png new file mode 100644 index 0000000..20f978d Binary files /dev/null and b/docs/images/themes/teal-city.png differ diff --git a/docs/images/themes/tucan.png b/docs/images/themes/tucan.png new file mode 100644 index 0000000..3cf2a76 Binary files /dev/null and b/docs/images/themes/tucan.png differ diff --git a/docs/images/themes/zebra.png b/docs/images/themes/zebra.png new file mode 100644 index 0000000..ec240c5 Binary files /dev/null and b/docs/images/themes/zebra.png differ diff --git a/docs/images/twitch-channels-widget-preview.png b/docs/images/twitch-channels-widget-preview.png new file mode 100644 index 0000000..40825a3 Binary files /dev/null and b/docs/images/twitch-channels-widget-preview.png differ diff --git a/docs/images/twitch-top-games-widget-preview.png b/docs/images/twitch-top-games-widget-preview.png new file mode 100644 index 0000000..cc63752 Binary files /dev/null and b/docs/images/twitch-top-games-widget-preview.png differ diff --git a/docs/images/videos-channel-description-example.png b/docs/images/videos-channel-description-example.png new file mode 100644 index 0000000..2418e6b Binary files /dev/null and b/docs/images/videos-channel-description-example.png differ diff --git a/docs/images/videos-copy-channel-id-example.png b/docs/images/videos-copy-channel-id-example.png new file mode 100644 index 0000000..178e514 Binary files /dev/null and b/docs/images/videos-copy-channel-id-example.png differ diff --git a/docs/images/videos-widget-preview.png b/docs/images/videos-widget-preview.png new file mode 100644 index 0000000..de1f801 Binary files /dev/null and b/docs/images/videos-widget-preview.png differ diff --git a/docs/images/weather-widget-preview.png b/docs/images/weather-widget-preview.png new file mode 100644 index 0000000..39ae8cf Binary files /dev/null and b/docs/images/weather-widget-preview.png differ diff --git a/docs/themes.md b/docs/themes.md new file mode 100644 index 0000000..a943f88 --- /dev/null +++ b/docs/themes.md @@ -0,0 +1,65 @@ +# Themes + +## Dark + +### Teal City +![screenshot](images/themes/teal-city.png) +```yaml +theme: + background-color: 225 14 15 + primary-color: 157 47 65 + contrast-multiplier: 1.1 +``` + +### Catppuccin +![screenshot](images/themes/catppuccin.png) +```yaml +theme: + background-color: 240 21 15 + contrast-multiplier: 1.2 + primary-color: 217 92 83 + positive-color: 115 54 76 + negative-color: 347 70 65 +``` + +### Camouflage +![screenshot](images/themes/camouflage.png) +```yaml +theme: + background-color: 186 21 20 + contrast-multiplier: 1.2 + primary-color: 97 13 80 +``` + +### Tucan +![screenshot](images/themes/tucan.png) +```yaml +theme: + background-color: 50 1 6 + primary-color: 24 97 58 + negative-color: 209 88 54 +``` + +## Light + +### Peachy +![screenshot](images/themes/peachy.png) +```yaml +theme: + light: true + background-color: 28 40 77 + primary-color: 155 100 20 + negative-color: 0 100 60 + contrast-multiplier: 1.1 + text-saturation-multiplier: 0.5 +``` + +### Zebra +![screenshot](images/themes/zebra.png) +```yaml +theme: + light: true + background-color: 0 0 95 + primary-color: 0 0 10 + negative-color: 0 90 50 +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..34f68ac --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module github.com/glanceapp/glance + +go 1.22.0 + +require ( + golang.org/x/text v0.14.0 + gopkg.in/yaml.v3 v3.0.1 + github.com/mmcdole/gofeed v1.3.0 +) + +require ( + github.com/PuerkitoBio/goquery v1.8.0 // indirect + github.com/andybalholm/cascadia v1.3.1 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + golang.org/x/net v0.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..50ff10f --- /dev/null +++ b/go.sum @@ -0,0 +1,35 @@ +github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0gta/U= +github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI= +github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c= +github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/mmcdole/gofeed v1.3.0 h1:5yn+HeqlcvjMeAI4gu6T+crm7d0anY85+M+v6fIFNG4= +github.com/mmcdole/gofeed v1.3.0/go.mod h1:9TGv2LcJhdXePDzxiuMnukhV2/zb6VtnZt1mS+SjkLE= +github.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23 h1:Zr92CAlFhy2gL+V1F+EyIuzbQNbSgP4xhTODZtrXUtk= +github.com/mmcdole/goxpp v1.1.1-0.20240225020742-a0c311522b23/go.mod h1:v+25+lT2ViuQ7mVxcncQ8ch1URund48oH+jhjiwEgS8= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU= +golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/assets/files.go b/internal/assets/files.go new file mode 100644 index 0000000..bfb2b4c --- /dev/null +++ b/internal/assets/files.go @@ -0,0 +1,15 @@ +package assets + +import ( + "embed" + "io/fs" +) + +//go:embed static +var _publicFS embed.FS + +//go:embed templates +var _templateFS embed.FS + +var PublicFS, _ = fs.Sub(_publicFS, "static") +var TemplateFS, _ = fs.Sub(_templateFS, "templates") diff --git a/internal/assets/static/favicon.png b/internal/assets/static/favicon.png new file mode 100644 index 0000000..8323483 Binary files /dev/null and b/internal/assets/static/favicon.png differ diff --git a/internal/assets/static/fonts/JetBrainsMono-Regular.woff2 b/internal/assets/static/fonts/JetBrainsMono-Regular.woff2 new file mode 100644 index 0000000..40da427 Binary files /dev/null and b/internal/assets/static/fonts/JetBrainsMono-Regular.woff2 differ diff --git a/internal/assets/static/main.css b/internal/assets/static/main.css new file mode 100644 index 0000000..4824536 --- /dev/null +++ b/internal/assets/static/main.css @@ -0,0 +1,1032 @@ +@font-face { + font-family: 'JetBrains Mono'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url('fonts/JetBrainsMono-Regular.woff2') format('woff2'); +} + +:root { + font-size: 10px; + + --scheme: ; + --bgh: 240; + --bgs: 8%; + --bgl: 9%; + --bghs: var(--bgh), var(--bgs); + --cm: 1; + --tsm: 1; + + --widget-gap: 25px; + --widget-content-vertical-padding: 15px; + --widget-content-horizontal-padding: 17px; + --widget-content-padding: var(--widget-content-vertical-padding) var(--widget-content-horizontal-padding); + --content-bounds-padding: 15px; + --border-radius: 5px; + --mobile-navigation-height: 50px; + + --color-primary: hsl(43, 50%, 70%); + --color-positive: var(--color-primary); + --color-negative: hsl(0, 70%, 70%); + --color-background: hsl(var(--bghs), var(--bgl)); + --color-widget-background-hsl-values: var(--bghs), calc(var(--bgl) + 1%); + --color-widget-background: hsl(var(--color-widget-background-hsl-values)); + --color-separator: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 4% * var(--cm)))); + --color-widget-content-border: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 4%))); + + --ths: var(--bgh), calc(var(--bgs) * var(--tsm)); + --color-text-base: hsl(var(--ths), calc(var(--scheme) var(--cm) * 58%)); + --color-text-highlight: hsl(var(--ths), calc(var(--scheme) var(--cm) * 85%)); + --color-text-subdue: hsl(var(--ths), calc(var(--scheme) var(--cm) * 35%)); + + --font-size-h1: 1.7rem; + --font-size-h2: 1.6rem; + --font-size-h3: 1.5rem; + --font-size-h4: 1.4rem; + --font-size-base: 1.3rem; + --font-size-h5: 1.2rem; + --font-size-h6: 1.1rem; +} + +.light-scheme { + --scheme: 100% -; +} + +.size-title-dynamic { + font-size: var(--font-size-h4); +} + +.page-column-full .size-title-dynamic { + font-size: var(--font-size-h3); +} + +.color-primary-if-not-visited:not(:visited) { + color: var(--color-primary); +} + +.text-truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.text-truncate-3-lines { + overflow: hidden; + text-overflow: ellipsis; + -webkit-line-clamp: 3; + display: -webkit-box; + -webkit-box-orient: vertical; +} + +.visited-indicator:not(.text-truncate)::after, +.visited-indicator.text-truncate::before, +.bookmarks-link::after { + content: '↗'; + margin-left: 0.5em; + display: inline-block; + position: relative; + top: 0.15em; + color: var(--color-text-base); +} + +.visited-indicator.text-truncate { + direction: rtl; + text-align: left; +} + +.visited-indicator:not(:visited)::before, .visited-indicator:not(:visited)::after { + color: var(--color-primary); +} + +.list { --list-half-gap: 0rem; } +.list-gap-2 { --list-half-gap: 0.1rem; } +.list-gap-4 { --list-half-gap: 0.2rem; } +.list-gap-14 { --list-half-gap: 0.7rem; } +.list-gap-20 { --list-half-gap: 1rem; } +.list-gap-24 { --list-half-gap: 1.2rem; } + +.list > *:not(:first-child) { + margin-top: calc(var(--list-half-gap) * 2 + 1px); +} + +.list-with-separator > *:not(:first-child) { + margin-top: var(--list-half-gap); + border-top: 1px solid var(--color-separator); + padding-top: var(--list-half-gap); +} + +@keyframes listItemReveal { + from { + opacity: 0; + transform: translateY(10px); + } +} + +.list-collapsible-item { + display: none; + animation: listItemReveal 0.3s backwards; + animation-delay: var(--animation-delay); +} + +.list-collapsible-label { + display: flex; + align-items: center; + gap: 1rem; + padding: var(--widget-content-vertical-padding) 0; + background: var(--color-widget-background); +} + +.list-collapsible-label:has(.list-collapsible-input:checked) { + position: sticky; + bottom: 0; +} + +.list-collapsible:has(+ .list-collapsible-label > .list-collapsible-input:checked) .list-collapsible-item { + display: block; +} + +.list-collapsible-input { + display: none; +} + +.list-collapsible-label::before, .list-collapsible-label::after { + cursor: pointer; + display: block; +} + +.list-collapsible-label::before { + content: 'SHOW MORE'; + font-size: var(--font-size-h4); +} + +.list-collapsible-label:has(.list-collapsible-input:checked)::before { + content: 'SHOW LESS'; +} + +.list-collapsible-label::after { + content: ''; + font-size: 0.8rem; + transform: rotate(90deg); + line-height: 1; + transition: transform 0.3s; +} + +.list-collapsible-label:has(.list-collapsible-input:checked)::after { + transform: rotate(-90deg); +} + +.widget-content:has(.list-collapsible-label:last-child) { + padding-bottom: 0; +} + +::selection { + background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl) + 20%))); + color: var(--color-text-highlight); +} + +::-webkit-scrollbar-thumb { + background: var(--color-text-subdue); + border-radius: var(--border-radius); +} + +::-webkit-scrollbar { + background: var(--color-background); + height: 5px; + width: 10px; +} + +*, *::before, *::after { + box-sizing: border-box; +} + +* { + padding: 0; + margin: 0; +} + +img, svg { + display: block; + max-width: 100%; +} + +html { + scrollbar-color: var(--color-text-subdue) transparent; + scroll-behavior: smooth; +} + +a { + text-decoration: none; + color: inherit; +} + +ul { + list-style: none; +} + +body { + font-size: 1.3rem; + font-family: 'JetBrains Mono', monospace; + font-variant-ligatures: none; + line-height: 1.6; + color: var(--color-text-base); + background-color: var(--color-background); + overflow-y: scroll; +} + +.page-column-small { + width: 300px; + flex-shrink: 0; +} + +.page-column-full { + width: 100%; + min-width: 0; +} + +.page-columns { + display: flex; + gap: var(--widget-gap); + margin: var(--widget-gap) 0; + animation: pageColumnsEntrance .3s cubic-bezier(0.25, 1, 0.5, 1) backwards; +} + +@keyframes pageColumnsEntrance { + from { + opacity: 0; + transform: translateY(10px); + } +} + +.page-loading-container { + margin: 50px auto; + width: fit-content; + animation: loadingContainerEntrance 200ms backwards; + animation-delay: 150ms; + font-size: 2rem; +} + +@keyframes loadingContainerEntrance { + from { + opacity: 0; + } +} + +.loading-icon { + min-width: 1.5em; + width: 1.5em; + height: 1.5em; + border: 0.25em solid hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 12%))); + border-top-color: hsl(var(--bghs), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%))); + border-radius: 50%; + animation: loadingIconSpin 800ms infinite linear; +} + +@keyframes loadingIconSpin { + to { + transform: rotate(360deg); + } +} + +@keyframes loadingIconSpin { + to { + transform: rotate(360deg); + } +} + +.notice-icon { + width: 0.7rem; + height: 0.7rem; + border-radius: 50%; +} + +.notice-icon-major { + background: var(--color-negative); +} + +.notice-icon-minor { + border: 1px solid var(--color-negative); +} + +.content-bounds { + max-width: 1600px; + margin-inline: auto; + padding: 0 var(--content-bounds-padding); +} + +.cards-vertical { + flex-direction: column; +} + +.cards-horizontal { + --cards-per-row: 6.5; +} + +.cards-grid { + --cards-per-row: 6; +} + +.cards-horizontal, .cards-vertical, .cards-grid { + --cards-gap: calc(var(--widget-content-vertical-padding) * 0.7); + display: flex; + gap: var(--cards-gap); +} + +.cards-horizontal { + overflow-x: auto; + padding-bottom: 1rem; +} + +.cards-grid { + flex-wrap: wrap; +} + +@container widget (max-width: 1300px) { .cards-horizontal { --cards-per-row: 5.5; } } +@container widget (max-width: 1100px) { .cards-horizontal { --cards-per-row: 4.5; } } +@container widget (max-width: 850px) { .cards-horizontal { --cards-per-row: 3.5; } } +@container widget (max-width: 750px) { .cards-horizontal { --cards-per-row: 3.5; } } +@container widget (max-width: 650px) { .cards-horizontal { --cards-per-row: 2.2; } } + +@container widget (max-width: 1300px) { .cards-grid { --cards-per-row: 5; } } +@container widget (max-width: 1100px) { .cards-grid { --cards-per-row: 4; } } +@container widget (max-width: 850px) { .cards-grid { --cards-per-row: 3; } } +@container widget (max-width: 750px) { .cards-grid { --cards-per-row: 3; } } +@container widget (max-width: 650px) { .cards-grid { --cards-per-row: 2; } } + +.card { + flex-shrink: 0; + width: calc(100% / var(--cards-per-row) - var(--cards-gap) * (var(--cards-per-row) - 1) / var(--cards-per-row)); + display: flex; + flex-direction: column; +} + +.widget-error-header { + display: flex; + align-items: center; + justify-content: space-between; + position: relative; + margin-bottom: 1.8rem; +} + +.widget-error-header::before { + content: ''; + position: absolute; + inset: calc(0rem - (var(--widget-content-vertical-padding) / 2)) calc(0rem - (var(--widget-content-horizontal-padding) / 2)); + background: var(--color-negative); + opacity: 0.05; + border-radius: var(--border-radius); + z-index: -1; +} + +.widget-error-icon { + width: 2.4rem; + height: 2.4rem; + border: 0.2rem solid var(--color-negative); + border-radius: 50%; + text-align: center; + line-height: 2rem; + flex-shrink: 0; + opacity: 0.6; +} + +.widget-error-icon::before { + content: '!'; + color: var(--color-text-highlight); +} + +.widget-content { + container-type: inline-size; + container-name: widget; +} + +.widget-content:not(.widget-content-frameless) { + padding: var(--widget-content-padding); +} + +.widget-content:not(.widget-content-frameless), .widget-content-frame { + background: var(--color-widget-background); + border-radius: var(--border-radius); + border: 1px solid var(--color-widget-content-border); + box-shadow: 0px 3px 0px 0px hsl(var(--bghs), calc(var(--scheme) (var(--scheme) var(--bgl)) - 0.5%)); +} + +.padding-widget { + padding: var(--widget-content-padding); +} + +.margin-bottom-widget { + margin-bottom: var(--widget-content-vertical-padding); +} + +.padding-block-widget { + padding-block: var(--widget-content-vertical-padding); +} + +.padding-inline-widget { + padding-inline: var(--widget-content-horizontal-padding); +} + +.widget-header { + padding: 0 calc(var(--widget-content-horizontal-padding) + 1px); + font-size: var(--font-size-h4); + margin-bottom: 1rem; + display: flex; + align-items: center; + gap: 1rem; +} + +.widget + .widget { + margin-top: var(--widget-gap); +} + +.list-horizontal-text { + display: flex; + list-style: none; + flex-wrap: wrap; + align-items: center; +} + +.list-horizontal-text > *:not(:last-child)::after { + content: '•'; + color: var(--color-text-subdue); + margin: 0 0.5rem; + position: relative; + top: 0.1rem; +} + +.header-container { + margin-top: calc(var(--widget-gap) / 2); + --header-height: 45px; + --header-items-gap: 2.5rem; +} + +.header { + display: flex; + height: var(--header-height); + gap: var(--header-items-gap); +} + +.logo { + height: 100%; + line-height: var(--header-height); + font-size: 2rem; + color: var(--color-text-highlight); + border-right: 1px solid var(--color-widget-content-border); + padding-right: var(--widget-content-horizontal-padding); +} + +.nav { + height: 100%; + gap: var(--header-items-gap); +} + +.nav .nav-item { + line-height: var(--header-height); +} + +.footer { + margin-block: calc(var(--widget-gap) * 1.5); + animation: loadingContainerEntrance 200ms backwards; + animation-delay: 150ms; +} + +.mobile-navigation { + display: none; +} + +.nav-item { + display: block; + height: 100%; + border-bottom: 2px solid transparent; + transition: color .3s, border-color .3s; + font-size: var(--font-size-h3); +} + +.nav-item:not(.nav-item-current):hover { + border-bottom-color: var(--color-text-subdue); + color: var(--color-text-highlight); +} + +.nav-item.nav-item-current { + border-bottom-color: var(--color-primary); + color: var(--color-text-highlight); +} + +.stock-chart { + margin-left: auto; + width: 6.5rem; +} + +.stock-values { + min-width: 8rem; +} + +.carousel-container { + position: relative; +} + +.carousel-container::before, .carousel-container::after { + content: ''; + position: absolute; + width: 2rem; + top: 0; + bottom: 1rem; + z-index: 10; + opacity: 0; + pointer-events: none; + transition-duration: 0.2s; +} + +.carousel-container::before { + left: 0; + background: linear-gradient(to right, var(--color-background), transparent); +} + +.carousel-container::after { + right: 0; + background: linear-gradient(to left, var(--color-background), transparent); +} + +.carousel-container.show-left-cutoff::before, .carousel-container.show-right-cutoff::after { + opacity: 1; +} + +.video-thumbnail { + width: 100%; + aspect-ratio: 16 / 9; + object-fit: cover; + border-radius: var(--border-radius) var(--border-radius) 0 0; +} + +.video-title { + margin-bottom: auto; + overflow: hidden; + display: block; + text-overflow: ellipsis; + -webkit-line-clamp: 2; + display: -webkit-box; + -webkit-box-orient: vertical; +} + +.bookmarks-group { + --bookmarks-group-color: var(--color-primary); +} + +.bookmarks-group-title { + color: var(--bookmarks-group-color); +} + +.bookmarks-link::after { + color: var(--bookmarks-group-color); +} + +.calendar-day { + width: calc(100% / 7); + text-align: center; + padding: 0.6rem 0; +} + +.calendar-day-today { + border-radius: var(--border-radius); + background-color: hsl(var(--bghs), calc(var(--scheme) (var(--scheme) (var(--bgl)) + 6%))); + color: var(--color-text-highlight); +} + +.weather-column { + position: relative; + display: flex; + align-items: center; + justify-content: end; + flex-direction: column; + width: calc(100% / 12); + padding-top: 3px; + max-width: 3.5rem; +} + +.weather-column-value, .weather-columns:hover .weather-column-value { + font-size: 13px; + color: var(--color-text-highlight); + letter-spacing: -0.1rem; + margin-right: 0.1rem; + position: relative; + margin-bottom: 0.3rem; + opacity: 0; + transform: translateY(0.5rem); + transition: opacity .2s, transform .2s; + user-select: none; +} + +.weather-column-current .weather-column-value, .weather-column:hover .weather-column-value { + opacity: 1; + transform: translateY(0); +} + +.weather-column-value::after { + position: absolute; + content: '°'; + left: 100%; + color: var(--color-text-subdue); +} + +.weather-column-value.weather-column-value-negative::before { + position: absolute; + content: '-'; + right: 100%; +} + +.weather-bar, .weather-columns:hover .weather-bar { + height: calc(20px + var(--weather-bar-height) * 40px); + width: 6px; + background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 18%))); + border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 24%))); + border-bottom: 0; + border-radius: 6px 6px 0 0; + mask-image: linear-gradient(0deg, transparent 0, #000 10px); + -webkit-mask-image: linear-gradient(0deg, transparent 0, #000 10px); + transition: background-color .2s, border-color .2s, width .2s; +} + +.weather-column-current .weather-bar, .weather-column:hover .weather-bar { + width: 10px; + background-color: hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 40%))); + border: 1px solid hsl(var(--ths), calc(var(--scheme) ((var(--scheme) var(--bgl)) + 50%))); +} + +.weather-column-rain { + position: absolute; + inset: 0; + bottom: 20%; + overflow: hidden; + mask-image: linear-gradient(0deg, transparent 40%, #000); + -webkit-mask-image: linear-gradient(0deg, transparent 40%, #000); + z-index: -1; +} + +.weather-column-rain::before { + content: ''; + position: absolute; + /* TODO: figure out a way to make it look continuous between columns, right now + depending on the width of the page the rain inside two columns next to each other + can overlap and look bad */ + background: radial-gradient(circle at 4px 4px, hsl(200, 90%, 70%, 0.4) 1px, transparent 0); + background-size: 8px 8px; + transform: rotate(45deg) translate(-50%, 25%); + height: 130%; + aspect-ratio: 1; + left: 55%; +} + +.weather-column:nth-child(3) .weather-column-time, +.weather-column:nth-child(7) .weather-column-time, +.weather-column:nth-child(11) .weather-column-time { + opacity: 1; + transform: translateY(0); +} + +.weather-column-time, .weather-columns:hover .weather-column-time { + margin-top: 0.3rem; + font-size: var(--font-size-h6); + opacity: 0; + transform: translateY(-0.5rem); + transition: opacity .2s, transform .2s; + user-select: none; +} + +.weather-column:hover .weather-column-time { + opacity: 1; + transform: translateY(0); +} + +.weather-column-daylight { + position: absolute; + inset: 0; + background: linear-gradient(0deg, transparent 30px, hsl(50, 50%, 30%, 0.2)); +} + +.weather-column-daylight-sunrise { + border-radius: 20px 0 0 0; +} + +.weather-column-daylight-sunset { + border-radius: 0 20px 0 0; +} + +.location-icon { + width: 0.8em; + height: 0.8em; + border-radius: 0 50% 50% 50%; + background-color: currentColor; + transform: rotate(225deg) translate(.1em, .1em); + position: relative; + flex-shrink: 0; +} + +.location-icon::after { + content: ''; + position: absolute; + z-index: 2; + width: .4em; + height: .4em; + border-radius: 50%; + background-color: var(--color-widget-background); + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} + +.monitor-site-icon { + display: block; + opacity: 0.8; + filter: grayscale(0.4); + object-fit: contain; + aspect-ratio: 1 / 1; + width: 3.2rem; + position: relative; + top: -0.1rem; + transition: filter 0.3s, opacity 0.3s; +} + +.monitor-site:hover .monitor-site-icon { + filter: grayscale(0); + opacity: 1; +} + +.monitor-site-status-icon { + margin-left: auto; + width: 2rem; + height: 2rem; +} + +.thumbnail { + filter: grayscale(0.2) contrast(0.9); + transition: all 0.2s; + opacity: 0.8; +} + +.thumbnail-container:hover .thumbnail { + opacity: 1; + filter: none; +} + +.rss-card-image { + height: 10rem; + object-fit: cover; + border-radius: var(--border-radius) var(--border-radius) 0 0; +} + +.twitch-category-thumbnail { + width: 5rem; + border-radius: var(--border-radius); +} + +.twitch-channel-avatar { + aspect-ratio: 1; + border-radius: 50%; +} + +.twitch-channel-avatar-container { + width: 4.4rem; + height: 4.4rem; + border: 2px solid var(--color-text-subdue); + padding: 2px; + border-radius: 50%; + position: relative; + flex-shrink: 0; +} + +.twitch-channel-live .twitch-channel-avatar-container { + border: 2px solid var(--color-positive); + margin-bottom: 1rem; +} + +.twitch-channel-live .twitch-channel-avatar-container::after { + content: 'LIVE'; + position: absolute; + background: var(--color-positive); + color: var(--color-widget-background); + font-size: var(--font-size-h6); + left: 50%; + bottom: -35%; + border-radius: var(--border-radius); + padding-inline: 0.3rem; + transform: translate(-50%); + border: 2px solid var(--color-widget-background); +} + +.reddit-card-thumbnail { + width: 100%; + height: 100%; + object-fit: cover; + object-position: 0% 20%; + opacity: 0.15; + filter: blur(1px); +} + +.reddit-card-thumbnail-container { + position: absolute; + inset: 0; + overflow: hidden; + border-radius: var(--border-radius); +} + +.reddit-card-thumbnail-container::after { + content: ''; + position: absolute; + inset: 0; + background: linear-gradient(0deg, var(--color-widget-background) 10%, transparent); +} + +@media (max-width: 1190px) { + .header-container { + display: none; + } + + .page-column-full .size-title-dynamic { + font-size: var(--font-size-h3); + } + + .page-column-small { + width: 100%; + flex-shrink: 1; + } + + .page-column { + display: none; + animation: columnEntrance 0s cubic-bezier(0.25, 1, 0.5, 1) backwards; + } + + .animate-element-transition .page-column { + animation-duration: .3s; + } + + @keyframes columnEntrance { + from { + opacity: 0; + transform: scaleX(0.95); + } + } + + body { + padding-bottom: calc(var(--mobile-navigation-height) + var(--content-bounds-padding)); + } + + .mobile-navigation { + display: block; + position: fixed; + bottom: 0; + transform: translateY(calc(100% - var(--mobile-navigation-height))); + left: var(--content-bounds-padding); + right: var(--content-bounds-padding); + z-index: 10; + background-color: var(--color-widget-background); + border: 1px solid var(--color-widget-content-border); + border-bottom: 0; + border-radius: var(--border-radius) var(--border-radius) 0 0; + transition: transform .3s; + } + + .mobile-navigation:has(.mobile-navigation-page-links-input:checked) .hamburger-icon { + --spacing: 7px; + color: var(--color-primary); + height: 2px; + } + + .mobile-navigation:has(.mobile-navigation-page-links-input:checked) { + transform: translateY(0); + } + + .mobile-navigation-page-links { + border-top: 1px solid var(--color-widget-content-border); + padding: 15px var(--content-bounds-padding); + display: flex; + align-items: center; + overflow-x: scroll; + gap: 2.5rem; + } + + .mobile-navigation-icons { + display: flex; + justify-content: space-around; + align-items: center; + } + + body:has(.mobile-navigation-input[value="0"]:checked) .page-columns > :nth-child(1), + body:has(.mobile-navigation-input[value="1"]:checked) .page-columns > :nth-child(2), + body:has(.mobile-navigation-input[value="2"]:checked) .page-columns > :nth-child(3) { + display: block; + } + + .mobile-navigation-label { + display: flex; + flex: 1; + max-width: 50px; + height: var(--mobile-navigation-height); + justify-content: center; + align-items: center; + cursor: pointer; + font-size: 15px; + line-height: var(--mobile-navigation-height); + } + + .mobile-navigation-pill { + display: block; + background: var(--color-text-base); + height: 10px; + width: 10px; + border-radius: 10px; + transition: width .3s, background-color .3s; + } + + .mobile-navigation-label:hover > .mobile-navigation-pill { + background-color: var(--color-text-highlight); + } + + .mobile-navigation-label:hover { + color: var(--color-text-highlight); + } + + .mobile-navigation-input:checked + .mobile-navigation-pill { + background: var(--color-primary); + width: 30px; + } + + .mobile-navigation-input, .mobile-navigation-page-links-input { + display: none; + } + + .hamburger-icon { + --spacing: 4px; + width: 1em; + height: 1px; + background-color: currentColor; + transition: color .3s, box-shadow .3s; + box-shadow: 0 calc(var(--spacing) * -1) 0 0 currentColor, 0 var(--spacing) 0 0 currentColor; + } + + .list-collapsible-label:has(.list-collapsible-input:checked) { + bottom: var(--mobile-navigation-height); + } +} + +@media (max-width: 550px) { + :root { + font-size: 9px; + --widget-gap: 15px; + --widget-content-vertical-padding: 10px; + --widget-content-horizontal-padding: 10px; + --content-bounds-padding: 10px; + } +} + +.size-h1 { font-size: var(--font-size-h1); } +.size-h2 { font-size: var(--font-size-h2); } +.size-h3 { font-size: var(--font-size-h3); } +.size-h4 { font-size: var(--font-size-h4); } +.size-base { font-size: var(--font-size-base); } +.size-h5 { font-size: var(--font-size-h5); } +.size-h6 { font-size: var(--font-size-h6); } + +.color-highlight { color: var(--color-text-highlight); } +.color-base { color: var(--color-text-base); } +.color-subdue { color: var(--color-text-subdue); } +.color-negative { color: var(--color-negative); } +.color-positive { color: var(--color-positive); } +.color-primary { color: var(--color-primary); } + +.break-all { word-break: break-all; } +.text-left { text-align: left; } +.text-right { text-align: right; } +.text-center { text-align: center; } +.rtl { direction: rtl; } +.shrink { flex-shrink: 1; } +.shrink-0 { flex-shrink: 0; } +.min-width-0 { min-width: 0; } +.block { display: block; } +.overflow-hidden { overflow: hidden; } +.relative { position: relative; } +.flex { display: flex; } +.flex-wrap { flex-wrap: wrap; } +.flex-nowrap { flex-wrap: nowrap; } +.justify-between { justify-content: space-between; } +.justify-stretch { justify-content: stretch; } +.justify-center { justify-content: center; } +.justify-end { justify-content: end; } +.uppercase { text-transform: uppercase; } +.flex-grow { flex-grow: 1; } +.flex-column { flex-direction: column; } +.items-center { align-items: center; } +.items-start { align-items: start; } +.gap-5 { gap: 0.5rem; } +.gap-7 { gap: 0.7rem; } +.gap-10 { gap: 1rem; } +.gap-15 { gap: 1.5rem; } +.margin-top-3 { margin-top: 0.3rem; } +.margin-top-5 { margin-top: 0.5rem; } +.margin-top-7 { margin-top: 0.7rem; } +.margin-top-10 { margin-top: 1rem; } +.margin-top-15 { margin-top: 1.5rem; } +.margin-bottom-3 { margin-bottom: 0.3rem; } +.margin-bottom-5 { margin-bottom: 0.5rem; } +.margin-bottom-7 { margin-bottom: 0.7rem; } +.margin-bottom-10 { margin-bottom: 1rem; } +.margin-bottom-15 { margin-bottom: 1.5rem; } +.margin-bottom-auto { margin-bottom: auto; } diff --git a/internal/assets/static/main.js b/internal/assets/static/main.js new file mode 100644 index 0000000..3a6ec0b --- /dev/null +++ b/internal/assets/static/main.js @@ -0,0 +1,163 @@ +function throttledDebounce(callback, maxDebounceTimes, debounceDelay) { + let debounceTimeout; + let timesDebounced = 0; + + return function () { + if (timesDebounced == maxDebounceTimes) { + clearTimeout(debounceTimeout); + timesDebounced = 0; + callback(); + return; + } + + clearTimeout(debounceTimeout); + timesDebounced++; + + debounceTimeout = setTimeout(() => { + timesDebounced = 0; + callback(); + }, debounceDelay); + }; +}; + + +async function fetchPageContents (pageSlug) { + // TODO: handle non 200 status codes/time outs + // TODO: add retries + const response = await fetch(`/api/pages/${pageSlug}/content/`); + const content = await response.text(); + + return content; +} + +function setupCarousels() { + const carouselElements = document.getElementsByClassName("carousel-container"); + + for (let i = 0; i < carouselElements.length; i++) { + const carousel = carouselElements[i]; + const itemsContainer = carousel.getElementsByClassName("carousel-items-container")[0]; + + const determineSideCutoffs = () => { + if (itemsContainer.scrollLeft != 0) { + carousel.classList.add("show-left-cutoff"); + } else { + carousel.classList.remove("show-left-cutoff"); + } + + if (Math.ceil(itemsContainer.scrollLeft) + itemsContainer.clientWidth < itemsContainer.scrollWidth) { + carousel.classList.add("show-right-cutoff"); + } else { + carousel.classList.remove("show-right-cutoff"); + } + } + + const determineSideCutoffsRateLimited = throttledDebounce(determineSideCutoffs, 20, 100); + + itemsContainer.addEventListener("scroll", determineSideCutoffsRateLimited); + document.addEventListener("resize", determineSideCutoffsRateLimited); + + determineSideCutoffs(); + } +} + +const minuteInSeconds = 60; +const hourInSeconds = minuteInSeconds * 60; +const dayInSeconds = hourInSeconds * 24; +const monthInSeconds = dayInSeconds * 30; +const yearInSeconds = monthInSeconds * 12; + +function relativeTimeSince(timestamp) { + const delta = Math.round((Date.now() / 1000) - timestamp); + + if (delta < minuteInSeconds) { + return "1m"; + } + if (delta < hourInSeconds) { + return Math.floor(delta / minuteInSeconds) + "m"; + } + if (delta < dayInSeconds) { + return Math.floor(delta / hourInSeconds) + "h"; + } + if (delta < monthInSeconds) { + return Math.floor(delta / dayInSeconds) + "d"; + } + if (delta < yearInSeconds) { + return Math.floor(delta / monthInSeconds) + "mo"; + } + + return Math.floor(delta / yearInSeconds) + "y"; +} + +function updateRelativeTimeForElements(elements) +{ + for (let i = 0; i < elements.length; i++) + { + const element = elements[i]; + const timestamp = element.dataset.dynamicRelativeTime; + + if (timestamp === undefined) + continue + + element.innerText = relativeTimeSince(timestamp); + } +} + +function setupDynamicRelativeTime() { + const elements = document.querySelectorAll("[data-dynamic-relative-time]"); + const updateInterval = 60 * 1000; + let lastUpdateTime = Date.now(); + + const updateElementsAndTimestamp = () => { + updateRelativeTimeForElements(elements); + lastUpdateTime = Date.now(); + }; + + const scheduleRepeatingUpdate = () => setInterval(updateElementsAndTimestamp, updateInterval); + + if (document.hidden === undefined) { + scheduleRepeatingUpdate(); + return; + } + + let timeout = scheduleRepeatingUpdate(); + + document.addEventListener("visibilitychange", () => { + if (document.hidden) { + clearTimeout(timeout); + return; + } + + const delta = Date.now() - lastUpdateTime; + + if (delta >= updateInterval) { + updateElementsAndTimestamp(); + timeout = scheduleRepeatingUpdate(); + return; + } + + timeout = setTimeout(() => { + updateElementsAndTimestamp(); + timeout = scheduleRepeatingUpdate(); + }, updateInterval - delta); + }); +} + +async function setupPage() { + const pageElement = document.getElementById("page"); + const pageContents = await fetchPageContents(pageData.slug); + + pageElement.innerHTML = pageContents; + + setTimeout(() => { + document.body.classList.add("animate-element-transition"); + }, 150); + + setupCarousels(); + setupDynamicRelativeTime(); +} + +if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", setupPage); +} else { + setupPage(); +} diff --git a/internal/assets/templates.go b/internal/assets/templates.go new file mode 100644 index 0000000..fe82ed5 --- /dev/null +++ b/internal/assets/templates.go @@ -0,0 +1,112 @@ +package assets + +import ( + "fmt" + "html/template" + "math" + "strconv" + "time" + + "golang.org/x/text/language" + "golang.org/x/text/message" +) + +var ( + PageTemplate = compileTemplate("page.html", "document.html", "page-style-overrides.gotmpl") + PageContentTemplate = compileTemplate("content.html") + CalendarTemplate = compileTemplate("calendar.html", "widget-base.html") + BookmarksTemplate = compileTemplate("bookmarks.html", "widget-base.html") + IFrameTemplate = compileTemplate("iframe.html", "widget-base.html") + WeatherTemplate = compileTemplate("weather.html", "widget-base.html") + ForumPostsTemplate = compileTemplate("forum-posts.html", "widget-base.html") + RedditCardsHorizontalTemplate = compileTemplate("reddit-horizontal-cards.html", "widget-base.html") + RedditCardsVerticalTemplate = compileTemplate("reddit-vertical-cards.html", "widget-base.html") + ReleasesTemplate = compileTemplate("releases.html", "widget-base.html") + VideosTemplate = compileTemplate("videos.html", "widget-base.html") + StocksTemplate = compileTemplate("stocks.html", "widget-base.html") + RSSListTemplate = compileTemplate("rss-list.html", "widget-base.html") + RSSCardsTemplate = compileTemplate("rss-cards.html", "widget-base.html") + MonitorTemplate = compileTemplate("monitor.html", "widget-base.html") + TwitchGamesListTemplate = compileTemplate("twitch-games-list.html", "widget-base.html") + TwitchChannelsTemplate = compileTemplate("twitch-channels.html", "widget-base.html") +) + +var globalTemplateFunctions = template.FuncMap{ + "relativeTime": relativeTimeSince, + "formatViewerCount": formatViewerCount, + "formatNumber": intl.Sprint, + "absInt": func(i int) int { + return int(math.Abs(float64(i))) + }, + "formatPrice": func(price float64) string { + return intl.Sprintf("%.2f", price) + }, + "formatTime": func(t time.Time) string { + return t.Format("2006-01-02 15:04:05") + }, + "shouldCollapse": func(i int, collapseAfter int) bool { + if collapseAfter < -1 { + return false + } + + return i >= collapseAfter + }, + "itemAnimationDelay": func(i int, collapseAfter int) string { + return fmt.Sprintf("%dms", (i-collapseAfter)*30) + }, + "dynamicRelativeTimeAttrs": func(t time.Time) template.HTMLAttr { + return template.HTMLAttr(fmt.Sprintf(`data-dynamic-relative-time="%d"`, t.Unix())) + }, +} + +func compileTemplate(primary string, dependencies ...string) *template.Template { + t, err := template.New(primary). + Funcs(globalTemplateFunctions). + ParseFS(TemplateFS, append([]string{primary}, dependencies...)...) + + if err != nil { + panic(err) + } + + return t +} + +var intl = message.NewPrinter(language.English) + +func formatViewerCount(count int) string { + if count < 1_000 { + return strconv.Itoa(count) + } + + if count < 10_000 { + return fmt.Sprintf("%.1fk", float64(count)/1_000) + } + + if count < 1_000_000 { + return fmt.Sprintf("%dk", count/1_000) + } + + return fmt.Sprintf("%.1fm", float64(count)/1_000_000) +} + +func relativeTimeSince(t time.Time) string { + delta := time.Since(t) + + if delta < time.Minute { + return "1m" + } + if delta < time.Hour { + return fmt.Sprintf("%dm", delta/time.Minute) + } + if delta < 24*time.Hour { + return fmt.Sprintf("%dh", delta/time.Hour) + } + if delta < 30*24*time.Hour { + return fmt.Sprintf("%dd", delta/(24*time.Hour)) + } + if delta < 12*30*24*time.Hour { + return fmt.Sprintf("%dmo", delta/(30*24*time.Hour)) + } + + return fmt.Sprintf("%dy", delta/(365*24*time.Hour)) +} diff --git a/internal/assets/templates/bookmarks.html b/internal/assets/templates/bookmarks.html new file mode 100644 index 0000000..92421e1 --- /dev/null +++ b/internal/assets/templates/bookmarks.html @@ -0,0 +1,16 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range .Groups }} +
  • + {{ if ne .Title "" }}
    {{ .Title }}
    {{ end }} + +
  • + {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/calendar.html b/internal/assets/templates/calendar.html new file mode 100644 index 0000000..68fda83 --- /dev/null +++ b/internal/assets/templates/calendar.html @@ -0,0 +1,27 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
+
{{ .Calendar.CurrentMonthName }}
+
    +
  • Week {{ .Calendar.CurrentWeekNumber }}
  • +
  • {{ .Calendar.CurrentYear }}
  • +
+
+ +
+
Mo
+
Tu
+
We
+
Th
+
Fr
+
Sa
+
Su
+
+ +
+ {{ range .Calendar.Days }} +
{{ . }}
+ {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/content.html b/internal/assets/templates/content.html new file mode 100644 index 0000000..845507f --- /dev/null +++ b/internal/assets/templates/content.html @@ -0,0 +1,9 @@ +
+{{ range .Page.Columns }} +
+ {{ range .Widgets }} + {{ .Render }} + {{ end }} +
+{{ end }} +
diff --git a/internal/assets/templates/document.html b/internal/assets/templates/document.html new file mode 100644 index 0000000..04984f8 --- /dev/null +++ b/internal/assets/templates/document.html @@ -0,0 +1,17 @@ + + + + {{ block "document-head-before" . }}{{ end }} + {{ block "document-title" . }}{{ end }} + + + + + + + {{ block "document-head-after" . }}{{ end }} + + +{{ template "document-body" . }} + + diff --git a/internal/assets/templates/forum-posts.html b/internal/assets/templates/forum-posts.html new file mode 100644 index 0000000..856f259 --- /dev/null +++ b/internal/assets/templates/forum-posts.html @@ -0,0 +1,22 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $post := .Posts }} +
  • + {{ .Title }} +
      +
    • {{ $post.TimePosted | relativeTime }}
    • +
    • {{ $post.Score | formatNumber }} points
    • +
    • {{ $post.CommentCount | formatNumber }} comments
    • + {{ if $post.HasTargetUrl }} +
    • {{ $post.TargetUrlDomain }}
    • + {{ end }} +
    +
  • + {{ end }} +
+{{ if gt (len .Posts) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/assets/templates/iframe.html b/internal/assets/templates/iframe.html new file mode 100644 index 0000000..4d9519c --- /dev/null +++ b/internal/assets/templates/iframe.html @@ -0,0 +1,7 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content-classes" }}widget-content-frameless{{ end }} + +{{ define "widget-content" }} + +{{ end }} diff --git a/internal/assets/templates/monitor.html b/internal/assets/templates/monitor.html new file mode 100644 index 0000000..602c334 --- /dev/null +++ b/internal/assets/templates/monitor.html @@ -0,0 +1,39 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range .Sites }} +
  • + {{ if .IconUrl }} + + {{ end }} +
    + {{ .Title }} +
      + {{ if not .Status.Error }} +
    • {{ .StatusText }}
    • +
    • {{ .Status.ResponseTime.Milliseconds | formatNumber }}ms
    • + {{ else if .Status.TimedOut }} +
    • Timed Out
    • + {{ else }} +
    • ERROR
    • + {{ end }} +
    +
    + {{ if eq .StatusStyle "good" }} +
    + + + +
    + {{ else }} +
    + + + +
    + {{ end }} +
  • + {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/page-style-overrides.gotmpl b/internal/assets/templates/page-style-overrides.gotmpl new file mode 100644 index 0000000..0bf2a99 --- /dev/null +++ b/internal/assets/templates/page-style-overrides.gotmpl @@ -0,0 +1,14 @@ + diff --git a/internal/assets/templates/page.html b/internal/assets/templates/page.html new file mode 100644 index 0000000..b5481a1 --- /dev/null +++ b/internal/assets/templates/page.html @@ -0,0 +1,64 @@ +{{ template "document.html" . }} + +{{ define "document-title" }}{{ .Page.Title }} - Glance{{ end }} + +{{ define "document-head-before" }} + +{{ end }} + +{{ define "document-root-attrs" }}{{ if .App.Config.Theme.Light }}class="light-scheme"{{ end }}{{ end }} +{{ define "document-head-after" }}{{ template "page-style-overrides.gotmpl" . }}{{ end }} + +{{ define "navigation-links" }} +{{ range .App.Config.Pages }} +{{ .Title }} +{{ end }} +{{ end }} + +{{ define "document-body" }} +
+
+ + + +
+
+ +
+
+ + {{ range $i, $column := .Page.Columns }} + + {{ end }} + +
+ +
+ +
+
+
+ +
+
+
+
+ + +{{ end }} diff --git a/internal/assets/templates/reddit-horizontal-cards.html b/internal/assets/templates/reddit-horizontal-cards.html new file mode 100644 index 0000000..5744cea --- /dev/null +++ b/internal/assets/templates/reddit-horizontal-cards.html @@ -0,0 +1,31 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content-classes" }}widget-content-frameless{{ end }} + +{{ define "widget-content" }} + +{{ end }} diff --git a/internal/assets/templates/reddit-vertical-cards.html b/internal/assets/templates/reddit-vertical-cards.html new file mode 100644 index 0000000..1ca0996 --- /dev/null +++ b/internal/assets/templates/reddit-vertical-cards.html @@ -0,0 +1,29 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content-classes" }}widget-content-frameless{{ end }} + +{{ define "widget-content" }} +
+ {{ range .Posts }} +
+ {{ if ne "" .ThumbnailUrl }} +
+ +
+ {{ end }} +
+ {{ if ne "" .TargetUrl }} + {{ .TargetUrlDomain }} + {{ else }} +
/r/{{ $.Subreddit }}
+ {{ end }} + {{ .Title }} +
    +
  • {{ .TimePosted | relativeTime }}
  • +
  • {{ .Score | formatNumber }} points
  • +
+
+
+ {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/releases.html b/internal/assets/templates/releases.html new file mode 100644 index 0000000..2600dc2 --- /dev/null +++ b/internal/assets/templates/releases.html @@ -0,0 +1,21 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $release := .Releases }} +
  • + {{ .Name }} +
      +
    • {{ $release.TimeReleased | relativeTime }}
    • +
    • {{ $release.Version }}
    • + {{ if gt $release.Downvotes 3 }} +
    • {{ $release.Downvotes | formatNumber }} ⚠
    • + {{ end }} +
    +
  • + {{ end }} +
+{{ if gt (len .Releases) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/assets/templates/rss-cards.html b/internal/assets/templates/rss-cards.html new file mode 100644 index 0000000..1b5e721 --- /dev/null +++ b/internal/assets/templates/rss-cards.html @@ -0,0 +1,28 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content-classes" }}widget-content-frameless{{ end }} + +{{ define "widget-content" }} + +{{ end }} diff --git a/internal/assets/templates/rss-list.html b/internal/assets/templates/rss-list.html new file mode 100644 index 0000000..69bab75 --- /dev/null +++ b/internal/assets/templates/rss-list.html @@ -0,0 +1,20 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $item := .Items }} +
  • + {{ .Title }} +
      +
    • {{ .PublishedAt | relativeTime }}
    • + {{ if gt (len $.FeedRequests) 1 }} +
    • {{ .ChannelName }}
    • + {{ end }} +
    +
  • + {{ end }} +
+ {{ if gt (len .Items) $.CollapseAfter }} + + {{ end }} +{{ end }} diff --git a/internal/assets/templates/stocks.html b/internal/assets/templates/stocks.html new file mode 100644 index 0000000..2bdb02e --- /dev/null +++ b/internal/assets/templates/stocks.html @@ -0,0 +1,23 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range .Stocks }} +
  • +
    +
    {{ .Symbol }}
    +
    {{ .Name }}
    +
    + + + + + +
    +
    {{ printf "%+.2f" .PercentChange }}%
    +
    ${{ .Price | formatPrice }}
    +
    +
  • + {{ end }} +
+{{ end }} diff --git a/internal/assets/templates/twitch-channels.html b/internal/assets/templates/twitch-channels.html new file mode 100644 index 0000000..32175f7 --- /dev/null +++ b/internal/assets/templates/twitch-channels.html @@ -0,0 +1,40 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $channel := .Channels }} +
  • +
    +
    + {{ if $channel.Exists }} + + {{ else }} + + + + {{ end }} +
    +
    + {{ $channel.Name }} + {{ if $channel.Exists }} + {{ if $channel.IsLive }} + {{ $channel.Category }} +
      +
    • {{ $channel.LiveSince | relativeTime }}
    • +
    • {{ $channel.ViewersCount | formatViewerCount }} viewers
    • +
    + {{ else }} +
    Offline
    + {{ end }} + {{ else }} +
    Not found
    + {{ end }} +
    +
    +
  • + {{ end }} +
+{{ if gt (len .Channels) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/assets/templates/twitch-games-list.html b/internal/assets/templates/twitch-games-list.html new file mode 100644 index 0000000..c0f904b --- /dev/null +++ b/internal/assets/templates/twitch-games-list.html @@ -0,0 +1,35 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
    + {{ range $i, $category := .Categories }} + {{ $shouldCollapseItem := shouldCollapse $i $.CollapseAfter }} +
  • +
    + +
    + {{ $category.Name }} +
      +
    • {{ $category.ViewersCount | formatViewerCount }} viewers
    • + {{ if $category.IsNew }} +
    • NEW
    • + {{ end }} +
    +
      + {{ range $i, $tag := $category.Tags }} + {{ if eq $i 0 }} +
    • {{ $tag.Name }}
    • + {{ else }} +
    • {{ $tag.Name }}
    • + {{ end }} + {{ end }} +
    +
    +
    +
  • + {{ end }} +
+{{ if gt (len .Categories) $.CollapseAfter }} + +{{ end }} +{{ end }} diff --git a/internal/assets/templates/videos.html b/internal/assets/templates/videos.html new file mode 100644 index 0000000..0610f8c --- /dev/null +++ b/internal/assets/templates/videos.html @@ -0,0 +1,24 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content-classes" }}widget-content-frameless{{ end }} + +{{ define "widget-content" }} + +{{ end }} diff --git a/internal/assets/templates/weather.html b/internal/assets/templates/weather.html new file mode 100644 index 0000000..1cccdc0 --- /dev/null +++ b/internal/assets/templates/weather.html @@ -0,0 +1,29 @@ +{{ template "widget-base.html" . }} + +{{ define "widget-content" }} +
{{ .Weather.WeatherCodeAsString }}
+
Feels like {{ .Weather.ApparentTemperature }}°C
+ +
+ {{ range $i, $column := .Weather.Columns }} +
+ {{ if $column.HasPrecipitation }} +
+ {{ end }} + {{ if and (ge $i $.Weather.SunriseColumn) (le $i $.Weather.SunsetColumn ) }} +
+ {{ end }} +
{{ $column.Temperature | absInt }}
+
+
{{ index $.TimeLabels $i }}
+
+ {{ end }} +
+ +{{ if not .HideLocation }} +
+
+
{{ .Place.Name }}, {{ .Place.Country }}
+
+{{ end }} +{{ end }} diff --git a/internal/assets/templates/widget-base.html b/internal/assets/templates/widget-base.html new file mode 100644 index 0000000..e37d53f --- /dev/null +++ b/internal/assets/templates/widget-base.html @@ -0,0 +1,21 @@ +
+
+
{{ .Title }}
+ {{ if and .Error .ContentAvailable }} +
+ {{ else if .Notice }} +
+ {{ end }} +
+
+ {{ if .ContentAvailable }} + {{ block "widget-content" . }}{{ end }} + {{ else }} +
+
ERROR
+
+
+

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

+ {{ end}} +
+
diff --git a/internal/feed/calendar.go b/internal/feed/calendar.go new file mode 100644 index 0000000..f7ec5d4 --- /dev/null +++ b/internal/feed/calendar.go @@ -0,0 +1,53 @@ +package feed + +import "time" + +// TODO: very inflexible, refactor to allow more customizability +// TODO: allow changing first day of week +// TODO: allow changing between showing the previous and next week and the entire month +func NewCalendar(now time.Time) *Calendar { + year, week := now.ISOWeek() + weekday := now.Weekday() + + if weekday == 0 { + weekday = 7 + } + + currentMonthDays := daysInMonth(now.Month(), year) + + var previousMonthDays int + + if previousMonthNumber := now.Month() - 1; previousMonthNumber < 1 { + previousMonthDays = daysInMonth(12, year-1) + } else { + previousMonthDays = daysInMonth(previousMonthNumber, year) + } + + startDaysFrom := now.Day() - int(weekday+6) + + days := make([]int, 21) + + for i := 0; i < 21; i++ { + day := startDaysFrom + i + + if day < 1 { + day = previousMonthDays + day + } else if day > currentMonthDays { + day = day - currentMonthDays + } + + days[i] = day + } + + return &Calendar{ + CurrentDay: now.Day(), + CurrentWeekNumber: week, + CurrentMonthName: now.Month().String(), + CurrentYear: year, + Days: days, + } +} + +func daysInMonth(m time.Month, year int) int { + return time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day() +} diff --git a/internal/feed/github.go b/internal/feed/github.go new file mode 100644 index 0000000..4a34182 --- /dev/null +++ b/internal/feed/github.go @@ -0,0 +1,117 @@ +package feed + +import ( + "fmt" + "log/slog" + "net/http" + "time" +) + +type githubReleaseResponseJson struct { + TagName string `json:"tag_name"` + PublishedAt string `json:"published_at"` + HtmlUrl string `json:"html_url"` + Draft bool `json:"draft"` + PreRelease bool `json:"prerelease"` + Reactions struct { + Downvotes int `json:"-1"` + } `json:"reactions"` +} + +func parseGithubTime(t string) time.Time { + parsedTime, err := time.Parse("2006-01-02T15:04:05Z", t) + + if err != nil { + return time.Now() + } + + return parsedTime +} + +func FetchLatestReleasesFromGithub(repositories []string, token string) (AppReleases, error) { + appReleases := make(AppReleases, 0, len(repositories)) + + if len(repositories) == 0 { + return appReleases, nil + } + + requests := make([]*http.Request, len(repositories)) + + for i, repository := range repositories { + request, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/%s/releases?per_page=10", repository), nil) + + if token != "" { + request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) + } + + requests[i] = request + } + + task := decodeJsonFromRequestTask[[]githubReleaseResponseJson](defaultClient) + job := newJob(task, requests).withWorkers(15) + responses, errs, err := workerPoolDo(job) + + if err != nil { + return nil, err + } + + var failed int + + for i := range responses { + if errs[i] != nil { + failed++ + slog.Error("Failed to fetch or parse github release", "error", errs[i], "url", requests[i].URL) + continue + } + + releases := responses[i] + + if len(releases) < 1 { + failed++ + slog.Error("No releases found", "repository", repositories[i], "url", requests[i].URL) + continue + } + + var liveRelease *githubReleaseResponseJson + + for i := range releases { + release := &releases[i] + + if !release.Draft && !release.PreRelease { + liveRelease = release + break + } + } + + if liveRelease == nil { + slog.Error("No live release found", "repository", repositories[i], "url", requests[i].URL) + continue + } + + version := liveRelease.TagName + + if version[0] != 'v' { + version = "v" + version + } + + appReleases = append(appReleases, AppRelease{ + Name: repositories[i], + Version: version, + NotesUrl: liveRelease.HtmlUrl, + TimeReleased: parseGithubTime(liveRelease.PublishedAt), + Downvotes: liveRelease.Reactions.Downvotes, + }) + } + + if len(appReleases) == 0 { + return nil, ErrNoContent + } + + appReleases.SortByNewest() + + if failed > 0 { + return appReleases, fmt.Errorf("%w: could not get %d releases", ErrPartialContent, failed) + } + + return appReleases, nil +} diff --git a/internal/feed/hacker-news.go b/internal/feed/hacker-news.go new file mode 100644 index 0000000..8e7ad73 --- /dev/null +++ b/internal/feed/hacker-news.go @@ -0,0 +1,89 @@ +package feed + +import ( + "fmt" + "log/slog" + "net/http" + "strconv" + "time" +) + +type hackerNewsPostResponseJson struct { + Id int `json:"id"` + Score int `json:"score"` + Title string `json:"title"` + TargetUrl string `json:"url,omitempty"` + CommentCount int `json:"descendants"` + TimePosted int64 `json:"time"` +} + +func getHackerNewsTopPostIds() ([]int, error) { + request, _ := http.NewRequest("GET", "https://hacker-news.firebaseio.com/v0/topstories.json", nil) + response, err := decodeJsonFromRequest[[]int](defaultClient, request) + + if err != nil { + return nil, fmt.Errorf("%w: could not fetch list of post IDs", ErrNoContent) + } + + return response, nil +} + +func getHackerNewsPostsFromIds(postIds []int) (ForumPosts, error) { + requests := make([]*http.Request, len(postIds)) + + for i, id := range postIds { + request, _ := http.NewRequest("GET", fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json", id), nil) + requests[i] = request + } + + task := decodeJsonFromRequestTask[hackerNewsPostResponseJson](defaultClient) + job := newJob(task, requests).withWorkers(30) + results, errs, err := workerPoolDo(job) + + if err != nil { + return nil, err + } + + posts := make(ForumPosts, 0, len(postIds)) + + for i := range results { + if errs[i] != nil { + slog.Error("Failed to fetch or parse hacker news post", "error", errs[i], "url", requests[i].URL) + continue + } + + posts = append(posts, ForumPost{ + Title: results[i].Title, + DiscussionUrl: "https://news.ycombinator.com/item?id=" + strconv.Itoa(results[i].Id), + TargetUrl: results[i].TargetUrl, + TargetUrlDomain: extractDomainFromUrl(results[i].TargetUrl), + CommentCount: results[i].CommentCount, + Score: results[i].Score, + TimePosted: time.Unix(results[i].TimePosted, 0), + }) + } + + if len(posts) == 0 { + return nil, ErrNoContent + } + + if len(posts) != len(postIds) { + return posts, fmt.Errorf("%w could not fetch some hacker news posts", ErrPartialContent) + } + + return posts, nil +} + +func FetchHackerNewsTopPosts(limit int) (ForumPosts, error) { + postIds, err := getHackerNewsTopPostIds() + + if err != nil { + return nil, err + } + + if len(postIds) > limit { + postIds = postIds[:limit] + } + + return getHackerNewsPostsFromIds(postIds) +} diff --git a/internal/feed/monitor.go b/internal/feed/monitor.go new file mode 100644 index 0000000..e08964f --- /dev/null +++ b/internal/feed/monitor.go @@ -0,0 +1,51 @@ +package feed + +import ( + "context" + "errors" + "net/http" + "time" +) + +type SiteStatus struct { + Code int + TimedOut bool + ResponseTime time.Duration + Error error +} + +func getSiteStatusTask(request *http.Request) (SiteStatus, error) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) + defer cancel() + request = request.WithContext(ctx) + start := time.Now() + response, err := http.DefaultClient.Do(request) + took := time.Since(start) + status := SiteStatus{ResponseTime: took} + + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + status.TimedOut = true + } + + status.Error = err + return status, err + } + + defer response.Body.Close() + + status.Code = response.StatusCode + + return status, nil +} + +func FetchStatusesForRequests(requests []*http.Request) ([]SiteStatus, error) { + job := newJob(getSiteStatusTask, requests).withWorkers(20) + results, _, err := workerPoolDo(job) + + if err != nil { + return nil, err + } + + return results, nil +} diff --git a/internal/feed/openmeteo.go b/internal/feed/openmeteo.go new file mode 100644 index 0000000..604ac05 --- /dev/null +++ b/internal/feed/openmeteo.go @@ -0,0 +1,151 @@ +package feed + +import ( + "fmt" + "math" + "net/http" + "net/url" + "slices" + "time" + + _ "time/tzdata" +) + +type PlacesResponseJson struct { + Results []PlaceJson +} + +type PlaceJson struct { + Name string + Latitude float64 + Longitude float64 + Timezone string + Country string + location *time.Location +} + +type WeatherResponseJson struct { + Daily struct { + Sunrise []int64 `json:"sunrise"` + Sunset []int64 `json:"sunset"` + } `json:"daily"` + + Hourly struct { + Temperature []float64 `json:"temperature_2m"` + PrecipitationProbability []int `json:"precipitation_probability"` + } `json:"hourly"` + + Current struct { + Temperature float64 `json:"temperature_2m"` + ApparentTemperature float64 `json:"apparent_temperature"` + WeatherCode int `json:"weather_code"` + } `json:"current"` +} + +type weatherColumn struct { + Temperature int + Scale float64 + HasPrecipitation bool +} + +func FetchPlaceFromName(location string) (*PlaceJson, error) { + requestUrl := fmt.Sprintf("https://geocoding-api.open-meteo.com/v1/search?name=%s&count=1&language=en&format=json", url.QueryEscape(location)) + request, _ := http.NewRequest("GET", requestUrl, nil) + responseJson, err := decodeJsonFromRequest[PlacesResponseJson](defaultClient, request) + + if err != nil { + return nil, fmt.Errorf("could not fetch places data: %v", err) + } + + if len(responseJson.Results) == 0 { + return nil, fmt.Errorf("no places found for %s", location) + } + + place := &responseJson.Results[0] + + loc, err := time.LoadLocation(place.Timezone) + + if err != nil { + return nil, fmt.Errorf("could not load location: %v", err) + } + + place.location = loc + + return place, nil +} + +func barIndexFromHour(h int) int { + return h / 2 +} + +// TODO: bunch of spaget, refactor +// TODO: allow changing between C and F +func FetchWeatherForPlace(place *PlaceJson) (*Weather, error) { + query := url.Values{} + + query.Add("latitude", fmt.Sprintf("%f", place.Latitude)) + query.Add("longitude", fmt.Sprintf("%f", place.Longitude)) + query.Add("timeformat", "unixtime") + query.Add("timezone", place.Timezone) + query.Add("forecast_days", "1") + query.Add("current", "temperature_2m,apparent_temperature,weather_code,wind_speed_10m") + query.Add("hourly", "temperature_2m,precipitation_probability") + query.Add("daily", "sunrise,sunset") + + requestUrl := "https://api.open-meteo.com/v1/forecast?" + query.Encode() + request, _ := http.NewRequest("GET", requestUrl, nil) + responseJson, err := decodeJsonFromRequest[WeatherResponseJson](defaultClient, request) + + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrNoContent, err) + } + + now := time.Now().In(place.location) + bars := make([]weatherColumn, 0, 24) + currentBar := barIndexFromHour(now.Hour()) + sunriseBar := barIndexFromHour(time.Unix(int64(responseJson.Daily.Sunrise[0]), 0).In(place.location).Hour()) + sunsetBar := barIndexFromHour(time.Unix(int64(responseJson.Daily.Sunset[0]), 0).In(place.location).Hour()) - 1 + + if sunsetBar < 0 { + sunsetBar = 0 + } + + if len(responseJson.Hourly.Temperature) == 24 { + temperatures := make([]int, 12) + precipitations := make([]bool, 12) + + t := responseJson.Hourly.Temperature + p := responseJson.Hourly.PrecipitationProbability + + for i := 0; i < 24; i += 2 { + if i/2 == currentBar { + temperatures[i/2] = int(responseJson.Current.Temperature) + } else { + temperatures[i/2] = int(math.Round((t[i] + t[i+1]) / 2)) + } + + precipitations[i/2] = (p[i]+p[i+1])/2 > 75 + } + + minT := slices.Min(temperatures) + maxT := slices.Max(temperatures) + + for i := 0; i < 12; i++ { + bars = append(bars, weatherColumn{ + Temperature: temperatures[i], + Scale: float64(temperatures[i]-minT) / float64(maxT-minT), + HasPrecipitation: precipitations[i], + }) + } + } + + return &Weather{ + Temperature: int(responseJson.Current.Temperature), + ApparentTemperature: int(responseJson.Current.ApparentTemperature), + WeatherCode: responseJson.Current.WeatherCode, + CurrentColumn: currentBar, + SunriseColumn: sunriseBar, + SunsetColumn: sunsetBar, + Columns: bars, + }, nil +} diff --git a/internal/feed/primitives.go b/internal/feed/primitives.go new file mode 100644 index 0000000..7f4f464 --- /dev/null +++ b/internal/feed/primitives.go @@ -0,0 +1,183 @@ +package feed + +import ( + "math" + "sort" + "time" +) + +type ForumPost struct { + Title string + DiscussionUrl string + TargetUrl string + TargetUrlDomain string + ThumbnailUrl string + CommentCount int + Score int + Engagement float64 + TimePosted time.Time +} + +type ForumPosts []ForumPost + +type Calendar struct { + CurrentDay int + CurrentWeekNumber int + CurrentMonthName string + CurrentYear int + Days []int +} + +type Weather struct { + Temperature int + ApparentTemperature int + WeatherCode int + CurrentColumn int + SunriseColumn int + SunsetColumn int + Columns []weatherColumn +} + +type AppRelease struct { + Name string + Version string + NotesUrl string + TimeReleased time.Time + Downvotes int +} + +type AppReleases []AppRelease + +type Video struct { + ThumbnailUrl string + Title string + Url string + Author string + AuthorUrl string + TimePosted time.Time +} + +type Videos []Video + +type Stock struct { + Name string + Symbol string + Price float64 + PercentChange float64 + SvgChartPoints string +} + +type Stocks []Stock + +func (t Stocks) SortByAbsChange() { + sort.Slice(t, func(i, j int) bool { + return math.Abs(t[i].PercentChange) > math.Abs(t[j].PercentChange) + }) +} + +var weatherCodeTable = map[int]string{ + 0: "Clear Sky", + 1: "Mainly Clear", + 2: "Partly Cloudy", + 3: "Overcast", + 45: "Fog", + 48: "Rime Fog", + 51: "Drizzle", + 53: "Drizzle", + 55: "Drizzle", + 56: "Drizzle", + 57: "Drizzle", + 61: "Rain", + 63: "Moderate Rain", + 65: "Heavy Rain", + 66: "Freezing Rain", + 67: "Freezing Rain", + 71: "Snow", + 73: "Moderate Snow", + 75: "Heavy Snow", + 77: "Snow Grains", + 80: "Rain", + 81: "Moderate Rain", + 82: "Heavy Rain", + 85: "Snow", + 86: "Snow", + 95: "Thunderstorm", + 96: "Thunderstorm", + 99: "Thunderstorm", +} + +func (w *Weather) WeatherCodeAsString() string { + if weatherCode, ok := weatherCodeTable[w.WeatherCode]; ok { + return weatherCode + } + + return "" +} + +const depreciatePostsOlderThanHours = 7 +const maxDepreciation = 0.9 +const maxDepreciationAfterHours = 24 + +func (p ForumPosts) CalculateEngagement() { + var totalComments int + var totalScore int + + for i := range p { + totalComments += p[i].CommentCount + totalScore += p[i].Score + } + + numberOfPosts := float64(len(p)) + averageComments := float64(totalComments) / numberOfPosts + averageScore := float64(totalScore) / numberOfPosts + + for i := range p { + p[i].Engagement = (float64(p[i].CommentCount)/averageComments + float64(p[i].Score)/averageScore) / 2 + + elapsed := time.Since(p[i].TimePosted) + + if elapsed < time.Hour*depreciatePostsOlderThanHours { + continue + } + + p[i].Engagement *= 1.0 - (math.Max(elapsed.Hours()-depreciatePostsOlderThanHours, maxDepreciationAfterHours)/maxDepreciationAfterHours)*maxDepreciation + } +} + +func (p ForumPosts) SortByEngagement() { + sort.Slice(p, func(i, j int) bool { + return p[i].Engagement > p[j].Engagement + }) +} + +func (s *ForumPost) HasTargetUrl() bool { + return s.TargetUrl != "" +} + +func (p ForumPosts) FilterPostedBefore(postedBefore time.Duration) []ForumPost { + recent := make([]ForumPost, 0, len(p)) + + for i := range p { + if time.Since(p[i].TimePosted) < postedBefore { + recent = append(recent, p[i]) + } + } + + return recent +} + +func (r AppReleases) SortByNewest() AppReleases { + sort.Slice(r, func(i, j int) bool { + return r[i].TimeReleased.After(r[j].TimeReleased) + }) + + return r +} + +func (v Videos) SortByNewest() Videos { + sort.Slice(v, func(i, j int) bool { + return v[i].TimePosted.After(v[j].TimePosted) + }) + + return v +} diff --git a/internal/feed/reddit.go b/internal/feed/reddit.go new file mode 100644 index 0000000..b8449f9 --- /dev/null +++ b/internal/feed/reddit.go @@ -0,0 +1,83 @@ +package feed + +import ( + "fmt" + "html" + "net/http" + "net/url" + "time" +) + +type subredditResponseJson struct { + Data struct { + Children []struct { + Data struct { + Title string `json:"title"` + Upvotes int `json:"ups"` + Url string `json:"url"` + Time float64 `json:"created"` + CommentsCount int `json:"num_comments"` + Domain string `json:"domain"` + Permalink string `json:"permalink"` + Stickied bool `json:"stickied"` + Pinned bool `json:"pinned"` + IsSelf bool `json:"is_self"` + Thumbnail string `json:"thumbnail"` + } `json:"data"` + } `json:"children"` + } `json:"data"` +} + +func FetchSubredditPosts(subreddit string) (ForumPosts, error) { + requestUrl := fmt.Sprintf("https://www.reddit.com/r/%s/hot.json", url.QueryEscape(subreddit)) + request, err := http.NewRequest("GET", requestUrl, nil) + + if err != nil { + return nil, err + } + + // Required to increase rate limit, otherwise Reddit randomly returns 429 even after just 2 requests + addBrowserUserAgentHeader(request) + responseJson, err := decodeJsonFromRequest[subredditResponseJson](defaultClient, request) + + if err != nil { + return nil, err + } + + if len(responseJson.Data.Children) == 0 { + return nil, fmt.Errorf("no posts found") + } + + posts := make(ForumPosts, 0, len(responseJson.Data.Children)) + + for i := range responseJson.Data.Children { + post := &responseJson.Data.Children[i].Data + + if post.Stickied || post.Pinned { + continue + } + + forumPost := ForumPost{ + Title: html.UnescapeString(post.Title), + DiscussionUrl: "https://www.reddit.com" + post.Permalink, + TargetUrlDomain: post.Domain, + CommentCount: post.CommentsCount, + Score: post.Upvotes, + TimePosted: time.Unix(int64(post.Time), 0), + } + + if post.Thumbnail != "" && post.Thumbnail != "self" && post.Thumbnail != "default" { + forumPost.ThumbnailUrl = post.Thumbnail + } + + if !post.IsSelf { + forumPost.TargetUrl = post.Url + } + + posts = append(posts, forumPost) + } + + posts.CalculateEngagement() + + return posts, nil +} diff --git a/internal/feed/requests.go b/internal/feed/requests.go new file mode 100644 index 0000000..2181b75 --- /dev/null +++ b/internal/feed/requests.go @@ -0,0 +1,195 @@ +package feed + +import ( + "context" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + "sync" + "time" +) + +var defaultClient = &http.Client{ + Timeout: 5 * time.Second, +} + +type RequestDoer interface { + Do(*http.Request) (*http.Response, error) +} + +func addBrowserUserAgentHeader(request *http.Request) { + request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0") +} + +func decodeJsonFromRequest[T any](client RequestDoer, request *http.Request) (T, error) { + response, err := client.Do(request) + var result T + + if err != nil { + return result, err + } + + defer response.Body.Close() + + body, err := io.ReadAll(response.Body) + + if err != nil { + return result, err + } + + if response.StatusCode != http.StatusOK { + return result, fmt.Errorf("unexpected status code %d for %s, response: %s", response.StatusCode, request.URL, string(body)) + } + + err = json.Unmarshal(body, &result) + + if err != nil { + return result, err + } + + return result, nil +} + +func decodeJsonFromRequestTask[T any](client RequestDoer) func(*http.Request) (T, error) { + return func(request *http.Request) (T, error) { + return decodeJsonFromRequest[T](client, request) + } +} + +// TODO: tidy up, these are a copy of the above but with a line changed +func decodeXmlFromRequest[T any](client RequestDoer, request *http.Request) (T, error) { + response, err := client.Do(request) + var result T + + if err != nil { + return result, err + } + + defer response.Body.Close() + + body, err := io.ReadAll(response.Body) + + if err != nil { + return result, err + } + + if response.StatusCode != http.StatusOK { + return result, fmt.Errorf("unexpected status code %d for %s, response: %s", response.StatusCode, request.URL, string(body)) + } + + err = xml.Unmarshal(body, &result) + + if err != nil { + return result, err + } + + return result, nil +} + +func decodeXmlFromRequestTask[T any](client RequestDoer) func(*http.Request) (T, error) { + return func(request *http.Request) (T, error) { + return decodeXmlFromRequest[T](client, request) + } +} + +type workerPoolTask[I any, O any] struct { + index int + input I + output O + err error +} + +type workerPoolJob[I any, O any] struct { + data []I + workers int + task func(I) (O, error) + ctx context.Context +} + +const defaultNumWorkers = 10 + +func (job *workerPoolJob[I, O]) withWorkers(workers int) *workerPoolJob[I, O] { + if workers == 0 { + job.workers = defaultNumWorkers + } else if workers > len(job.data) { + job.workers = len(job.data) + } else { + job.workers = workers + } + + return job +} + +// func (job *workerPoolJob[I, O]) withContext(ctx context.Context) *workerPoolJob[I, O] { +// if ctx != nil { +// job.ctx = ctx +// } + +// return job +// } + +func newJob[I any, O any](task func(I) (O, error), data []I) *workerPoolJob[I, O] { + return &workerPoolJob[I, O]{ + workers: defaultNumWorkers, + task: task, + data: data, + ctx: context.Background(), + } +} + +func workerPoolDo[I any, O any](job *workerPoolJob[I, O]) ([]O, []error, error) { + results := make([]O, len(job.data)) + errs := make([]error, len(job.data)) + + if len(job.data) == 0 { + return results, errs, nil + } + + tasksQueue := make(chan *workerPoolTask[I, O]) + resultsQueue := make(chan *workerPoolTask[I, O]) + + var wg sync.WaitGroup + + for range job.workers { + wg.Add(1) + go func() { + defer wg.Done() + + for t := range tasksQueue { + t.output, t.err = job.task(t.input) + resultsQueue <- t + } + }() + } + + var err error + + go func() { + loop: + for i := range job.data { + select { + default: + tasksQueue <- &workerPoolTask[I, O]{ + index: i, + input: job.data[i], + } + case <-job.ctx.Done(): + err = job.ctx.Err() + break loop + } + } + + close(tasksQueue) + wg.Wait() + close(resultsQueue) + }() + + for task := range resultsQueue { + errs[task.index] = task.err + results[task.index] = task.output + } + + return results, errs, err +} diff --git a/internal/feed/rss.go b/internal/feed/rss.go new file mode 100644 index 0000000..533bb11 --- /dev/null +++ b/internal/feed/rss.go @@ -0,0 +1,117 @@ +package feed + +import ( + "context" + "fmt" + "log/slog" + "sort" + "time" + + "github.com/mmcdole/gofeed" +) + +type RSSFeedItem struct { + ChannelName string + ChannelURL string + Title string + Link string + ImageURL string + PublishedAt time.Time +} + +type RSSFeedRequest struct { + Url string `yaml:"url"` + Title string `yaml:"title"` +} + +type RSSFeedItems []RSSFeedItem + +func (f RSSFeedItems) SortByNewest() RSSFeedItems { + sort.Slice(f, func(i, j int) bool { + return f[i].PublishedAt.After(f[j].PublishedAt) + }) + + return f +} + +var feedParser = gofeed.NewParser() + +func getItemsFromRSSFeedTask(request RSSFeedRequest) ([]RSSFeedItem, error) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + feed, err := feedParser.ParseURLWithContext(request.Url, ctx) + + if err != nil { + return nil, err + } + + items := make(RSSFeedItems, 0, len(feed.Items)) + + for i := range feed.Items { + item := feed.Items[i] + + rssItem := RSSFeedItem{ + ChannelURL: feed.Link, + Title: item.Title, + Link: item.Link, + } + + if request.Title != "" { + rssItem.ChannelName = request.Title + } else { + rssItem.ChannelName = feed.Title + } + + if item.Image != nil { + rssItem.ImageURL = item.Image.URL + } else if feed.Image != nil { + rssItem.ImageURL = feed.Image.URL + } + + if item.PublishedParsed != nil { + rssItem.PublishedAt = *item.PublishedParsed + } else { + rssItem.PublishedAt = time.Now() + } + + items = append(items, rssItem) + } + + return items, nil +} + +func GetItemsFromRSSFeeds(requests []RSSFeedRequest) (RSSFeedItems, error) { + job := newJob(getItemsFromRSSFeedTask, requests).withWorkers(10) + feeds, errs, err := workerPoolDo(job) + + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrNoContent, err) + } + + failed := 0 + + entries := make(RSSFeedItems, 0, len(feeds)*10) + + for i := range feeds { + if errs[i] != nil { + failed++ + slog.Error("failed to get rss feed", "error", errs[i], "url", requests[i].Url) + continue + } + + entries = append(entries, feeds[i]...) + } + + if len(entries) == 0 { + return nil, ErrNoContent + } + + entries.SortByNewest() + + if failed > 0 { + return entries, fmt.Errorf("%w: missing %d RSS feeds", ErrPartialContent, failed) + } + + return entries, nil +} diff --git a/internal/feed/twitch.go b/internal/feed/twitch.go new file mode 100644 index 0000000..1ff82ee --- /dev/null +++ b/internal/feed/twitch.go @@ -0,0 +1,248 @@ +package feed + +import ( + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "slices" + "sort" + "strings" + "time" +) + +type TwitchCategory struct { + Slug string `json:"slug"` + Name string `json:"name"` + AvatarUrl string `json:"avatarURL"` + ViewersCount int `json:"viewersCount"` + Tags []struct { + Name string `json:"tagName"` + } `json:"tags"` + GameReleaseDate string `json:"originalReleaseDate"` + IsNew bool `json:"-"` +} + +type TwitchChannel struct { + Login string + Exists bool + Name string + AvatarUrl string + IsLive bool + LiveSince time.Time + Category string + CategorySlug string + ViewersCount int +} + +type TwitchChannels []TwitchChannel + +func (channels TwitchChannels) SortByViewers() { + sort.Slice(channels, func(i, j int) bool { + return channels[i].ViewersCount > channels[j].ViewersCount + }) +} + +type twitchOperationResponse struct { + Data json.RawMessage + Extensions struct { + OperationName string `json:"operationName"` + } +} + +type twitchChannelShellOperationResponse struct { + UserOrError struct { + Type string `json:"__typename"` + DisplayName string `json:"displayName"` + ProfileImageUrl string `json:"profileImageURL"` + Stream *struct { + ViewersCount int `json:"viewersCount"` + } + } `json:"userOrError"` +} + +type twitchStreamMetadataOperationResponse struct { + UserOrNull *struct { + Stream *struct { + StartedAt string `json:"createdAt"` + Game *struct { + Slug string `json:"slug"` + Name string `json:"name"` + } `json:"game"` + } `json:"stream"` + } `json:"user"` +} + +type twitchDirectoriesOperationResponse struct { + Data struct { + DirectoriesWithTags struct { + Edges []struct { + Node TwitchCategory `json:"node"` + } `json:"edges"` + } `json:"directoriesWithTags"` + } `json:"data"` +} + +const twitchGqlEndpoint = "https://gql.twitch.tv/gql" +const twitchGqlClientId = "kimne78kx3ncx6brgo4mv6wki5h1ko" + +const twitchDirectoriesOperationRequestBody = `[{"operationName": "BrowsePage_AllDirectories","variables": {"limit": %d,"options": {"sort": "VIEWER_COUNT","tags": []}},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "2f67f71ba89f3c0ed26a141ec00da1defecb2303595f5cda4298169549783d9e"}}}]` + +func FetchTopGamesFromTwitch(exclude []string, limit int) ([]TwitchCategory, error) { + reader := strings.NewReader(fmt.Sprintf(twitchDirectoriesOperationRequestBody, len(exclude)+limit)) + request, _ := http.NewRequest("POST", twitchGqlEndpoint, reader) + request.Header.Add("Client-ID", twitchGqlClientId) + response, err := decodeJsonFromRequest[[]twitchDirectoriesOperationResponse](defaultClient, request) + + if err != nil { + return nil, err + } + + if len(response) == 0 { + return nil, errors.New("no categories could be retrieved") + } + + edges := (response)[0].Data.DirectoriesWithTags.Edges + categories := make([]TwitchCategory, 0, len(edges)) + + for i := range edges { + if slices.Contains(exclude, edges[i].Node.Slug) { + continue + } + + category := &edges[i].Node + category.AvatarUrl = strings.Replace(category.AvatarUrl, "285x380", "144x192", 1) + + if len(category.Tags) > 2 { + category.Tags = category.Tags[:2] + } + + gameReleasedDate, err := time.Parse("2006-01-02T15:04:05Z", category.GameReleaseDate) + + if err == nil { + if time.Since(gameReleasedDate) < 14*24*time.Hour { + category.IsNew = true + } + } + + categories = append(categories, *category) + } + + if len(categories) > limit { + categories = categories[:limit] + } + + return categories, nil +} + +const twitchChannelStatusOperationRequestBody = `[{"operationName":"ChannelShell","variables":{"login":"%s"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe"}}},{"operationName":"StreamMetadata","variables":{"channelLogin":"%s"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"676ee2f834ede42eb4514cdb432b3134fefc12590080c9a2c9bb44a2a4a63266"}}}]` + +// TODO: rework +// The operations for multiple channels can all be sent in a single request +// rather than sending a separate request for each channel. Need to figure out +// what the limit is for max operations per request and batch operations in +// multiple requests if number of channels exceeds allowed limit. + +func fetchChannelFromTwitchTask(channel string) (TwitchChannel, error) { + result := TwitchChannel{ + Login: strings.ToLower(channel), + } + + reader := strings.NewReader(fmt.Sprintf(twitchChannelStatusOperationRequestBody, channel, channel)) + request, _ := http.NewRequest("POST", twitchGqlEndpoint, reader) + request.Header.Add("Client-ID", twitchGqlClientId) + + response, err := decodeJsonFromRequest[[]twitchOperationResponse](defaultClient, request) + + if err != nil { + return result, err + } + + if len(response) != 2 { + return result, fmt.Errorf("expected 2 operation responses, got %d", len(response)) + } + + var channelShell twitchChannelShellOperationResponse + var streamMetadata twitchStreamMetadataOperationResponse + + for i := range response { + switch response[i].Extensions.OperationName { + case "ChannelShell": + err = json.Unmarshal(response[i].Data, &channelShell) + + if err != nil { + return result, fmt.Errorf("failed to unmarshal channel shell: %w", err) + } + case "StreamMetadata": + err = json.Unmarshal(response[i].Data, &streamMetadata) + + if err != nil { + return result, fmt.Errorf("failed to unmarshal stream metadata: %w", err) + } + default: + return result, fmt.Errorf("unknown operation name: %s", response[i].Extensions.OperationName) + } + } + + if channelShell.UserOrError.Type != "User" { + result.Name = result.Login + return result, nil + } + + result.Exists = true + result.Name = channelShell.UserOrError.DisplayName + result.AvatarUrl = channelShell.UserOrError.ProfileImageUrl + + if channelShell.UserOrError.Stream != nil { + result.IsLive = true + result.ViewersCount = channelShell.UserOrError.Stream.ViewersCount + + if streamMetadata.UserOrNull != nil && streamMetadata.UserOrNull.Stream != nil && streamMetadata.UserOrNull.Stream.Game != nil { + result.Category = streamMetadata.UserOrNull.Stream.Game.Name + result.CategorySlug = streamMetadata.UserOrNull.Stream.Game.Slug + startedAt, err := time.Parse("2006-01-02T15:04:05Z", streamMetadata.UserOrNull.Stream.StartedAt) + + if err == nil { + result.LiveSince = startedAt + } else { + slog.Warn("failed to parse twitch stream started at", "error", err, "started_at", streamMetadata.UserOrNull.Stream.StartedAt) + } + } + } + + return result, nil +} + +func FetchChannelsFromTwitch(channelLogins []string) (TwitchChannels, error) { + result := make(TwitchChannels, 0, len(channelLogins)) + + job := newJob(fetchChannelFromTwitchTask, channelLogins).withWorkers(10) + channels, errs, err := workerPoolDo(job) + + if err != nil { + return result, err + } + + var failed int + + for i := range channels { + if errs[i] != nil { + failed++ + slog.Warn("failed to fetch twitch channel", "channel", channelLogins[i], "error", errs[i]) + continue + } + + result = append(result, channels[i]) + } + + if failed == len(channelLogins) { + return result, ErrNoContent + } + + if failed > 0 { + return result, fmt.Errorf("%w: failed to fetch %d channels", ErrPartialContent, failed) + } + + return result, nil +} diff --git a/internal/feed/utils.go b/internal/feed/utils.go new file mode 100644 index 0000000..a861e8a --- /dev/null +++ b/internal/feed/utils.go @@ -0,0 +1,79 @@ +package feed + +import ( + "errors" + "fmt" + "net/url" + "slices" + "strings" +) + +var ( + ErrNoContent = errors.New("failed to retrieve any content") + ErrPartialContent = errors.New("failed to retrieve some of the content") +) + +func percentChange(current, previous float64) float64 { + return (current/previous - 1) * 100 +} + +func extractDomainFromUrl(u string) string { + if u == "" { + return "" + } + + parsed, err := url.Parse(u) + + if err != nil { + return "" + } + + return strings.TrimPrefix(parsed.Host, "www.") +} + +func SvgPolylineCoordsFromYValues(width float64, height float64, values []float64) string { + if len(values) < 2 { + return "" + } + + verticalPadding := height * 0.02 + height -= verticalPadding * 2 + coordinates := make([]string, len(values)) + distanceBetweenPoints := width / float64(len(values)-1) + min := slices.Min(values) + max := slices.Max(values) + + for i := range values { + coordinates[i] = fmt.Sprintf( + "%.2f,%.2f", + float64(i)*distanceBetweenPoints, + ((max-values[i])/(max-min))*height+verticalPadding, + ) + } + + return strings.Join(coordinates, " ") +} + +func maybeCopySliceWithoutZeroValues[T int | float64](values []T) []T { + if len(values) == 0 { + return values + } + + for i := range values { + if values[i] != 0 { + continue + } + + c := make([]T, 0, len(values)-1) + + for i := range values { + if values[i] != 0 { + c = append(c, values[i]) + } + } + + return c + } + + return values +} diff --git a/internal/feed/yahoo.go b/internal/feed/yahoo.go new file mode 100644 index 0000000..9412665 --- /dev/null +++ b/internal/feed/yahoo.go @@ -0,0 +1,102 @@ +package feed + +import ( + "fmt" + "log/slog" + "net/http" +) + +type stockResponseJson struct { + Chart struct { + Result []struct { + Meta struct { + Symbol string `json:"symbol"` + RegularMarketPrice float64 `json:"regularMarketPrice"` + ChartPreviousClose float64 `json:"chartPreviousClose"` + } `json:"meta"` + Indicators struct { + Quote []struct { + Close []float64 `json:"close,omitempty"` + } `json:"quote"` + } `json:"indicators"` + } `json:"result"` + } `json:"chart"` +} + +type StockRequest struct { + Symbol string + Name string +} + +// TODO: allow changing chart time frame +const stockChartDays = 21 + +func FetchStocksDataFromYahoo(stockRequests []StockRequest) (Stocks, error) { + requests := make([]*http.Request, 0, len(stockRequests)) + + for i := range stockRequests { + request, _ := http.NewRequest("GET", fmt.Sprintf("https://query1.finance.yahoo.com/v8/finance/chart/%s?range=1mo&interval=1d", stockRequests[i].Symbol), nil) + requests = append(requests, request) + } + + job := newJob(decodeJsonFromRequestTask[stockResponseJson](defaultClient), requests) + responses, errs, err := workerPoolDo(job) + + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrNoContent, err) + } + + stocks := make(Stocks, 0, len(responses)) + var failed int + + for i := range responses { + if errs[i] != nil { + failed++ + slog.Error("Failed to fetch stock data", "symbol", stockRequests[i].Symbol, "error", errs[i]) + continue + } + + response := responses[i] + + if len(response.Chart.Result) == 0 { + failed++ + slog.Error("Stock response contains no data", "symbol", stockRequests[i].Symbol) + continue + } + + prices := response.Chart.Result[0].Indicators.Quote[0].Close + + if len(prices) > stockChartDays { + prices = prices[len(prices)-stockChartDays:] + } + + previous := response.Chart.Result[0].Meta.RegularMarketPrice + + if len(prices) >= 2 && prices[len(prices)-2] != 0 { + previous = prices[len(prices)-2] + } + + points := SvgPolylineCoordsFromYValues(100, 50, maybeCopySliceWithoutZeroValues(prices)) + + stocks = append(stocks, Stock{ + Name: stockRequests[i].Name, + Symbol: response.Chart.Result[0].Meta.Symbol, + Price: response.Chart.Result[0].Meta.RegularMarketPrice, + PercentChange: percentChange( + response.Chart.Result[0].Meta.RegularMarketPrice, + previous, + ), + SvgChartPoints: points, + }) + } + + if len(stocks) == 0 { + return nil, ErrNoContent + } + + if failed > 0 { + return stocks, fmt.Errorf("%w: could not fetch data for %d stock(s)", ErrPartialContent, failed) + } + + return stocks, nil +} diff --git a/internal/feed/youtube.go b/internal/feed/youtube.go new file mode 100644 index 0000000..e22b8bb --- /dev/null +++ b/internal/feed/youtube.go @@ -0,0 +1,100 @@ +package feed + +import ( + "fmt" + "log/slog" + "net/http" + "strings" + "time" +) + +type youtubeFeedResponseXml struct { + Channel string `xml:"title"` + ChannelLink struct { + Href string `xml:"href,attr"` + } `xml:"link"` + Videos []struct { + Title string `xml:"title"` + Published string `xml:"published"` + Link struct { + Href string `xml:"href,attr"` + } `xml:"link"` + + Group struct { + Thumbnail struct { + Url string `xml:"url,attr"` + } `xml:"http://search.yahoo.com/mrss/ thumbnail"` + } `xml:"http://search.yahoo.com/mrss/ group"` + } `xml:"entry"` +} + +func parseYoutubeFeedTime(t string) time.Time { + parsedTime, err := time.Parse("2006-01-02T15:04:05-07:00", t) + + if err != nil { + return time.Now() + } + + return parsedTime +} + +func FetchYoutubeChannelUploads(channelIds []string) (Videos, error) { + requests := make([]*http.Request, 0, len(channelIds)) + + for i := range channelIds { + request, _ := http.NewRequest("GET", "https://www.youtube.com/feeds/videos.xml?channel_id="+channelIds[i], nil) + requests = append(requests, request) + } + + job := newJob(decodeXmlFromRequestTask[youtubeFeedResponseXml](defaultClient), requests).withWorkers(30) + + responses, errs, err := workerPoolDo(job) + + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrNoContent, err) + } + + videos := make(Videos, 0, len(channelIds)*15) + + var failed int + + for i := range responses { + if errs[i] != nil { + failed++ + slog.Error("Failed to fetch youtube feed", "channel", channelIds[i], "error", errs[i]) + continue + } + + response := responses[i] + + for j := range response.Videos { + video := &response.Videos[j] + + // TODO: figure out a better way of skipping shorts + if strings.Contains(video.Title, "#shorts") { + continue + } + + videos = append(videos, Video{ + ThumbnailUrl: video.Group.Thumbnail.Url, + Title: video.Title, + Url: video.Link.Href, + Author: response.Channel, + AuthorUrl: response.ChannelLink.Href + "/videos", + TimePosted: parseYoutubeFeedTime(video.Published), + }) + } + } + + if len(videos) == 0 { + return nil, ErrNoContent + } + + videos.SortByNewest() + + if failed > 0 { + return videos, fmt.Errorf("%w: missing videos from %d channels", ErrPartialContent, failed) + } + + return videos, nil +} diff --git a/internal/glance/cli.go b/internal/glance/cli.go new file mode 100644 index 0000000..5987368 --- /dev/null +++ b/internal/glance/cli.go @@ -0,0 +1,42 @@ +package glance + +import ( + "flag" + "os" +) + +type CliIntent uint8 + +const ( + CliIntentServe CliIntent = iota + CliIntentCheckConfig = iota +) + +type CliOptions struct { + Intent CliIntent + ConfigPath string +} + +func ParseCliOptions() (*CliOptions, error) { + flags := flag.NewFlagSet("", flag.ExitOnError) + + checkConfig := flags.Bool("check-config", false, "Check whether the config is valid") + configPath := flags.String("config", "glance.yml", "Set config path") + + err := flags.Parse(os.Args[1:]) + + if err != nil { + return nil, err + } + + intent := CliIntentServe + + if *checkConfig { + intent = CliIntentCheckConfig + } + + return &CliOptions{ + Intent: intent, + ConfigPath: *configPath, + }, nil +} diff --git a/internal/glance/config.go b/internal/glance/config.go new file mode 100644 index 0000000..9acc3be --- /dev/null +++ b/internal/glance/config.go @@ -0,0 +1,79 @@ +package glance + +import ( + "fmt" + "io" + + "gopkg.in/yaml.v3" +) + +type Config struct { + Server Server `yaml:"server"` + Theme Theme `yaml:"theme"` + Pages []Page `yaml:"pages"` +} + +func NewConfigFromYml(contents io.Reader) (*Config, error) { + config := NewConfig() + + contentBytes, err := io.ReadAll(contents) + + if err != nil { + return nil, err + } + + err = yaml.Unmarshal(contentBytes, config) + + if err != nil { + return nil, err + } + + if err = configIsValid(config); err != nil { + return nil, err + } + + return config, nil +} + +func NewConfig() *Config { + config := &Config{} + + config.Server.Host = "" + config.Server.Port = 8080 + + return config +} + +func configIsValid(config *Config) error { + for i := range config.Pages { + if config.Pages[i].Title == "" { + return fmt.Errorf("Page %d has no title", i+1) + } + + if len(config.Pages[i].Columns) == 0 { + return fmt.Errorf("Page %d has no columns", i+1) + } + + if len(config.Pages[i].Columns) > 3 { + return fmt.Errorf("Page %d has more than 3 columns: %d", i+1, len(config.Pages[i].Columns)) + } + + columnSizesCount := make(map[string]int) + + for j := range config.Pages[i].Columns { + if config.Pages[i].Columns[j].Size != "small" && config.Pages[i].Columns[j].Size != "full" { + return fmt.Errorf("Column %d of page %d: size can only be either small or full", j+1, i+1) + } + + columnSizesCount[config.Pages[i].Columns[j].Size]++ + } + + full := columnSizesCount["full"] + + if full > 2 || full == 0 { + return fmt.Errorf("Page %d must have either 1 or 2 full width columns", i+1) + } + } + + return nil +} diff --git a/internal/glance/glance.go b/internal/glance/glance.go new file mode 100644 index 0000000..0c4001d --- /dev/null +++ b/internal/glance/glance.go @@ -0,0 +1,221 @@ +package glance + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/widget" +) + +var buildVersion = "dev" + +var sequentialWhitespacePattern = regexp.MustCompile(`\s+`) + +type Application struct { + Version string + Config Config + slugToPage map[string]*Page +} + +type Theme struct { + BackgroundColor *widget.HSLColorField `yaml:"background-color"` + PrimaryColor *widget.HSLColorField `yaml:"primary-color"` + PositiveColor *widget.HSLColorField `yaml:"positive-color"` + NegativeColor *widget.HSLColorField `yaml:"negative-color"` + Light bool `yaml:"light"` + ContrastMultiplier float32 `yaml:"contrast-multiplier"` + TextSaturationMultiplier float32 `yaml:"text-saturation-multiplier"` +} + +type Server struct { + Host string `yaml:"host"` + Port uint16 `yaml:"port"` + AssetsPath string `yaml:"assets-path"` + StartedAt time.Time `yaml:"-"` +} + +type Column struct { + Size string `yaml:"size"` + Widgets widget.Widgets `yaml:"widgets"` +} + +type templateData struct { + App *Application + Page *Page +} + +type Page struct { + Title string `yaml:"name"` + Slug string `yaml:"slug"` + Columns []Column `yaml:"columns"` + mu sync.Mutex +} + +func (p *Page) UpdateOutdatedWidgets() { + now := time.Now() + + var wg sync.WaitGroup + context := context.Background() + + for c := range p.Columns { + for w := range p.Columns[c].Widgets { + widget := p.Columns[c].Widgets[w] + + if !widget.RequiresUpdate(&now) { + continue + } + + wg.Add(1) + go func() { + defer wg.Done() + widget.Update(context) + }() + } + } + + wg.Wait() +} + +// TODO: fix, currently very simple, lots of uncovered edge cases +func titleToSlug(s string) string { + s = strings.ToLower(s) + s = sequentialWhitespacePattern.ReplaceAllString(s, "-") + s = strings.Trim(s, "-") + + return s +} + +func NewApplication(config *Config) (*Application, error) { + if len(config.Pages) == 0 { + return nil, fmt.Errorf("no pages configured") + } + + app := &Application{ + Version: buildVersion, + Config: *config, + slugToPage: make(map[string]*Page), + } + + app.slugToPage[""] = &config.Pages[0] + + for i := range config.Pages { + if config.Pages[i].Slug == "" { + config.Pages[i].Slug = titleToSlug(config.Pages[i].Title) + } + + app.slugToPage[config.Pages[i].Slug] = &config.Pages[i] + } + + return app, nil +} + +func (a *Application) HandlePageRequest(w http.ResponseWriter, r *http.Request) { + page, exists := a.slugToPage[r.PathValue("page")] + + if !exists { + a.HandleNotFound(w, r) + return + } + + pageData := templateData{ + Page: page, + App: a, + } + + var responseBytes bytes.Buffer + err := assets.PageTemplate.Execute(&responseBytes, pageData) + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(responseBytes.Bytes()) +} + +func (a *Application) HandlePageContentRequest(w http.ResponseWriter, r *http.Request) { + page, exists := a.slugToPage[r.PathValue("page")] + + if !exists { + a.HandleNotFound(w, r) + return + } + + pageData := templateData{ + Page: page, + } + + page.mu.Lock() + defer page.mu.Unlock() + page.UpdateOutdatedWidgets() + + var responseBytes bytes.Buffer + err := assets.PageContentTemplate.Execute(&responseBytes, pageData) + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(err.Error())) + return + } + + w.Write(responseBytes.Bytes()) +} + +func (a *Application) HandleNotFound(w http.ResponseWriter, r *http.Request) { + // TODO: add proper not found page + w.WriteHeader(http.StatusNotFound) + w.Write([]byte("Page not found")) +} + +func FileServerWithCache(fs http.FileSystem, cacheDuration time.Duration) http.Handler { + server := http.FileServer(fs) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // TODO: fix always setting cache control even if the file doesn't exist + w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(cacheDuration.Seconds()))) + server.ServeHTTP(w, r) + }) +} + +func (a *Application) Serve() error { + // TODO: add gzip support, static files must have their gzipped contents cached + // TODO: add HTTPS support + mux := http.NewServeMux() + + mux.HandleFunc("GET /{$}", a.HandlePageRequest) + mux.HandleFunc("GET /{page}", a.HandlePageRequest) + mux.HandleFunc("GET /api/pages/{page}/content/{$}", a.HandlePageContentRequest) + mux.Handle("GET /static/{path...}", http.StripPrefix("/static/", FileServerWithCache(http.FS(assets.PublicFS), 2*time.Hour))) + + if a.Config.Server.AssetsPath != "" { + absAssetsPath, err := filepath.Abs(a.Config.Server.AssetsPath) + + if err != nil { + return fmt.Errorf("invalid assets path: %s", a.Config.Server.AssetsPath) + } + + slog.Info("Serving assets", "path", absAssetsPath) + assetsFS := FileServerWithCache(http.Dir(a.Config.Server.AssetsPath), 2*time.Hour) + mux.Handle("/assets/{path...}", http.StripPrefix("/assets/", assetsFS)) + } + + server := http.Server{ + Addr: fmt.Sprintf("%s:%d", a.Config.Server.Host, a.Config.Server.Port), + Handler: mux, + } + + a.Config.Server.StartedAt = time.Now() + + slog.Info("Starting server", "host", a.Config.Server.Host, "port", a.Config.Server.Port) + return server.ListenAndServe() +} diff --git a/internal/glance/main.go b/internal/glance/main.go new file mode 100644 index 0000000..5eee962 --- /dev/null +++ b/internal/glance/main.go @@ -0,0 +1,46 @@ +package glance + +import ( + "fmt" + "os" +) + +func Main() int { + options, err := ParseCliOptions() + + if err != nil { + fmt.Println(err) + return 1 + } + + configFile, err := os.Open(options.ConfigPath) + + if err != nil { + fmt.Printf("failed opening config file: %v\n", err) + return 1 + } + + config, err := NewConfigFromYml(configFile) + configFile.Close() + + if err != nil { + fmt.Printf("failed parsing config file: %v\n", err) + return 1 + } + + if options.Intent == CliIntentServe { + app, err := NewApplication(config) + + if err != nil { + fmt.Printf("failed creating application: %v\n", err) + return 1 + } + + if app.Serve() != nil { + fmt.Printf("http server error: %v\n", err) + return 1 + } + } + + return 0 +} diff --git a/internal/widget/bookmarks.go b/internal/widget/bookmarks.go new file mode 100644 index 0000000..a3e3d28 --- /dev/null +++ b/internal/widget/bookmarks.go @@ -0,0 +1,31 @@ +package widget + +import ( + "html/template" + + "github.com/glanceapp/glance/internal/assets" +) + +type Bookmarks struct { + widgetBase `yaml:",inline"` + cachedHTML template.HTML `yaml:"-"` + Groups []struct { + Title string `yaml:"title"` + Color *HSLColorField `yaml:"color"` + Links []struct { + Title string `yaml:"title"` + URL string `yaml:"url"` + } `yaml:"links"` + } `yaml:"groups"` +} + +func (widget *Bookmarks) Initialize() error { + widget.withTitle("Bookmarks").withError(nil) + widget.cachedHTML = widget.render(widget, assets.BookmarksTemplate) + + return nil +} + +func (widget *Bookmarks) Render() template.HTML { + return widget.cachedHTML +} diff --git a/internal/widget/calendar.go b/internal/widget/calendar.go new file mode 100644 index 0000000..a126353 --- /dev/null +++ b/internal/widget/calendar.go @@ -0,0 +1,30 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Calendar struct { + widgetBase `yaml:",inline"` + Calendar *feed.Calendar +} + +func (widget *Calendar) Initialize() error { + widget.withTitle("Calendar").withCacheOnTheHour() + + return nil +} + +func (widget *Calendar) Update(ctx context.Context) { + widget.Calendar = feed.NewCalendar(time.Now()) + widget.withError(nil).scheduleNextUpdate() +} + +func (widget *Calendar) Render() template.HTML { + return widget.render(widget, assets.CalendarTemplate) +} diff --git a/internal/widget/fields.go b/internal/widget/fields.go new file mode 100644 index 0000000..eecb916 --- /dev/null +++ b/internal/widget/fields.go @@ -0,0 +1,152 @@ +package widget + +import ( + "fmt" + "html/template" + "os" + "regexp" + "strconv" + "time" + + "gopkg.in/yaml.v3" +) + +var HSLColorPattern = regexp.MustCompile(`^(?:hsla?\()?(\d{1,3})(?: |,)+(\d{1,3})%?(?: |,)+(\d{1,3})%?\)?$`) +var EnvFieldPattern = regexp.MustCompile(`^\${([A-Z_]+)}$`) + +const ( + HSLHueMax = 360 + HSLSaturationMax = 100 + HSLLightnessMax = 100 +) + +type HSLColorField struct { + Hue uint16 + Saturation uint8 + Lightness uint8 +} + +func (c *HSLColorField) String() string { + return fmt.Sprintf("hsl(%d, %d%%, %d%%)", c.Hue, c.Saturation, c.Lightness) +} + +func (c *HSLColorField) AsCSSValue() template.CSS { + return template.CSS(c.String()) +} + +func (c *HSLColorField) UnmarshalYAML(node *yaml.Node) error { + var value string + + if err := node.Decode(&value); err != nil { + return err + } + + matches := HSLColorPattern.FindStringSubmatch(value) + + if len(matches) != 4 { + return fmt.Errorf("invalid HSL color format: %s", value) + } + + hue, err := strconv.ParseUint(matches[1], 10, 16) + + if err != nil { + return err + } + + if hue > HSLHueMax { + return fmt.Errorf("HSL hue must be between 0 and %d", HSLHueMax) + } + + saturation, err := strconv.ParseUint(matches[2], 10, 8) + + if err != nil { + return err + } + + if saturation > HSLSaturationMax { + return fmt.Errorf("HSL saturation must be between 0 and %d", HSLSaturationMax) + } + + lightness, err := strconv.ParseUint(matches[3], 10, 8) + + if err != nil { + return err + } + + if lightness > HSLLightnessMax { + return fmt.Errorf("HSL lightness must be between 0 and %d", HSLLightnessMax) + } + + c.Hue = uint16(hue) + c.Saturation = uint8(saturation) + c.Lightness = uint8(lightness) + + return nil +} + +var DurationPattern = regexp.MustCompile(`^(\d+)(s|m|h|d)$`) + +type DurationField time.Duration + +func (d *DurationField) UnmarshalYAML(node *yaml.Node) error { + var value string + + if err := node.Decode(&value); err != nil { + return err + } + + matches := DurationPattern.FindStringSubmatch(value) + + if len(matches) != 3 { + return fmt.Errorf("invalid duration format: %s", value) + } + + duration, err := strconv.Atoi(matches[1]) + + if err != nil { + return err + } + + switch matches[2] { + case "s": + *d = DurationField(time.Duration(duration) * time.Second) + case "m": + *d = DurationField(time.Duration(duration) * time.Minute) + case "h": + *d = DurationField(time.Duration(duration) * time.Hour) + case "d": + *d = DurationField(time.Duration(duration) * 24 * time.Hour) + } + + return nil +} + +type OptionalEnvString string + +func (f *OptionalEnvString) UnmarshalYAML(node *yaml.Node) error { + var value string + + err := node.Decode(&value) + + if err != nil { + return err + } + + matches := EnvFieldPattern.FindStringSubmatch(value) + + if len(matches) != 2 { + *f = OptionalEnvString(value) + + return nil + } + + value, found := os.LookupEnv(matches[1]) + + if !found { + return fmt.Errorf("environment variable %s not found", matches[1]) + } + + *f = OptionalEnvString(value) + + return nil +} diff --git a/internal/widget/hacker-news.go b/internal/widget/hacker-news.go new file mode 100644 index 0000000..9870e74 --- /dev/null +++ b/internal/widget/hacker-news.go @@ -0,0 +1,52 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type HackerNews struct { + widgetBase `yaml:",inline"` + Posts feed.ForumPosts `yaml:"-"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *HackerNews) Initialize() error { + widget.withTitle("Hacker News").withCacheDuration(30 * time.Minute) + + if widget.Limit <= 0 { + widget.Limit = 15 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *HackerNews) Update(ctx context.Context) { + posts, err := feed.FetchHackerNewsTopPosts(40) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + posts.CalculateEngagement() + posts.SortByEngagement() + + if widget.Limit < len(posts) { + posts = posts[:widget.Limit] + } + + widget.Posts = posts +} + +func (widget *HackerNews) Render() template.HTML { + return widget.render(widget, assets.ForumPostsTemplate) +} diff --git a/internal/widget/iframe.go b/internal/widget/iframe.go new file mode 100644 index 0000000..44d0822 --- /dev/null +++ b/internal/widget/iframe.go @@ -0,0 +1,45 @@ +package widget + +import ( + "errors" + "fmt" + "html/template" + "net/url" + + "github.com/glanceapp/glance/internal/assets" +) + +type IFrame struct { + widgetBase `yaml:",inline"` + cachedHTML template.HTML `yaml:"-"` + Source string `yaml:"source"` + Height int `yaml:"height"` +} + +func (widget *IFrame) Initialize() error { + widget.withTitle("IFrame").withError(nil) + + if widget.Source == "" { + return errors.New("missing source for iframe") + } + + _, err := url.Parse(widget.Source) + + if err != nil { + return fmt.Errorf("invalid source for iframe: %v", err) + } + + if widget.Height == 50 { + widget.Height = 300 + } else if widget.Height < 50 { + widget.Height = 50 + } + + widget.cachedHTML = widget.render(widget, assets.IFrameTemplate) + + return nil +} + +func (widget *IFrame) Render() template.HTML { + return widget.cachedHTML +} diff --git a/internal/widget/monitor.go b/internal/widget/monitor.go new file mode 100644 index 0000000..639e7f4 --- /dev/null +++ b/internal/widget/monitor.go @@ -0,0 +1,100 @@ +package widget + +import ( + "context" + "fmt" + "html/template" + "net/http" + "strconv" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +func statusCodeToText(status int) string { + if status == 200 { + return "OK" + } + if status == 404 { + return "Not Found" + } + if status == 403 { + return "Forbidden" + } + if status == 401 { + return "Unauthorized" + } + if status >= 400 { + return "Client Error" + } + if status >= 500 { + return "Server Error" + } + + return strconv.Itoa(status) +} + +func statusCodeToStyle(status int) string { + if status == 200 { + return "good" + } + + return "bad" +} + +type Monitor struct { + widgetBase `yaml:",inline"` + Sites []struct { + Title string `yaml:"title"` + Url string `yaml:"url"` + IconUrl string `yaml:"icon"` + Status *feed.SiteStatus `yaml:"-"` + StatusText string `yaml:"-"` + StatusStyle string `yaml:"-"` + } `yaml:"sites"` +} + +func (widget *Monitor) Initialize() error { + widget.withTitle("Monitor").withCacheDuration(5 * time.Minute) + + return nil +} + +func (widget *Monitor) Update(ctx context.Context) { + requests := make([]*http.Request, len(widget.Sites)) + + for i := range widget.Sites { + request, err := http.NewRequest("HEAD", widget.Sites[i].Url, nil) + + if err != nil { + message := fmt.Errorf("failed to create http request for %s: %s", widget.Sites[i].Url, err) + widget.withNotice(message) + continue + } + + requests[i] = request + } + + statuses, err := feed.FetchStatusesForRequests(requests) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + for i := range widget.Sites { + site := &widget.Sites[i] + status := &statuses[i] + + site.Status = status + + if !status.TimedOut { + site.StatusText = statusCodeToText(status.Code) + site.StatusStyle = statusCodeToStyle(status.Code) + } + } +} + +func (widget *Monitor) Render() template.HTML { + return widget.render(widget, assets.MonitorTemplate) +} diff --git a/internal/widget/reddit.go b/internal/widget/reddit.go new file mode 100644 index 0000000..3287fcf --- /dev/null +++ b/internal/widget/reddit.go @@ -0,0 +1,66 @@ +package widget + +import ( + "context" + "errors" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Reddit struct { + widgetBase `yaml:",inline"` + Posts feed.ForumPosts `yaml:"-"` + Subreddit string `yaml:"subreddit"` + Style string `yaml:"style"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *Reddit) Initialize() error { + if widget.Subreddit == "" { + return errors.New("no subreddit specified") + } + + if widget.Limit <= 0 { + widget.Limit = 15 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + widget.withTitle("/r/" + widget.Subreddit).withCacheDuration(30 * time.Minute) + + return nil +} + +func (widget *Reddit) Update(ctx context.Context) { + posts, err := feed.FetchSubredditPosts(widget.Subreddit) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(posts) > widget.Limit { + posts = posts[:widget.Limit] + } + + posts.SortByEngagement() + widget.Posts = posts +} + +func (widget *Reddit) Render() template.HTML { + if widget.Style == "horizontal-cards" { + return widget.render(widget, assets.RedditCardsHorizontalTemplate) + } + + if widget.Style == "vertical-cards" { + return widget.render(widget, assets.RedditCardsVerticalTemplate) + } + + return widget.render(widget, assets.ForumPostsTemplate) + +} diff --git a/internal/widget/releases.go b/internal/widget/releases.go new file mode 100644 index 0000000..77fe103 --- /dev/null +++ b/internal/widget/releases.go @@ -0,0 +1,51 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Releases struct { + widgetBase `yaml:",inline"` + Releases feed.AppReleases `yaml:"-"` + Repositories []string `yaml:"repositories"` + Token OptionalEnvString `yaml:"token"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *Releases) Initialize() error { + widget.withTitle("Releases").withCacheDuration(2 * time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 10 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *Releases) Update(ctx context.Context) { + releases, err := feed.FetchLatestReleasesFromGithub(widget.Repositories, string(widget.Token)) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(releases) > widget.Limit { + releases = releases[:widget.Limit] + } + + widget.Releases = releases +} + +func (widget *Releases) Render() template.HTML { + return widget.render(widget, assets.ReleasesTemplate) +} diff --git a/internal/widget/rss.go b/internal/widget/rss.go new file mode 100644 index 0000000..81bd3ae --- /dev/null +++ b/internal/widget/rss.go @@ -0,0 +1,55 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type RSS struct { + widgetBase `yaml:",inline"` + FeedRequests []feed.RSSFeedRequest `yaml:"feeds"` + Style string `yaml:"style"` + Items feed.RSSFeedItems `yaml:"-"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *RSS) Initialize() error { + widget.withTitle("RSS Feed").withCacheDuration(1 * time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 25 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *RSS) Update(ctx context.Context) { + items, err := feed.GetItemsFromRSSFeeds(widget.FeedRequests) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(items) > widget.Limit { + items = items[:widget.Limit] + } + + widget.Items = items +} + +func (widget *RSS) Render() template.HTML { + if widget.Style == "horizontal-cards" { + return widget.render(widget, assets.RSSCardsTemplate) + } + + return widget.render(widget, assets.RSSListTemplate) +} diff --git a/internal/widget/stocks.go b/internal/widget/stocks.go new file mode 100644 index 0000000..afba0e4 --- /dev/null +++ b/internal/widget/stocks.go @@ -0,0 +1,37 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Stocks struct { + widgetBase `yaml:",inline"` + Stocks feed.Stocks `yaml:"-"` + Tickers []feed.StockRequest `yaml:"stocks"` +} + +func (widget *Stocks) Initialize() error { + widget.withTitle("Stocks").withCacheDuration(time.Hour) + + return nil +} + +func (widget *Stocks) Update(ctx context.Context) { + stocks, err := feed.FetchStocksDataFromYahoo(widget.Tickers) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + stocks.SortByAbsChange() + widget.Stocks = stocks +} + +func (widget *Stocks) Render() template.HTML { + return widget.render(widget, assets.StocksTemplate) +} diff --git a/internal/widget/twitch-channels.go b/internal/widget/twitch-channels.go new file mode 100644 index 0000000..3f36669 --- /dev/null +++ b/internal/widget/twitch-channels.go @@ -0,0 +1,42 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type TwitchChannels struct { + widgetBase `yaml:",inline"` + ChannelsRequest []string `yaml:"channels"` + Channels []feed.TwitchChannel `yaml:"-"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *TwitchChannels) Initialize() error { + widget.withTitle("Twitch Channels").withCacheDuration(time.Minute * 10) + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *TwitchChannels) Update(ctx context.Context) { + channels, err := feed.FetchChannelsFromTwitch(widget.ChannelsRequest) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + channels.SortByViewers() + widget.Channels = channels +} + +func (widget *TwitchChannels) Render() template.HTML { + return widget.render(widget, assets.TwitchChannelsTemplate) +} diff --git a/internal/widget/twitch-top-games.go b/internal/widget/twitch-top-games.go new file mode 100644 index 0000000..812c3c6 --- /dev/null +++ b/internal/widget/twitch-top-games.go @@ -0,0 +1,46 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type TwitchGames struct { + widgetBase `yaml:",inline"` + Categories []feed.TwitchCategory `yaml:"-"` + Exclude []string `yaml:"exclude"` + Limit int `yaml:"limit"` + CollapseAfter int `yaml:"collapse-after"` +} + +func (widget *TwitchGames) Initialize() error { + widget.withTitle("Top games on Twitch").withCacheDuration(time.Minute * 10) + + if widget.Limit <= 0 { + widget.Limit = 10 + } + + if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 { + widget.CollapseAfter = 5 + } + + return nil +} + +func (widget *TwitchGames) Update(ctx context.Context) { + categories, err := feed.FetchTopGamesFromTwitch(widget.Exclude, widget.Limit) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + widget.Categories = categories +} + +func (widget *TwitchGames) Render() template.HTML { + return widget.render(widget, assets.TwitchGamesListTemplate) +} diff --git a/internal/widget/videos.go b/internal/widget/videos.go new file mode 100644 index 0000000..2652768 --- /dev/null +++ b/internal/widget/videos.go @@ -0,0 +1,45 @@ +package widget + +import ( + "context" + "html/template" + "time" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Videos struct { + widgetBase `yaml:",inline"` + Videos feed.Videos `yaml:"-"` + Channels []string `yaml:"channels"` + Limit int `yaml:"limit"` +} + +func (widget *Videos) Initialize() error { + widget.withTitle("Videos").withCacheDuration(time.Hour) + + if widget.Limit <= 0 { + widget.Limit = 25 + } + + return nil +} + +func (widget *Videos) Update(ctx context.Context) { + videos, err := feed.FetchYoutubeChannelUploads(widget.Channels) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + if len(videos) > widget.Limit { + videos = videos[:widget.Limit] + } + + widget.Videos = videos +} + +func (widget *Videos) Render() template.HTML { + return widget.render(widget, assets.VideosTemplate) +} diff --git a/internal/widget/weather.go b/internal/widget/weather.go new file mode 100644 index 0000000..390f9d7 --- /dev/null +++ b/internal/widget/weather.go @@ -0,0 +1,50 @@ +package widget + +import ( + "context" + "fmt" + "html/template" + + "github.com/glanceapp/glance/internal/assets" + "github.com/glanceapp/glance/internal/feed" +) + +type Weather struct { + widgetBase `yaml:",inline"` + Location string `yaml:"location"` + HideLocation bool `yaml:"hide-location"` + Place *feed.PlaceJson `yaml:"-"` + Weather *feed.Weather `yaml:"-"` + TimeLabels [12]string `yaml:"-"` +} + +var timeLabels = [12]string{"2am", "4am", "6am", "8am", "10am", "12pm", "2pm", "4pm", "6pm", "8pm", "10pm", "12am"} + +func (widget *Weather) Initialize() error { + widget.withTitle("Weather").withCacheOnTheHour() + widget.TimeLabels = timeLabels + + place, err := feed.FetchPlaceFromName(widget.Location) + + if err != nil { + return fmt.Errorf("failed fetching data for %s: %v", widget.Location, err) + } + + widget.Place = place + + return nil +} + +func (widget *Weather) Update(ctx context.Context) { + weather, err := feed.FetchWeatherForPlace(widget.Place) + + if !widget.canContinueUpdateAfterHandlingErr(err) { + return + } + + widget.Weather = weather +} + +func (widget *Weather) Render() template.HTML { + return widget.render(widget, assets.WeatherTemplate) +} diff --git a/internal/widget/widget.go b/internal/widget/widget.go new file mode 100644 index 0000000..367d822 --- /dev/null +++ b/internal/widget/widget.go @@ -0,0 +1,282 @@ +package widget + +import ( + "bytes" + "context" + "errors" + "fmt" + "html/template" + "log/slog" + "math" + "time" + + "github.com/glanceapp/glance/internal/feed" + + "gopkg.in/yaml.v3" +) + +func New(widgetType string) (Widget, error) { + switch widgetType { + case "calendar": + return &Calendar{}, nil + case "weather": + return &Weather{}, nil + case "bookmarks": + return &Bookmarks{}, nil + case "iframe": + return &IFrame{}, nil + case "hacker-news": + return &HackerNews{}, nil + case "releases": + return &Releases{}, nil + case "videos": + return &Videos{}, nil + case "stocks": + return &Stocks{}, nil + case "reddit": + return &Reddit{}, nil + case "rss": + return &RSS{}, nil + case "monitor": + return &Monitor{}, nil + case "twitch-top-games": + return &TwitchGames{}, nil + case "twitch-channels": + return &TwitchChannels{}, nil + default: + return nil, fmt.Errorf("unknown widget type: %s", widgetType) + } +} + +type Widgets []Widget + +func (w *Widgets) UnmarshalYAML(node *yaml.Node) error { + var nodes []yaml.Node + + if err := node.Decode(&nodes); err != nil { + return err + } + + for _, node := range nodes { + meta := struct { + Type string `yaml:"type"` + }{} + + if err := node.Decode(&meta); err != nil { + return err + } + + widget, err := New(meta.Type) + + if err != nil { + return err + } + + if err = node.Decode(widget); err != nil { + return err + } + + if err = widget.Initialize(); err != nil { + return err + } + + *w = append(*w, widget) + } + + return nil +} + +type Widget interface { + Initialize() error + RequiresUpdate(*time.Time) bool + Update(context.Context) + Render() template.HTML + GetType() string +} + +type cacheType int + +const ( + cacheTypeInfinite cacheType = iota + cacheTypeDuration + cacheTypeOnTheHour +) + +type widgetBase struct { + Type string `yaml:"type"` + Title string `yaml:"title"` + CustomCacheDuration DurationField `yaml:"cache"` + ContentAvailable bool `yaml:"-"` + Error error `yaml:"-"` + Notice error `yaml:"-"` + templateBuffer bytes.Buffer `yaml:"-"` + cacheDuration time.Duration `yaml:"-"` + cacheType cacheType `yaml:"-"` + nextUpdate time.Time `yaml:"-"` + updateRetriedTimes int `yaml:"-"` +} + +func (w *widgetBase) RequiresUpdate(now *time.Time) bool { + if w.cacheType == cacheTypeInfinite { + return false + } + + if w.nextUpdate.IsZero() { + return true + } + + return now.After(w.nextUpdate) +} + +func (w *widgetBase) Update(ctx context.Context) { + +} + +func (w *widgetBase) GetType() string { + return w.Type +} + +func (w *widgetBase) render(data any, t *template.Template) template.HTML { + w.templateBuffer.Reset() + err := t.Execute(&w.templateBuffer, data) + + if err != nil { + w.ContentAvailable = false + w.Error = err + + slog.Error("failed to render template", "error", err) + + // need to immediately re-render with the error, + // otherwise risk breaking the page since the widget + // will likely be partially rendered with tags not closed. + w.templateBuffer.Reset() + err2 := t.Execute(&w.templateBuffer, data) + + if err2 != nil { + slog.Error("failed to render error within widget", "error", err2, "initial_error", err) + w.templateBuffer.Reset() + // TODO: add some kind of a generic widget error template when the widget + // failed to render, and we also failed to re-render the widget with the error + } + } + + return template.HTML(w.templateBuffer.String()) +} + +func (w *widgetBase) withTitle(title string) *widgetBase { + if w.Title == "" { + w.Title = title + } + + return w +} + +func (w *widgetBase) withCacheDuration(duration time.Duration) *widgetBase { + w.cacheType = cacheTypeDuration + + if duration == -1 || w.CustomCacheDuration == 0 { + w.cacheDuration = duration + } else { + w.cacheDuration = time.Duration(w.CustomCacheDuration) + } + + return w +} + +func (w *widgetBase) withCacheOnTheHour() *widgetBase { + w.cacheType = cacheTypeOnTheHour + + return w +} + +func (w *widgetBase) withNotice(err error) *widgetBase { + w.Notice = err + + return w +} + +func (w *widgetBase) withError(err error) *widgetBase { + if err == nil && !w.ContentAvailable { + w.ContentAvailable = true + } + + w.Error = err + + return w +} + +func (w *widgetBase) canContinueUpdateAfterHandlingErr(err error) bool { + // TODO: needs covering more edge cases. + // if there's partial content and we update early there's a chance + // the early update returns even less content than the initial update. + // need some kind of mechanism that tells us whether we should update early + // or not depending on the number of things that failed during the initial + // and subsequent update and how they failed - ie whether it was server + // error (like gateway timeout, do retry early) or client error (like + // hitting a rate limit, don't retry early). will require reworking a + // good amount of code in the feed package and probably having a custom + // error type that holds more information because screw wrapping errors. + // alternatively have a resource cache and only refetch the failed resources, + // then rebuild the widget. + + if err != nil { + w.scheduleEarlyUpdate() + + if !errors.Is(err, feed.ErrPartialContent) { + w.withError(err) + w.withNotice(nil) + return false + } + + w.withError(nil) + w.withNotice(err) + return true + } + + w.withNotice(nil) + w.withError(nil) + w.scheduleNextUpdate() + return true +} + +func (w *widgetBase) getNextUpdateTime() time.Time { + now := time.Now() + + if w.cacheType == cacheTypeDuration { + return now.Add(w.cacheDuration) + } + + if w.cacheType == cacheTypeOnTheHour { + return now.Add(time.Duration( + ((60-now.Minute())*60)-now.Second(), + ) * time.Second) + } + + return time.Time{} +} + +func (w *widgetBase) scheduleNextUpdate() *widgetBase { + w.nextUpdate = w.getNextUpdateTime() + w.updateRetriedTimes = 0 + + return w +} + +func (w *widgetBase) scheduleEarlyUpdate() *widgetBase { + w.updateRetriedTimes++ + + if w.updateRetriedTimes > 5 { + w.updateRetriedTimes = 5 + } + + nextEarlyUpdate := time.Now().Add(time.Duration(math.Pow(float64(w.updateRetriedTimes), 2)) * time.Minute) + nextUsualUpdate := w.getNextUpdateTime() + + if nextEarlyUpdate.After(nextUsualUpdate) { + w.nextUpdate = nextUsualUpdate + } else { + w.nextUpdate = nextEarlyUpdate + } + + return w +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..fa1d7f2 --- /dev/null +++ b/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "os" + + "github.com/glanceapp/glance/internal/glance" +) + +func main() { + os.Exit(glance.Main()) +} diff --git a/scripts/build-and-ship/main.go b/scripts/build-and-ship/main.go new file mode 100644 index 0000000..2349947 --- /dev/null +++ b/scripts/build-and-ship/main.go @@ -0,0 +1,237 @@ +package main + +import ( + "fmt" + "os" + "os/exec" + "path" + "strings" +) + +// bunch of spaget but it does the job for now +// TODO: tidy up and add a proper build system with CI + +const buildPath = "./build" +const archivesPath = "./build/archives" +const executableName = "glance" +const ownerAndRepo = "glanceapp/glance" +const moduleName = "github.com/" + ownerAndRepo + +type archiveType int + +const ( + archiveTypeTarGz archiveType = iota + archiveTypeZip +) + +type buildInfo struct { + version string +} + +type buildTarget struct { + os string + arch string + armV int + extension string + archive archiveType +} + +var buildTargets = []buildTarget{ + { + os: "windows", + arch: "amd64", + extension: ".exe", + archive: archiveTypeZip, + }, + { + os: "windows", + arch: "arm64", + extension: ".exe", + archive: archiveTypeZip, + }, + { + os: "linux", + arch: "amd64", + }, + { + os: "linux", + arch: "arm64", + }, + { + os: "linux", + arch: "arm", + armV: 6, + }, + { + os: "linux", + arch: "arm", + armV: 7, + }, +} + +func main() { + cwd, err := os.Getwd() + + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + _, err = os.Stat(buildPath) + + if err == nil { + fmt.Println("Cleaning up build path") + os.RemoveAll(buildPath) + } + + os.Mkdir(buildPath, 0755) + os.Mkdir(archivesPath, 0755) + + version, err := getVersionFromGit() + + if err != nil { + fmt.Println(version, err) + os.Exit(1) + } + + info := buildInfo{ + version: version, + } + + for _, target := range buildTargets { + fmt.Printf("Building for %s/%s\n", target.os, target.arch) + if err := build(cwd, info, target); err != nil { + fmt.Println(err) + os.Exit(1) + } + } + + versionTag := fmt.Sprintf("%s:%s", ownerAndRepo, version) + latestTag := fmt.Sprintf("%s:latest", ownerAndRepo) + + fmt.Println("Building docker image") + + output, err := exec.Command( + "sudo", "docker", "build", + "--platform=linux/arm64,linux/amd64", + "-t", versionTag, + "-t", latestTag, + ".", + ).CombinedOutput() + + if err != nil { + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } + + var input string + fmt.Print("Push docker image? [y/n]: ") + fmt.Scanln(&input) + + if input != "y" { + os.Exit(0) + } + + output, err = exec.Command( + "sudo", "docker", "push", versionTag, + ).CombinedOutput() + + if err != nil { + fmt.Printf("Failed pushing %s:\n", versionTag) + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } + + output, err = exec.Command( + "sudo", "docker", "push", latestTag, + ).CombinedOutput() + + if err != nil { + fmt.Printf("Failed pushing %s:\n", latestTag) + fmt.Println(string(output)) + fmt.Println(err) + os.Exit(1) + } +} + +func getVersionFromGit() (string, error) { + output, err := exec.Command("git", "describe", "--tags", "--abbrev=0").CombinedOutput() + + if err == nil { + return strings.TrimSpace(string(output)), err + } + + return string(output), err +} + +func archiveFile(name string, target string, t archiveType) error { + var output []byte + var err error + + if t == archiveTypeZip { + output, err = exec.Command("zip", "-j", path.Join(archivesPath, name+".zip"), target).CombinedOutput() + } else if t == archiveTypeTarGz { + output, err = exec.Command("tar", "-C", buildPath, "-czf", path.Join(archivesPath, name+".tar.gz"), name).CombinedOutput() + } + + if err != nil { + fmt.Println(string(output)) + return err + } + + return nil +} + +func build(workingDir string, info buildInfo, target buildTarget) error { + var name string + + if target.arch != "arm" { + name = fmt.Sprintf("%s-%s-%s%s", executableName, target.os, target.arch, target.extension) + } else { + name = fmt.Sprintf("%s-%s-%sv%d", executableName, target.os, target.arch, target.armV) + } + + binaryPath := path.Join(buildPath, name) + + glancePackage := moduleName + "/internal/glance" + + flags := "-s -w" + flags += fmt.Sprintf(" -X %s.buildVersion=%s", glancePackage, info.version) + + cmd := exec.Command( + "go", + "build", + "--trimpath", + "--ldflags", + flags, + "-o", + binaryPath, + ) + + cmd.Dir = workingDir + env := append(os.Environ(), "GOOS="+target.os, "GOARCH="+target.arch, "CGO_ENABLED=0") + + if target.arch == "arm" { + env = append(env, fmt.Sprintf("GOARM=%d", target.armV)) + } + + cmd.Env = env + output, err := cmd.CombinedOutput() + + if err != nil { + fmt.Println(err) + fmt.Println(string(output)) + return err + } + + os.Chmod(binaryPath, 0755) + + fmt.Println("Creating archive") + if err := archiveFile(name, binaryPath, target.archive); err != nil { + return err + } + + return nil +}