diff options
117 files changed, 721 insertions, 4631 deletions
diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 96f580f..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "static/sfw"] - path = static/sfw - url = https://git.nathanreiner.xyz/sfw diff --git a/LICENCE.txt b/LICENCE.txt new file mode 100644 index 0000000..281d399 --- /dev/null +++ b/LICENCE.txt @@ -0,0 +1,619 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. @@ -1,17 +1 @@ # Memora - -## TODO - -### Frontend -- [ ] Shuffle-Mode - - [ ] Something like *X* years/months/days ago this happened. -- [x] Settings - - [x] Profile picture - - [x] Profile name - - [x] Birthday such we can flag pictures as birthday pictures. -- [x] Upload progress bar - -### Backend -- [x] Not all files are delivered. -- [X] **Removing file makes date ordering wrong**. -- [ ] Cache shuffle data in backend and drop them when next day starts. @@ -4,22 +4,25 @@ pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const opts = b.addOptions(); - - const disable_auth = b.option(bool, "disable-auth", "disable-authentication") orelse false; - opts.addOption(bool, "disable_auth", disable_auth); + const db_mod = b.addModule("db", .{ + .root_source_file = b.path("src/db/root.zig"), + .target = target, + }); - const static_path = b.option([]const u8, "static-path", "static-path") orelse "zig-out/dist"; - opts.addOption([]const u8, "static_path", static_path); + const api_mod = b.addModule("api", .{ + .root_source_file = b.path("src/api/root.zig"), + .target = target, + }); - const mod = b.addModule("memora", .{ - .root_source_file = b.path("src/root.zig"), + const frontend_mod = b.addModule("frontend", .{ + .root_source_file = b.path("src/frontend/root.zig"), .target = target, }); - mod.addOptions("config", opts); - mod.addImport("memora", mod); - mod.linkSystemLibrary("exif", .{}); + const http_mod = b.addModule("http", .{ + .root_source_file = b.path("src/http/root.zig"), + .target = target, + }); const exe = b.addExecutable(.{ .name = "memora", @@ -28,33 +31,16 @@ pub fn build(b: *std.Build) void { .target = target, .optimize = optimize, .imports = &.{ - .{ .name = "memora", .module = mod }, + .{ .name = "db", .module = db_mod }, + .{ .name = "api", .module = api_mod }, + .{ .name = "frontend", .module = frontend_mod }, + .{ .name = "http", .module = http_mod }, }, }), }); - exe.linkLibC(); b.installArtifact(exe); - const fonts_dist = b.addSystemCommand( - &.{ "cp", "-r", "static/fonts", "zig-out/dist" }, - ); - - const dist = b.addSystemCommand( - &.{ - "bun", - "build", - "static/index.html", - "--outdir", - "zig-out/dist", - "--loader", - ".css:text" - } - ); - - b.default_step.dependOn(&dist.step); - dist.step.dependOn(&fonts_dist.step); - const run_step = b.step("run", "Run the app"); const run_cmd = b.addRunArtifact(exe); @@ -66,20 +52,56 @@ pub fn build(b: *std.Build) void { run_cmd.addArgs(args); } - const mod_tests = b.addTest(.{ - .root_module = mod, + const db_tests = b.addTest(.{ + .root_module = db_mod, }); + const run_db_tests = b.addRunArtifact(db_tests); + const db_test_step = b.step("test-db", "Run database tests"); + db_test_step.dependOn(&run_db_tests.step); - const run_mod_tests = b.addRunArtifact(mod_tests); + const api_tests = b.addTest(.{ + .root_module = api_mod, + }); + const run_api_tests = b.addRunArtifact(api_tests); + const api_test_step = b.step("test-api", "Run api tests"); + api_test_step.dependOn(&run_api_tests.step); + + const frontend_tests = b.addTest(.{ + .root_module = frontend_mod, + }); + const run_frontend_tests = b.addRunArtifact(frontend_tests); + const frontend_test_step = b.step("test-frontend", "Run frontend tests"); + frontend_test_step.dependOn(&run_frontend_tests.step); + + const http_tests = b.addTest(.{ + .root_module = http_mod, + }); + const run_http_tests = b.addRunArtifact(http_tests); + const http_test_step = b.step("test-http", "Run http tests"); + http_test_step.dependOn(&run_http_tests.step); const exe_tests = b.addTest(.{ .root_module = exe.root_module, }); - const run_exe_tests = b.addRunArtifact(exe_tests); - const test_step = b.step("test", "Run tests"); - test_step.dependOn(&run_mod_tests.step); + const test_step = b.step("test", "Run all tests"); + test_step.dependOn(&run_db_tests.step); + test_step.dependOn(&run_api_tests.step); + test_step.dependOn(&run_frontend_tests.step); + test_step.dependOn(&run_http_tests.step); test_step.dependOn(&run_exe_tests.step); + const fmt_step = b.step("fmt", "Format"); + const do_fmt = b.addFmt(.{ + .paths = &.{ "src" }, + }); + fmt_step.dependOn(&do_fmt.step); + + const check_fmt_step = b.step("check", "Check format and syntax"); + const do_check_fmt = b.addFmt(.{ + .paths = &.{ "src" }, + .check = true, + }); + check_fmt_step.dependOn(&do_check_fmt.step); } diff --git a/build.zig.zon b/build.zig.zon index 511d4c1..5ac92c9 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,81 +1,12 @@ .{ - // This is the default name used by packages depending on this one. For - // example, when a user runs `zig fetch --save <url>`, this field is used - // as the key in the `dependencies` table. Although the user can choose a - // different name, most users will stick with this provided value. - // - // It is redundant to include "zig" in this name because it is already - // within the Zig package namespace. .name = .memora, - // This is a [Semantic Version](https://semver.org/). - // In a future version of Zig it will be used for package deduplication. .version = "0.0.0", - // Together with name, this represents a globally unique package - // identifier. This field is generated by the Zig toolchain when the - // package is first created, and then *never changes*. This allows - // unambiguous detection of one package being an updated version of - // another. - // - // When forking a Zig project, this id should be regenerated (delete the - // field and run `zig build`) if the upstream project is still maintained. - // Otherwise, the fork is *hostile*, attempting to take control over the - // original project's identity. Thus it is recommended to leave the comment - // on the following line intact, so that it shows up in code reviews that - // modify the field. - .fingerprint = 0xf901ac632f19fccc, // Changing this has security and trust implications. - // Tracks the earliest Zig version that the package considers to be a - // supported use case. - .minimum_zig_version = "0.15.2", - // This field is optional. - // Each dependency must either provide a `url` and `hash`, or a `path`. - // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. - // Once all dependencies are fetched, `zig build` no longer requires - // internet connectivity. + .minimum_zig_version = "0.16.0", .dependencies = .{ - // See `zig fetch --save <url>` for a command-line interface for adding dependencies. - //.example = .{ - // // When updating this field to a new URL, be sure to delete the corresponding - // // `hash`, otherwise you are communicating that you expect to find the old hash at - // // the new URL. If the contents of a URL change this will result in a hash mismatch - // // which will prevent zig from using it. - // .url = "https://example.com/foo.tar.gz", - // - // // This is computed from the file contents of the directory of files that is - // // obtained after fetching `url` and applying the inclusion rules given by - // // `paths`. - // // - // // This field is the source of truth; packages do not come from a `url`; they - // // come from a `hash`. `url` is just one of many possible mirrors for how to - // // obtain a package matching this `hash`. - // // - // // Uses the [multihash](https://multiformats.io/multihash/) format. - // .hash = "...", - // - // // When this is provided, the package is found in a directory relative to the - // // build root. In this case the package's hash is irrelevant and therefore not - // // computed. This field and `url` are mutually exclusive. - // .path = "foo", - // - // // When this is set to `true`, a package is declared to be lazily - // // fetched. This makes the dependency only get fetched if it is - // // actually used. - // .lazy = false, - //}, }, - // Specifies the set of files and directories that are included in this package. - // Only files and directories listed here are included in the `hash` that - // is computed for this package. Only files listed here will remain on disk - // when using the zig package manager. As a rule of thumb, one should list - // files required for compilation plus any license(s). - // Paths are relative to the build root. Use the empty string (`""`) to refer to - // the build root itself. - // A directory listed here means that all files within, recursively, are included. .paths = .{ "build.zig", "build.zig.zon", "src", - // For example... - //"LICENSE", - //"README.md", }, } @@ -21,16 +21,12 @@ buildInputs = [ pkgs.zig - pkgs.libexif - pkgs.bun ]; }; devShells.x86_64-linux.default = pkgs.mkShell { packages = [ pkgs.zig - pkgs.libexif - pkgs.bun ]; }; }; diff --git a/src/ansi.zig b/src/ansi.zig deleted file mode 100644 index 44f5de6..0000000 --- a/src/ansi.zig +++ /dev/null @@ -1,94 +0,0 @@ -const std = @import("std"); - -fn write_csi(writer: anytype, args: anytype, command: u8) !void { - try writer.writeAll("\x1b["); - - inline for (args, 0..) |code, index| { - try writer.print("{}", .{code}); - - if (index < args.len - 1) { - try writer.writeByte(';'); - } - } - - try writer.writeByte(command); -} - -pub const Color = enum(u8) { - const Self = @This(); - - black = 0, - red = 1, - green = 2, - yellow = 3, - blue = 4, - magenta = 5, - cyan = 6, - white = 7, - gray = 60, - bright_red = 61, - bright_green = 62, - bright_yellow = 63, - bright_blue = 64, - bright_magenta = 65, - bright_cyan = 66, - bright_white = 67, - - const foreground_offset = 30; - const background_offset = 40; - - pub fn to_fg(self: Self) u8 { - return @intFromEnum(self) + foreground_offset; - } - - pub fn to_bg(self: Self) u8 { - return @intFromEnum(self) + background_offset; - } -}; - -pub const Styled = struct { - const Self = @This(); - - text: []const u8, - fg: Color = .white, - bg: Color = .black, - bold: bool = false, - dim: bool = false, - italic: bool = false, - underline: bool = false, - - const Codes = struct { - const reset = 0; - const bold = 1; - const dim = 2; - const italic = 3; - const underline = 4; - }; - - pub fn format( - self: *const Self, - writer: *std.Io.Writer, - ) !void { - try write_csi(writer, .{self.fg.to_fg()}, 'm'); - try write_csi(writer, .{self.bg.to_bg()}, 'm'); - - if (self.bold) try write_csi(writer, .{Codes.bold}, 'm'); - if (self.dim) try write_csi(writer, .{Codes.dim}, 'm'); - if (self.italic) try write_csi(writer, .{Codes.italic}, 'm'); - if (self.underline) try write_csi(writer, .{Codes.underline}, 'm'); - - try writer.writeAll(self.text); - - try write_csi(writer, .{Codes.reset}, 'm'); - } -}; - -pub const ClearLine = struct { - pub fn format( - self: *const @This(), - writer: *std.Io.Writer, - ) !void { - _ = self; - try writer.writeAll("\x1b[2K\r"); - } -}; diff --git a/src/api/root.zig b/src/api/root.zig new file mode 100644 index 0000000..5128aa1 --- /dev/null +++ b/src/api/root.zig @@ -0,0 +1,8 @@ +//! There should not be any http specific stuff in here, +//! only the specific api endpoints. + +const std = @import("std"); + +test { + _ = std.testing.refAllDecls(@This()); +} diff --git a/src/config.zig b/src/config.zig deleted file mode 100644 index 02d3c8a..0000000 --- a/src/config.zig +++ /dev/null @@ -1,41 +0,0 @@ -const std = @import("std"); - -const Self = @This(); - -const Config = struct { - storage_path: []const u8, - session_expires_after: usize, -}; - -arena: *std.heap.ArenaAllocator, -storage_path: []const u8, -session_expires_after: usize, - -pub fn load(allocator: std.mem.Allocator) !Self { - const home_path = std.posix.getenv("HOME") orelse return error.MissingHome; - const home = try std.fs.cwd().openDirZ( - home_path, - .{}, - ); - const file = home.openFile( - ".config/memora/config.json", - .{} - ) catch return error.MissingConfig; - - const content = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); - defer allocator.free(content); - - const parsed = try std.json.parseFromSlice(Config, allocator, content, .{ - .allocate = .alloc_always, - }); - return .{ - .arena = parsed.arena, - .storage_path = parsed.value.storage_path, - .session_expires_after = parsed.value.session_expires_after * std.time.ns_per_day, - }; -} - -pub fn deinit(self: *Self) void { - self.arena.deinit(); - self.* = undefined; -} diff --git a/src/context.zig b/src/context.zig deleted file mode 100644 index 6e73b5d..0000000 --- a/src/context.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Storage = memora.Storage; - -const Self = @This(); - -allocator: std.mem.Allocator, -request: *std.http.Server.Request, -storage: *Storage, -fingerprint: []const u8, -response: struct { - headers: struct { - content_type: []const u8 = "application/json", - fingerprint: ?[]const u8 = null, - } = .{}, -} = .{}, diff --git a/src/db/root.zig b/src/db/root.zig new file mode 100644 index 0000000..049a63b --- /dev/null +++ b/src/db/root.zig @@ -0,0 +1,9 @@ +//! Implements the layer between the sqlite +//! database and the interface for the api endpoints or +//! the cli. + +const std = @import("std"); + +test { + _ = std.testing.refAllDecls(@This()); +} diff --git a/src/frontend/root.zig b/src/frontend/root.zig new file mode 100644 index 0000000..f2cce4c --- /dev/null +++ b/src/frontend/root.zig @@ -0,0 +1,8 @@ +//! Implementation of the frontend contains mainly javascript files +//! which will be embedded right into the ELF file to improve deployment. + +const std = @import("std"); + +test { + _ = std.testing.refAllDecls(@This()); +} diff --git a/src/http/root.zig b/src/http/root.zig new file mode 100644 index 0000000..743e1c4 --- /dev/null +++ b/src/http/root.zig @@ -0,0 +1,7 @@ +//! All HTTP specific abstractions belong here. + +const std = @import("std"); + +test { + _ = std.testing.refAllDecls(@This()); +} diff --git a/src/locked.zig b/src/locked.zig deleted file mode 100644 index 6c2edfe..0000000 --- a/src/locked.zig +++ /dev/null @@ -1,13 +0,0 @@ -const std = @import("std"); - -pub fn Shared(T: type) type { - return struct { - value: T, - rw_lock: *std.Thread.RwLock, - - pub fn unlock(self: *@This()) void { - self.rw_lock.unlockShared(); - self.* = undefined; - } - }; -} diff --git a/src/log.zig b/src/log.zig deleted file mode 100644 index 9d2b444..0000000 --- a/src/log.zig +++ /dev/null @@ -1,56 +0,0 @@ -const std = @import("std"); - -const ansi = @import("ansi.zig"); - -var log_buffer: [1024]u8 = undefined; -var writer_stderr = std.fs.File.stderr().writer(&log_buffer); -const stderr = &writer_stderr.interface; -var log_lock = std.Thread.Mutex{}; - -pub fn handler( - comptime message_level: std.log.Level, - comptime scope: @TypeOf(.enum_literal), - comptime format: []const u8, - args: anytype, -) void { - log_lock.lock(); - defer log_lock.unlock(); - defer stderr.flush() catch unreachable; - - const color = switch (message_level) { - .err => .red, - .warn => .yellow, - .info => .blue, - .debug => .magenta, - }; - - stderr.print( - "{f}{f}", - .{ - ansi.ClearLine {}, - ansi.Styled { - .text = " " ++ (comptime message_level.asText()) ++ " ", - .bg = color, - .bold = true, - }, - }, - ) catch unreachable; - - if (scope != .default) { - stderr.print( - "{f}", - .{ - ansi.Styled { - .text = " " ++ @tagName(scope) ++ " ", - .bg = .gray, - .fg = .black, - .italic = true, - }, - }, - ) catch unreachable; - } - - stderr.writeByte(' ') catch unreachable; - stderr.print(format, args) catch unreachable; - stderr.writeAll("\n") catch unreachable; -} diff --git a/src/main.zig b/src/main.zig index 4ea4954..1a66b63 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,36 +1,14 @@ -const std = @import("std"); -const memora = @import("memora"); - -pub const std_options = std.Options { - .logFn = memora.log.handler, -}; - -fn signal_handler(signo: i32) callconv(.c) void { - if (signo == std.os.linux.SIG.INT) { - server.deinit(); - std.process.exit(0); - } -} +//! This is the main executable file. +//! Here we will add all cli interfaces +//! to interact with the state of the application +//! but also the actual running of the server / webapp. -fn register_sigaction() void { - var sa = std.os.linux.Sigaction{ - .handler = .{ .handler = signal_handler }, - .mask = std.mem.zeroes(std.os.linux.sigset_t), - .flags = 0, - }; +const std = @import("std"); - _ = std.os.linux.sigaction(std.os.linux.SIG.INT, &sa, null); +pub fn main(init: std.process.Init) !void { + _ = init; } -var server = memora.Server{}; - -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer std.debug.assert(gpa.deinit() == .ok); - const allocator = gpa.allocator(); - - const address = try std.net.Address.parseIpAndPort("0.0.0.0:8080"); - try server.init(address, allocator); - register_sigaction(); - server.run(allocator); +test { + _ = std.testing.refAllDecls(@This()); } diff --git a/src/mime.zig b/src/mime.zig deleted file mode 100644 index c60ab74..0000000 --- a/src/mime.zig +++ /dev/null @@ -1,88 +0,0 @@ -const std = @import("std"); - -pub fn get_type(file_name: []const u8) []const u8 { - const suffix_pos = std.mem.lastIndexOfScalar(u8, file_name, '.') orelse file_name.len; - const suffix = file_name[suffix_pos..]; - return content_types.get(suffix) orelse "text/plain"; -} - -pub const content_types = std.StaticStringMap([]const u8).initComptime(.{ - .{ ".aac", "audio/aac" }, - .{ ".abw", "application/x-abiword" }, - .{ ".apng", "image/apng" }, - .{ ".arc", "application/x-freearc" }, - .{ ".avif", "image/avif" }, - .{ ".avi", "video/x-msvideo" }, - .{ ".azw", "application/vnd.amazon.ebook" }, - .{ ".bin", "application/octet-stream" }, - .{ ".bmp", "image/bmp" }, - .{ ".bz", "application/x-bzip" }, - .{ ".bz2", "application/x-bzip2" }, - .{ ".cda", "application/x-cdf" }, - .{ ".csh", "application/x-csh" }, - .{ ".css", "text/css" }, - .{ ".csv", "text/csv" }, - .{ ".doc", "application/msword" }, - .{ ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, - .{ ".eot", "application/vnd.ms-fontobject" }, - .{ ".epub", "application/epub+zip" }, - .{ ".gz", "application/gzip." }, - .{ ".gif", "image/gif" }, - .{ ".htm", "text/html" }, - .{ ".html", "text/html" }, - .{ ".ico", "image/vnd.microsoft.icon" }, - .{ ".ics", "text/calendar" }, - .{ ".jar", "application/java-archive" }, - .{ ".jpeg", "image/jpeg" }, - .{ ".jpg", "image/jpeg" }, - .{ ".js", "text/javascript" }, - .{ ".json", "application/json" }, - .{ ".jsonld", "application/ld+json" }, - .{ ".md", "text/markdown" }, - .{ ".mid, .midi", "audio/midi," }, - .{ ".mjs", "text/javascript" }, - .{ ".mp3", "audio/mpeg" }, - .{ ".mp4", "video/mp4" }, - .{ ".mpeg", "video/mpeg" }, - .{ ".mpkg", "application/vnd.apple.installer+xml" }, - .{ ".odp", "application/vnd.oasis.opendocument.presentation" }, - .{ ".ods", "application/vnd.oasis.opendocument.spreadsheet" }, - .{ ".odt", "application/vnd.oasis.opendocument.text" }, - .{ ".oga", "audio/ogg" }, - .{ ".ogv", "video/ogg" }, - .{ ".ogx", "application/ogg" }, - .{ ".opus", "audio/ogg" }, - .{ ".otf", "font/otf" }, - .{ ".png", "image/png" }, - .{ ".pdf", "application/pdf" }, - .{ ".php", "application/x-httpd-php" }, - .{ ".ppt", "application/vnd.ms-powerpoint" }, - .{ ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, - .{ ".rar", "application/vnd.rar" }, - .{ ".rtf", "application/rtf" }, - .{ ".sh", "application/x-sh" }, - .{ ".svg", "image/svg+xml" }, - .{ ".tar", "application/x-tar" }, - .{ ".tif, .tiff", "image/tiff" }, - .{ ".ts", "video/mp2t" }, - .{ ".ttf", "font/ttf" }, - .{ ".txt", "text/plain" }, - .{ ".vsd", "application/vnd.visio" }, - .{ ".wav", "audio/wav" }, - .{ ".weba", "audio/webm" }, - .{ ".webm", "video/webm" }, - .{ ".webmanifest", "application/manifest+json" }, - .{ ".webp", "image/webp" }, - .{ ".woff", "font/woff" }, - .{ ".woff2", "font/woff2" }, - .{ ".xhtml", "application/xhtml+xml" }, - .{ ".xls", "application/vnd.ms-excel" }, - .{ ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, - .{ ".xml", "application/xml" }, - .{ ".xul", "application/vnd.mozilla.xul+xml" }, - .{ ".zip", "application/zip." }, - .{ ".3gp", "video/3gpp;" }, - .{ ".3g2", "video/3gpp2;" }, - .{ ".7z", "application/x-7z-compressed" }, -}); - diff --git a/src/prompt.zig b/src/prompt.zig deleted file mode 100644 index 9fa9a9a..0000000 --- a/src/prompt.zig +++ /dev/null @@ -1,44 +0,0 @@ -const std = @import("std"); -const ansi = @import("ansi.zig"); - -var output_buffer: [1024]u8 = undefined; -var writer_stderr = std.fs.File.stderr().writer(&output_buffer); -const stderr = &writer_stderr.interface; - -var input_buffer: [1024]u8 = undefined; -var reader_stdin = std.fs.File.stdin().reader(&input_buffer); -const stdin = &reader_stdin.interface; - -pub fn read( - prompt: []const u8, - allocator: std.mem.Allocator, -) ![]u8 { - try stderr.print( - "{f}{f}{f} ", - .{ - ansi.Styled { - .text = " ", - .bg = .blue, - .bold = true, - }, - ansi.Styled { - .text = prompt, - .bg = .blue, - .bold = true, - }, - ansi.Styled { - .text = ": ", - .bg = .blue, - .bold = true, - }, - }, - ); - - try stderr.flush(); - - var output = std.Io.Writer.Allocating.init(allocator); - errdefer output.deinit(); - _ = try stdin.streamDelimiter(&output.writer, '\n'); - stdin.toss(1); - return output.toOwnedSlice(); -} diff --git a/src/root.zig b/src/root.zig deleted file mode 100644 index ab7a62b..0000000 --- a/src/root.zig +++ /dev/null @@ -1,11 +0,0 @@ -const std = @import("std"); - -pub const log = @import("log.zig"); - -pub const routes = @import("routes/root.zig"); - -pub const Server = @import("server.zig"); -pub const Storage = @import("storage/root.zig"); -pub const Context = @import("context.zig"); -pub const Stream = @import("stream/root.zig").Stream; -pub const locked = @import("locked.zig"); diff --git a/src/routes/access.zig b/src/routes/access.zig deleted file mode 100644 index 39872b8..0000000 --- a/src/routes/access.zig +++ /dev/null @@ -1,6 +0,0 @@ - -pub const Access = enum { - everyone, - users, - admins, -}; diff --git a/src/routes/api/auth/first-login.zig b/src/routes/api/auth/first-login.zig deleted file mode 100644 index 523fdf4..0000000 --- a/src/routes/api/auth/first-login.zig +++ /dev/null @@ -1,15 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .everyone; - -const Result = struct { - is_first: bool, -}; - -pub fn post(ctx: *Context) anyerror!Result { - _ = ctx; - return .{ .is_first = false }; -} diff --git a/src/routes/api/auth/login.zig b/src/routes/api/auth/login.zig deleted file mode 100644 index 8a33082..0000000 --- a/src/routes/api/auth/login.zig +++ /dev/null @@ -1,34 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -const Body = struct { - user: []const u8, - password: []const u8, -}; - -const Result = struct { - success: bool, -}; - -pub const access = .everyone; - -pub fn post(ctx: *Context, body: Body) anyerror!Result { - var user = Storage.User.open(ctx.storage, body.user) catch return .{ - .success = false - }; - defer user.deinit(); - - const result = Result { - .success = user.check_password(body.password) - }; - - if (result.success) { - const session = try ctx.storage.sessions.add(ctx.storage, user.info); - ctx.response.headers.fingerprint = session.fingerprint; - } - - return result; -} diff --git a/src/routes/api/auth/root.zig b/src/routes/api/auth/root.zig deleted file mode 100644 index 5f45891..0000000 --- a/src/routes/api/auth/root.zig +++ /dev/null @@ -1,4 +0,0 @@ -const HandlerInfo = @import("../../handler-info.zig"); - -pub const login: HandlerInfo = .from_type(@import("login.zig")); -pub const @"first-login": HandlerInfo = .from_type(@import("first-login.zig")); diff --git a/src/routes/api/image/list.zig b/src/routes/api/image/list.zig deleted file mode 100644 index 5d2eace..0000000 --- a/src/routes/api/image/list.zig +++ /dev/null @@ -1,42 +0,0 @@ -const std = @import("std"); -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .users; - -const ImageInfo = struct { - id: []const u8, - timestamp: ?i64, -}; - -const Result = struct { - images: []ImageInfo, -}; - -pub fn get(ctx: *Context) !Result { - var images: std.ArrayList(ImageInfo) = .empty; - - var images_list = ctx.storage.images.list(); - defer images_list.unlock(); - - var locked = ctx.storage.images.first_by_timestamp(); - defer locked.unlock(); - - var current = locked.value; - - while (current) |c| { - const image = ctx.storage.images.items.items[c.index]; - - try images.append(ctx.allocator, .{ - .id = try ctx.allocator.dupe(u8, image.id), - .timestamp = image.timestamp, - }); - - current = c.next(); - } - - return .{ - .images = try images.toOwnedSlice(ctx.allocator), - }; -} diff --git a/src/routes/api/image/load.zig b/src/routes/api/image/load.zig deleted file mode 100644 index 3ef25d6..0000000 --- a/src/routes/api/image/load.zig +++ /dev/null @@ -1,15 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; -const mime = @import("../../../mime.zig"); - -pub const access = .users; - -pub fn get(ctx: *Context) !memora.Stream { - const id = ctx.request.head.target["/api/image/load/".len..]; - var image = Storage.Image { .id = id, .timestamp = null }; - ctx.response.headers.content_type = comptime mime.content_types.get(".jpeg") orelse unreachable; - return .from_file(try image.file(ctx.storage)); -} diff --git a/src/routes/api/image/query.zig b/src/routes/api/image/query.zig deleted file mode 100644 index e69de29..0000000 --- a/src/routes/api/image/query.zig +++ /dev/null diff --git a/src/routes/api/image/remove.zig b/src/routes/api/image/remove.zig deleted file mode 100644 index d99cbb4..0000000 --- a/src/routes/api/image/remove.zig +++ /dev/null @@ -1,14 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .users; - -const Body = struct { - id: []const u8, -}; - -pub fn post(ctx: *Context, body: Body) anyerror!void { - return ctx.storage.images.delete(ctx.storage, body.id); -} diff --git a/src/routes/api/image/root.zig b/src/routes/api/image/root.zig deleted file mode 100644 index 931bb06..0000000 --- a/src/routes/api/image/root.zig +++ /dev/null @@ -1,6 +0,0 @@ -const HandlerInfo = @import("../../handler-info.zig"); - -pub const upload: HandlerInfo = .from_type(@import("upload.zig")); -pub const list: HandlerInfo = .from_type(@import("list.zig")); -pub const load: HandlerInfo = .from_type(@import("load.zig")); -pub const remove: HandlerInfo = .from_type(@import("remove.zig")); diff --git a/src/routes/api/image/upload.zig b/src/routes/api/image/upload.zig deleted file mode 100644 index 72c8a2d..0000000 --- a/src/routes/api/image/upload.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -const log = std.log.scoped(.image_upload); - -pub const access = .users; - -pub fn post(ctx: *Context) !void { - if (ctx.request.head.content_length) |length| { - var buffer: [1024]u8 = undefined; - const reader = try ctx.request.readerExpectContinue(&buffer); - try ctx.storage.images.save(ctx.storage, reader, length); - } -} diff --git a/src/routes/api/profile/create.zig b/src/routes/api/profile/create.zig deleted file mode 100644 index 68f32ec..0000000 --- a/src/routes/api/profile/create.zig +++ /dev/null @@ -1,29 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .admins; - -const Body = struct { - name: []const u8, - full_name: []const u8, - birthday: []const u8, - password: []const u8, -}; - -pub fn post(ctx: *Context, body: Body) !void { - var user = try Storage.User.new( - ctx.storage, - body.name, - body.full_name, - body.birthday, - body.password, - true, - ctx.storage.allocator, - ); - defer user.deinit(); - - try user.sync(); -} diff --git a/src/routes/api/profile/image/load.zig b/src/routes/api/profile/image/load.zig deleted file mode 100644 index 4b696ce..0000000 --- a/src/routes/api/profile/image/load.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .users; - -pub fn get(ctx: *Context) !memora.Stream { - const name = ctx.request.head.target["/api/profile/image/load/".len..]; - if (Storage.User.image(ctx.storage, name)) |file| { - ctx.response.headers.content_type = "image/jpeg"; - return .from_file(file); - } - - return error.NotFound; -} diff --git a/src/routes/api/profile/image/root.zig b/src/routes/api/profile/image/root.zig deleted file mode 100644 index d6b77f2..0000000 --- a/src/routes/api/profile/image/root.zig +++ /dev/null @@ -1,5 +0,0 @@ -const memora = @import("memora"); -const HandlerInfo = memora.routes.HandlerInfo; - -pub const upload: HandlerInfo = .from_type(@import("upload.zig")); -pub const load: HandlerInfo = .from_type(@import("load.zig")); diff --git a/src/routes/api/profile/image/upload.zig b/src/routes/api/profile/image/upload.zig deleted file mode 100644 index db140d4..0000000 --- a/src/routes/api/profile/image/upload.zig +++ /dev/null @@ -1,19 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .users; - -pub fn post(ctx: *Context) !void { - const name = ctx.request.head.target["/api/profile/image/upload/".len..]; - if (ctx.request.head.content_length) |length| { - var buffer: [1024]u8 = undefined; - const reader = try ctx.request.readerExpectContinue(&buffer); - - try Storage.User.set_image(ctx.storage, name, reader, length); - - ctx.response.headers.content_type = "image/jpeg"; - } -} diff --git a/src/routes/api/profile/list.zig b/src/routes/api/profile/list.zig deleted file mode 100644 index 59d4684..0000000 --- a/src/routes/api/profile/list.zig +++ /dev/null @@ -1,17 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .admins; - -const Response = struct { - users: [][]const u8, -}; - -pub fn get(ctx: *Context) !Response { - return .{ - .users = try Storage.User.list(ctx.storage, ctx.allocator) - }; -} diff --git a/src/routes/api/profile/root.zig b/src/routes/api/profile/root.zig deleted file mode 100644 index 45dec8e..0000000 --- a/src/routes/api/profile/root.zig +++ /dev/null @@ -1,8 +0,0 @@ -const memora = @import("memora"); -const HandlerInfo = memora.routes.HandlerInfo; - -pub const image = @import("image/root.zig"); -pub const set: HandlerInfo = .from_type(@import("set.zig")); -pub const @"update-password": HandlerInfo = .from_type(@import("update-password.zig")); -pub const create: HandlerInfo = .from_type(@import("create.zig")); -pub const list: HandlerInfo = .from_type(@import("list.zig")); diff --git a/src/routes/api/profile/set.zig b/src/routes/api/profile/set.zig deleted file mode 100644 index a007b23..0000000 --- a/src/routes/api/profile/set.zig +++ /dev/null @@ -1,26 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .users; - -const Body = struct { - full_name: []const u8, - birthday: []const u8, -}; - -pub fn post(ctx: *Context, body: Body) !void { - if (ctx.storage.sessions.get(ctx.storage, ctx.fingerprint)) |session| { - var user = try Storage.User.open(ctx.storage, session.info.name); - defer user.deinit(); - - user.info.full_name = body.full_name; - user.info.birthday = body.birthday; - - try user.sync(); - } else { - return error.UnknownSession; - } -} diff --git a/src/routes/api/profile/update-password.zig b/src/routes/api/profile/update-password.zig deleted file mode 100644 index ac6ceed..0000000 --- a/src/routes/api/profile/update-password.zig +++ /dev/null @@ -1,37 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -pub const access = .users; - -const Body = struct { - current_password: []const u8, - new_password: []const u8, -}; - -const Response = struct { - success: bool, -}; - -pub fn post(ctx: *Context, body: Body) !Response { - if (ctx.storage.sessions.get(ctx.storage, ctx.fingerprint)) |session| { - var user = try Storage.User.open(ctx.storage, session.info.name); - defer user.deinit(); - - const result = Response { - .success = user.check_password(body.current_password) - }; - - if (result.success) { - try user.set_password(body.new_password); - try user.sync(); - } - - return result; - - } else { - return error.UnknownSession; - } -} diff --git a/src/routes/api/root.zig b/src/routes/api/root.zig deleted file mode 100644 index 5f731c3..0000000 --- a/src/routes/api/root.zig +++ /dev/null @@ -1,4 +0,0 @@ -pub const auth = @import("auth/root.zig"); -pub const session = @import("session/root.zig"); -pub const image = @import("image/root.zig"); -pub const profile = @import("profile/root.zig"); diff --git a/src/routes/api/session/current.zig b/src/routes/api/session/current.zig deleted file mode 100644 index 897d01c..0000000 --- a/src/routes/api/session/current.zig +++ /dev/null @@ -1,27 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .users; - -const Result = struct { - name: []const u8, - full_name: []const u8, - birthday: []const u8, - is_admin: bool, -}; - -pub fn get(ctx: *Context) !Result { - const session = ctx.storage.sessions.get( - ctx.storage, - ctx.fingerprint, - ) orelse return error.UserDoesNotExist; - - return .{ - .name = session.info.name, - .full_name = session.info.full_name, - .birthday = session.info.birthday, - .is_admin = session.info.is_admin, - }; -} diff --git a/src/routes/api/session/drop.zig b/src/routes/api/session/drop.zig deleted file mode 100644 index 4b193e0..0000000 --- a/src/routes/api/session/drop.zig +++ /dev/null @@ -1,9 +0,0 @@ -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .users; - -pub fn get(ctx: *Context) !void { - ctx.storage.sessions.remove(ctx.storage, ctx.fingerprint); - ctx.response.headers.fingerprint = ""; -} diff --git a/src/routes/api/session/is-online.zig b/src/routes/api/session/is-online.zig deleted file mode 100644 index f5ebaee..0000000 --- a/src/routes/api/session/is-online.zig +++ /dev/null @@ -1,15 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .everyone; - -const Result = struct { - is_online: bool, -}; - -pub fn get(ctx: *Context) !Result { - _ = ctx; - return .{ .is_online = true }; -} diff --git a/src/routes/api/session/is-valid.zig b/src/routes/api/session/is-valid.zig deleted file mode 100644 index 8cf6794..0000000 --- a/src/routes/api/session/is-valid.zig +++ /dev/null @@ -1,21 +0,0 @@ -const std = @import("std"); -const config = @import("config"); - -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .everyone; - -const Result = struct { - is_valid: bool -}; - -pub fn get(ctx: *Context) !Result { - if (comptime config.disable_auth) { - return .{ .is_valid = true }; - } - - return .{ - .is_valid = ctx.storage.sessions.get(ctx.storage, ctx.fingerprint) != null - }; -} diff --git a/src/routes/api/session/renew.zig b/src/routes/api/session/renew.zig deleted file mode 100644 index c13e27e..0000000 --- a/src/routes/api/session/renew.zig +++ /dev/null @@ -1,9 +0,0 @@ -const memora = @import("memora"); -const Context = memora.Context; - -pub const access = .users; - -pub fn get(ctx: *Context) !void { - const new = try ctx.storage.sessions.renew(ctx.storage, ctx.fingerprint); - ctx.response.headers.fingerprint = new.fingerprint; -} diff --git a/src/routes/api/session/root.zig b/src/routes/api/session/root.zig deleted file mode 100644 index a889869..0000000 --- a/src/routes/api/session/root.zig +++ /dev/null @@ -1,7 +0,0 @@ -const HandlerInfo = @import("../../handler-info.zig"); - -pub const current: HandlerInfo = .from_type(@import("current.zig")); -pub const drop: HandlerInfo = .from_type(@import("drop.zig")); -pub const renew: HandlerInfo = .from_type(@import("renew.zig")); -pub const @"is-valid": HandlerInfo = .from_type(@import("is-valid.zig")); -pub const @"is-online": HandlerInfo = .from_type(@import("is-online.zig")); diff --git a/src/routes/handler-info.zig b/src/routes/handler-info.zig deleted file mode 100644 index ca4babd..0000000 --- a/src/routes/handler-info.zig +++ /dev/null @@ -1,225 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Context = memora.Context; -const Storage = memora.Storage; - -const config = @import("config"); - -const Access = @import("access.zig").Access; - -const log = std.log.scoped(.handler_info); - -const Self = @This(); - -const Handler = *const fn (*Context) anyerror!memora.Stream; - -get: ?Handler, -head: ?Handler, -post: ?Handler, -put: ?Handler, -delete: ?Handler, -connect: ?Handler, -options: ?Handler, -trace: ?Handler, -patch: ?Handler, -access: Access, - -inline fn handler_from_method(self: *const Self, method: std.http.Method) ?Handler { - return switch (method) { - .GET => self.get, - .HEAD => self.head, - .POST => self.post, - .PUT => self.put, - .DELETE => self.delete, - .CONNECT => self.connect, - .OPTIONS => self.options, - .TRACE => self.trace, - .PATCH => self.patch, - }; -} - -inline fn get_fingerprint(cookie: []const u8) []const u8 { - const start = std.mem.indexOf(u8, cookie, "fingerprint=") orelse return ""; - const end = std.mem.indexOf(u8, cookie[start + 12..], " ") orelse return cookie[start + 12..]; - return cookie[start..end + 1]; -} - -pub fn handle( - self: *const Self, - request: *std.http.Server.Request, - storage: *Storage, - allocator: std.mem.Allocator, -) !void { - const target = try allocator.dupe(u8, request.head.target); - defer allocator.free(target); - - const handler = self.handler_from_method(request.head.method) orelse return request.respond( - "{ \"error\": \"Bad Request\" }", - .{ .status = .bad_request } - ); - - const cookie = cookie: { - var iterator = request.iterateHeaders(); - while (iterator.next()) |header| { - if (std.ascii.eqlIgnoreCase(header.name, "cookie")) { - break :cookie header.value; - } - } - break :cookie ""; - }; - - var arena = std.heap.ArenaAllocator.init(allocator); - defer arena.deinit(); - var context: Context = .{ - .request = request, - .storage = storage, - .allocator = arena.allocator(), - .fingerprint = get_fingerprint(cookie), - }; - - if (!comptime config.disable_auth) { - const allowed = switch (self.access) { - .everyone => true, - .users => storage.sessions.get(storage, context.fingerprint) != null, - .admins => admin: { - if (storage.sessions.get(storage, context.fingerprint)) |session| { - break :admin session.info.is_admin; - } - break :admin false; - }, - }; - - if (!allowed) { - return request.respond( - "{ \"error\": \"Forbidden\" }", - .{ .status = .forbidden } - ); - } - } - - var stream = handler(&context) catch |err| { - const response, const status_code: std.http.Status = switch (err) { - error.BadRequest => .{ "{ \"error\": \"Bad Request\" }", .bad_request }, - error.Unauthorized => .{ "{ \"error\": \"Unauthorized\" }", .unauthorized }, - error.Forbidden => .{ "{ \"error\": \"Forbidden\" }", .forbidden }, - error.NotFound => .{ "{ \"error\": \"Not Found\" }", .not_found }, - else => blk: { - log.err("handler for '{s}' returned {}", .{target, err}); - break :blk .{ "{ \"error\": \"Internal Server Error\" }", .internal_server_error }; - }, - }; - - return request.respond(response, .{ .status = status_code }); - }; - defer stream.close(); - - var headers: std.ArrayList(std.http.Header) = .empty; - defer headers.deinit(allocator); - - try headers.append(allocator, .{ - .name = "Content-Type", - .value = context.response.headers.content_type - }); - - try headers.append(allocator, .{ - .name = "Service-Worker-Allowed", - .value = "/", - }); - - if (context.response.headers.fingerprint) |auth_token| { - var value = std.Io.Writer.Allocating.init(arena.allocator()); - - try value.writer.print("fingerprint={s}; Secure; Path=/; Max-Age={}", .{ - auth_token, - storage.config.session_expires_after / std.time.ns_per_s, - }); - - try headers.append(allocator, .{ - .name = "Set-Cookie", - .value = value.written(), - }); - } - - var read_buffer: [1024]u8 = undefined; - var reader = stream.reader(&read_buffer); - - var write_buffer: [1024]u8 = undefined; - var body_writer = try request.respondStreaming(&write_buffer, .{ - .respond_options = .{ - .extra_headers = headers.items, - .transfer_encoding = .chunked, - }, - }); - - _ = try reader.streamRemaining(&body_writer.writer); - try body_writer.end(); -} - -fn HandlerWrapper(T: type, name: []const u8) type { - const info = @typeInfo(@TypeOf(@field(T, name))); - const return_type = info.@"fn".return_type orelse void; - const payload_type = @typeInfo(return_type).error_union.payload; - - return struct { - pub fn call(ctx: *Context) anyerror!memora.Stream { - const args = args: { - const tuple = std.meta.fields(std.meta.ArgsTuple(@TypeOf(@field(T, name)))); - - if (tuple.len == 1) { - break :args .{ ctx }; - } else if (tuple.len == 2) { - const Body = tuple[1].@"type"; - - var writer = std.Io.Writer.Allocating.init(ctx.allocator); - const interface = &writer.writer; - - var buffer: [1024]u8 = undefined; - const reader = try ctx.request.readerExpectContinue(&buffer); - - try reader.streamExact64(interface, ctx.request.head.content_length orelse 0); - - const body = std.json.parseFromSliceLeaky( - Body, - ctx.allocator, - writer.written(), - .{}, - ) catch |err| { - log.warn("failed to parse JSON {}", .{err}); - return error.BadRequest; - }; - break :args .{ ctx, body }; - } else { - @compileError("invalid amount of arguments for request function"); - } - }; - - if (payload_type == memora.Stream) { - return @call(.auto, @field(T, name), args); - } else if (payload_type == void) { - try @call(.auto, @field(T, name), args); - return memora.Stream.from_buffer("{}"); - } else { - var writer = std.Io.Writer.Allocating.init(ctx.allocator); - var stringify = std.json.Stringify { .writer = &writer.writer }; - try stringify.write(try @call(.auto, @field(T, name), args)); - return memora.Stream.from_buffer(writer.written()); - } - } - }; -} - -pub fn from_type(T: type) @This() { - return Self { - .get = if (@hasDecl(T, "get")) HandlerWrapper(T, "get").call else null, - .head = if (@hasDecl(T, "head")) HandlerWrapper(T, "head").call else null, - .post = if (@hasDecl(T, "post")) HandlerWrapper(T, "post").call else null, - .put = if (@hasDecl(T, "put")) HandlerWrapper(T, "put").call else null, - .delete = if (@hasDecl(T, "delete")) HandlerWrapper(T, "delete").call else null, - .connect = if (@hasDecl(T, "connect")) HandlerWrapper(T, "connect").call else null, - .options = if (@hasDecl(T, "options")) HandlerWrapper(T, "options").call else null, - .trace = if (@hasDecl(T, "trace")) HandlerWrapper(T, "trace").call else null, - .patch = if (@hasDecl(T, "patch")) HandlerWrapper(T, "patch").call else null, - .access = T.access, - }; -} diff --git a/src/routes/root.zig b/src/routes/root.zig deleted file mode 100644 index c438893..0000000 --- a/src/routes/root.zig +++ /dev/null @@ -1,49 +0,0 @@ -const std = @import("std"); - -pub const HandlerInfo = @import("handler-info.zig"); - -pub const api = @import("api/root.zig"); -pub const static: HandlerInfo = .from_type(@import("static.zig")); - -const routes = (Routes {}) - .with("", static) - .with_module("/api", api); - -pub const handlers = std.StaticStringMap(HandlerInfo).initComptime(routes.items); - -pub fn get(path: []const u8) HandlerInfo { - return (handlers.getLongestPrefix(std.mem.trimEnd(u8, path, "/")) orelse unreachable).value; -} - -const Routes = struct { - const Self = @This(); - - const Route = struct{ []const u8, HandlerInfo }; - - items: []const Route = &[0]Route{}, - - pub fn with(self: Self, comptime route: []const u8, handler: HandlerInfo) Self { - var next = self; - const tail: []const Route = &[1]Route { .{ route, handler } }; - next.items = self.items ++ tail; - return next; - } - - pub fn with_module(self: Self, comptime prefix: []const u8, module: type) Self { - var next = self; - - if (@typeInfo(module) != .@"struct") return self; - - inline for (@typeInfo(module).@"struct".decls) |decl| { - const field = @field(module, decl.name); - const route = prefix ++ "/" ++ decl.name; - switch (@TypeOf(field)) { - type => next = next.with_module(route, field), - HandlerInfo => next = next.with(route, field), - else => {}, - } - } - - return next; - } -}; diff --git a/src/routes/static.zig b/src/routes/static.zig deleted file mode 100644 index f8f7a6c..0000000 --- a/src/routes/static.zig +++ /dev/null @@ -1,35 +0,0 @@ -const std = @import("std"); -const mime = @import("../mime.zig"); -const config = @import("config"); - -const memora = @import("memora"); -const Context = memora.Context; - -const log = std.log.scoped(.fallback); - -pub const access = .everyone; - -pub fn get(ctx: *Context) anyerror!memora.Stream { - var static = try std.fs.cwd().openDir(config.static_path, .{}); - defer static.close(); - - if (static.openFile(ctx.request.head.target[1..], .{})) |file| { - const mime_type = mime.get_type(ctx.request.head.target); - ctx.response.headers.content_type = mime_type; - return .from_file(file); - } else |_| { - var subdir = if (ctx.request.head.target.len == 1) static - else (static.openDir(ctx.request.head.target[1..], .{}) catch { - return error.NotFound; - }); - defer if (ctx.request.head.target.len > 1) subdir.close(); - - if (subdir.openFile("index.html", .{})) |file| { - ctx.response.headers.content_type = "text/html"; - return .from_file(file); - } else |_| { - log.warn("File '{s}' Not Found", .{ ctx.request.head.target }); - return error.NotFound; - } - } -} diff --git a/src/server.zig b/src/server.zig deleted file mode 100644 index 5a9be74..0000000 --- a/src/server.zig +++ /dev/null @@ -1,73 +0,0 @@ -const std = @import("std"); -const log = std.log.scoped(.server); - -const routes = @import("routes/root.zig"); -const Storage = @import("storage/root.zig"); -const config = @import("config"); - -const Self = @This(); - -storage: Storage = undefined, -net_server: std.net.Server = undefined, -pool: std.Thread.Pool = undefined, - -pub fn init( - self: *Self, - address: std.net.Address, - allocator: std.mem.Allocator, -) !void { - self.storage = try .init(allocator); - self.net_server = try address.listen(.{ .reuse_address = true }); - try self.pool.init(.{ .allocator = allocator }); - log.info("listing on {f}", .{address}); - - if (comptime config.disable_auth) { - log.warn("authentication is disabled", .{}); - } -} - -pub fn run(self: *Self, allocator: std.mem.Allocator) void { - while (true) { - const connection = self.net_server.accept() catch |err| { - log.err("error: {}", .{err}); - continue; - }; - - self.pool.spawn(handle_connection, .{self, allocator, connection}) catch |err| { - std.log.err("failed to spawn thread: {}", .{err}); - }; - } -} - -fn handle_connection( - self: *Self, - allocator: std.mem.Allocator, - connection: std.net.Server.Connection, -) void { - defer connection.stream.close(); - - var read_buf: [1024 * 8]u8 = undefined; - var write_buf: [1024 * 8]u8 = undefined; - var reader = connection.stream.reader(&read_buf); - var writer = connection.stream.writer(&write_buf); - var http_server = std.http.Server.init(reader.interface(), &writer.interface); - - while (true) { - var request = http_server.receiveHead() catch return; - log.info("{s} {s}", .{ - std.enums.tagName(std.http.Method, request.head.method) orelse "<unknown>", - request.head.target, - }); - - const handler_info = routes.get(request.head.target); - handler_info.handle(&request, &self.storage, allocator) catch |err| { - std.log.err("{}", .{err}); - }; - } -} - -pub fn deinit(self: *Self) void { - log.info("shutdown", .{}); - self.net_server.deinit(); - self.storage.deinit(); -} diff --git a/src/storage/image-manager/exif.zig b/src/storage/image-manager/exif.zig deleted file mode 100644 index 88e9b48..0000000 --- a/src/storage/image-manager/exif.zig +++ /dev/null @@ -1,57 +0,0 @@ -const std = @import("std"); -const exif = @cImport(@cInclude("libexif/exif-data.h")); -const cstd = @cImport(@cInclude("time.h")); - -const tags = [_]c_uint { - exif.EXIF_TAG_DATE_TIME, - exif.EXIF_TAG_DATE_TIME_ORIGINAL, - exif.EXIF_TAG_DATE_TIME_DIGITIZED, -}; - -pub fn get_date_time(path: [*:0]const u8) ?i64 { - const exif_data = exif.exif_data_new_from_file(path); - defer exif.exif_data_unref(exif_data); - - if (exif_data == 0) { - return null; - } - - var entry: ?[*c]exif.struct__ExifEntry = null; - for (0..exif.EXIF_IFD_COUNT) |index| { - for (tags) |tag| { - entry = exif.exif_content_get_entry((exif_data.*).ifd[index], tag); - - if (entry) |_| { break; } - } - - if (entry) |_| { break; } - } - - if (entry == 0) { - return null; - } - - if (entry) |e| { - const c_data = (e.*).data; - return parse_date(c_data); - } - - return null; -} - -extern fn strptime( - s: [*c]const u8, - format: [*c]const u8, - tm: *cstd.tm, -) ?*const u8; - -extern fn mktime(tm: *cstd.tm) i64; - -fn parse_date(date: [*:0]const u8) ?i64 { - var tm: cstd.tm = std.mem.zeroes(cstd.tm); - if (strptime(date, "%Y:%m:%d %H:%M:%S", &tm)) |_| { - return mktime(&tm); - } - - return null; -} diff --git a/src/storage/image-manager/image.zig b/src/storage/image-manager/image.zig deleted file mode 100644 index bdac5c7..0000000 --- a/src/storage/image-manager/image.zig +++ /dev/null @@ -1,110 +0,0 @@ -const std = @import("std"); -const Storage = @import("../root.zig"); - -const exif = @import("exif.zig"); - -const id_size = 32; - -const log = std.log.scoped(.image); - -fn new_id() [id_size]u8 { - var buffer: [id_size]u8 = undefined; - var raw_buffer: [id_size / 2]u8 = undefined; - std.crypto.random.bytes(&raw_buffer); - - var writer = std.Io.Writer.fixed(buffer[0..]); - writer.print("{x}", .{raw_buffer}) catch unreachable; - - return buffer[0..].*; -} - -const Self = @This(); - -id: []const u8, -timestamp: ?i64, - -pub fn new( - storage: *Storage, - reader: *std.Io.Reader, - size: usize, -) !Self { - var dir = try storage.dir.openDir("image", .{}); - defer dir.close(); - - var self: Self = undefined; - - self.id = try storage.allocator.dupe(u8, &new_id()); - - var file_name: [id_size + 4]u8 = undefined; - @memcpy(file_name[0..id_size], self.id); - @memcpy(file_name[id_size..], ".jpg"); - - var image_file = try dir.createFile(&file_name, .{}); - defer image_file.close(); - - var buffer: [1024]u8 = undefined; - var file_writer = image_file.writer(&buffer); - - try reader.streamExact(&file_writer.interface, size); - - try file_writer.interface.flush(); - - log.info("uploaded {s} [{} bytes]", .{ self.id, size }); - - self.timestamp = try load_timestamp(storage, self.id); - - return self; -} - -pub fn delete(self: *Self, storage: *Storage) !void { - var dir = try storage.dir.openDir("image", .{}); - defer dir.close(); - - var file_name: [id_size + 4]u8 = undefined; - @memcpy(file_name[0..id_size], self.id); - @memcpy(file_name[id_size..], ".jpg"); - - try dir.deleteFile(&file_name); -} - -pub fn init(storage: *Storage, id: []const u8) !Self { - return .{ - .id = try storage.allocator.dupe(u8, id), - .timestamp = try load_timestamp(storage, id), - }; -} - -pub fn file(self: *Self, storage: *Storage) !std.fs.File { - var dir = storage.dir.openDir("image", .{}) catch blk: { - try storage.dir.makeDir("image"); - break :blk try storage.dir.openDir("image", .{}); - }; - defer dir.close(); - - var file_name: [id_size + 4]u8 = undefined; - @memcpy(file_name[0..id_size], self.id); - @memcpy(file_name[id_size..], ".jpg"); - - return dir.openFile(&file_name, .{}); -} - -pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { - allocator.free(self.id); -} - -fn load_timestamp(storage: *Storage, id: []const u8) !?i64 { - var dir = storage.dir.openDir("image", .{}) catch blk: { - try storage.dir.makeDir("image"); - break :blk try storage.dir.openDir("image", .{}); - }; - defer dir.close(); - - var file_name: [id_size + 4]u8 = undefined; - @memcpy(file_name[0..id_size], id); - @memcpy(file_name[id_size..], ".jpg"); - - var path_buffer: [std.fs.max_path_bytes:0]u8 = std.mem.zeroes([std.fs.max_path_bytes:0]u8); - const path = try dir.realpath(&file_name, &path_buffer); - - return exif.get_date_time(@ptrCast(path)); -} diff --git a/src/storage/image-manager/root.zig b/src/storage/image-manager/root.zig deleted file mode 100644 index efc216f..0000000 --- a/src/storage/image-manager/root.zig +++ /dev/null @@ -1,138 +0,0 @@ -const std = @import("std"); - -const memora = @import("memora"); -const Storage = memora.Storage; -pub const Image = @import("image.zig"); - -const Self = @This(); - -pub const empty: Self = .{}; - -const Timestamp = struct { - index: usize, - node: std.DoublyLinkedList.Node, - - pub fn next(self: *Timestamp) ?*Timestamp { - return @fieldParentPtr("node", self.node.next orelse return null); - } - - pub fn prev(self: *Timestamp) ?*Timestamp { - return @fieldParentPtr("node", self.node.prev orelse return null); - } -}; - -items: std.ArrayList(Image) = .empty, -rw_lock: std.Thread.RwLock = .{}, -timestamp_order: std.DoublyLinkedList = .{}, - -pub fn init( - self: *Self, - storage: *Storage, -) !void { - var dir = storage.dir.openDir("image", .{ .iterate = true }) catch blk: { - try storage.dir.makeDir("image"); - break :blk try storage.dir.openDir("image", .{ .iterate = true }); - }; - defer dir.close(); - - var iterator = dir.iterate(); - - errdefer self.items.deinit(storage.allocator); - - while (try iterator.next()) |entry| { - if (entry.kind == .file and std.mem.endsWith(u8, entry.name, ".jpg")) { - try self.add( - storage.allocator, - try .init(storage, entry.name[0..entry.name.len - 4]) - ); - } - } -} - -pub fn add(self: *Self, allocator: std.mem.Allocator, image: Image) !void { - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - try self.items.append( - allocator, - image, - ); - - var current = self.timestamp_order.first; - - while (current) |c| { - const index = @as(*Timestamp, @fieldParentPtr("node", c)).index; - if (image.timestamp orelse 0 > self.items.items[index].timestamp orelse 0) { - const timestamp = try allocator.create(Timestamp); - timestamp.index = self.items.items.len - 1; - self.timestamp_order.insertBefore(c, ×tamp.node); - return; - } - - current = c.next; - } - - const timestamp = try allocator.create(Timestamp); - timestamp.index = self.items.items.len - 1; - self.timestamp_order.append(×tamp.node); - return; -} - -pub fn save( - self: *Self, - storage: *Storage, - reader: *std.Io.Reader, - size: usize, -) !void { - return self.add(storage.allocator, try Image.new(storage, reader, size)); -} - -pub fn list(self: *Self) memora.locked.Shared([]Image) { - self.rw_lock.lockShared(); - return .{ - .value = self.items.items, - .rw_lock = &self.rw_lock, - }; -} - -pub fn first_by_timestamp(self: *Self) memora.locked.Shared(?*Timestamp) { - self.rw_lock.lockShared(); - return .{ - .value = if (self.timestamp_order.first) |first| @fieldParentPtr("node", first) - else null, - .rw_lock = &self.rw_lock, - }; -} - -pub fn delete(self: *Self, storage: *Storage, id: []const u8) !void { - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - const index = index: { - for (self.items.items, 0..) |image, index| { - if (std.mem.eql(u8, image.id, id)) { - break :index index; - } - } - break :index null; - }; - - if (index) |idx| { - try self.items.items[idx].delete(storage); - const old_index = self.items.items.len - 1; - _ = self.items.swapRemove(idx); - - var current: ?*Timestamp = if (self.timestamp_order.first) |c| @fieldParentPtr("node", c) else null; - - while (current) |c| { - if (c.index == idx) { - self.timestamp_order.remove(&c.node); - storage.allocator.destroy(c); - } else if (c.index == old_index) { - c.index = idx; - } - - current = c.next(); - } - } -} diff --git a/src/storage/media-manager/root.zig b/src/storage/media-manager/root.zig deleted file mode 100644 index e69de29..0000000 --- a/src/storage/media-manager/root.zig +++ /dev/null diff --git a/src/storage/root.zig b/src/storage/root.zig deleted file mode 100644 index f11798b..0000000 --- a/src/storage/root.zig +++ /dev/null @@ -1,79 +0,0 @@ -const std = @import("std"); -const prompt = @import("../prompt.zig"); -const Config = @import("../config.zig"); - -pub const User = @import("user.zig"); - -pub const ImageManager = @import("image-manager/root.zig"); -pub const Image = ImageManager.Image; - -pub const SessionManager = @import("session-manager/root.zig"); -pub const Session = SessionManager.Session; - -const Self = @This(); - -dir: std.fs.Dir, -sessions: SessionManager = .empty, -images: ImageManager = .empty, -config: Config, -allocator: std.mem.Allocator, - -pub fn init( - allocator: std.mem.Allocator, -) !Self { - var config = try Config.load(allocator); - errdefer config.deinit(); - - const dir = std.fs.cwd().openDir(config.storage_path, .{}) catch blk: { - try std.fs.cwd().makeDir(config.storage_path); - break :blk try std.fs.cwd().openDir(config.storage_path, .{}); - }; - - var self = Self { - .config = config, - .dir = dir, - .allocator = allocator, - }; - - dir.access("user", .{}) catch |err| switch (err) { - error.FileNotFound => { - const name = try prompt.read("Username", allocator); - defer allocator.free(name); - - const full_name = try prompt.read("Full Name", allocator); - defer allocator.free(full_name); - - const birthday = try prompt.read("Birthday", allocator); - defer allocator.free(birthday); - - const password = try prompt.read("Password", allocator); - defer allocator.free(password); - - try self.dir.makeDir("user"); - - var user: User = try .new( - &self, - name, - full_name, - birthday, - password, - true, - allocator, - ); - defer user.deinit(); - - try user.sync(); - }, - else => return err, - }; - - try self.images.init(&self); - - return self; -} - -pub fn deinit(self: *Self) void { - self.dir.close(); - self.config.deinit(); - self.* = undefined; -} diff --git a/src/storage/session-manager/root.zig b/src/storage/session-manager/root.zig deleted file mode 100644 index db95629..0000000 --- a/src/storage/session-manager/root.zig +++ /dev/null @@ -1,78 +0,0 @@ -const std = @import("std"); -const config = @import("../../config.zig"); -const Storage = @import("../root.zig"); - -pub const Session = @import("session.zig"); - -const Self = @This(); - -pub const empty: Self = .{ - .cache = .empty, -}; - -cache: std.StringHashMapUnmanaged(Session), -rw_lock: std.Thread.RwLock = .{}, - -pub fn add(self: *Self, storage: *Storage, info: Storage.User.Info) !*Session { - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - const session = try Session.init(storage.allocator, info); - errdefer session.deinit(storage.allocator); - try self.cache.put(storage.allocator, session.fingerprint, session); - return self.cache.getPtr(session.fingerprint) orelse unreachable; -} - -pub fn renew(self: *Self, storage: *Storage, fingerprint: []const u8) !*Session { - self.rw_lock.lockShared(); - if (self.cache.get(fingerprint)) |s| { - self.rw_lock.unlockShared(); - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - var session = s; - try session.reset(); - - try self.cache.put(storage.allocator, session.fingerprint, session); - - _ = self.cache.remove(fingerprint); - - return self.cache.getPtr(session.fingerprint) orelse unreachable; - } else { - self.rw_lock.unlockShared(); - } - return error.SessionNotFound; -} - -pub fn remove(self: *Self, storage: *Storage, fingerprint: []const u8) void { - self.rw_lock.lockShared(); - if (self.cache.contains(fingerprint)) { - self.rw_lock.unlockShared(); - self.rw_lock.lock(); - defer self.rw_lock.unlock(); - - const kv = self.cache.fetchRemove(fingerprint) orelse return; - kv.value.deinit(storage.allocator); - } else { - self.rw_lock.unlockShared(); - } -} - -pub fn get(self: *Self, storage: *Storage, fingerprint: []const u8) ?*Session { - self.rw_lock.lockShared(); - defer self.rw_lock.unlockShared(); - if (self.cache.getPtr(fingerprint)) |session| { - const now = std.time.Instant.now() catch return null; - const since = now.since(session.age); - - if (since > storage.config.session_expires_after) { - session.deinit(storage.allocator); - _ = self.cache.remove(fingerprint); - return null; - } - - return session; - } - - return null; -} diff --git a/src/storage/session-manager/session.zig b/src/storage/session-manager/session.zig deleted file mode 100644 index 943334b..0000000 --- a/src/storage/session-manager/session.zig +++ /dev/null @@ -1,34 +0,0 @@ -const std = @import("std"); -const User = @import("../user.zig"); - -const Self = @This(); - -const fingerprint_size = 512; - -age: std.time.Instant, -info: User.Info, -fingerprint: []u8, - -pub fn init(allocator: std.mem.Allocator, info: User.Info) !Self { - var self: Self = undefined; - self.info = try info.clone(allocator); - self.fingerprint = try allocator.alloc(u8, fingerprint_size); - try self.reset(); - - return self; -} - -pub fn reset(self: *Self) !void { - var raw_buffer: [fingerprint_size / 2]u8 = undefined; - std.crypto.random.bytes(&raw_buffer); - - var writer = std.Io.Writer.fixed(self.fingerprint); - writer.print("{x}", .{raw_buffer}) catch unreachable; - - self.age = try std.time.Instant.now(); -} - -pub fn deinit(self: *const Self, allocator: std.mem.Allocator) void { - self.info.deinit(allocator); - allocator.free(self.fingerprint); -} diff --git a/src/storage/user.zig b/src/storage/user.zig deleted file mode 100644 index c2cc82a..0000000 --- a/src/storage/user.zig +++ /dev/null @@ -1,234 +0,0 @@ -const std = @import("std"); -const Storage = @import("root.zig"); - -const log = std.log.scoped(.user); - -const Self = @This(); - -pub const Info = struct { - name: []const u8, - full_name: []const u8, - birthday: []const u8, - hash: []const u8, - is_admin: bool, - - pub fn clone(self: *const @This(), allocator: std.mem.Allocator) !@This() { - var clone_self: @This() = undefined; - var i: usize = 0; - - inline for (std.meta.fields(@This())) |field_info| { - if (field_info.type == []const u8) { - @field(clone_self, field_info.name) = try allocator.dupe( - u8, - @field(self, field_info.name), - ); - errdefer allocator.free(@field(clone_self, field_info.name)); - } else { - @field(clone_self, field_info.name) = @field(self, field_info.name); - } - i += 1; - } - - return clone_self; - } - - pub fn deinit(self: *const @This(), allocator: std.mem.Allocator) void { - inline for (std.meta.fields(@This())) |field_info| { - if (field_info.type == []const u8) { - allocator.free(@field(self, field_info.name)); - } - } - } -}; - -dir: std.fs.Dir, -info: Info, -arena: std.heap.ArenaAllocator, - -pub fn open( - storage: *Storage, - name: []const u8, -) !Self { - var arena: std.heap.ArenaAllocator = .init(storage.allocator); - errdefer arena.deinit(); - const allocator = arena.allocator(); - - var user_dir = try storage.dir.openDir("user", .{}); - defer user_dir.close(); - - var dir = try user_dir.openDir(name, .{}); - errdefer dir.close(); - - const file = try dir.openFile("info.json", .{ .lock = .shared }); - defer file.close(); - const content = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); - - const info = try std.json.parseFromSliceLeaky(Info, allocator, content, .{}); - - return .{ - .dir = dir, - .arena = arena, - .info = info, - }; -} - -pub fn new( - storage: *Storage, - name: []const u8, - full_name: []const u8, - birthday: []const u8, - password: []const u8, - is_admin: bool, - inner_allocator: std.mem.Allocator -) !Self { - var arena: std.heap.ArenaAllocator = .init(inner_allocator); - const allocator = arena.allocator(); - errdefer arena.deinit(); - - var user_dir = try storage.dir.openDir("user", .{}); - defer user_dir.close(); - - try user_dir.makeDir(name); - var dir = try user_dir.openDir(name, .{}); - errdefer dir.close(); - - var file = try dir.createFile("info.json", .{ .lock = .exclusive }); - file.close(); - - const hash_buf = try allocator.alloc(u8, 256); - const hash = try std.crypto.pwhash.bcrypt.strHash( - password, - .{ - .params = .{ - .rounds_log = 3, - .silently_truncate_password = false, - }, - .encoding = .phc, - }, - hash_buf - ); - - const info: Info = .{ - .name = name, - .full_name = full_name, - .birthday = birthday, - .hash = hash, - .is_admin = is_admin, - }; - - - return .{ - .dir = dir, - .arena = arena, - .info = info, - }; -} - -pub fn set_password(self: *Self, password: []const u8) !void { - const allocator = self.arena.allocator(); - const hash_buf = try allocator.alloc(u8, 256); - const hash = try std.crypto.pwhash.bcrypt.strHash( - password, - .{ - .params = .{ - .rounds_log = 3, - .silently_truncate_password = false, - }, - .encoding = .phc, - }, - hash_buf - ); - - self.info.hash = hash; -} - -pub fn sync(self: *Self) !void { - const file = try self.dir.createFile("info.json", .{ - .lock = .exclusive, - }); - defer file.close(); - - var buffer: [1024]u8 = undefined; - var writer = file.writer(&buffer); - - var stringify = std.json.Stringify { - .writer = &writer.interface, - .options = .{ .whitespace = .indent_2 } - }; - - try stringify.write(self.info); - try writer.interface.flush(); -} - -pub fn check_password(self: *Self, password: []const u8) bool { - std.crypto.pwhash.bcrypt.strVerify(self.info.hash, password, .{ - .silently_truncate_password = false, - }) catch return false; - return true; -} - -pub fn deinit(self: *Self) void { - self.dir.close(); - self.arena.deinit(); - self.* = undefined; -} - -pub fn exists(storage: *Storage, name: []const u8) bool { - var user = storage.dir.openDir("user", .{}) catch return false; - defer user.close(); - - user.access(name, .{}) catch return false; - return true; -} - -pub fn image(storage: *Storage, name: []const u8) ?std.fs.File { - var user = storage.dir.openDir("user", .{}) catch return null; - defer user.close(); - - var profile = user.openDir(name, .{}) catch return null; - defer profile.close(); - return profile.openFile("image.jpg", .{ .lock = .shared }) catch null; -} - -pub fn set_image( - storage: *Storage, - name: []const u8, - reader: *std.Io.Reader, - size: usize, -) !void { - var user = try storage.dir.openDir("user", .{}); - defer user.close(); - - var profile = try user.openDir(name, .{}); - defer profile.close(); - - var image_file = try profile.createFile("image.jpg", .{ .lock = .exclusive }); - defer image_file.close(); - - var buffer: [1024]u8 = undefined; - var file_writer = image_file.writer(&buffer); - - log.info("uploaded to profile {s} [{} bytes]", .{ name, size }); - - try reader.streamExact(&file_writer.interface, size); - - try file_writer.interface.flush(); -} - -pub fn list( - storage: *Storage, - allocator: std.mem.Allocator, -) ![][]const u8 { - var user = try storage.dir.openDir("user", .{ .iterate = true }); - defer user.close(); - - var ids: std.ArrayList([]const u8) = .empty; - - var iterator = user.iterate(); - - while (try iterator.next()) |entry| { - try ids.append(allocator, try allocator.dupe(u8, entry.name)); - } - - return ids.toOwnedSlice(allocator); -} diff --git a/src/stream/buffer.zig b/src/stream/buffer.zig deleted file mode 100644 index fca1deb..0000000 --- a/src/stream/buffer.zig +++ /dev/null @@ -1,28 +0,0 @@ -const std = @import("std"); - -const Self = @This(); - -buffer: []const u8, -buffer_reader: ?std.Io.Reader, - -pub fn init(buffer: []const u8) Self { - return .{ - .buffer = buffer, - .buffer_reader = null, - }; -} - -pub fn reader(self: *Self, buffer: []u8) *std.Io.Reader { - _ = buffer; - - if (self.buffer_reader) |*r| { - return r; - } - - self.buffer_reader = std.Io.Reader.fixed(self.buffer); - return &self.buffer_reader.?; -} - -pub fn close(self: *Self) void { - _ = self; -} diff --git a/src/stream/file.zig b/src/stream/file.zig deleted file mode 100644 index bb6407b..0000000 --- a/src/stream/file.zig +++ /dev/null @@ -1,22 +0,0 @@ -const std = @import("std"); - -const Self = @This(); - -file: std.fs.File, -file_reader: ?std.fs.File.Reader, - -pub fn init(file: std.fs.File) Self { - return .{ - .file = file, - .file_reader = null, - }; -} - -pub fn reader(self: *Self, buffer: []u8) *std.Io.Reader { - self.file_reader = self.file.reader(buffer); - return &self.file_reader.?.interface; -} - -pub fn close(self: *Self) void { - self.file.close(); -} diff --git a/src/stream/root.zig b/src/stream/root.zig deleted file mode 100644 index 11580ac..0000000 --- a/src/stream/root.zig +++ /dev/null @@ -1,33 +0,0 @@ -const std = @import("std"); - -pub const Stream = union(enum) { - const Self = @This(); - - pub const File = @import("file.zig"); - pub const Buffer = @import("buffer.zig"); - - file: File, - buffer: Buffer, - - pub fn from_file(file: std.fs.File) Self { - return .{ .file = File.init(file) }; - } - - pub fn from_buffer(buffer: []const u8) Self { - return .{ .buffer = Buffer.init(buffer) }; - } - - pub fn reader(self: *Self, buffer: []u8) *std.Io.Reader { - return switch(self.*) { - .file => |*f| f.reader(buffer), - .buffer => |*b| b.reader(buffer), - }; - } - - pub fn close(self: *Self) void { - return switch(self.*) { - .file => |*f| f.close(), - .buffer => |*b| b.close(), - }; - } -}; diff --git a/static/api/auth.js b/static/api/auth.js deleted file mode 100644 index e663d88..0000000 --- a/static/api/auth.js +++ /dev/null @@ -1,12 +0,0 @@ -import * as rest from './rest.js'; - - -export async function login(user, password) { - const response = await rest.post('/api/auth/login', { user, password }); - return response?.success ?? false; -} - -export async function is_first_login(user) { - const response = await rest.post('/api/auth/first-login', { user }); - return response?.is_first ?? false; -} diff --git a/static/api/images.js b/static/api/images.js deleted file mode 100644 index 8e9cff2..0000000 --- a/static/api/images.js +++ /dev/null @@ -1,83 +0,0 @@ -import * as sfw from 'sfw'; -const { Input } = sfw.element.native; -import * as rest from './rest.js'; - -class FileUploader { - constructor(url, files) { - this.onprogress = () => {} - this.ondone = () => {} - this.url = url; - this.sessions = []; - this.files = files; - } - - send() { - let count = 0; - this.sessions = this.sessions.concat(this.files.map( - (file) => new Promise((resolve) => { - const xhr = new XMLHttpRequest(); - xhr.addEventListener("loadend", (event) => { - count += 1; - - this.onprogress(count, this.files.length) - - resolve(xhr.readyState === 4 && xhr.status === 200); - - if (count == this.files.length) { - this.ondone(); - } - }); - - xhr.open("POST", this.url, true); - xhr.setRequestHeader("Content-Type", "application/octet-stream"); - xhr.send(file.slice()); - }) - )); - } -} - -export async function upload_to_timeline() { - const input = Input.new({ - type: 'file', - multiple: true, - accept: 'image/jpeg', - }) - input.click(); - - - return new Promise((resolve) => { - input.onchange = () => { - resolve(new FileUploader('/api/image/upload', [...input.files])); - } - }) -} - -export async function upload_to_profile(id) { - const input = Input.new({ - type: 'file', - multiple: false, - accept: 'image/jpeg', - }) - input.click(); - - return new Promise((resolve) => { - input.onchange = () => { - resolve(new FileUploader(`/api/profile/image/upload/${id}`, [...input.files])); - } - }) -} - -export function list() { - return rest.get('/api/image/list') - .then(r => { - r.images.forEach(i => { - i.date = new Date(i.timestamp * 1000) - }); - return r.images; - }); -} - - -export function remove(id) { - return rest.post('/api/image/remove', { id: id }); -} diff --git a/static/api/index.js b/static/api/index.js deleted file mode 100644 index cddd7bd..0000000 --- a/static/api/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export * as images from './images.js'; -export * as auth from './auth.js'; -export * as session from './session.js'; -export * as profile from './profile.js'; diff --git a/static/api/profile.js b/static/api/profile.js deleted file mode 100644 index d6acd16..0000000 --- a/static/api/profile.js +++ /dev/null @@ -1,15 +0,0 @@ -import * as rest from './rest.js'; - -export async function set(name, birthday) { - await rest.post('/api/profile/set', { - full_name: name, - birthday: birthday, - }); -} - -export function update_password(old, next) { - return rest.post('/api/profile/update-password', { - current_password: old, - new_password: next, - }).then(r => r.success); -} diff --git a/static/api/rest.js b/static/api/rest.js deleted file mode 100644 index 6b14034..0000000 --- a/static/api/rest.js +++ /dev/null @@ -1,22 +0,0 @@ - -async function handle_fetch(promise) { - const result = await promise; - const json = await result.json(); - - if (!result.ok) { - throw json; - } - - return json; -} - -export function get(url) { - return handle_fetch(fetch(url)); -} - -export function post(url, body) { - return handle_fetch(fetch(url, { - method: 'POST', - body: JSON.stringify(body), - })); -} diff --git a/static/api/session.js b/static/api/session.js deleted file mode 100644 index 6e14d55..0000000 --- a/static/api/session.js +++ /dev/null @@ -1,23 +0,0 @@ -import * as rest from './rest.js'; - -export function current() { - return rest.get('/api/session/current'); -} - -export async function is_valid() { - const result = await rest.get('/api/session/is-valid'); - return result.is_valid; -} - -export async function drop() { - const result = await rest.get('/api/session/drop'); -} - -export async function is_online() { - try { - const result = await rest.get('/api/session/is-online'); - return result.is_online; - } catch { - return false; - } -} diff --git a/static/fonts/noto-sans/default.ttf b/static/fonts/noto-sans/default.ttf Binary files differdeleted file mode 100644 index 9530d84..0000000 --- a/static/fonts/noto-sans/default.ttf +++ /dev/null diff --git a/static/fonts/noto-sans/italic.ttf b/static/fonts/noto-sans/italic.ttf Binary files differdeleted file mode 100644 index 6245ba0..0000000 --- a/static/fonts/noto-sans/italic.ttf +++ /dev/null diff --git a/static/fonts/pacifico/regular.ttf b/static/fonts/pacifico/regular.ttf Binary files differdeleted file mode 100644 index e7def95..0000000 --- a/static/fonts/pacifico/regular.ttf +++ /dev/null diff --git a/static/icon.png b/static/icon.png Binary files differdeleted file mode 100644 index 7ff5837..0000000 --- a/static/icon.png +++ /dev/null diff --git a/static/icon.svg b/static/icon.svg deleted file mode 100644 index 83fc1bd..0000000 --- a/static/icon.svg +++ /dev/null @@ -1,75 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<!-- Created with Inkscape (http://www.inkscape.org/) --> - -<svg - width="512" - height="512" - viewBox="0 0 512 512" - version="1.1" - id="svg1" - inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)" - sodipodi:docname="icon.svg" - inkscape:export-filename="icon.png" - inkscape:export-xdpi="96" - inkscape:export-ydpi="96" - xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" - xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" - xmlns="http://www.w3.org/2000/svg" - xmlns:svg="http://www.w3.org/2000/svg"> - <sodipodi:namedview - id="namedview1" - pagecolor="#ffffff" - bordercolor="#000000" - borderopacity="0.25" - inkscape:showpageshadow="2" - inkscape:pageopacity="0.0" - inkscape:pagecheckerboard="true" - inkscape:deskcolor="#d1d1d1" - inkscape:document-units="px" - inkscape:zoom="0.60644339" - inkscape:cx="112.12918" - inkscape:cy="349.57921" - inkscape:window-width="1914" - inkscape:window-height="1054" - inkscape:window-x="0" - inkscape:window-y="0" - inkscape:window-maximized="1" - inkscape:current-layer="layer1" /> - <defs - id="defs1" /> - <g - inkscape:label="Layer 1" - inkscape:groupmode="layer" - id="layer1"> - <circle - style="fill:#dfdfdf;fill-opacity:1;stroke:none;stroke-width:15.5767;stroke-dasharray:none;stroke-opacity:1" - id="path2-1" - cx="256" - cy="256" - r="448.711" /> - <circle - style="fill:#726eff;fill-opacity:1;stroke-width:1.32394" - id="path1" - cx="23.562067" - cy="215.85896" - r="250.06198" /> - <circle - style="fill:#212b38;fill-opacity:1;stroke:none;stroke-width:6.64688;stroke-dasharray:none;stroke-opacity:1" - id="path2" - cx="474.28168" - cy="398.27499" - r="191.47348" /> - <text - xml:space="preserve" - style="font-size:24px;font-family:'Sans Serif';-inkscape-font-specification:'Sans Serif';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;white-space:pre;inline-size:34.4024;display:inline;fill:#212b38;fill-opacity:1;stroke:#dfdfdf;stroke-width:0.523775;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1" - x="254.17958" - y="345.31635" - id="text1" - transform="matrix(9.4165391,0,0,9.677421,-2291.1707,-2987.8748)"><tspan - x="254.17958" - y="345.31635" - id="tspan3"><tspan - style="font-family:Pacifico;-inkscape-font-specification:Pacifico" - id="tspan2">M</tspan></tspan></text> - </g> -</svg> diff --git a/static/icons/192.png b/static/icons/192.png Binary files differdeleted file mode 100644 index 38ee689..0000000 --- a/static/icons/192.png +++ /dev/null diff --git a/static/icons/512.png b/static/icons/512.png Binary files differdeleted file mode 100644 index 7ff5837..0000000 --- a/static/icons/512.png +++ /dev/null diff --git a/static/icons/add.js b/static/icons/add.js deleted file mode 100644 index 12650a8..0000000 --- a/static/icons/add.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus" viewBox="0 0 16 16"> - <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4"/> -</svg>`; diff --git a/static/icons/calendar.js b/static/icons/calendar.js deleted file mode 100644 index 9d9b2ec..0000000 --- a/static/icons/calendar.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-calendar-week-fill" viewBox="0 0 16 16"> - <path d="M4 .5a.5.5 0 0 0-1 0V1H2a2 2 0 0 0-2 2v1h16V3a2 2 0 0 0-2-2h-1V.5a.5.5 0 0 0-1 0V1H4zM16 14V5H0v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M9.5 7h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5m3 0h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5M2 10.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5zm3.5-.5h1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5"/> -</svg>`; diff --git a/static/icons/check.js b/static/icons/check.js deleted file mode 100644 index dfc2763..0000000 --- a/static/icons/check.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-lg" viewBox="0 0 16 16"> - <path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425z"/> -</svg>` diff --git a/static/icons/close.js b/static/icons/close.js deleted file mode 100644 index 8c96dbd..0000000 --- a/static/icons/close.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x" viewBox="0 0 16 16"> - <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708"/> -</svg>`; diff --git a/static/icons/edit.js b/static/icons/edit.js deleted file mode 100644 index e13bb8a..0000000 --- a/static/icons/edit.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pen-fill" viewBox="0 0 16 16"> - <path d="m13.498.795.149-.149a1.207 1.207 0 1 1 1.707 1.708l-.149.148a1.5 1.5 0 0 1-.059 2.059L4.854 14.854a.5.5 0 0 1-.233.131l-4 1a.5.5 0 0 1-.606-.606l1-4a.5.5 0 0 1 .131-.232l9.642-9.642a.5.5 0 0 0-.642.056L6.854 4.854a.5.5 0 1 1-.708-.708L9.44.854A1.5 1.5 0 0 1 11.5.796a1.5 1.5 0 0 1 1.998-.001"/> -</svg>`; diff --git a/static/icons/home.js b/static/icons/home.js deleted file mode 100644 index a6b4886..0000000 --- a/static/icons/home.js +++ /dev/null @@ -1,4 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house-fill" viewBox="0 0 16 16"> - <path d="M8.707 1.5a1 1 0 0 0-1.414 0L.646 8.146a.5.5 0 0 0 .708.708L8 2.207l6.646 6.647a.5.5 0 0 0 .708-.708L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293z"/> - <path d="m8 3.293 6 6V13.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5V9.293z"/> -</svg>`; diff --git a/static/icons/icon.svg b/static/icons/icon.svg deleted file mode 100644 index 87b8771..0000000 --- a/static/icons/icon.svg +++ /dev/null @@ -1,51 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<!-- Created with Inkscape (http://www.inkscape.org/) --> - -<svg - width="512" - height="512" - viewBox="0 0 512 512" - version="1.1" - id="svg1" - inkscape:export-filename="192.png" - inkscape:export-xdpi="36" - inkscape:export-ydpi="36" - inkscape:version="1.4.2 (ebf0e940d0, 2025-05-08)" - sodipodi:docname="icon.svg" - xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" - xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" - xmlns="http://www.w3.org/2000/svg" - xmlns:svg="http://www.w3.org/2000/svg"> - <sodipodi:namedview - id="namedview1" - pagecolor="#ffffff" - bordercolor="#000000" - borderopacity="0.25" - inkscape:showpageshadow="2" - inkscape:pageopacity="0.0" - inkscape:pagecheckerboard="0" - inkscape:deskcolor="#d1d1d1" - inkscape:document-units="px" - inkscape:zoom="1.1960048" - inkscape:cx="267.55745" - inkscape:cy="277.59085" - inkscape:window-width="1914" - inkscape:window-height="1054" - inkscape:window-x="0" - inkscape:window-y="0" - inkscape:window-maximized="1" - inkscape:current-layer="layer1" /> - <defs - id="defs1" /> - <g - inkscape:label="Layer 1" - inkscape:groupmode="layer" - id="layer1"> - <circle - style="fill:#000000;stroke-width:3.04152;stroke-linecap:round;stroke-linejoin:round" - id="path1" - cx="256" - cy="256" - r="227.42381" /> - </g> -</svg> diff --git a/static/icons/index.js b/static/icons/index.js deleted file mode 100644 index 5402be0..0000000 --- a/static/icons/index.js +++ /dev/null @@ -1,39 +0,0 @@ -import * as sfw from 'sfw'; -const { I } = sfw.element.native; - -import Settings from './settings'; -import Shuffle from './shuffle'; -import Calendar from './calendar'; -import Search from './search'; -import Close from './close'; -import Home from './home'; -import Add from './add'; -import Edit from './edit'; -import Check from './check'; -import Next from './next'; - -const icons = { - 'settings': Settings, - 'shuffle': Shuffle, - 'calendar': Calendar, - 'search': Search, - 'close': Close, - 'home': Home, - 'add': Add, - 'edit': Edit, - 'check': Check, - 'next': Next, -}; - -const target = { icons: icons }; - -const handler = { - get(target, prop, receiver) { - return I.new({ - innerHTML: target.icons[prop] ?? '?', - className: 'icon', - }); - } -}; - -export default new Proxy(target, handler); diff --git a/static/icons/next.js b/static/icons/next.js deleted file mode 100644 index 9728ee7..0000000 --- a/static/icons/next.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right-short" viewBox="0 0 16 16"> - <path fill-rule="evenodd" d="M4 8a.5.5 0 0 1 .5-.5h5.793L8.146 5.354a.5.5 0 1 1 .708-.708l3 3a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708-.708L10.293 8.5H4.5A.5.5 0 0 1 4 8"/> -</svg>`; diff --git a/static/icons/search.js b/static/icons/search.js deleted file mode 100644 index a35ff2a..0000000 --- a/static/icons/search.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16"> - <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001q.044.06.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1 1 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0"/> -</svg>`; diff --git a/static/icons/settings.js b/static/icons/settings.js deleted file mode 100644 index 258c8f8..0000000 --- a/static/icons/settings.js +++ /dev/null @@ -1,3 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-gear-fill" viewBox="0 0 16 16"> - <path d="M9.405 1.05c-.413-1.4-2.397-1.4-2.81 0l-.1.34a1.464 1.464 0 0 1-2.105.872l-.31-.17c-1.283-.698-2.686.705-1.987 1.987l.169.311c.446.82.023 1.841-.872 2.105l-.34.1c-1.4.413-1.4 2.397 0 2.81l.34.1a1.464 1.464 0 0 1 .872 2.105l-.17.31c-.698 1.283.705 2.686 1.987 1.987l.311-.169a1.464 1.464 0 0 1 2.105.872l.1.34c.413 1.4 2.397 1.4 2.81 0l.1-.34a1.464 1.464 0 0 1 2.105-.872l.31.17c1.283.698 2.686-.705 1.987-1.987l-.169-.311a1.464 1.464 0 0 1 .872-2.105l.34-.1c1.4-.413 1.4-2.397 0-2.81l-.34-.1a1.464 1.464 0 0 1-.872-2.105l.17-.31c.698-1.283-.705-2.686-1.987-1.987l-.311.169a1.464 1.464 0 0 1-2.105-.872zM8 10.93a2.929 2.929 0 1 1 0-5.86 2.929 2.929 0 0 1 0 5.858z"/> -</svg>`; diff --git a/static/icons/shuffle.js b/static/icons/shuffle.js deleted file mode 100644 index d538fd8..0000000 --- a/static/icons/shuffle.js +++ /dev/null @@ -1,4 +0,0 @@ -export default `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-shuffle" viewBox="0 0 16 16"> - <path fill-rule="evenodd" d="M0 3.5A.5.5 0 0 1 .5 3H1c2.202 0 3.827 1.24 4.874 2.418.49.552.865 1.102 1.126 1.532.26-.43.636-.98 1.126-1.532C9.173 4.24 10.798 3 13 3v1c-1.798 0-3.173 1.01-4.126 2.082A9.6 9.6 0 0 0 7.556 8a9.6 9.6 0 0 0 1.317 1.918C9.828 10.99 11.204 12 13 12v1c-2.202 0-3.827-1.24-4.874-2.418A10.6 10.6 0 0 1 7 9.05c-.26.43-.636.98-1.126 1.532C4.827 11.76 3.202 13 1 13H.5a.5.5 0 0 1 0-1H1c1.798 0 3.173-1.01 4.126-2.082A9.6 9.6 0 0 0 6.444 8a9.6 9.6 0 0 0-1.317-1.918C4.172 5.01 2.796 4 1 4H.5a.5.5 0 0 1-.5-.5"/> - <path d="M13 5.466V1.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384l-2.36 1.966a.25.25 0 0 1-.41-.192m0 9v-3.932a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384l-2.36 1.966a.25.25 0 0 1-.41-.192"/> -</svg>`; diff --git a/static/index.css b/static/index.css deleted file mode 100644 index d5d74cd..0000000 --- a/static/index.css +++ /dev/null @@ -1,70 +0,0 @@ -:host, :root { - --primary: #726eff; - --fg-primary: #fff; - --fg: #212b38; - --fg-disabled: #37465b; - --bg-label: #dedee8; - --border-radius: 4px; - --card-background: #fff; - --page-background: #dfdfdf; - --shadow: #223223aa 1px 1px 4px; -} - -html, body { - margin: 0; - padding: 0; - width: 100%; - height: 100%; - overflow: hidden; -} - -body { - font-family: "Noto Sans", sans-serif; - color: var(--fg); -} - -button { - font-family: "Noto Sans", sans-serif; - background: var(--primary); - color: var(--fg-primary); - padding: 10px; - border: none; - border-radius: var(--border-radius); - font-weight: bold; - cursor: pointer; -} - -input { - font-family: "Noto Sans", sans-serif; - color: var(--fg); - padding: 10px; - border: none; - outline: none; - background: var(--bg-label); - border-radius: var(--border-radius); -} - -* { - box-sizing: border-box; -} - -.icon svg { - width: 100%; - height: 100%; -} - -@font-face { - font-family: Pacifico; - src: url(/fonts/pacifico/regular.ttf); -} - -@font-face { - font-family: "Noto Sans"; - src: url(/fonts/noto-sans/default.ttf); -} - -@font-face { - font-family: "Noto Sans"; - font-style: italic - src: url(/fonts/noto-sans/italic.ttf); -} diff --git a/static/index.html b/static/index.html deleted file mode 100644 index 8fa5079..0000000 --- a/static/index.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <title>Memora</title> - <script type="module" src="index.js"></script> - <link rel="icon" href="icon.png" type="image/png"> - <link rel="manifest" href="manifest.json" /> - </head> - <body> - </body> -</html> diff --git a/static/index.js b/static/index.js deleted file mode 100644 index ddbead7..0000000 --- a/static/index.js +++ /dev/null @@ -1,137 +0,0 @@ -import * as sfw from 'sfw'; -import * as api from 'api'; -import Month from './month.js'; - -import LoginView from './pages/login/index.js'; -import MainView from './pages/main/index.js'; -import ImageViewer from './pages/image-viewer/index.js'; -import Search from './widgets/search/index.js'; -import MonthSelect from './widgets/month-select/index.js'; -import SettingsView from './pages/settings/index.js'; -import ShuffleView from './pages/shuffle/index.js'; -import UploadBar from './widgets/upload-bar/index.js'; - -import stylesheet from './index.css'; -sfw.theme.add_css(await sfw.css.sheet(stylesheet)); - -const image_viewer = ImageViewer.new(); - -const reload = () => { - api.images.list().then(images => { - const last = Month.from_unix(images[0].timestamp); - let first = Month.from_unix(images.findLast(i => i.timestamp).timestamp); - month_select.months = first.to(last); - - image_viewer.images = images; - shuffle.images = images; - }); -} - -const login = LoginView.new({ - onlogin: async (user, password) => { - if (await api.auth.login(user, password)) { - reload(); - login.hide(); - } else { - login.comment = 'Incorrect username or password.'; - } - }, - - onpassword: async (user) => { - if (await api.auth.is_first_login(user)) { - login.comment = 'Please enter a new password.'; - } else { - login.comment = ''; - } - }, -}); - -const search = Search.new({ - onsubmit: (content) => console.log(content), - onhide: () => main.show(), -}); - -const month_select = MonthSelect.new({ - onmonth: (month) => image_viewer.jump_to(month), -}); -const upload_bar = UploadBar.new(); - -const settings = SettingsView.new({ - onlogout: async () => { - await api.session.drop(); - login.show(); - main.active_view = image_viewer; - settings.profile = null; - }, -}); - -const shuffle = ShuffleView.new({ }); - -const main = MainView.new({ - active_view: image_viewer, - active_kind: MainView.Kind.upload, - - onsearch: () => { - main.active_kind = MainView.Kind.upload; - main.active_view = image_viewer; - search.toggle(); - main.hide(); - }, - onmonth: () => { - main.active_kind = MainView.Kind.upload; - main.active_view = image_viewer; - month_select.show(); - }, - onupload: async () => { - upload_bar.progress = 0; - upload_bar.show(); - - const uploader = await api.images.upload_to_timeline(); - - uploader.onprogress = (count, total) => { - upload_bar.progress = count / total; - } - - uploader.ondone = () => { - upload_bar.hide(); - reload(); - } - - uploader.send(); - }, - onshuffle: () => { - shuffle.open(); - main.active_kind = MainView.Kind.home; - main.active_view = shuffle; - }, - onsettings: async () => { - if (!settings.profile) { - settings.profile = await api.session.current(); - } - - main.active_kind = MainView.Kind.home; - main.active_view = settings; - }, - onhome: () => { - main.active_kind = MainView.Kind.upload; - main.active_view = image_viewer; - }, -}); - -document.body.append( - login, - main, - search, - month_select, - upload_bar, -); - -if (!await api.session.is_online()) { - login.hide(); - reload(); -} if (await api.session.is_valid()) { - login.hide(); - reload(); -} else { - login.focus(); -} diff --git a/static/manifest.json b/static/manifest.json deleted file mode 100644 index e91b5dc..0000000 --- a/static/manifest.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "Memora", - "icons": [ - { - "src": "icons/512.png", - "type": "image/png", - "sizes": "512x512" - }, - { - "src": "icons/192.png", - "type": "image/png", - "sizes": "192x192" - } - ], - "start_url": ".", - "display": "standalone" -} diff --git a/static/month.js b/static/month.js deleted file mode 100644 index 05037d4..0000000 --- a/static/month.js +++ /dev/null @@ -1,95 +0,0 @@ - -export default class Month { - constructor(month, year) { - this.month = month; - this.year = year; - } - - next(n) { - n = n ?? 1; - - const month = this.month + n - 1; - this.month = (month % 12) + 1; - this.year += Math.floor(month / 12); - - return this; - } - - previous(n) { - n = n ?? 1; - - let month = this.month - n - 1; - - if (month < 0) { - month += 12; - } - - this.month = (month % 12) + 1; - this.year += Math.floor(month / 12); - - return this; - } - - to(other) { - const inner = []; - const current = this.copy(); - - while (current.is_same(other) || current.is_before(other)) { - inner.push(current.copy()); - current.next(); - } - - return inner; - } - - copy() { - return new Month(this.month, this.year); - } - - is_before(other) { - return this.year < other.year || (this.year == other.year && this.month < other.month); - } - - is_after(other) { - return this.year > other.year || (this.year == other.year && this.month > other.month); - } - - is_same(other) { - return this.year == other?.year && this.month == other?.month; - } - - is_same_year(other) { - return this.year == other.year; - } - - get name() { - const date = new Date(); - date.setMonth(this.month - 1); - return date.toLocaleDateString('default', { month: 'long' }) - } - - static from_unix(date) { - if (date == null) return null; - - return Month.from_date(new Date(date * 1000)); - } - - static from_date(date) { - return new Month(date.getMonth() + 1, date.getFullYear()); - } - - static from_string(string) { - const [ year, month ] = string.split('-'); - return new Month(parseInt(month), parseInt(year)) - } - - static literal(strings) { - return Month.from_string(strings[0]); - } - - static get current() { - return Month.from_date(new Date()); - } -} - -export const literal = Month.literal; diff --git a/static/pages/image-viewer/index.css b/static/pages/image-viewer/index.css deleted file mode 100644 index 4567050..0000000 --- a/static/pages/image-viewer/index.css +++ /dev/null @@ -1,9 +0,0 @@ - -#container { - width: 100%; - height: 100vh; - overflow-y: auto; - display: grid; - gap: 10px; - padding: 10px; -} diff --git a/static/pages/image-viewer/index.js b/static/pages/image-viewer/index.js deleted file mode 100644 index 34b5f69..0000000 --- a/static/pages/image-viewer/index.js +++ /dev/null @@ -1,34 +0,0 @@ -import * as sfw from 'sfw'; -const { Img, Div } = sfw.element.native; - -import Month from '../../month.js'; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class ImageViewer extends sfw.element.Container { - #images - #image_elements - - constructor() { - super({ css }); - - this.#images = []; - - this.body.append( - Div.new({ - id: 'container', - onscroll: () => console.log('scroll'), - }) - ); - } - - set images(images) { - this.#images = images; - } - - jump_to(month) { - // TODO - } -} diff --git a/static/pages/index.js b/static/pages/index.js deleted file mode 100644 index 56b0848..0000000 --- a/static/pages/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export ImageViewer from './image-viewer/index.js'; -export LoginView from './login/index.js'; -export MainView from './main/index.js'; -export SettingsView from './settings/index.js'; -export ShuffleView from './shuffle/index.js'; diff --git a/static/pages/login/index.css b/static/pages/login/index.css deleted file mode 100644 index d9d0f41..0000000 --- a/static/pages/login/index.css +++ /dev/null @@ -1,153 +0,0 @@ -#container { - background: var(--page-background); - overflow: hidden; - width: 100%; - height: 100%; - z-index: 1000; - position: absolute; - top: 0; - bottom: 0; - transition: top 0.2s ease; -} - -#container.hidden { - top: -100%; -} - -#box { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - max-width: 300px; - width: 100%; - padding: 0px; - box-shadow: #223223aa 1px 1px 4px; - border-radius: var(--border-radius); - z-index: 5000; - display: grid; - grid-template-columns: auto 30px; - background: #ffffff99; - backdrop-filter: blur(10px); -} - -#box input { - border-top-right-radius: 0px; - border-bottom-right-radius: 0px; - background: #0000; -} - -#box #submit { - border-top-left-radius: 0px; - border-bottom-left-radius: 0px; - background: var(--page-background); - color: var(--fg); - padding: 5px; - background: #0000; -} - -#username-label { - position: absolute; - top: calc(50% - 40px); - left: 50%; - transform: translate(-50%, -50%); - z-index: 10000; - user-select: none; - color: var(--fg-primary); - font-size: 0.8em; - cursor: pointer; -} -#comment { - position: absolute; - top: calc(50% + 40px); - left: 50%; - transform: translate(-50%, -50%); - z-index: 10000; - user-select: none; - color: var(--primary); - font-size: 0.8em; - cursor: pointer; -} - -#title { - font-family: 'Pacifico'; - position: absolute; - width: 100%; - height: 100%; - text-align: center; - top: 0px; - padding-top: 50px; - font-size: 2.5em; - z-index: 1000; - text-shadow: -1px -1px 0 var(--page-background), - 1px 1px 0 var(--page-background), - 1px -1px 0 var(--page-background), - -1px 1px 0 var(--page-background); - overflow: hidden; -} - -@keyframes left-bubble { - from { - width: 0px; - height: 0px; - } - to { - width: 100vw; - height: 100vw; - } -} - -#title:before { - content: ''; - display: block; - position: absolute; - top: -30px; - left: 0px; - background: var(--primary); - transform: translate(-50%, -50%); - border-radius: 100%; - z-index: -1; - animation: left-bubble 1s normal forwards ease; - width: 100vw; - height: 100vw; -} - -@keyframes right-bubble { - from { - width: 0px; - height: 0px; - } - to { - width: 200vw; - height: 200vw; - } -} - -#title:after { - content: ''; - display: block; - position: absolute; - bottom: 55%; - right: 0px; - width: 200vw; - height: 200vw; - transform: translate(50%, 50%); - background: var(--fg); - border-radius: 100%; - z-index: -2; - animation: right-bubble 1s normal forwards ease; -} -#subtitle { - position: absolute; - bottom: 50px; - left: 50%; - transform: translate(-50%, 0); - white-space: nowrap; - font-family: 'Pacifico'; - color: #69717d; - z-index: 1000; - text-shadow: -1px -1px 0 var(--page-background), - 1px 1px 0 var(--page-background), - 1px -1px 0 var(--page-background), - -1px 1px 0 var(--page-background); -} diff --git a/static/pages/login/index.js b/static/pages/login/index.js deleted file mode 100644 index 0390cc0..0000000 --- a/static/pages/login/index.js +++ /dev/null @@ -1,118 +0,0 @@ -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div, Label, H1: Title, Input, Button, Form } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class LoginView extends sfw.element.Container { - #container - #user - #username - #password - #comment - - constructor() { - super({ css }); - - this.onlogin = () => {}; - this.onpassword = () => {}; - - this.body.append( - this.#container = Div.new({ - id: 'container', - children: [ - Div.new({ id: 'title', innerText: 'Memora' }), - this.#user = Div.new({ - id: 'username-label', - onclick: () => this.#reset(), - }), - Form.new({ - id: 'box', - onsubmit: (e) => e.preventDefault(), - children: [ - this.#username = Input.new({ - id: 'username', - placeholder: 'Username', - autocomplete: 'username', - }), - this.#password = Input.new({ - id: 'password', - placeholder: 'Password', - autocomplete: 'current-password', - type: 'password', - style: { display: 'none' }, - onkeydown: (e) => { - if (e.key === 'Enter') { - return this.#login(); - } - }, - }), - Button.new({ - id: 'submit', - children: [ icons.next ], - onclick: () => this.#next(), - }), - ] - }), - this.#comment = Div.new({ - id: 'comment', - onclick: () => this.#reset(), - }), - Div.new({ - id: 'subtitle', - innerText: 'Where nostalgia is home.', - }), - ] - }) - ); - } - - #next() { - if (this.#username.style.display != 'none') { - this.#go_to_password(); - } else { - this.#login(); - } - } - - #go_to_password() { - if (this.#username.value === '') return; - - this.#user.innerText = this.#username.value; - this.#username.style.display = 'none'; - this.#password.style.display = ''; - this.#password.focus(); - } - - async #login() { - await this.onlogin(this.#username.value, this.#password.value); - this.#reset(); - } - - #reset() { - this.#user.innerText = ''; - this.#username.value = ''; - this.#password.value = ''; - this.#username.style.display = ''; - this.#password.style.display = 'none'; - } - - set comment(value) { - this.#comment.innerText = value; - } - - show() { - this.#container.classList.remove('hidden'); - this.focus(); - } - - hide() { - this.#container.classList.add('hidden'); - } - - focus() { - this.#username.focus(); - } -} diff --git a/static/pages/main/index.css b/static/pages/main/index.css deleted file mode 100644 index 21d5022..0000000 --- a/static/pages/main/index.css +++ /dev/null @@ -1,70 +0,0 @@ - -:host { - display: grid; - height: 100%; - width: 100%; - background: var(--page-background); -} - -#bar { - position: fixed; - bottom: 5px; - left: 5px; - right: 5px; - background: #fff9; - box-shadow: #223223aa 1px 1px 4px; - display: grid; - grid-template-columns: 1fr 1fr 1fr 1fr 1fr ; - height: 50px; - backdrop-filter: blur(10px); - border-radius: var(--border-radius); - transition: bottom 0.2s ease; - max-width: 600px; - margin: 0 auto; -} - -#bar.hidden { - bottom: -200px; -} - -.menu-button { - color: var(--fg-disabled); - width: 18px; - height: 18px; - border-radius: 100%; - margin: auto; - cursor: pointer; - user-select: none; - align-content: center; - text-align: center; -} - -.menu-button.add { - width: 60px; - height: 60px; - margin-top: -20px; - background: var(--primary); - color: var(--card-background); - font-weight: bold; - font-size: 2em; -} - -.menu-button.add .icon { - width: 30px; - height: 30px; - display: grid; - margin: auto; -} - -.menu-button.add .icon .bi-house-fill { - width: 20px; - height: 20px; - margin: auto; -} - -.menu-button .icon { - width: 100%; - height: 100%; - display: grid; - margin: auto; -} diff --git a/static/pages/main/index.js b/static/pages/main/index.js deleted file mode 100644 index b0a13f6..0000000 --- a/static/pages/main/index.js +++ /dev/null @@ -1,98 +0,0 @@ -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div, Input } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class MainView extends sfw.element.Container { - #active_kind - #active_button - #active_view - #bar - - static Kind = Object.freeze({ - 'upload': 0, - 'home': 1, - }); - - constructor() { - super({ css }); - - this.onsearch = () => {} - this.onmonth = () => {} - this.onupload = () => {} - this.onshuffle = () => {} - this.onhome = () => {} - - this.body.append( - this.#active_view = Div.new({ id: 'main' }), - - this.#bar = Div.new({ - id: 'bar', - children: [ - Div.new({ - className: 'menu-button', - children: [ icons.search ], - onclick: (e) => { - e.stopPropagation(); - this.onsearch(); - } - }), - - Div.new({ - className: 'menu-button', - children: [ icons.calendar ], - onclick: () => this.onmonth(), - }), - - this.#active_button = Div.new({ - className: 'menu-button add', - children: [ icons.add ], - onclick: () => this.onupload() - }), - - Div.new({ - className: 'menu-button', - children: [ icons.shuffle ], - onclick: () => this.onshuffle(), - }), - - Div.new({ - className: 'menu-button', - children: [ icons.settings ], - onclick: () => this.onsettings(), - }), - ], - }), - ); - } - - hide() { - this.#bar.classList.add('hidden'); - } - - show() { - this.#bar.classList.remove('hidden'); - } - - set active_view(element) { - this.#active_view.innerHTML = ''; - this.#active_view.append(element); - } - - set active_kind(kind) { - if (kind == MainView.Kind.home) { - this.#active_button.innerHTML = ''; - this.#active_button.append(icons.home); - this.#active_button.onclick = () => this.onhome(); - } else if (kind == MainView.Kind.upload) { - this.#active_button.innerHTML = ''; - this.#active_button.append(icons.add); - this.#active_button.onclick = () => this.onupload(); - } else { - console.error(`invalid kind ${kind}`); - } - } -} diff --git a/static/pages/settings/index.css b/static/pages/settings/index.css deleted file mode 100644 index dcd952f..0000000 --- a/static/pages/settings/index.css +++ /dev/null @@ -1,104 +0,0 @@ - -#container { - width: 100%; - height: 100%; - background: var(--page-background); - padding: 40px; - display: flex; - flex-flow: column; - gap: 20px; - max-width: 700px; - margin: auto; -} - -#profile-image { - width: 200px; - height: 200px; - position: relative; - margin: auto; - margin-top: 50px; - margin-bottom: 30px; -} - -#image-container { - background: #fff; - position: relative; - border-radius: 100%; - width: 100%; - height: 100%; - top: 0px; - left: 0px; - overflow: hidden; -} - -#image-container img { - visibility: hidden; - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - min-width: 100%; - min-height: 100%; - width: 100%; - height: 100%; - object-fit: cover; - user-select: none; -} - -#image-container img[src] { - visibility: visible; -} - -#profile-image #edit-container { - overflow: unset; -} - -#profile-image #edit { - position: absolute; - top: 15px; - right: 15px; - background: var(--card-background); - width: 30px; - height: 30px; - padding: 6px; - border-radius: 100%; - box-shadow: var(--shadow); - cursor: pointer; -} - -#info-box { - width: 100%; - text-align: center; - color: var(--fg-disabled); - font-weight: lighter; - user-select: none; -} - -#info-box #name { - font-family: 'Pacifico'; -} - -#change-password { - background: var(--primary); - padding: 10px; - border-radius: var(--border-radius); - color: var(--fg-primary); - box-shadow: var(--shadow); - font-weight: bold; - text-align: center; - cursor: pointer; - user-select: none; -} - -#logout { - padding: 10px; - width: 100%; - text-align: center; - background: #ee5151; - box-shadow: var(--shadow); - color: #fff; - font-weight: bold; - border-radius: var(--border-radius); - cursor: pointer; - user-select: none; -} diff --git a/static/pages/settings/index.js b/static/pages/settings/index.js deleted file mode 100644 index 5cc40be..0000000 --- a/static/pages/settings/index.js +++ /dev/null @@ -1,112 +0,0 @@ -import icons from 'icons'; -import * as api from 'api'; -import * as sfw from 'sfw'; -const { Div, Img } = sfw.element.native; - -import Editable from '../../widgets/editable/index.js'; -import PasswordDialog from '../../widgets/password-dialog/index.js'; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class SettingsView extends sfw.element.Container { - #profile_image - #name - #birthday - - #profile - #change_password - - constructor() { - super({ css }); - - this.onlogout = () => {}; - - this.body.append( - Div.new({ - id: 'container', - children: [ - Div.new({ - id: 'profile-image', - children: [ - Div.new({ - id: 'image-container', - children: [ - this.#profile_image = Img.new(), - ] - }), - Div.new({ - id: 'edit', - children: [ icons.edit ], - onclick: async () => { - const uploader = await api.images.upload_to_profile(this.#profile.name); - uploader.ondone = async () => { - const blob = await fetch( - `/api/profile/image/load/${this.#profile.name}`, - {cache: 'reload', mode: 'no-cors'} - ).then(r => r.blob()); - - this.#profile_image.src = URL.createObjectURL(blob); - }; - uploader.send() - } - }), - ] - }), - this.#name = Editable.new({ - title: 'Name', - value: '', - onupdate: () => this.#update(), - }), - this.#birthday = Editable.new({ - title: 'Birthday', - type: 'date', - value: '', - onupdate: () => this.#update(), - }), - Div.new({ - id: 'change-password', - innerText: 'Change Password', - onclick: (e) => { - e.stopPropagation(); - this.body.append(PasswordDialog.new()); - } - }), - Div.new({ - id: 'logout', - innerText: 'Logout', - onclick: () => this.onlogout(), - }), - Div.new({ - id: 'info-box', - children: [ - Div.new({ id: 'name', innerText: 'Memora' }), - Div.new({ id: 'version', innerText: '0.0.1-unstable' }), - ] - }), - ] - }) - ) - } - - #update() { - api.profile.set(this.#name.value, this.#birthday.value); - } - - set profile(profile) { - this.#profile = profile; - - if (this.#profile) { - this.#profile_image.src = `/api/profile/image/load/${profile.name}`; - this.#profile_image.onerror = () => this.#profile_image.removeAttribute('src'); - - this.#name.value = profile.full_name; - this.#birthday.value = profile.birthday; - } - } - - get profile() { - return this.#profile; - } -} diff --git a/static/pages/shuffle/index.css b/static/pages/shuffle/index.css deleted file mode 100644 index 30d30ac..0000000 --- a/static/pages/shuffle/index.css +++ /dev/null @@ -1,39 +0,0 @@ -:host { - display: block; - width: 100vw; - height: 100vh; - top: 0px; - left: 0px; - overflow: hidden; - position: relative; -} - -sfw-image { - position: absolute; - left: 50%; - top: 50%; - transform: translate(-50%, calc(-50% - 50px)); - width: 100%; - max-width: calc(100vw - 20px); - max-height: calc(100vh - 200px); - user-select: none; - transition: transform 0.05s ease; -} - -#front { - z-index: 1000; -} - -#back { - z-index: 500; - filter: blur(50px); -} - -#date { - margin: 10px; - border-radius: var(--border-radius); - padding: 10px; - background: #efefef99; - backdrop-filter: blur(10px); - box-shadow: #223223aa 1px 1px 4px; -} diff --git a/static/pages/shuffle/index.js b/static/pages/shuffle/index.js deleted file mode 100644 index 620195c..0000000 --- a/static/pages/shuffle/index.js +++ /dev/null @@ -1,110 +0,0 @@ -import * as sfw from 'sfw'; -const { Div, Canvas } = sfw.element.native; - -import { Image } from 'widgets'; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class ShuffleView extends sfw.element.Container { - #front_image - #back_image - #front_image_index - #back_image_index - #images - #date - #drag_start_position - #drag_strength - - constructor() { - super({ css }); - - this.#front_image_index = null; - this.#back_image_index = null; - - this.body.append( - this.#date = Div.new({ id: 'date' }), - this.#front_image = Image.new({ - id: 'front', - disabled: true, - ontouchstart: (e) => { - if (e.touches.length != 1) return; - - this.#drag_start_position = [e.touches[0].pageX, e.touches[0].pageY]; - }, - ontouchmove: (e) => { - if (e.touches.length != 1) return; - - const position = [e.touches[0].pageX, e.touches[0].pageY]; - - const delta = [ - position[0] - this.#drag_start_position[0], - position[1] - this.#drag_start_position[1] - ]; - - const strength = Math.min(1, Math.max((delta[0]**2 + delta[1]**2) / (40 ** 2), 0) / 100); - this.#drag_strength = strength; - - const angle_x = position[0] - window.screen.width / 2; - const angle_y = position[1] - window.screen.height * 1.2; - let angle = (Math.atan((angle_y) / (angle_x)) * 180 / Math.PI + 90); - - if (angle_x < 0) { - angle -= 180; - } - - this.#front_image.style.transform = ` - translate(-50%, calc(-50% - 50px)) - translate(${delta[0]}px, ${delta[1]}px) - rotate(${angle}deg) - `; - this.#back_image.style.filter = `blur(${(1 - strength) * 50}px)`; - }, - ontouchend: (e) => { - if (this.#drag_strength > 0.3) { - this.next(); - } - - this.#front_image.style.transform = ''; - this.#back_image.style.filter = ''; - }, - }), - this.#back_image = Image.new({ id: 'back', disabled: true }), - ) - - this.onclick = () => this.next(); - } - - set images(images) { - this.#images = images; - } - - open() { - this.next(); - this.next(); - } - - next() { - this.#front_image_index = this.#back_image_index; - this.#back_image_index = Math.floor(Math.random() * this.#images.length); - - if (this.#front_image_index !== null) { - this.#front_image.metadata = this.#images[this.#front_image_index]; - this.#front_image.load(); - - const date = this.#images[this.#front_image_index].date - - this.#date.innerText = date.toLocaleString('default', { - month: 'long', - year: 'numeric', - day: 'numeric', - hour: 'numeric', - minute: 'numeric' - }); ; - } - - this.#back_image.metadata = this.#images[this.#back_image_index]; - this.#back_image.load(); - } -} diff --git a/static/service-worker/index.js b/static/service-worker/index.js deleted file mode 100644 index cff4b95..0000000 --- a/static/service-worker/index.js +++ /dev/null @@ -1,21 +0,0 @@ -export const register = async () => { - if (!'serviceWorker' in navigator) { - console.warn('service worker not supported by browser'); - return; - } - - try { - const registration = await navigator.serviceWorker.register("/service-worker/worker.js", { - scope: "/", - }); - if (registration.installing) { - console.log("Service worker installing"); - } else if (registration.waiting) { - console.log("Service worker installed"); - } else if (registration.active) { - console.log("Service worker active"); - } - } catch (error) { - console.error(`Registration failed with ${error}`); - } -} diff --git a/static/service-worker/worker.js b/static/service-worker/worker.js deleted file mode 100644 index 666c7d3..0000000 --- a/static/service-worker/worker.js +++ /dev/null @@ -1,41 +0,0 @@ -const cachable_api = [ - '/api/image/load/', -]; - -const is_cachable = (url) => { - for (const api of cachable_api) { - console.log(api, url); - if (url.includes(api)) { - return true; - } - } - - return false; -} - -const put_in_cache = async (request, response) => { - const cache = await caches.open("v1"); - await cache.put(request, response); -}; - -const cache_first = async (request, event) => { - if (request.method !== 'GET') { - return await fetch(request); - } - - if (!is_cachable(request.url)) { - return await fetch(request); - } - - const cache_response = await caches.match(request); - if (cache_response) { - return cache_response; - } - const network_response = await fetch(request); - event.waitUntil(put_in_cache(request, network_response.clone())); - return network_response; -}; - -self.addEventListener("fetch", (event) => { - event.respondWith(cache_first(event.request, event)); -}); diff --git a/static/sfw b/static/sfw deleted file mode 160000 -Subproject 9d74e1679915cc0c5f56413879276fc43b09389 diff --git a/static/tsconfig.json b/static/tsconfig.json deleted file mode 100644 index 97d1355..0000000 --- a/static/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "paths": { - "sfw": ["./sfw"], - "api": ["./api"], - "icons": ["./icons"], - "widgets": ["./widgets"] - }, - } -} diff --git a/static/widgets/editable/index.css b/static/widgets/editable/index.css deleted file mode 100644 index b474370..0000000 --- a/static/widgets/editable/index.css +++ /dev/null @@ -1,36 +0,0 @@ - -#container { - width: 100%; - background: var(--card-background); - box-shadow: var(--shadow); - border-radius: var(--border-radius); - display: grid; - grid-template-columns: min-content auto min-content; -} - -#container label { - user-select: none; - font-weight: bold; - background: var(--primary); - color: var(--fg-primary); - align-content: center; - padding: 10px; - border-top-left-radius: var(--border-radius); - border-bottom-left-radius: var(--border-radius); -} - -#container input { - background: var(--card-background); - user-select: none; - font-size: 1em; -} - -#container input:read-only { - caret-color: transparent; -} - -#edit { - width: 35px; - padding: 10px; - cursor: pointer; -} diff --git a/static/widgets/editable/index.js b/static/widgets/editable/index.js deleted file mode 100644 index b7e24de..0000000 --- a/static/widgets/editable/index.js +++ /dev/null @@ -1,77 +0,0 @@ -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div, Label, Input } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class Editable extends sfw.element.Container { - #label - #input - #edit - - constructor() { - super({ css }); - - this.onupdate = () => {}; - - this.body.append( - Div.new({ - id: 'container', - children: [ - this.#label = Label.new({ htmlFor: 'input' }), - this.#input = Input.new({ - readOnly: true, - onkeydown: (e) => { - if (e.key === 'Enter') { - this.#input.readOnly = true; - this.#update() - this.onupdate(); - } - }, - }), - this.#edit = Div.new({ - id: 'edit', - children: [ icons.edit ], - onclick: () => { - this.#input.readOnly = !this.#input.readOnly; - this.#update(); - - if (this.#input.readOnly) { - this.onupdate(); - } - } - }), - ], - }) - ); - } - - #update() { - this.#edit.innerHTML = ''; - this.#edit.append( - this.#input.readOnly ? icons.edit : icons.check - ); - - if (!this.#input.readOnly) { - this.#input.select(); - } - } - - set title(value) { - this.#label.innerText = value; - } - - set value(value) { - this.#input.value = value; - } - - get value() { - return this.#input.value; - } - - set type(type) { - this.#input.type = type; - } -} diff --git a/static/widgets/image/index.css b/static/widgets/image/index.css deleted file mode 100644 index a4105e9..0000000 --- a/static/widgets/image/index.css +++ /dev/null @@ -1,134 +0,0 @@ -#container { - position: relative; - height: 100%; - min-height: 100px; - border-radius: var(--border-radius); - overflow: hidden; - box-shadow: #223223aa 1px 1px 4px; - background: var(--card-background); - margin: auto; -} - -#container img { - border-radius: var(--border-radius); - max-width: 700px; - width: calc(100vw - 20px); - visibility: hidden; - margin-bottom: -5px; - height: calc((100vw - 20px) * 0.8); -} - -#container.loaded img { - visibility: visible; - width: 100%; - height: unset; -} - -@keyframes loader { - 0% { - width: 60px; - height: 60px; - } - - 25% { - border: 5px solid var(--page-background); - } - - 50% { - width: 80px; - height: 80px; - } - - 75% { - border: 10px solid var(--page-background); - } - - 100% { - width: 60px; - height: 60px; - } -} - -#loading { - position: absolute; - border: 10px solid var(--page-background); - border-radius: 100%; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - animation: 0.5s infinite loader ease; -} - -.loaded #loading { - display: none; -} - -#menu { - position: absolute; - top: 0px; - left: 0px; - height: 100%; - width: 0px; - background: #efefef99; - backdrop-filter: blur(5px); - border-radius: var(--border-radius); - transition: width 0.2s ease, padding 0.2s ease; - overflow: hidden; - align-content: center; - overflow: hidden; - padding: 0px; - display: grid; - grid-template-columns: 1fr; - gap: 10px; -} - -#menu.open { - width: 100%; - padding: 10px; -} - -#delete { - background: #ee5151; - padding: 10px; - color: #fff; - font-weight: bold; - border-radius: var(--border-radius); - cursor: pointer; - user-select: none; -} - -#download { - background: var(--primary); - padding: 10px; - border-radius: var(--border-radius); - color: #fff; - font-weight: bold; - user-select: none; - cursor: pointer; -} - -#label { - display: grid; - grid-template-columns: 55px auto; -} - -#label #title { - padding: 10px; - background: var(--primary); - border-top-left-radius: var(--border-radius); - border-bottom-left-radius: var(--border-radius); - color: #fff; - font-weight: bold; - user-select: none; -} - -.element { - background: #efefef99; - padding: 10px; - font-weight: bold; - overflow-x: auto; - user-select: none; - white-space: nowrap; - border-top-right-radius: var(--border-radius); - border-bottom-right-radius: var(--border-radius); -} diff --git a/static/widgets/image/index.js b/static/widgets/image/index.js deleted file mode 100644 index b063864..0000000 --- a/static/widgets/image/index.js +++ /dev/null @@ -1,108 +0,0 @@ -import * as api from 'api'; -import * as sfw from 'sfw'; -import Month from '../../month.js'; -const { Div, Img, A: Link } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class Image extends sfw.element.Container { - #container - #image - #menu - #id - #month - #date - #id_element - #disabled - - constructor() { - super ({ css }) - - this.#disabled = false; - - this.body.append( - this.#container = Div.new({ - id: 'container', - children: [ - this.#image = Img.new({ - onload: () => this.#container.classList.add('loaded'), - }), - Div.new({ id: 'loading' }), - this.#menu = Div.new({ - id: 'menu', - children: [ - Div.new({ - id: 'label', - children: [ - Div.new({ id: 'title', innerText: 'Id' }), - this.#id_element = Div.new({ className: 'element id' }), - ], - }), - Div.new({ - id: 'label', - children: [ - Div.new({ id: 'title', innerText: 'Date' }), - this.#date = Div.new({ className: 'element' }), - ], - }), - Div.new({ - id: 'download', - innerText: 'Download', - onclick: () => { - const a = Link.new({ - href: `/api/image/load/${this.#id}`, - download: `${this.#id}.jpeg` - }) - a.click() - } - }), - Div.new({ - id: 'delete', - innerText: 'Delete', - onclick: () => { - api.images.remove(this.#id); - this.parentNode.removeChild(this); - } - }), - ], - ondblclick: (e) => { - if (e.target != this.#menu) { - e.stopPropagation(); - } - } - }) - ], - ondblclick: (e) => { - if (!this.#disabled) { - this.#menu.classList.toggle('open'); - e.preventDefault(); - } - } - }) - ); - } - - set metadata(image) { - const date = new Date(image.timestamp * 1000); - this.#id = image.id; - this.#month = Month.from_unix(image.timestamp); - this.#container.classList.remove('loaded'); - this.#date.innerText = date.toLocaleString(); - this.#id_element.innerText = image.id; - } - - load() { - this.#image.src = `/api/image/load/${this.#id}`; - } - - get month() { - return this.#month; - } - - set disabled(value) { - this.#disabled = value; - this.#image.setAttribute('draggable', !value); - } -} diff --git a/static/widgets/index.js b/static/widgets/index.js deleted file mode 100644 index 6220318..0000000 --- a/static/widgets/index.js +++ /dev/null @@ -1,6 +0,0 @@ -export { default as Editable } from './editable/index.js'; -export { default as Image } from './image/index.js'; -export { default as MonthSelect } from './month-select/index.js'; -export { default as PasswordDialog } from './password-dialog/index.js'; -export { default as Search } from './search/index.js'; -export { default as UploadBar } from './upload-bar/index.js'; diff --git a/static/widgets/month-select/index.css b/static/widgets/month-select/index.css deleted file mode 100644 index 25ed5d2..0000000 --- a/static/widgets/month-select/index.css +++ /dev/null @@ -1,134 +0,0 @@ -:host { - position: fixed; - top: 0; - left: 0; -} - -#container { - z-index: 1000; - position: fixed; - bottom: -100%; - left: 5px; - right: 5px; - background: #fff9; - backdrop-filter: blur(10px); - border-radius: var(--border-radius); - transition: bottom 0.2s ease; - height: calc(100% - 10px); - box-shadow: var(--shadow); - padding: 10px; -} - -#container.visible { - bottom: 5px; -} - -#close-button { - position: absolute; - top: 10px; - right: 10px; - width: 25px; - height: 25px; - border-radius: 100%; - background: var(--page-background); - cursor: pointer; -} - -#title { - font-size: 1.2em; - user-select: none; - margin-bottom: 10px; -} - -#month-container { - height: calc(100% - 30px); - overflow-y: auto; - overscroll-behavior: contain; -} - -.month-item { - padding: 10px; - padding-left: 20px; - margin: 5px; - border-radius: var(--border-radius); - user-select: none; - cursor: pointer; - position: relative; -} - -.month-item.none { - font-style: italic; -} - -.month-item:before { - content: ''; - display: block; - position: absolute; - background: var(--primary); - top: 0px; - left: 0px; - width: 4px; - height: 47px; -} - -.month-item:after { - content: ''; - display: block; - position: absolute; - background: var(--primary); - top: 50%; - transform: translate(0, -50%); - left: 0px; - width: 12px; - height: 4px; -} - -.month-item:first-child:before { - top: 50%; - height: 27px; -} - -.month-item.none:before { - top: 0; - height: 20px; -} - -.month-item:hover { - background: var(--primary); - color: var(--fg-primary); -} - -.year-item { - padding: 10px 20px; - font-size: 1.1em; - margin: 5px; - position: relative; - font-weight: bold; - background: #fffa; - border-radius: var(--border-radius); - box-shadow: #22322355 1px 1px 2px; -} - -.year-item:before { - content: ''; - display: block; - position: absolute; - background: var(--primary); - top: 0px; - left: 0px; - width: 4px; - height: 50px; -} - -.year-item:after { - content: ''; - display: block; - position: absolute; - background: var(--primary); - top: 50%; - transform: translate(0, -50%); - left: -4px; - width: 12px; - height: 12px; - border-radius: 100%; -} diff --git a/static/widgets/month-select/index.js b/static/widgets/month-select/index.js deleted file mode 100644 index 7e4d583..0000000 --- a/static/widgets/month-select/index.js +++ /dev/null @@ -1,87 +0,0 @@ -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class MonthSelect extends sfw.element.Container { - #container - #month_container - - constructor() { - super({ css }); - - this.onscroll = (e) => e.stopPropagate(); - this.onmonth = () => {}; - - this.body.append( - this.#container = Div.new({ - id: 'container', - children: [ - Div.new({ id: 'title', innerText: 'Select Month' }), - Div.new({ - id: 'close-button', - children: [ icons.close ], - onclick: () => this.hide(), - }), - this.#month_container = Div.new({ - id: 'month-container', - }), - ], - }), - ); - } - - show() { - this.#container.classList.add('visible'); - } - - hide() { - this.#container.classList.remove('visible'); - } - - set months(months) { - months.sort((a, b) => a.is_before(b)); - - this.#month_container.innerHTML = ''; - - let last = null; - - for (const month of months) { - if (last != null && !last.is_same_year(month)) { - this.#month_container.append( - Div.new({ - className: 'year-item', - innerText: last.year, - }) - ); - } - - this.#month_container.append( - Div.new({ - className: 'month-item', - innerText: month.name, - onclick: () => { - this.hide(); - this.onmonth(month); - } - }) - ); - - last = month; - } - - this.#month_container.append( - Div.new({ - className: 'month-item none', - innerText: 'No Date', - onclick: () => { - this.hide(); - this.onmonth(null); - } - }) - ); - } -} diff --git a/static/widgets/password-dialog/index.css b/static/widgets/password-dialog/index.css deleted file mode 100644 index ad8c1c2..0000000 --- a/static/widgets/password-dialog/index.css +++ /dev/null @@ -1,51 +0,0 @@ -#container { - position: absolute; - max-width: 500px; - width: 70%; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - display: grid; - gap: 10px; - background: #efefef99; - backdrop-filter: blur(10px); - padding: 10px; - border-radius: var(--border-radius); - box-shadow: var(--shadow); -} - -#title { - font-size: 1.1em; -} - -#close { - width: 25px; - height: 25px; - position: absolute; - top: 5px; - right: 5px; - cursor: pointer; - background: var(--page-background); - border-radius: 100%; - padding: 2px; -} - -#button { - background: var(--primary); - padding: 10px; - color: var(--fg-primary); - font-weight: bold; - border-radius: var(--border-radius); - box-shadow: var(--box-shadow); - text-align: center; -} - -#error { - font-style: italic; - font-weight: bold; - color: #ee5151; -} - -#error.hidden { - display: none; -} diff --git a/static/widgets/password-dialog/index.js b/static/widgets/password-dialog/index.js deleted file mode 100644 index 76fbec6..0000000 --- a/static/widgets/password-dialog/index.js +++ /dev/null @@ -1,60 +0,0 @@ -import * as api from 'api'; -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div, Input } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class PasswordDialog extends sfw.element.Container { - #current - #new - #confirm - #error - - constructor() { - super({ css }); - - this.callclose = () => this.close(); - - document.body.addEventListener('click', this.callclose); - this.onclick = (e) => e.stopPropagation(); - - this.body.append(Div.new({ - id: 'container', - children: [ - Div.new({ id: 'title', innerText: 'Change Password' }), - Div.new({ id: 'close', children: [ icons.close ], onclick: () => this.close() }), - this.#current = Input.new({ placeholder: 'Current Password', type: 'password' }), - this.#new = Input.new({ placeholder: 'New Password', type: 'password' }), - this.#confirm = Input.new({ placeholder: 'Confirm Password', type: 'password' }), - this.#error = Div.new({ id: 'error', className: 'hidden' }), - Div.new({ - id: 'button', - innerText: 'Update', - onclick: async () => { - if (this.#new.value !== this.#confirm.value) { - this.#error.innerText = 'Passwords do not match'; - this.#error.className = ''; - return; - } - - if (!await api.profile.update_password(this.#current.value, this.#new.value)) { - this.#error.innerText = 'invalid password'; - this.#error.className = ''; - return; - } - - this.close(); - }, - }), - ], - })); - } - - close() { - this.parentNode.removeChild(this); - document.body.removeEventListener('click', this.callclose); - } -} diff --git a/static/widgets/search/index.css b/static/widgets/search/index.css deleted file mode 100644 index 14e650d..0000000 --- a/static/widgets/search/index.css +++ /dev/null @@ -1,50 +0,0 @@ -:host { - position: fixed; - top: 0; - left: 0; -} - -#container { - position: fixed; - top: -200px; - left: 5px; - right: 5px; - height: 100px; - background: #fff9; - backdrop-filter: blur(10px); - border-radius: var(--border-radius); - transition: top 0.2s ease; - padding: 10px; - display: grid; - gap: 10px; - box-shadow: var(--shadow); -} - -#container.visible { - top: 5px; -} - -#title { - font-size: 1.2em; - align-content: center; - padding-left: 5px; - user-select: none; -} - -#search-box { - width: 100%; - display: grid; - grid-template-columns: auto 50px; -} - -input { - border-top-right-radius: 0px !important; - border-bottom-right-radius: 0px !important; -} - -button { - width: 50px; - border-top-left-radius: 0px !important; - border-bottom-left-radius: 0px !important; - height: 42px; -} diff --git a/static/widgets/search/index.js b/static/widgets/search/index.js deleted file mode 100644 index b014cdd..0000000 --- a/static/widgets/search/index.js +++ /dev/null @@ -1,68 +0,0 @@ -import icons from 'icons'; -import * as sfw from 'sfw'; -const { Div, Input, Button } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class Search extends sfw.element.Container { - #container - #search - - constructor() { - super({ css }); - - this.onsubmit = () => {} - this.onhide = () => {} - - this.onclick = (e) => e.stopPropagation(); - this.hide = () => { - this.#container.classList.remove('visible'); - document.removeEventListener('click', this.hide); - this.onhide(); - }; - - this.body.append( - this.#container = Div.new({ - id: 'container', - children: [ - Div.new({ innerText: 'Search', id: 'title' }), - Div.new({ - id: 'search-box', - children: [ - this.#search = Input.new({ - type: 'search', - onsearch: () => this.submit(), - onkeydown: (event) => { - if (event.key === 'Enter') { - this.submit(); - } - } - }), - Button.new({ - children: [ icons.search ], - onclick: () => this.submit(), - }), - ] - }) - ] - }) - ); - } - - submit() { - this.onsubmit(this.#search.value); - this.#search.blur(); - this.hide(); - } - - toggle() { - this.#container.classList.toggle('visible'); - - if (this.#container.classList.contains('visible')) { - this.#search.focus() - document.addEventListener('click', this.hide) - } - } -} diff --git a/static/widgets/upload-bar/index.css b/static/widgets/upload-bar/index.css deleted file mode 100644 index 8ec1697..0000000 --- a/static/widgets/upload-bar/index.css +++ /dev/null @@ -1,41 +0,0 @@ - -#container { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: calc(100% - 10px); - height: 100px; - background: #efefef99; - backdrop-filter: blur(10px); - border-radius: var(--border-radius); - max-width: 500px; - padding: 10px 20px; - display: grid; -} - -#files { - background: #efefef; - padding: 10px; - border-radius: 20px; - margin: auto; - width: min-content; - white-space: nowrap; -} - -#inner-progress { - width: 100%; - height: 5px; - border-radius: 5px; - background: #efefef; - overflow: hidden; - margin: auto; -} - - -#progress { - background: var(--primary); - height: 100%; - border-radius: 5px; - transition: width 0.2s ease; -} diff --git a/static/widgets/upload-bar/index.js b/static/widgets/upload-bar/index.js deleted file mode 100644 index f6d37b5..0000000 --- a/static/widgets/upload-bar/index.js +++ /dev/null @@ -1,44 +0,0 @@ -import * as sfw from 'sfw'; -const { Div } = sfw.element.native; - -import stylesheet from './index.css'; - -const css = await sfw.css.sheet(stylesheet); - -export default class UploadBar extends sfw.element.Container { - #files_progress - #inner_progress - #container - - constructor() { - super({ css }); - - this.body.append( - this.#container = Div.new({ - id: 'container', - style: { display: 'none' }, - children: [ - this.#files_progress = Div.new({ id: 'files', innerText: 'Uploading...' }), - Div.new({ - id: 'inner-progress', - children: [ - this.#inner_progress = Div.new({ id: 'progress' }), - ] - }) - ] - }) - ); - } - - set progress(progress) { - this.#inner_progress.style.width = `${progress * 100}%` - } - - hide() { - this.#container.style.display = 'none'; - } - - show() { - this.#container.style.display = ''; - } -} |