From e3a41da5a0a3d70ac53591f2b66144f2be2b3871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yaroslav=20de=20la=20Pe=C3=B1a=20Smirnov?= Date: Sun, 7 Nov 2021 02:02:45 +0300 Subject: Initial commit. Almost functional but still missing features and lacking testing. --- .exrc | 1 + .gitignore | 3 + .gitmodules | 6 + COPYING | 7 + LICENSE | 458 ++++++++++++++++++++++++++++++++++++++++++++++++++ Makefile | 47 ++++++ README.md | 33 ++++ compile_commands.json | 314 ++++++++++++++++++++++++++++++++++ include/bstree.h | 68 ++++++++ include/components.h | 82 +++++++++ include/config.h | 43 +++++ include/fs.h | 43 +++++ include/log.h | 58 +++++++ include/render.h | 38 +++++ include/site.h | 46 +++++ include/tests/tests.h | 45 +++++ parcini | 1 + src/bstree.c | 183 ++++++++++++++++++++ src/components.c | 239 ++++++++++++++++++++++++++ src/config.c | 264 +++++++++++++++++++++++++++++ src/fs.c | 144 ++++++++++++++++ src/log.c | 25 +++ src/render.c | 234 ++++++++++++++++++++++++++ src/revela.c | 74 ++++++++ src/site.c | 269 +++++++++++++++++++++++++++++ src/tests/config.c | 54 ++++++ src/tests/fs.c | 74 ++++++++ template-vars.md | 37 ++++ tests/album.ini | 2 + tests/empty | 0 tests/site.ini | 17 ++ unja | 1 + 32 files changed, 2910 insertions(+) create mode 100644 .exrc create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 COPYING create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 compile_commands.json create mode 100644 include/bstree.h create mode 100644 include/components.h create mode 100644 include/config.h create mode 100644 include/fs.h create mode 100644 include/log.h create mode 100644 include/render.h create mode 100644 include/site.h create mode 100644 include/tests/tests.h create mode 160000 parcini create mode 100644 src/bstree.c create mode 100644 src/components.c create mode 100644 src/config.c create mode 100644 src/fs.c create mode 100644 src/log.c create mode 100644 src/render.c create mode 100644 src/revela.c create mode 100644 src/site.c create mode 100644 src/tests/config.c create mode 100644 src/tests/fs.c create mode 100644 template-vars.md create mode 100644 tests/album.ini create mode 100644 tests/empty create mode 100644 tests/site.ini create mode 160000 unja diff --git a/.exrc b/.exrc new file mode 100644 index 0000000..236a385 --- /dev/null +++ b/.exrc @@ -0,0 +1 @@ +let ch_syntax_for_h = 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b0b5a06 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.cache +obj/ +build/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..79b35f2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "unja"] + path = unja + url = https://github.com/dannyvankooten/unja.git +[submodule "parcini"] + path = parcini + url = https://git.yaroslavps.com/parcini diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..85810d6 --- /dev/null +++ b/COPYING @@ -0,0 +1,7 @@ +Copyright (c) 2021 Yaroslav de la Peña Smirnov + +This is free software, which you can redistribute and/or modify under the terms +of the GNU Lesser General Public License, version 2.1 only, unless otherwise +noted inside of individual source files. It is provided AS IS and WITHOUT ANY +WARRANTY whatsoever. For more information read the LICENSE file and/or the +individual source file. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..23632ca --- /dev/null +++ b/LICENSE @@ -0,0 +1,458 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ed44d6e --- /dev/null +++ b/Makefile @@ -0,0 +1,47 @@ +CC?=gcc +XFLAGS=-D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L +CFLAGS?=-std=c99 -O2 -Wall $(XFLAGS) + +LIBS:=-lexif +LIBS+=$(shell pkg-config --cflags --libs GraphicsMagickWand) +IDIRS:=$(addprefix -iquote,include unja/src unja parcini/include) + +BUILDIR?=build/release + +ifdef DEBUG +BUILDIR:=build/debug +CFLAGS:=-std=c99 -O0 -g -DDEBUG $(XFLAGS) +endif + +OBJDIR=$(BUILDIR)/obj + +UNJA_SRCS+=$(shell find unja -name '*.c' -not -path '*/tests/*') +UNJA_OBJS:=$(UNJA_SRCS:%.c=$(OBJDIR)/%.o) +PARCINI_SRCS:=$(wildcard parcini/src/*.c) +PARCINI_OBJS:=$(PARCINI_SRCS:%.c=$(OBJDIR)/%.o) +REVELA_SRCS:=$(shell find src -name '*.c' -not -path '*/tests/*') +REVELA_OBJS:=$(REVELA_SRCS:%.c=$(OBJDIR)/%.o) +ALL_OBJS:=$(UNJA_OBJS) $(PARCINI_OBJS) $(REVELA_OBJS) +TEST_OBJS:=$(filter-out $(OBJDIR)/src/revela.o,$(ALL_OBJS)) + +all: revela + +test: tests/config tests/fs + +tests/%: $(OBJDIR)/src/tests/%.o $(TEST_OBJS) + mkdir -p $(BUILDIR)/$(@D) + $(CC) -o $(BUILDIR)/$@ $^ $(LDFLAGS) $(IDIRS) $(LIBS) + +$(OBJDIR)/%.o: %.c + mkdir -p $(@D) + $(CC) -c $(CFLAGS) $(IDIRS) -o $@ $< $(LIBS) + +revela: $(ALL_OBJS) + $(CC) $(LDFLAGS) -o $(BUILDIR)/$@ $^ $(LIBS) $(CFLAGS) + +clean: + rm -r build + +.PHONY: clean all test + +.PRECIOUS: $(OBJDIR)/src/tests/%.o diff --git a/README.md b/README.md new file mode 100644 index 0000000..c5cb8d1 --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# revela + +A static web image gallery generator. It optimizes images for the web and +generates HTML files to create a photo/image gallery web site ready to be served +by an HTML server. + +VERY EARLY STAGES! It's semifunctional but not very useful yet. + +## Building + +``` +git submodule update --init +make +``` + +or for debugging: + +``` +DEBUG=1 make +``` + +## TODO: + +* Copy CSS and static files +* Fix template generation on outdated html files. Right now if, for example, a + new image was added, the templates for the next and prev images, and the album + are not updated accordingly. +* Add exif tags to template hashmap. +* Clean out-of-date dirs and files (i.e. removed albums/images from the source + dir). +* Improve unja or find better alternative. +* Better test coverage? (if I am not too lazy) +* Document. diff --git a/compile_commands.json b/compile_commands.json new file mode 100644 index 0000000..d39baf1 --- /dev/null +++ b/compile_commands.json @@ -0,0 +1,314 @@ +[ + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/config.o", + "src/config.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/config.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/revela.o", + "src/revela.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/revela.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/unja/src/hashmap.o", + "unja/src/hashmap.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "unja/src/hashmap.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/unja/src/template.o", + "unja/src/template.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "unja/src/template.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/unja/src/vector.o", + "unja/src/vector.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "unja/src/vector.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/unja/vendor/mpc.o", + "unja/vendor/mpc.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "unja/vendor/mpc.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/parcini/src/parcini.o", + "parcini/src/parcini.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "parcini/src/parcini.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/fs.o", + "src/fs.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/fs.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/log.o", + "src/log.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/log.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/llist.o", + "src/llist.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/llist.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/bstree.o", + "src/bstree.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/bstree.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/site.o", + "src/site.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/site.c" + }, + { + "directory": "/home/yaroslav/repos/personal/revela", + "arguments": [ + "cc", + "-c", + "-std=c99", + "-O2", + "-Wall", + "-D_XOPEN_SOURCE=500", + "-D_POSIX_C_SOURCE=200809L", + "-iquoteinclude", + "-iquoteunja/src", + "-iquoteunja", + "-iquoteparcini/include", + "-o", + "build/release/obj/src/components.o", + "src/components.c", + "-lexif", + "-I/usr/include/GraphicsMagick", + "-lGraphicsMagickWand", + "-lGraphicsMagick" + ], + "file": "src/components.c" + } +] diff --git a/include/bstree.h b/include/bstree.h new file mode 100644 index 0000000..9577b73 --- /dev/null +++ b/include/bstree.h @@ -0,0 +1,68 @@ +/* + * Copyright 2021 Yaroslav de la Peña Smirnov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef BSTREE_H +#define BSTREE_H + +#include + +/* < 0 means a less than b; 0 means equal; > 0 means a more than b. */ +typedef int (*bst_cmp_fn)(const void *a, const void *b); +typedef void (*bst_free_fn)(void *data); + +struct bstree { + struct bstnode *root; + bst_cmp_fn cmp; + /* It can be NULL, in which case you will have to free the values manually */ + bst_free_fn free; +}; + +struct bstnode { + void *value; + struct bstnode *parent; + struct bstnode *left; + struct bstnode *right; +}; + +typedef bool (*bst_walk_cb)(struct bstnode *, void *data); + +struct bstree *bstree_new(bst_cmp_fn, bst_free_fn); + +struct bstnode *bstree_add(struct bstree *, void *val); + +/* Returns NULL if a node with the value wasn't found */ +struct bstnode *bstree_search(struct bstree *, void *val); + +struct bstnode *bstree_min(struct bstnode *); + +struct bstnode *bstree_max(struct bstnode *); + +struct bstnode *bstree_predecessor(struct bstnode *); + +struct bstnode *bstree_successor(struct bstnode *); + +bool bstree_inorder_walk(struct bstnode *, bst_walk_cb, void *data); + +void bstree_remove(struct bstree *, struct bstnode *); + +void bstree_destroy(struct bstree *); + +#endif diff --git a/include/components.h b/include/components.h new file mode 100644 index 0000000..ba5c866 --- /dev/null +++ b/include/components.h @@ -0,0 +1,82 @@ +#ifndef REVELA_COMPONENTS_H +#define REVELA_COMPONENTS_H + +#include +#include +#include + +#include "config.h" +#include "hashmap.h" + +#define PHOTO_THUMB_SUFFIX "_thumb" + +struct image { + /* The path to the source image file */ + char *source; + /* Points to the basename in source */ + const char *basename; + /* Points to the extension in source */ + const char *ext; + /* The "url" to the dir where index.html for this image will be located */ + char *url; + /* The "url" to the image file */ + char *url_image; + /* The "url" to the thumbnail image file */ + char *url_thumb; + /* Pointers to the relative urls in their respective urls */ + const char *dst; + const char *dst_image; + const char *dst_thumb; + /* The "raw" exif data extracted from the original file */ + ExifData *exif_data; + /* Last modified time of source file */ + struct timespec modtime; + /* The datetime this image was taken in human friendly form */ + char datestr[24]; + /* Same as date but in seconds for easier comparison. See image_set_date() */ + time_t tstamp; + struct album *album; + /* Hashmap with values to be passed to the image template */ + struct hashmap *map; + /* Hashmap with values to be passed to thumbs and previews vectors */ + struct hashmap *thumb; +}; + +struct album { + struct album_config *config; + /* The path to the source directory */ + char *source; + /* The full url that will be used in the template */ + char *url; + /* Pointer to the slug part in url that will be used for the new dir */ + const char *slug; + /* Pointer to the human readable date of the earliest image */ + const char *datestr; + /* The year of this album in human readable form; used to categorize */ + char year[8]; + /* The date of the album is the date of the earliest image */ + time_t tstamp; + struct bstree *images; + /* Hashmap with values to be passed to the template */ + struct hashmap *map; + /* Vector with hashmaps of images to be passed to the templates */ + struct vector *thumbs; + struct vector *previews; +}; + +struct image *image_new(char *src, const struct stat *, struct album *); + +int image_cmp(const void *a, const void *b); + +void image_destroy(void *data); + +struct album *album_new(struct album_config *, struct site_config *, + const char *src, const char *rsrc, const struct stat *); + +int album_cmp(const void *a, const void *b); + +void album_add_image(struct album *, struct image *); + +void album_destroy(void *data); + +#endif diff --git a/include/config.h b/include/config.h new file mode 100644 index 0000000..398160b --- /dev/null +++ b/include/config.h @@ -0,0 +1,43 @@ +#ifndef REVELA_CONFIG_H +#define REVELA_CONFIG_H +#include +#include +#include + +#define SITE_CONF "site.ini" +#define ALBUM_CONF "album.ini" + +struct image_config { + bool strip; + uint8_t quality; + size_t max_width; + size_t max_height; + bool smart_resize; +}; + +struct site_config { + char *title; + char *base_url; + uint32_t max_previews; + struct image_config images; + struct image_config thumbnails; +}; + +struct album_config { + char *title; + char *desc; +}; + +bool site_config_read_ini(const char *wdir, struct site_config *); + +bool album_config_read_ini(const char *adir, struct album_config *); + +struct site_config *site_config_init(void); + +struct album_config *album_config_init(void); + +void site_config_destroy(struct site_config *config); + +void album_config_destroy(struct album_config *config); + +#endif diff --git a/include/fs.h b/include/fs.h new file mode 100644 index 0000000..015214a --- /dev/null +++ b/include/fs.h @@ -0,0 +1,43 @@ +#ifndef REVELA_FS_H +#define REVELA_FS_H + +#include +#include +#include + +/* + * Returns a pointer to where the basename of the file is inside path. + */ +const char *rbasename(const char *path); + +/* + * Makes a new directory if it doesn't exist. If there were errors returns + * false, otherwise returns true. + */ +bool nmkdir(const char *path, struct stat *dstat, bool dry); + +#define joinpathb(buf, a, b) sprintf(buf, "%s/%s", a, b) + +/* + * Joins two paths into one, e.g. /hello, word -> /hello/world + * This function allocates a new string and returns it. + */ +char *joinpath(const char *restrict a, const char *restrict b); + +bool isimage(const char *fname); + +/* + * Removes extension from file name "e.g. pepe.gif -> pepe. Returns a pointer to + * location of the extension in the string. + */ +const char *delext(const char *restrict basename, char *restrict dest, size_t n); + +/* + * -1 if error; 0 if the timestamps are different; 1 if they are equal. + */ +int file_is_uptodate(const char *path, const struct timespec *srcmtim); + +/* Sets access and modification times to the time passed */ +void setdatetime(const char *path, const struct timespec *mtim); + +#endif diff --git a/include/log.h b/include/log.h new file mode 100644 index 0000000..2be35ee --- /dev/null +++ b/include/log.h @@ -0,0 +1,58 @@ +#ifndef REVELA_LOG_H +#define REVELA_LOG_H + +#include +#include + +enum log_level { + LOG_SILENT, + LOG_FATAL, + LOG_ERROR, + LOG_INFO, + LOG_DETAIL, + LOG_DEBUG, +}; + +#ifdef DEBUG +static const char *log_level_names[] = { + "", + "FATAL", + "ERROR", + "INFO", + "DETAIL", + "DEBUG", +}; +#endif + +void log_set_verbosity(enum log_level); + +void log_printf(enum log_level, const char *restrict fmt, ...); + +#ifdef DEBUG +#define log_print(v, fmt, ...) \ + log_printf(v, "[%s] %s:%d " fmt, log_level_names[v], \ + __FILE__, __LINE__, ##__VA_ARGS__) +#else +#define log_print(v, fmt, ...) \ + log_printf(v, fmt, ##__VA_ARGS__) +#endif + +#ifdef DEBUG +#define log_printl(v, fmt, ...) \ + log_printf(v, "[%s] %s:%d " fmt "\n", log_level_names[v], \ + __FILE__, __LINE__, ##__VA_ARGS__) +#else +#define log_printl(v, fmt, ...) \ + log_printf(v, fmt "\n", ##__VA_ARGS__) +#endif + +#ifdef DEBUG +#define log_printl_errno(v, fmt, ...) \ + log_printf(v, "[%s] %s:%d " fmt ": %s\n", log_level_names[v], \ + __FILE__, __LINE__, ##__VA_ARGS__, strerror(errno)) +#else +#define log_printl_errno(v, fmt, ...) \ + log_printf(v, fmt ": %s\n", ##__VA_ARGS__, strerror(errno)) +#endif + +#endif diff --git a/include/render.h b/include/render.h new file mode 100644 index 0000000..faa6f73 --- /dev/null +++ b/include/render.h @@ -0,0 +1,38 @@ +#ifndef REVELA_RENDER_H +#define REVELA_RENDER_H + +#include + +#include "bstree.h" +#include "config.h" +#include "template.h" +#include "components.h" + +struct render { + /* Unja environment */ + struct env *env; + /* List of years with albums in each year */ + struct vector *years; + /* List of albums */ + struct vector *albums; + /* Hashmap used for all templates */ + struct hashmap *common_vars; + /* Modification time for the templates dir */ + struct timespec modtime; + bool dry_run; +}; + +bool render_make_index(struct render *, const char *path); + +bool render_make_album(struct render *r, const char *path, + const struct album *album); + +bool render_make_image(struct render *r, const char *path, + const struct image *image); + +bool render_init(struct render *, const char *path, struct site_config *, + struct bstree *albums); + +void render_deinit(struct render *); + +#endif diff --git a/include/site.h b/include/site.h new file mode 100644 index 0000000..678cd47 --- /dev/null +++ b/include/site.h @@ -0,0 +1,46 @@ +#ifndef REVELA_SITE_H +#define REVELA_SITE_H + +#include "config.h" +#include "bstree.h" +#include "render.h" +#include "components.h" + +#include + +#ifndef SITE_DEFAULT_RESOURCES +#define SITE_DEFAULT_RESOURCES "/usr/share/revela" +#endif + +#define CSSDIR "css" +#define STATICDIR "static" +#define CONTENTDIR "content" +#define TEMPLATESDIR "templates" +#define DEFAULTALBUM "unorganized" + +struct site { + struct site_config *config; + MagickWand *wand; + char *root_dir; + const char *output_dir; + char *content_dir; + /* + * Indicates how many characters after the full root dir path of the input + * directory the relative path of the albums + the content dir start. See + * site_init() + */ + size_t rel_content_dir; + struct bstree *albums; + struct render render; + bool dry_run; +}; + +bool site_build(struct site *); + +bool site_load(struct site *); + +bool site_init(struct site *); + +void site_deinit(struct site *); + +#endif diff --git a/include/tests/tests.h b/include/tests/tests.h new file mode 100644 index 0000000..8c89fcc --- /dev/null +++ b/include/tests/tests.h @@ -0,0 +1,45 @@ +#ifndef TESTS_H +#define TESTS_H +#include +#include + +#ifndef NOCOLOR +#define TBLD "\033[1m" +#define TRED "\033[31m" +#define TGRN "\033[32m" +#define TBLU "\033[34m" +#define TRST "\033[0m" +#else +#define TBLD "" +#define TRED "" +#define TGRN "" +#define TBLU "" +#define TRST "" +#endif + +#define RUN_TEST(test_func) \ + printf("%s:\t", #test_func); \ + fflush(stdout); \ + test_func(); \ + printf(TGRN "OK!\n" TRST) + +#define INIT_TESTS() \ + printf(TBLD "running %s tests\n" TRST, __FILE__) + +#define FAIL_TEST(reason) \ + printf(TBLD TRED "FAIL!\n" TRST); \ + printf("%s:%d: %s: ", __FILE__, __LINE__, __func__); \ + printf(reason); \ + abort() + +#define asserteq(a, b) \ + if (a != b) { \ + FAIL_TEST("assertion " TBLD TBLU #a " == " #b TRST " failed\n"); \ + } + +#define assertneq(a, b) \ + if (a == b) { \ + FAIL_TEST("assertion " TBLD TBLU #a " != " #b TRST " failed\n"); \ + } + +#endif diff --git a/parcini b/parcini new file mode 160000 index 0000000..6e20bab --- /dev/null +++ b/parcini @@ -0,0 +1 @@ +Subproject commit 6e20bab8f5fcfbe4fe816425704f9edd8ad88444 diff --git a/src/bstree.c b/src/bstree.c new file mode 100644 index 0000000..f0312a8 --- /dev/null +++ b/src/bstree.c @@ -0,0 +1,183 @@ +/* + * Copyright 2021 Yaroslav de la Peña Smirnov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "bstree.h" + +#include + +struct bstree * +bstree_new(bst_cmp_fn bstcmp, bst_free_fn bstfree) +{ + struct bstree *tree = malloc(sizeof *tree); + tree->root = NULL; + tree->cmp = bstcmp; + tree->free = bstfree; + + return tree; +} + +struct bstnode * +bstree_add(struct bstree *tree, void *val) +{ + struct bstnode **cur; + struct bstnode *prev = NULL; + cur = &tree->root; + while (*cur != NULL) { + prev = *cur; + if (tree->cmp(val, prev->value) < 0) { + cur = &prev->left; + } else { + cur = &prev->right; + } + } + *cur = calloc(1, sizeof **cur); + (*cur)->value = val; + (*cur)->parent = prev; + + return *cur; +} + +struct bstnode * +bstree_search(struct bstree *tree, void *val) +{ + struct bstnode *node = tree->root; + while (node != NULL) { + int res; + if ((res = tree->cmp(val, node->value)) == 0) { + break; + } + if (res < 0) { + node = node->left; + } else { + node = node->right; + } + } + + return node; +} + +#define bstree_extreme(node, d) \ + while (node != NULL && node->d != NULL) { \ + node = node->d; \ + } + +struct bstnode * +bstree_max(struct bstnode *node) +{ + bstree_extreme(node, right) + return node; +} + +struct bstnode * +bstree_min(struct bstnode *node) +{ + bstree_extreme(node, left) + return node; +} + +#define bstree_xcessor(na, d, m) \ + if (na->d != NULL) { \ + return bstree_##m(na->d); \ + } \ + struct bstnode *nb = na->parent; \ + while (nb != NULL && nb->d == na) { \ + na = nb; \ + nb = nb->parent; \ + } \ + return nb + +struct bstnode * +bstree_successor(struct bstnode *na) +{ + bstree_xcessor(na, right, max); +} + +struct bstnode * +bstree_predecessor(struct bstnode *na) +{ + bstree_xcessor(na, left, min); +} + +bool +bstree_inorder_walk(struct bstnode *node, bst_walk_cb cb, void *data) +{ + if (node->left != NULL) { + if (!bstree_inorder_walk(node->left, cb, data)) return false; + } + if (!cb(node, data)) return false; + if (node->right != NULL) { + if (!bstree_inorder_walk(node->right, cb, data)) return false; + } + return true; +} + +static void +bstree_transplant(struct bstree *tree, struct bstnode *a, struct bstnode *b) +{ + if (a->parent == NULL) { + tree->root = b; + } else if (a == a->parent->left) { + a->parent->left = b; + } else { + a->parent->right = b; + } + if (b != NULL) { + b->parent = a->parent; + } +} + +void +bstree_remove(struct bstree *tree, struct bstnode *na) +{ + if (na->left == NULL) { + bstree_transplant(tree, na, na->right); + } else if (na->right == NULL) { + bstree_transplant(tree, na, na->left); + } else { + struct bstnode *nb = bstree_min(na->right); + if (nb->parent != na) { + bstree_transplant(tree, nb, nb->right); + nb->right = na->right; + nb->right->parent = nb; + } + bstree_transplant(tree, na, nb); + nb->left = na->left; + nb->left->parent = nb; + } + tree->free(na->value); + free(na); +} + +static void +bstree_subdestroy(struct bstree *tree, struct bstnode *node) +{ + if (node->right) bstree_subdestroy(tree, node->right); + if (node->left) bstree_subdestroy(tree, node->left); + tree->free(node->value); + free(node); +} + +void +bstree_destroy(struct bstree *tree) +{ + if (tree->root) bstree_subdestroy(tree, tree->root); + free(tree); +} diff --git a/src/components.c b/src/components.c new file mode 100644 index 0000000..082eab9 --- /dev/null +++ b/src/components.c @@ -0,0 +1,239 @@ +#include "components.h" + +#include +#include +#include +#include +#include +#include + +#include "fs.h" +#include "log.h" +#include "site.h" + +#define MAXTIME \ + ((unsigned long long)1 << ((sizeof(time_t) * CHAR_BIT) - 1)) - 1 + +#define TSTAMP_CMP(T, a, b) \ + (((T *)a)->tstamp > ((T *)b)->tstamp) - (((T *)a)->tstamp < ((T *)b)->tstamp) + +/* + * Reverses the order of the parent directories, changes '/' and spaces to '-', + * lowers the case of letters. E.g. "2019/Spain/Santiago de Compostela" -> + * "santiago-de-compostela-spain-2019". Returns pointer to slug inside of url. + */ +static const char * +slugify(const char *path, const char *base_url, char **url) +{ + size_t baselen = strlen(base_url), + pathlen, totlen; + + if (!strcmp(path, CONTENTDIR)) { + pathlen = strlen(DEFAULTALBUM); + totlen = baselen + pathlen + 2; + *url = malloc(totlen); + strncpy(*url, base_url, baselen); + (*url)[baselen] = '/'; + strncpy(*url + baselen + 1, DEFAULTALBUM, pathlen + 1); + + return *url + baselen + 1; + } + + path += strlen(CONTENTDIR) + 1; + pathlen = strlen(path); + totlen = baselen + pathlen + 2; + const char *start = path; + const char *end = strchr(start, '/'); + *url = malloc(totlen); + strncpy(*url, base_url, baselen); + (*url)[baselen] = '/'; + char *slug = *url + baselen + 1; + size_t offset = pathlen; + while (end != NULL) { + offset -= end - start; + memcpy(slug + offset, start, end - start); + slug[--offset] = '-'; + start = end + 1; + end = strchr(start, '/'); + } + memcpy(slug, start, path + pathlen - start); + for (size_t i = 0; i < pathlen; i++) { + if (isspace(slug[i])) { + slug[i] = '-'; + continue; + } + slug[i] = tolower(slug[i]); + } + (*url)[totlen - 1] = '\0'; + return slug; +} + +static void +image_date_from_stat(struct image *image, const struct stat *pstat, + struct tm *date) +{ + image->tstamp = pstat->st_ctim.tv_sec; + localtime_r(&image->tstamp, date); +} + +/* + * If exif data is present and either the tag DateTimeOriginal or + * CreateDate/DateTimeDigitized is present, then the date and time are taken + * from either (DateTimeOriginal takes precedence). Otherwise it uses the file's + * creation time (st_ctim). + */ +static void +image_set_date(struct image *image, const struct stat *pstat) +{ + struct tm date = {0}; + + if (image->exif_data == NULL) { + log_printl(LOG_DEBUG, "No exif data present in %s", image->source); + log_printl(LOG_DEBUG, "Using date from stat for file %s", image->source); + image_date_from_stat(image, pstat, &date); + goto out; + } + + ExifEntry *entry = exif_content_get_entry( + image->exif_data->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_ORIGINAL); + if (entry == NULL) { + entry = exif_content_get_entry( + image->exif_data->ifd[EXIF_IFD_EXIF], EXIF_TAG_DATE_TIME_DIGITIZED); + if (entry == NULL) { + log_printl(LOG_DEBUG, "No date exif tags present in %s", + image->source); + log_printl(LOG_DEBUG, "Using date from stat for file %s", + image->source); + image_date_from_stat(image, pstat, &date); + goto out; + } + } + + char buf[32]; + exif_entry_get_value(entry, buf, 32); + if (strptime(buf, "%Y:%m:%d %H:%M:%S", &date) == NULL) { + image_date_from_stat(image, pstat, &date); + goto out; + } + image->tstamp = mktime(&date); + +out: + /* TODO: honor user's locale and/or give an option to set the date format */ + strftime(image->datestr, 24, "%Y-%m-%d %H:%M:%S", &date); +} + +struct image * +image_new(char *src, const struct stat *pstat, struct album *album) +{ + struct image *image = calloc(1, sizeof *image); + if (image == NULL) { + log_printl_errno(LOG_FATAL, "Memory allocation error"); + return NULL; + } + char noext[NAME_MAX + 1]; + + image->album = album; + image->source = src; + image->basename = rbasename(src); + + if ((image->ext = delext(image->basename, noext, NAME_MAX + 1)) == NULL) { + log_printl(LOG_FATAL, "Can't read %s, file name too long", + image->basename); + free(image); + return NULL; + } + + size_t relstart = album->slug - album->url; + image->url = joinpath(album->url, noext); + image->url_image = joinpath(image->url, image->basename); + image->url_thumb = malloc(strlen(image->url) + strlen(PHOTO_THUMB_SUFFIX) + + strlen(image->basename) + 2); + image->dst = image->url + relstart; + image->dst_image = image->url_image + relstart; + image->dst_thumb = image->url_thumb + relstart; + sprintf(image->url_thumb, "%s/%s" PHOTO_THUMB_SUFFIX "%s", image->url, + noext, image->ext); + + image->exif_data = exif_data_new_from_file(image->source); + image->modtime = pstat->st_mtim; + image_set_date(image, pstat); + image->map = hashmap_new_with_cap(8); + image->thumb = hashmap_new_with_cap(4); + + return image; +} + +int +image_cmp(const void *a, const void *b) +{ + return TSTAMP_CMP(struct image, a, b); +} + +void +image_destroy(void *data) +{ + struct image *image = data; + free(image->source); + free(image->url); + free(image->url_image); + free(image->url_thumb); + if (image->exif_data) { + exif_data_unref(image->exif_data); + } + hashmap_free(image->map); + hashmap_free(image->thumb); + free(image); +} + +struct album * +album_new(struct album_config *conf, struct site_config *sconf, const char *src, + const char *rsrc, const struct stat *dstat) +{ + struct album *album = calloc(1, sizeof *album); + if (album == NULL) { + log_printl_errno(LOG_FATAL, "Memory allocation error"); + return NULL; + } + album->config = conf; + album->source = strdup(src); + album->slug = slugify(rsrc, sconf->base_url, &album->url); + album->images = bstree_new(image_cmp, image_destroy); + album->tstamp = MAXTIME; + album->map = hashmap_new_with_cap(8); + album->thumbs = vector_new(128); + album->previews = vector_new(sconf->max_previews); + + return album; +} + +int +album_cmp(const void *a, const void *b) +{ + return TSTAMP_CMP(struct album, a, b); +} + +void +album_add_image(struct album *album, struct image *image) +{ + if (image->tstamp < album->tstamp) { + album->tstamp = image->tstamp; + album->datestr = image->datestr; + } + bstree_add(album->images, image); +} + +void +album_destroy(void *data) +{ + struct album *album = data; + if (album->config != NULL) { + album_config_destroy(album->config); + } + free(album->source); + free(album->url); + bstree_destroy(album->images); + hashmap_free(album->map); + vector_free(album->thumbs); + vector_free(album->previews); + free(album); +} diff --git a/src/config.c b/src/config.c new file mode 100644 index 0000000..e9dd609 --- /dev/null +++ b/src/config.c @@ -0,0 +1,264 @@ +#include "config.h" + +#include +#include +#include +#include +#include +#include + +#include "fs.h" +#include "log.h" +#include "parcini.h" + +typedef enum kv_handler_result (*ini_keyvalue_handler_fn)(struct parcini_line *, void *dst); + +enum config_key_result { + CONFIG_KEY_NONE, + CONFIG_KEY_OK, + CONFIG_KEY_BADKEY, + CONFIG_KEY_BADVALUE, +}; + +enum kv_handler_result { + KV_HANDLER_OK, + KV_HANDLER_NOMATCH, + KV_HANDLER_BADVALUE, +}; + +static int +site_config_images_keyvalue_handler(struct parcini_line *parsed, + struct image_config *iconfig) +{ + int res = CONFIG_KEY_BADKEY; + if (!strcmp(parsed->key, "strip")) { + res = parcini_value_handle(&parsed->value, PARCINI_VALUE_BOOLEAN, + &iconfig->strip) ? CONFIG_KEY_OK : CONFIG_KEY_BADVALUE; + } + if (!strcmp(parsed->key, "quality")) { + long int temp; + res = parcini_value_handle(&parsed->value, PARCINI_VALUE_INTEGER, + &temp) ? CONFIG_KEY_OK : CONFIG_KEY_BADVALUE; + if (res == CONFIG_KEY_OK) { + if (temp > 100 || temp < 0) { + res = CONFIG_KEY_BADVALUE; + } else { + iconfig->quality = (uint8_t)temp; + } + } + } + if (!strcmp(parsed->key, "max_width")) { + long int temp; + res = parcini_value_handle(&parsed->value, PARCINI_VALUE_INTEGER, + &temp) ? CONFIG_KEY_OK : CONFIG_KEY_BADVALUE; + if (res == CONFIG_KEY_OK) { + if (temp < 1) { + res = CONFIG_KEY_BADVALUE; + } else { + iconfig->max_width = (size_t)temp; + } + } + } + if (!strcmp(parsed->key, "max_height")) { + long int temp; + res = parcini_value_handle(&parsed->value, PARCINI_VALUE_INTEGER, + &temp) ? CONFIG_KEY_OK : CONFIG_KEY_BADVALUE; + if (res == CONFIG_KEY_OK) { + if (temp < 1) { + res = CONFIG_KEY_BADVALUE; + } else { + iconfig->max_height = (size_t)temp; + } + } + } + if (!strcmp(parsed->key, "smart_resize")) { + res = parcini_value_handle(&parsed->value, PARCINI_VALUE_BOOLEAN, + &iconfig->smart_resize) ? CONFIG_KEY_OK : CONFIG_KEY_BADVALUE; + } + + return res; +} + +#define MATCHSK(s, k, p) !strcmp(s, p->section) && !strcmp(k, p->key) + +static enum kv_handler_result +site_config_keyvalue_handler(struct parcini_line *parsed, void *dst) +{ + struct site_config *config = dst; + enum config_key_result subconf = CONFIG_KEY_NONE; + if (!strcmp(parsed->section, "images")) { + subconf = site_config_images_keyvalue_handler(parsed, &config->images); + } else if (!strcmp(parsed->section, "thumbnails")) { + subconf = site_config_images_keyvalue_handler(parsed, + &config->thumbnails); + } + switch (subconf) { + case CONFIG_KEY_OK: + return KV_HANDLER_OK; + case CONFIG_KEY_BADKEY: + goto out; + case CONFIG_KEY_BADVALUE: + return KV_HANDLER_BADVALUE; + default: + break; + } + if (MATCHSK("", "title", parsed)) { + free(config->title); + return parcini_value_handle(&parsed->value, PARCINI_VALUE_STRING, + &config->title)? + KV_HANDLER_OK : KV_HANDLER_BADVALUE; + } + if (MATCHSK("", "base_url", parsed)) { + free(config->base_url); + return parcini_value_handle(&parsed->value, PARCINI_VALUE_STRING, + &config->base_url)? + KV_HANDLER_OK : KV_HANDLER_BADVALUE; + } + if (MATCHSK("", "max_previews", parsed)) { + return parcini_value_handle(&parsed->value, PARCINI_VALUE_INTEGER, + &config->max_previews)? + KV_HANDLER_OK : KV_HANDLER_BADVALUE; + } + + +out: + return KV_HANDLER_NOMATCH; +} + +static enum kv_handler_result +album_config_keyvalue_handler(struct parcini_line *parsed, void *dst) +{ + struct album_config *config = dst; + if (MATCHSK("", "title", parsed)) { + free(config->title); + return parcini_value_handle(&parsed->value, PARCINI_VALUE_STRING, + &config->title) ? + KV_HANDLER_OK : KV_HANDLER_BADVALUE; + } + if (MATCHSK("", "desc", parsed)) { + free(config->desc); + return parcini_value_handle(&parsed->value, PARCINI_VALUE_STRING, + &config->desc) ? + KV_HANDLER_OK : KV_HANDLER_BADVALUE; + } + + return KV_HANDLER_NOMATCH; +} + +static bool ini_handler(const char *fpath, ini_keyvalue_handler_fn kvhandler, + void *dst) +{ + struct parcini_line parsed; + enum parcini_result res; + parcini_t *parser = parcini_from_file(fpath); + if (parser == NULL){ + log_printl_errno(LOG_FATAL, "Couldn't open %s", fpath); + return false; + } + + bool ok = true; + enum kv_handler_result hres; + while ((res = parcini_parse_next_line(parser, &parsed)) != PARCINI_EOF + && ok) { + switch (res) { + case PARCINI_KEYVALUE: + if ((hres = kvhandler(&parsed, dst)) == KV_HANDLER_BADVALUE) { + log_printl(LOG_ERROR, "Error parsing %s:%ld, bad value for key" + "%s", fpath, parsed.lineno, parsed.key); + ok = false; + } else if(hres == KV_HANDLER_NOMATCH) { + log_printl(LOG_ERROR, + "Warning: key '%s' in section '%s' is not a valid " + "section-key combination for %s, ignoring.", + parsed.key, parsed.section, fpath); + } + continue; + + case PARCINI_EMPTY_LINE: + case PARCINI_SECTION: + continue; + + case PARCINI_STREAM_ERROR: + case PARCINI_MEMORY_ERROR: + log_printl_errno(LOG_FATAL, "Error reading %s", fpath); + ok = false; + break; + + default: + log_printl(LOG_FATAL, "Error parsing %s:%ld", fpath, parsed.lineno); + ok = false; + break; + } + } + + parcini_destroy(parser); + return ok; +} + +bool +site_config_read_ini(const char *wdir, struct site_config *config) +{ + if (wdir == NULL) { + return ini_handler(SITE_CONF, site_config_keyvalue_handler, + config); + } + char *fpath = joinpath(wdir, SITE_CONF); + bool ok = ini_handler(fpath, site_config_keyvalue_handler, config); + free(fpath); + return ok; +} + +bool +album_config_read_ini(const char *fpath, struct album_config *config) +{ + bool ok = ini_handler(fpath, album_config_keyvalue_handler, config); + return ok; +} + +struct site_config * +site_config_init(void) +{ + struct site_config *config = calloc(1, sizeof *config); + if (config != NULL) { + config->max_previews = 10; + config->images = (struct image_config) { + .strip = true, + .quality = 80, + .max_width = 3000, + .max_height = 2000, + .smart_resize = true, + }; + config->thumbnails = (struct image_config) { + .strip = true, + .quality = 60, + .max_width = 400, + .max_height = 270, + .smart_resize = true, + }; + } + + return config; +} + +struct album_config * +album_config_init(void) +{ + struct album_config *config = calloc(1, sizeof *config); + return config; +} + +void +site_config_destroy(struct site_config *config) +{ + free(config->title); + free(config->base_url); + free(config); +} + +void +album_config_destroy(struct album_config *config) +{ + free(config->title); + free(config->desc); + free(config); +} diff --git a/src/fs.c b/src/fs.c new file mode 100644 index 0000000..e4a6d7b --- /dev/null +++ b/src/fs.c @@ -0,0 +1,144 @@ +#include "fs.h" + +#include "log.h" +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CONTENTDIR "content" +#define DEFAULTALBUM "unorganized" + +/* + * File extensions based on which we add files to the list of images to be + * processed. + */ +static const char *img_extensions[] = { + "jpg", + "jpeg", + "png", + "tiff", + NULL, +}; + +const char * +rbasename(const char *path) +{ + char *delim = strrchr(path, '/'); + if (delim == NULL) { + return path; + } + return delim + 1; +} + +bool +nmkdir(const char *path, struct stat *dstat, bool dry) +{ + if (dry) { + if (stat(path, dstat)) { + if (errno == ENOENT) { + log_printl(LOG_DETAIL, "Created directory %s", path); + return true; + } + log_printl_errno(LOG_FATAL, "Can't read %s", path); + return false; + } + if (!S_ISDIR(dstat->st_mode)) { + log_printl(LOG_FATAL, "%s is not a directory", path); + return false; + } + return true; + } + + if(mkdir(path, 0755) < 0) { + if (errno == EEXIST) { + if (stat(path, dstat)) { + log_printl_errno(LOG_FATAL, "Can't read %s", path); + return false; + } + if (!S_ISDIR(dstat->st_mode)) { + log_printl(LOG_FATAL, "%s is not a directory", path); + return false; + } + } else { + log_printl_errno(LOG_FATAL, "Can't make directory %s", path); + return false; + } + } else { + log_printl(LOG_DETAIL, "Created directory %s", path); + } + + return true; +} + +char * +joinpath(const char *restrict a, const char *restrict b) +{ + char *fpath = malloc(strlen(a) + strlen(b) + 2); + joinpathb(fpath, a, b); + + return fpath; +} + +bool +isimage(const char *fname) +{ + char *ext = strrchr(fname, '.'); + if (!ext || *(ext + 1) == '\0') return false; + + ext++; + for (size_t i = 0; img_extensions[i] != NULL; i++) { + if (!strcasecmp(ext, img_extensions[i])) return true; + } + + return false; +} + +const char * +delext(const char *restrict basename, char *restrict buf, size_t n) +{ + const char *ext = strrchr(basename, '.'); + size_t i = ext - basename; + if (i + 1 > n) return NULL; + memcpy(buf, basename, i); + buf[i] = '\0'; + + return ext; +} + +int +file_is_uptodate(const char *path, const struct timespec *srcmtim) +{ + struct stat dststat; + if (stat(path, &dststat)) { + if (errno != ENOENT) { + log_printl_errno(LOG_FATAL, "Can't read file %s", path); + return -1; + } + return 0; + } else if (dststat.st_mtim.tv_sec != srcmtim->tv_sec + || dststat.st_mtim.tv_nsec != srcmtim->tv_nsec) { + return 0; + } + + return 1; +} + +void +setdatetime(const char *path, const struct timespec *mtim) +{ + struct timespec tms[] = { + { .tv_sec = mtim->tv_sec, .tv_nsec = mtim->tv_nsec }, + { .tv_sec = mtim->tv_sec, .tv_nsec = mtim->tv_nsec }, + }; + if (utimensat(AT_FDCWD, path, tms, 0) == -1) { + log_printl_errno(LOG_ERROR, "Warning: couldn't set times of %s", path); + } +} diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..4ff617f --- /dev/null +++ b/src/log.c @@ -0,0 +1,25 @@ +#include "log.h" + +#include +#include +#include +#include + +static enum log_level log_verbosity = LOG_INFO; + +void +log_set_verbosity(enum log_level lvl) +{ + log_verbosity = lvl; +} + +void +log_printf(enum log_level lvl, const char *restrict fmt, ...) +{ + if (lvl > log_verbosity) return; + FILE *out = lvl < LOG_INFO ? stderr : stdout; + va_list args; + va_start(args, fmt); + vfprintf(out, fmt, args); + va_end(args); +} diff --git a/src/render.c b/src/render.c new file mode 100644 index 0000000..7c72cad --- /dev/null +++ b/src/render.c @@ -0,0 +1,234 @@ +#include "render.h" + +#include +#include + +#include "fs.h" +#include "log.h" +#include "site.h" + +static bool +images_walk(struct bstnode *node, void *data) +{ + struct image *image = node->value; + + hashmap_insert(image->map, "source", image->url_image); + hashmap_insert(image->map, "date", image->datestr); + struct bstnode *prev = bstree_predecessor(node), + *next = bstree_successor(node); + char *url; + if (prev) { + url = ((struct image *)prev->value)->url; + hashmap_insert(image->map, "prev", url); + } + if (next) { + url = ((struct image *)next->value)->url; + hashmap_insert(image->map, "next", url); + } + + hashmap_insert(image->thumb, "link", image->url); + hashmap_insert(image->thumb, "source", image->url_thumb); + + vector_push(image->album->thumbs, image->thumb); + + return true; +} + +static struct hashmap * +years_push_new_year(struct vector *years, char *yearstr) +{ + struct hashmap *year = hashmap_new_with_cap(4); + struct vector *albums = vector_new(8); + hashmap_insert(year, "name", yearstr); + hashmap_insert(year, "albums", albums); + vector_push(years, year); + + return year; +} + +static void +years_push_album(struct vector *years, struct album *album) +{ + struct hashmap *year; + struct vector *albums; + if (years->size == 0) { + year = years_push_new_year(years, album->year); + } else { + year = years->values[years->size - 1]; + char *yearstr = hashmap_get(year, "name"); + if (strcmp(yearstr, album->year)) { + year = years_push_new_year(years, album->year); + } + } + albums = hashmap_get(year, "albums"); + vector_push(albums, album->map); +} + +static void +year_walk(const void *k, void *v) +{ + if (!strcmp(k, "albums")) { + struct vector *albums = v; + vector_free(albums); + } +} + +static void +years_destroy(struct vector *years) +{ + for (size_t i = 0; i < years->size; i++) { + struct hashmap *year = years->values[i]; + hashmap_walk(year, year_walk); + hashmap_free(year); + } + vector_free(years); +} + +static bool +albums_walk(struct bstnode *node, void *data) +{ + struct album *album = node->value; + struct render *r = data; + + hashmap_insert(album->map, "title", album->config->title); + hashmap_insert(album->map, "desc", album->config->desc); + hashmap_insert(album->map, "link", album->url); + + bstree_inorder_walk(album->images->root, images_walk, NULL); + + for (uint32_t i = 0; + i < album->thumbs->size && i < album->previews->cap; i++) { + vector_push(album->previews, album->thumbs->values[i]); + } + + hashmap_insert(album->map, "thumbs", album->thumbs); + hashmap_insert(album->map, "previews", album->previews); + + years_push_album(r->years, album); + vector_push(r->albums, album->map); + + return true; +} + +static bool +render(struct env *env, const char *tmpl, const char *opath, + struct hashmap *vars) +{ + bool ok = true; + char *output = template(env, tmpl, vars); + size_t outlen = strlen(output); + FILE *f = fopen(opath, "w"); + if (fwrite(output, 1, outlen, f) != outlen) { + ok = false; + log_printl_errno(LOG_FATAL, "Can't write %s", opath); + } + fclose(f); + free(output); + return ok; +} + +#define RENDER_MAKE_START \ + bool ok = true; \ + int isupdate = file_is_uptodate(path, &r->modtime); \ + if (isupdate == -1) return false; \ + if (isupdate == 1) return true; \ + log_print(LOG_INFO, "Rendering %s...", path); \ + if (r->dry_run) goto done + +#define RENDER_MAKE_END \ + setdatetime(path, &r->modtime); \ +done: \ + log_printf(LOG_INFO, " done.\n"); \ + return ok + +bool +render_make_index(struct render *r, const char *path) +{ + RENDER_MAKE_START; + + hashmap_insert(r->common_vars, "years", r->years); + hashmap_insert(r->common_vars, "albums", r->years); + ok = render(r->env, "index.html", path, r->common_vars); + hashmap_remove(r->common_vars, "years"); + hashmap_remove(r->common_vars, "albums"); + + RENDER_MAKE_END; +} + +bool +render_make_album(struct render *r, const char *path, const struct album *album) +{ + hashmap_insert(r->common_vars, "album", album->map); + + RENDER_MAKE_START; + + ok = render(r->env, "album.html", path, r->common_vars); + /* + * Since we actually still want this album's map for the image inside the + * album, we don't remove it. + */ + + RENDER_MAKE_END; +} + +bool +render_make_image(struct render *r, const char *path, const struct image *image) +{ + RENDER_MAKE_START; + + hashmap_insert(r->common_vars, "image", image->map); + ok = render(r->env, "image.html", path, r->common_vars); + hashmap_remove(r->common_vars, "image"); + + RENDER_MAKE_END; +} + +bool +render_init(struct render *r, const char *root, struct site_config *conf, + struct bstree *albums) +{ + char *tmplpath = joinpath(root, TEMPLATESDIR); + struct stat tstat; + if (stat(tmplpath, &tstat) == -1) { + if (errno == ENOENT) { + free(tmplpath); + tmplpath = joinpath(SITE_DEFAULT_RESOURCES, TEMPLATESDIR); + } else { + log_printl_errno(LOG_FATAL, "Unable to read templates dir"); + return false; + } + } + + r->modtime = tstat.st_mtim; + + if (r->dry_run) return true; + + r->env = env_new(tmplpath); + if (r->env == NULL) { + log_printl_errno(LOG_FATAL, "Couldn't initialize template engine"); + return false; + } + r->years = vector_new(8); + r->albums = vector_new(64); + + r->common_vars = hashmap_new_with_cap(8); + hashmap_insert(r->common_vars, "title", conf->title); + if (strlen(conf->base_url) == 0) { + hashmap_insert(r->common_vars, "index", "/"); + } else { + hashmap_insert(r->common_vars, "index", conf->base_url); + } + + bstree_inorder_walk(albums->root, albums_walk, (void *)r); + + return true; +} + +void +render_deinit(struct render *r) +{ + env_free(r->env); + years_destroy(r->years); + vector_free(r->albums); + hashmap_free(r->common_vars); +} diff --git a/src/revela.c b/src/revela.c new file mode 100644 index 0000000..89a7a7a --- /dev/null +++ b/src/revela.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +#include "fs.h" +#include "log.h" +#include "site.h" +#include "config.h" +#include "bstree.h" +#include "template.h" + +static const char *usage = + "Usage: %s [options] [-i ] -o \n"; + +static struct site site = {0}; +static enum log_level loglvl = LOG_DETAIL; + +static void +bad_arguments(const char *cmd) +{ + fprintf(stderr, usage, cmd); + exit(1); +} + +static void +parse_arguments(int argc, char *argv[]) +{ + int opt; + char *cmd = argv[0]; + while ((opt = getopt(argc, argv, "i:o:n")) != -1) { + switch (opt) { + case 'i': + site.root_dir = strdup(optarg); + break; + case 'o': + site.output_dir = optarg; + break; + case 'n': + site.dry_run = true; + break; + default: + bad_arguments(cmd); + } + } + if (site.output_dir == NULL) { + bad_arguments(cmd); + } +} + +int +main(int argc, char *argv[]) +{ + int ret = EXIT_SUCCESS; + + parse_arguments(argc, argv); + +#ifdef DEBUG + log_set_verbosity(LOG_DEBUG); +#else + log_set_verbosity(loglvl); +#endif + + ret = site_init(&site) && site_load(&site) && site_build(&site) + ? EXIT_SUCCESS : EXIT_FAILURE; + + if (site.dry_run) { + log_printl(LOG_INFO, "==== [DRY RUN] ===="); + } + + site_deinit(&site); + return ret; +} diff --git a/src/site.c b/src/site.c new file mode 100644 index 0000000..1acdc7c --- /dev/null +++ b/src/site.c @@ -0,0 +1,269 @@ +#include "site.h" + +#include +#include +#include +#include +#include + +#include "fs.h" +#include "log.h" +#include "hashmap.h" + +/* TODO: Probably shouldn't use PATH_MAX, but i'll leave it for now */ +/* TODO: handle error cases for paths that are too long */ + +#define THUMB_SUFFIX "_thumb" + +static bool +wand_passfail(MagickWand *wand, MagickPassFail status) +{ + if (status != MagickPass) { + char *desc; + ExceptionType severity; + desc = MagickGetException(wand, &severity); + log_printl(LOG_FATAL, "GraphicsMagick error: %.1024s severity: %d\n", + desc, severity); + return false; + } + + return true; +} + +#define TRYWAND(w, f) if (!wand_passfail(w, f)) goto magick_fail + +static bool +optimize_image(MagickWand *wand, const char *dst, + const struct image_config *conf, + const struct timespec *srcmtim, bool dry) +{ + int update = file_is_uptodate(dst, srcmtim); + if (update == -1) return false; + if (update == 1) return true; + + log_print(LOG_DETAIL, "Converting %s...", dst); + if (dry) goto out; + + unsigned long nx = conf->max_width, ny = conf->max_height; + if (conf->strip) { + TRYWAND(wand, MagickStripImage(wand)); + } + TRYWAND(wand, MagickSetCompressionQuality(wand, conf->quality)); + unsigned long x = MagickGetImageWidth(wand), + y = MagickGetImageHeight(wand); + /* Resize only if the image is actually bigger. No point in making small + * images bigger. */ + if (x > nx || y > ny) { + if (conf->smart_resize) { + double ratio = (double)x / y; + if (x > y) { + ny = ny / ratio; + } else { + nx = nx * ratio; + } + } + TRYWAND(wand, MagickResizeImage(wand, nx, ny, LanczosFilter, 0)); + } + TRYWAND(wand, MagickWriteImage(wand, dst)); + setdatetime(dst, srcmtim); + +out: + log_printf(LOG_DETAIL, " done.\n"); + return true; +magick_fail: + return false; +} + +static bool +images_walk(struct bstnode *node, void *data) +{ + struct site *site = data; + struct image *image = node->value; + struct stat dstat; + + log_printl(LOG_DEBUG, "Image: %s, datetime %s", image->basename, + image->datestr); + + if (!nmkdir(image->dst, &dstat, site->dry_run)) return false; + + if (!site->dry_run) { + TRYWAND(site->wand, MagickReadImage(site->wand, image->source)); + } + if (!optimize_image(site->wand, image->dst_image, &site->config->images, + &image->modtime, site->dry_run)) { + goto magick_fail; + } + if (!optimize_image(site->wand, image->dst_thumb, &site->config->thumbnails, + &image->modtime, site->dry_run)) { + goto magick_fail; + } + if (!site->dry_run) { + MagickRemoveImage(site->wand); + } + + char htmlpath[PATH_MAX]; + joinpathb(htmlpath, image->dst, "index.html"); + return render_make_image(&site->render, htmlpath, image); +magick_fail: + return false; +} + +static bool +albums_walk(struct bstnode *node, void *data) +{ + struct site *site = data; + struct album *album = node->value; + struct stat dstat; + if (!nmkdir(album->slug, &dstat, site->dry_run)) return false; + + char htmlpath[PATH_MAX]; + joinpathb(htmlpath, album->slug, "index.html"); + if (!render_make_album(&site->render, htmlpath, album)) return false; + + log_printl(LOG_DEBUG, "Album: %s, datetime %s", album->slug, album->datestr); + return bstree_inorder_walk(album->images->root, images_walk, site); +} + +/* + * Recursively traverse the content directory. If there are images in the + * directory, "create" an album. If an album.ini was found, then the title and + * description in that file are used. Otherwise, the date of the album is used + * as its title. If the images are in the root of the content directory, then a + * special "unorganized" album will be created. The title and description will + * be used, but the slug will always be "unorganized". + */ +static bool +traverse(struct site *site, const char *path, struct stat *dstat) +{ + bool ok = true; + DIR *dir = opendir(path); + if (!dir) { + log_printl_errno(LOG_FATAL, "Can't open directory %s", path); + return false; + } + struct dirent *ent; + struct album_config *album_conf = calloc(1, sizeof *album_conf); + struct album *album = album_new(album_conf, site->config, path, + path + site->rel_content_dir, dstat); + if (album == NULL) { + closedir(dir); + return false; + } + while ((ent = readdir(dir))) { + if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) { + continue; + } + + struct stat fstats; + char *subpath = joinpath(path, ent->d_name); + if (stat(subpath, &fstats)) { + log_printl_errno(LOG_FATAL, "Can't read %s", subpath); + ok = false; + goto fail; + } + + if (S_ISDIR(fstats.st_mode)) { + ok = traverse(site, subpath, &fstats); + if (!ok) goto fail; + } else if (!strcmp(ent->d_name, ALBUM_CONF)) { + ok = album_config_read_ini(subpath, album_conf); + if (!ok) goto fail; + } else if (isimage(subpath)) { + struct image *image = image_new(subpath, &fstats, album); + if (image == NULL) { + free(subpath); + goto fail; + } + album_add_image(album, image); + continue; + } + free(subpath); + } + + if (album->images->root != NULL) { + bstree_add(site->albums, album); + closedir(dir); + return true; + } + +fail: + album_destroy(album); + closedir(dir); + return ok; +} + +bool +site_build(struct site *site) +{ + struct stat dstat; + if (!nmkdir(site->output_dir, &dstat, false)) return false; + + if (chdir(site->output_dir)) { + log_printl_errno(LOG_FATAL, "Can't change to directory %s", + site->output_dir); + return false; + } + + if (!render_make_index(&site->render, "index.html")) return false; + + if (!bstree_inorder_walk(site->albums->root, albums_walk, (void *)site)) { + return false; + } + /* TODO: static files and css */ + chdir(site->root_dir); + return true; +} + +bool +site_load(struct site *site) +{ + struct stat cstat; + if (stat(site->content_dir, &cstat)) { + log_printl_errno(LOG_FATAL, "Can't read %s", site->content_dir); + return false; + } + + if (!traverse(site, site->content_dir, &cstat)) return false; + + return render_init(&site->render, site->root_dir, site->config, site->albums); +} + +bool +site_init(struct site *site) +{ + site->config = site_config_init(); + if (!site_config_read_ini(site->root_dir, site->config)) return false; + site->albums = bstree_new(album_cmp, album_destroy); + + if (site->root_dir == NULL) { + site->root_dir = malloc(PATH_MAX); + if (getcwd(site->root_dir, PATH_MAX) == NULL) { + log_printl_errno(LOG_FATAL, "Couldn't get working directory"); + return false; + } + } + + site->content_dir = joinpath(site->root_dir, CONTENTDIR); + site->rel_content_dir = strlen(site->root_dir) + 1; + InitializeMagick(NULL); + site->wand = NewMagickWand(); + site->render.dry_run = site->dry_run; + + return true; +} + +void +site_deinit(struct site *site) +{ + if (site->albums) bstree_destroy(site->albums); + site_config_destroy(site->config); + free(site->content_dir); + free(site->root_dir); + if (site->wand != NULL) { + DestroyMagickWand(site->wand); + DestroyMagick(); + } + if (!site->dry_run) { + render_deinit(&site->render); + } +} diff --git a/src/tests/config.c b/src/tests/config.c new file mode 100644 index 0000000..8d86a2f --- /dev/null +++ b/src/tests/config.c @@ -0,0 +1,54 @@ +#include + +#include "tests/tests.h" +#include "config.h" +#include "log.h" + +#define TESTS_DIR "tests" +#define TEST_ALBUM "tests/album.ini" + +static void +test_site_config_read_ini(void) +{ + struct site_config *config = site_config_init(); + asserteq(site_config_read_ini(TESTS_DIR, config), true); + asserteq(strcmp(config->title, "An example gallery"), 0); + asserteq(strcmp(config->base_url, "http://www.example.com/photos"), 0); + asserteq(config->max_previews, 20); + asserteq(config->images.strip, false); + asserteq(config->images.quality, 80); + asserteq(config->images.max_width, 3000); + asserteq(config->images.max_height, 2000); + asserteq(config->images.smart_resize, true); + asserteq(config->thumbnails.strip, true); + asserteq(config->thumbnails.quality, 75); + asserteq(config->thumbnails.max_width, 400); + asserteq(config->thumbnails.max_height, 270); + asserteq(config->thumbnails.smart_resize, true); + site_config_destroy(config); +} + +static void +test_album_config_read_ini(void) +{ + struct album_config *config = album_config_init(); + asserteq(album_config_read_ini(TEST_ALBUM, config), true); + asserteq(strcmp(config->title, "An example album"), 0); + asserteq(strcmp(config->desc, "Example description"), 0); + album_config_destroy(config); +} + +static void +init(void) +{ + log_set_verbosity(LOG_SILENT); +} + +int +main(void) +{ + INIT_TESTS(); + init(); + RUN_TEST(test_site_config_read_ini); + RUN_TEST(test_album_config_read_ini); +} diff --git a/src/tests/fs.c b/src/tests/fs.c new file mode 100644 index 0000000..db8ab96 --- /dev/null +++ b/src/tests/fs.c @@ -0,0 +1,74 @@ +#include "tests/tests.h" +#include "fs.h" + +#include +#include + +#define DATETIME_TEST_FILE "tests/empty" + +static void +test_rbasename(void) +{ + char *a = "/path/to/hello.jpg"; + const char *ob; + ob = rbasename(a); + asserteq(strcmp(ob, "hello.jpg"), 0); +} + +static void +test_joinpath(void) +{ + char *a = "hello", *b = "world.jpeg"; + char *joined = joinpath(a, b); + asserteq(strcmp(joined, "hello/world.jpeg"), 0); + free(joined); +} + +static void +test_isimage(void) +{ + char *a = "hello.jpg", *b = "goodbye.jpeg", *c = "iamge.png", *d = "b.tiff"; + char *notimg = "image.exe"; + asserteq(isimage(a), true); + asserteq(isimage(b), true); + asserteq(isimage(c), true); + asserteq(isimage(d), true); + asserteq(isimage(notimg), false); +} + +static void +test_delext(void) +{ + char *na = "hello.jpg", *nb = "goodbye.tar.gz"; + size_t bla = 16, blb = 16, blc = 4; + char bufa[bla], bufb[blb], bufc[blc]; + delext(na, bufa, bla); + asserteq(strcmp(bufa, "hello"), 0); + delext(nb, bufb, blb); + asserteq(strcmp(bufb, "goodbye.tar"), 0); + delext(nb, bufc, blc); +} + +static void +test_setdatetime_uptodate(void) +{ + time_t now = time(NULL); + struct timespec mtim = { + .tv_sec = now, + .tv_nsec = 690, + }; + asserteq(file_is_uptodate(DATETIME_TEST_FILE, &mtim), 0); + setdatetime(DATETIME_TEST_FILE, &mtim); + asserteq(file_is_uptodate(DATETIME_TEST_FILE, &mtim), 1); +} + +int +main(void) +{ + INIT_TESTS(); + RUN_TEST(test_rbasename); + RUN_TEST(test_joinpath); + RUN_TEST(test_isimage); + RUN_TEST(test_delext); + RUN_TEST(test_setdatetime_uptodate); +} diff --git a/template-vars.md b/template-vars.md new file mode 100644 index 0000000..2108b87 --- /dev/null +++ b/template-vars.md @@ -0,0 +1,37 @@ +# Variables + +A very rough and dirty representation of the variables in each template. + +## Common for all templates + +* `title` +* `index` + +## index.html + +* `albums` (vector) +* `years` (vector) + - `name` + - `albums` (vector) + +## album.html + +* `album` + - `title` + - `desc` + - `link` + - `date` + - `previews` (vector of thumbs) + - `thumbs` (vector) + - `link` + - `source` + +## image.html + +* `album` +* `image` + - `exif` **TODO!** + - `date` + - `source` + - `prev` + - `next` diff --git a/tests/album.ini b/tests/album.ini new file mode 100644 index 0000000..15137e6 --- /dev/null +++ b/tests/album.ini @@ -0,0 +1,2 @@ +title = "An example album" +desc = "Example description" diff --git a/tests/empty b/tests/empty new file mode 100644 index 0000000..e69de29 diff --git a/tests/site.ini b/tests/site.ini new file mode 100644 index 0000000..eca9e59 --- /dev/null +++ b/tests/site.ini @@ -0,0 +1,17 @@ +title = "An example gallery" +base_url = "http://www.example.com/photos" +max_previews = 20 + +[images] +strip = no +quality = 80 +max_width = 3000 +max_height = 2000 +smart_resize = yes + +[thumbnails] +strip = yes +quality = 75 +max_width = 400 +max_height = 270 +smart_resize = yes diff --git a/unja b/unja new file mode 160000 index 0000000..8a54056 --- /dev/null +++ b/unja @@ -0,0 +1 @@ +Subproject commit 8a5405629f7dcbc2504ac55f57775180a011b846 -- cgit v1.2.3