pax_global_header 0000666 0000000 0000000 00000000064 15122360213 0014505 g ustar 00root root 0000000 0000000 52 comment=0116bfd0723b7ecf22bc7e00aee18aa67997cd9e
email-reminder-1.0.1/ 0000775 0000000 0000000 00000000000 15122360213 0014376 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/COPYING 0000664 0000000 0000000 00000104513 15122360213 0015435 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU 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.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
email-reminder-1.0.1/Changes 0000664 0000000 0000000 00000012043 15122360213 0015671 0 ustar 00root root 0000000 0000000 1.0.1 (2025-12-22)
- fix Makefile and version number
- update installation instructions
- move collect-reminders manpage to section 8
1.0.0 (2025-12-21)
- rewrite the backend in Go
- increased test coverage
- move user config file to ~/.config/email-reminder/reminders.xml
- add --simulate flag to collect-reminders
- various security improvements
- include example systemd unit files
0.8.3 (2023-09-17)
- add missing changelog entry for 0.8.2 release
- add AppStream metadata
0.8.2 (2022-12-05)
- support unset EMAIL environment variables (bug #1983060)
0.8.1 (2020-09-19)
- fix user email lookups in ~/.email-reminders
- deal with invalid day inputs
- fix perl warning for anniversaries without a year
- fix perl warning with Monthly events on the 31st of the month
- make all collect-reminders and send-reminders output UTF-8
0.8.0 (2020-09-10)
- rewrite GUI editor using Qt For Python 5
0.7.8 (2014-10-09)
- remove author wishes functionality
- add keywords to the .desktop file
- remove noise in test output
0.7.7 (2014-01-27)
- update URL for the email-reminder homepage
- update author email address
- fix tests to work with a recent version of Perl
0.7.6 (2010-01-31)
- fix to make yearless events work again (thanks to Will Berriss!)
- more tolerant parsing of config options (yes/no, true/false now supported)
0.7.5 (2009-03-11)
- fix anniversary reminders not being sent if they have a special name
- email a warning message for occurring events that can't be processed
- use the correct recipient name in the salutation when the reminder is not
going to a third-party
- no longer require the Net::SMTP::SSL module
- update author email address
- option to send birthday wishes to the email-reminder author
0.7.4 (2008-11-20)
- support for SSL SMTP servers
- removed "No reminders found for..." message unless verbose is set
- added lots of tests from Andy Chilton
- update homepage URL in the footer of emails
0.7.3 (2008-04-13)
- subject line is now properly encoded as UTF-8
- don't bother untainting the home directory of system user accounts
- allow dots in user home directories
- debugging output is now UTF-8 encoded
- removed warning in monthly events validation
0.7.2 (2008-02-21)
- fixed a bug where the reminders file would not be saved in the UTF-8 encoding
and hence would not be read by the XML parser
- support UTF-8 characters in emails sent out
- removed unnecessary "Encoding" from the example desktop file
- added doap.xml description file to the tarball
- only display the "non-writable file" warning when editing the file
0.7.1 (2008-01-12)
- warn when the configuration file cannot be read because of permission problems
- fix a taint error while connecting to the SMTP server
0.7.0 (2007-12-11)
- create a new collect-reminders utility so that send-reminders can be run
without root privileges
- added support for SMTP servers requiring authentication
- report SMTP server errors in send-reminders
- enable taint mode on both cron job scripts
- make use of the 3-parameter open() function
- removed warning in weekly events validation
0.6.0 (2007-08-13)
- release under the GPL v3
- add monthly and weekly recurrences
- in the example cron job (INSTALL), don't output an error message when
the script cannot be found
0.5.7 (2007-05-29)
- add the date field to emails that we send out since some MTAs don't
include that field (patch by Ron Guerin)
0.5.6 (2005-12-11)
- support for sending the events to multiple email addresses through the
... tag list
- display the full date of the occurrence in advance notifications
(also fixes a bug with events w/o starting years)
- fixed typo in anniversary reminders
- update FSF's mailing address
0.5.5 (2005-08-26)
- display the date of the occurrence in advance notifications
0.5.4 (2005-06-07)
- fix the name of the global config file so that system configuration
is actually taken into account
0.5.3 (2005-04-25)
- add support for the and tags
which allows for different events to be sent to different accounts
- fix problems with events set on February 29th
0.5.2 (2005-01-31)
- fix email subject when sending advance notice of a birthday
- add version number and project URL to signature
0.5.1 (2004-09-08)
- fix the cron job so that it can find the send-reminders script
0.5.0 (2004-09-07)
- Initial public release
- custom data stores for lists (improves save speed)
- support birthdays and anniversaries without years
- normalize the date as entered by the user
- licensing everything on the GPL
- user documentation
0.2.0 (2004-08-11)
- Second private release
- select "same day" reminder by default
- gray out the spin button while "in advance" checkbox is disabled
- automatically fill-in the user's Full Name if possible
- ignore invalid email addresses
- warn about exiting with empty email address
- when some fields are not set, don't mention them in the email
- when send-reminder is not run as root, it looks only at the user's events
- add a test button to run send-reminders in the GUI
- ship a GNOME menu icon
0.1.0 (2004-07-01)
- Initial private release
email-reminder-1.0.1/EmailReminder/ 0000775 0000000 0000000 00000000000 15122360213 0017113 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/EmailReminder/Anniversary.py 0000664 0000000 0000000 00000004006 15122360213 0021766 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from EmailReminder.Birthday import BirthdayModel
from EmailReminder.Utils import EMAIL_REGEX, readXMLValue, writeXMLValue
class AnniversaryModel(BirthdayModel):
LABEL = 'Anniversaries'
TYPE = 'anniversary'
COLUMN_NAMES = ["Person 1", "Date", "Email 1", "Person 2", "Email 2"]
def fillNewEvent(self, event):
super().fillNewEvent(event)
writeXMLValue(self.document, event, 'partner_name', '')
writeXMLValue(self.document, event, 'partner_email', '')
def getDataInternal(self, column, row):
parentData = super().getDataInternal(column, row)
if parentData:
return parentData
if column == 3:
return readXMLValue(self.events[row], 'partner_name')
if column == 4:
return readXMLValue(self.events[row], 'partner_email')
return None
def setDataInternal(self, column, row, value):
if column == 3:
writeXMLValue(self.document, self.events[row], 'partner_name',
value)
elif column == 4:
if not EMAIL_REGEX.fullmatch(value):
value = ''
writeXMLValue(self.document, self.events[row], 'partner_email',
value)
else:
super().setDataInternal(column, row, value)
email-reminder-1.0.1/EmailReminder/Birthday.py 0000664 0000000 0000000 00000003215 15122360213 0021234 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from EmailReminder.Utils import EMAIL_REGEX, readXMLValue, writeXMLValue
from EmailReminder.Yearly import YearlyModel
class BirthdayModel(YearlyModel):
LABEL = 'Birthdays'
TYPE = 'birthday'
COLUMN_NAMES = ["Name", "Birth Date", "Email"]
def fillNewEvent(self, event):
super().fillNewEvent(event)
writeXMLValue(self.document, event, 'email', '')
def getDataInternal(self, column, row):
parentData = super().getDataInternal(column, row)
if parentData:
return parentData
if column == 2:
return readXMLValue(self.events[row], 'email')
return None
def setDataInternal(self, column, row, value):
if column == 2:
if not EMAIL_REGEX.fullmatch(value):
value = ''
writeXMLValue(self.document, self.events[row], 'email', value)
else:
super().setDataInternal(column, row, value)
email-reminder-1.0.1/EmailReminder/Event.py 0000664 0000000 0000000 00000016005 15122360213 0020550 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from PySide2.QtCore import QAbstractTableModel, QModelIndex, Qt
from EmailReminder.Utils import readXMLValue, writeXMLValue
def parseDay(dayString, lastDay):
try:
day = int(dayString)
except ValueError:
return 1
if day < 1:
return 1
if day > lastDay:
return lastDay
return day
class EventModel(QAbstractTableModel):
TYPE = 'event'
COLUMN_NAMES = ["Event Name"]
def __init__(self, document):
super().__init__()
self.document = document
self.events = []
self.column_count = len(self.COLUMN_NAMES)
def _createEvent(self):
event = self.document.createElement('event')
event.setAttribute('type', self.TYPE)
self.fillNewEvent(event)
user = self.document.getElementsByTagName('email-reminder_user')
events = user.item(0).getElementsByTagName('events')
events.item(0).appendChild(event)
return event
def fillNewEvent(self, event):
writeXMLValue(self.document, event, 'name', '')
reminders = self.document.createElement('reminders')
sameday = self.document.createElement('reminder')
sameday.setAttribute('type', 'same day')
reminders.appendChild(sameday)
event.appendChild(reminders)
def addEvent(self, event, parent=QModelIndex()):
self.beginInsertRows(parent, len(self.events), len(self.events))
self.events.append(event)
self.endInsertRows()
def rowCount(self, parent=QModelIndex()):
# pylint: disable=unused-argument
return len(self.events)
def columnCount(self, parent=QModelIndex()):
# pylint: disable=unused-argument
return self.column_count
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return None
if orientation != Qt.Horizontal:
return None
return self.COLUMN_NAMES[section]
def getDataInternal(self, column, row):
if column == 0:
return readXMLValue(self.events[row], 'name')
return None
def data(self, index, role=Qt.DisplayRole):
column = index.column()
row = index.row()
if role in (Qt.DisplayRole, Qt.EditRole):
return self.getDataInternal(column, row)
return None
def flags(self, index):
# pylint: disable=unused-argument
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
def getReminders(self, row):
sameDay = False
daysInAdvance = 0
event = self.events[row]
reminderList = event.getElementsByTagName('reminders')
if reminderList:
reminders = reminderList.item(0).getElementsByTagName('reminder')
for reminder in reminders:
typeAttribute = reminder.getAttribute('type')
if typeAttribute == 'same day':
sameDay = True
elif typeAttribute == 'days before':
if reminder.hasChildNodes() and reminder.firstChild:
daysInAdvance = int(reminder.firstChild.nodeValue)
return {'name': readXMLValue(self.events[row], 'name'),
'sameday': sameDay,
'daysinadvance': daysInAdvance}
def deleteReminder(self, parent, typeName):
reminders = parent.getElementsByTagName('reminder')
for reminder in reminders:
if reminder.getAttribute('type') == typeName:
parent.removeChild(reminder)
def setReminder(self, parent, typeName, nodeValue=None):
# Look for an existing element to modify.
for reminder in parent.getElementsByTagName('reminder'):
if reminder.getAttribute('type') == typeName:
if nodeValue:
if reminder.hasChildNodes():
reminder.firstChild.nodeValue = nodeValue
else:
reminder.appendChild(
self.document.createTextNode(str(nodeValue)))
return # nothing else to do
# Create a new element.
reminder = self.document.createElement('reminder')
reminder.setAttribute('type', typeName)
if nodeValue:
reminder.appendChild(self.document.createTextNode(str(nodeValue)))
parent.appendChild(reminder)
def setReminders(self, row, values):
event = self.events[row]
reminderList = event.getElementsByTagName('reminders')
if not reminderList:
reminders = self.document.createElement('reminders')
event.appendChild(reminders)
if not values['sameday']:
self.deleteReminder(reminderList.item(0), 'same day')
else:
self.setReminder(reminderList.item(0), 'same day')
if values['daysinadvance'] == 0:
self.deleteReminder(reminderList.item(0), 'days before')
else:
self.setReminder(reminderList.item(0), 'days before',
values['daysinadvance'])
def setDataInternal(self, column, row, value):
if column == 0:
writeXMLValue(self.document, self.events[row], 'name', value)
def setData(self, index, value, role=Qt.EditRole):
if role != Qt.EditRole:
return False
column = index.column()
row = index.row()
self.setDataInternal(column, row, value)
self.dataChanged.emit(index, index, [role])
return True
def insertRows(self, row, count, parent=QModelIndex()):
if count < 1:
return False
# These are not currently needed.
if count > 1:
return False
if row != self.rowCount():
return False
self.addEvent(self._createEvent(), parent)
return True
def removeRows(self, row, count, parent=QModelIndex()):
if count < 1:
return False
# This is neither implemented nor currently needed.
if count > 1:
return False
self.beginRemoveRows(parent, row, row)
event = self.events[row]
del self.events[row]
event.parentNode.removeChild(event)
self.endRemoveRows()
return True
def append(self):
return self.insertRows(self.rowCount(), 1)
def delete(self, row):
return self.removeRows(row, 1)
email-reminder-1.0.1/EmailReminder/EventList.py 0000664 0000000 0000000 00000010556 15122360213 0021411 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
import sys
import xml.parsers.expat
from xml.dom.minidom import getDOMImplementation # nosec
from defusedxml import minidom
from EmailReminder.Anniversary import AnniversaryModel
from EmailReminder.Birthday import BirthdayModel
from EmailReminder.Monthly import MonthlyModel
from EmailReminder.Utils import readXMLValue, writeXMLValue
from EmailReminder.Weekly import WeeklyModel
from EmailReminder.Yearly import YearlyModel
class EventList:
SUPPORTED_TYPES = ('birthday', 'anniversary', 'yearly', 'monthly',
'weekly')
def __init__(self, simulate, verbose):
self.stores = {}
self.filename = None
self.document = None
self.user = None
self.simulate = simulate
self.verbose = verbose
def _createDocument(self):
self.document = getDOMImplementation().createDocument(
None, 'email-reminder_user', None)
def getUser(self):
user = {}
if not self.user:
return user
for field in ('first_name', 'last_name', 'email'):
user[field] = readXMLValue(self.user, field)
return user
def setUser(self, user):
for field in ('first_name', 'last_name', 'email'):
if field in user:
writeXMLValue(self.document, self.user, field, user[field])
def load(self, filename):
self.filename = filename
if self.verbose:
print(f"Loading events from {self.filename}")
try:
with open(self.filename, encoding='utf-8') as fh:
try:
self.document = minidom.parseString(fh.read())
except xml.parsers.expat.ExpatError as err:
if err.code == 3: # no elements
self._createDocument()
else:
print(f"Error: '{filename}' is not a valid "
f"configuration file ({err})", file=sys.stderr)
return False
except FileNotFoundError:
self._createDocument()
users = self.document.getElementsByTagName('email-reminder_user')
self.user = users.item(0)
events = self.user.getElementsByTagName('events')
if events:
events = events.item(0)
else:
events = self.document.createElement('events')
self.document.documentElement.appendChild(events)
for event in events.getElementsByTagName('event'):
for eventType in self.SUPPORTED_TYPES:
if event.getAttribute('type') == eventType:
self.model(eventType).addEvent(event)
break
return True
def save(self):
if not self.document:
return
if self.simulate:
return
if self.verbose:
print(f"Writing events to {self.filename}")
with open(self.filename, mode='w', encoding='utf-8') as fh:
fh.write(self.document.toxml()) # TODO: use toprettyxml()?
def model(self, eventType):
if eventType not in self.stores:
if eventType == 'anniversary':
self.stores[eventType] = AnniversaryModel(self.document)
elif eventType == 'birthday':
self.stores[eventType] = BirthdayModel(self.document)
elif eventType == 'yearly':
self.stores[eventType] = YearlyModel(self.document)
elif eventType == 'monthly':
self.stores[eventType] = MonthlyModel(self.document)
elif eventType == 'weekly':
self.stores[eventType] = WeeklyModel(self.document)
return self.stores[eventType]
email-reminder-1.0.1/EmailReminder/Monthly.py 0000664 0000000 0000000 00000003142 15122360213 0021117 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from EmailReminder.Event import EventModel, parseDay
from EmailReminder.Utils import readXMLValue, writeXMLValue
class MonthlyModel(EventModel):
LABEL = 'Monthly Events'
TYPE = 'monthly'
COLUMN_NAMES = ["Event Name", "Day of the Month"]
def fillNewEvent(self, event):
super().fillNewEvent(event)
writeXMLValue(self.document, event, 'day', 1)
def getDataInternal(self, column, row):
parentData = super().getDataInternal(column, row)
if parentData:
return parentData
if column == 1:
return readXMLValue(self.events[row], 'day')
return None
def setDataInternal(self, column, row, value):
if column == 1:
writeXMLValue(self.document, self.events[row], 'day',
parseDay(value, 31))
else:
super().setDataInternal(column, row, value)
email-reminder-1.0.1/EmailReminder/Utils.py 0000664 0000000 0000000 00000003623 15122360213 0020571 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
import re
EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
def readXMLValue(parent, name):
element = None
for candidate in parent.getElementsByTagName(name):
element = candidate
if candidate.parentNode == parent:
break # found the right node
element = None # keep looking
if not element:
return None
if not element.firstChild:
return None
return element.firstChild.nodeValue
def writeXMLValue(document, parent, name, value):
element = None
for candidate in parent.getElementsByTagName(name):
element = candidate
if candidate.parentNode == parent:
break # found the right node
element = None # keep looking
if not value:
if element:
parent.removeChild(element)
return
if not element:
element = document.createElement(name)
element.appendChild(
document.createTextNode(str(value)))
parent.appendChild(element)
return
if not element.hasChildNodes():
element.appendChild(
document.createTextNode(str(value)))
return
element.firstChild.nodeValue = str(value)
email-reminder-1.0.1/EmailReminder/Weekly.py 0000664 0000000 0000000 00000003135 15122360213 0020727 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from EmailReminder.Event import EventModel, parseDay
from EmailReminder.Utils import readXMLValue, writeXMLValue
class WeeklyModel(EventModel):
LABEL = 'Weekly Events'
TYPE = 'weekly'
COLUMN_NAMES = ["Event Name", "Day of the Week"]
def fillNewEvent(self, event):
super().fillNewEvent(event)
writeXMLValue(self.document, event, 'day', 1)
def getDataInternal(self, column, row):
parentData = super().getDataInternal(column, row)
if parentData:
return parentData
if column == 1:
return readXMLValue(self.events[row], 'day')
return None
def setDataInternal(self, column, row, value):
if column == 1:
writeXMLValue(self.document, self.events[row], 'day',
parseDay(value, 7))
else:
super().setDataInternal(column, row, value)
email-reminder-1.0.1/EmailReminder/Yearly.py 0000664 0000000 0000000 00000005335 15122360213 0020740 0 ustar 00root root 0000000 0000000 # This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
import datetime
from EmailReminder.Event import EventModel
from EmailReminder.Utils import readXMLValue, writeXMLValue
def formatDate(year, month, day):
if not month or not day:
return ''
try:
if not year:
# 1980 is a leap year
return datetime.date(1980, int(month), int(day)).strftime('%m-%d')
return datetime.date(int(year), int(month), int(day)).isoformat()
except ValueError:
return ''
def parseDate(dateString):
try:
if len(dateString) == 5:
date = datetime.datetime.strptime(dateString, '%m-%d')
return {'year': None, 'month': date.month, 'day': date.day}
date = datetime.datetime.strptime(dateString, '%Y-%m-%d')
except ValueError:
date = datetime.datetime.today()
return {'year': date.year, 'month': date.month, 'day': date.day}
class YearlyModel(EventModel):
LABEL = 'Yearly Events'
TYPE = 'yearly'
COLUMN_NAMES = ["Event Name", "Event Date"]
def fillNewEvent(self, event):
super().fillNewEvent(event)
writeXMLValue(self.document, event, 'month', 1)
writeXMLValue(self.document, event, 'day', 15)
def getDataInternal(self, column, row):
parentData = super().getDataInternal(column, row)
if parentData:
return parentData
if column == 1:
event = self.events[row]
year = readXMLValue(event, 'year')
month = readXMLValue(event, 'month')
day = readXMLValue(event, 'day')
return formatDate(year, month, day)
return None
def setDataInternal(self, column, row, value):
if column == 1:
event = self.events[row]
date = parseDate(value)
writeXMLValue(self.document, event, 'year', date['year'])
writeXMLValue(self.document, event, 'month', date['month'])
writeXMLValue(self.document, event, 'day', date['day'])
else:
super().setDataInternal(column, row, value)
email-reminder-1.0.1/INSTALL 0000664 0000000 0000000 00000002775 15122360213 0015442 0 ustar 00root root 0000000 0000000 Dependencies
------------
Email-Reminder requires Python 3.6 or later, as well as the following packages:
- defusedxml
- PySide2.QtCore
- PySide2.QtGui
- PySide2.QtWidgets
Installation
------------
Here is the preferred way of installing Email-Reminder:
1- Run `make` to generate all binaries.
2- Run `make install` as root to install all program files.
3- Use the example systemd unit files or set up a cron job so that
the "collect-reminders" and "send-reminders" scripts run every day
as the `root` and `email-reminder` users, respectively. Under
Debian, this is done by putting the following shell script under
`/etc/cron.daily/`:
#!/bin/sh
COLLECT_SCRIPT=/usr/sbin/collect-reminders
SEND_SCRIPT=/usr/bin/send-reminders
if [ -x "$COLLECT_SCRIPT" -a -x "$SEND_SCRIPT" ]; then
$COLLECT_SCRIPT
su - email-reminder -c $SEND_SCRIPT
fi
4- Add an `email-reminder` user account (usually done with the `adduser` or
`useradd` commands).
5- Create the spool directory for that user only:
mkdir /var/spool/email-reminder
chown email-reminder:root /var/spool/email-reminder
chmod 770 /var/spool/email-reminder
6- Should you wish to add a menu entry for Email-Reminder Editor, use
the `email-reminder-editor.desktop` file.
7- Copy the example config file (`email-reminder.conf`) into `/etc` and adjust
its permissions:
cp examples/email-reminder.conf /etc/
chown email-reminder:root /etc/email-reminder.conf
chmod 640 /etc/email-reminder.conf
email-reminder-1.0.1/Makefile 0000664 0000000 0000000 00000005442 15122360213 0016043 0 ustar 00root root 0000000 0000000 NAME = email-reminder
PY_BINNAME = email-reminder-editor
PY_FILES = $(PY_BINNAME) EmailReminder/*.py
GO_BINARIES = collect-reminders send-reminders
VERSION := $(shell grep "VERSION =" $(PY_BINNAME) | grep -o "'[0-9]*\.[0-9]*\.[0-9]*'" | sed "s/'//g")
APPNAME = $(NAME)-$(VERSION)
# Standard installation directories
DESTDIR ?=
PREFIX ?= /usr
BINDIR ?= $(PREFIX)/bin
SBINDIR ?= $(PREFIX)/sbin
DATADIR ?= $(PREFIX)/share
MANDIR ?= $(DATADIR)/man
SYSCONFDIR ?= /etc
GO ?= go
GOFLAGS ?=
GO_LDFLAGS ?=
.PHONY: build clean install test lint \
pyflakes pydocstyle pycodestyle codespell pylint ruff isort bandit \
release commitsign
build: $(GO_BINARIES)
internal/config/version: $(PY_BINNAME)
echo -n "$(VERSION)" > $@
collect-reminders: internal/config/version
$(GO) build $(GOFLAGS) -ldflags "$(GO_LDFLAGS)" -o $@ ./cmd/collect-reminders
send-reminders: internal/config/version
$(GO) build $(GOFLAGS) -ldflags "$(GO_LDFLAGS)" -o $@ ./cmd/send-reminders
clean:
rm -f internal/config/version
rm -f $(GO_BINARIES)
rm -f $(APPNAME).tar.gz
rm -f $(APPNAME).tar.gz.asc
find -name "*.pyc" -delete
install: build
install -d $(DESTDIR)$(BINDIR)
install -d $(DESTDIR)$(SBINDIR)
install -d $(DESTDIR)$(DATADIR)/applications
install -d $(DESTDIR)$(DATADIR)/metainfo
install -d $(DESTDIR)$(MANDIR)/man1
install -d $(DESTDIR)$(MANDIR)/man8
install -m 0755 send-reminders $(DESTDIR)$(BINDIR)/
install -m 0755 $(PY_BINNAME) $(DESTDIR)$(BINDIR)/
install -m 0755 collect-reminders $(DESTDIR)$(SBINDIR)/
install -m 0644 $(PY_BINNAME).1 $(DESTDIR)$(MANDIR)/man1/
install -m 0644 send-reminders.1 $(DESTDIR)$(MANDIR)/man1/
install -m 0644 collect-reminders.8 $(DESTDIR)$(MANDIR)/man8/
install -m 0644 $(NAME).desktop $(DESTDIR)$(DATADIR)/applications/
install -m 0644 net.launchpad.email_reminder.metainfo.xml $(DESTDIR)$(DATADIR)/metainfo/
test: internal/config/version
$(GO) test $(GOFLAGS) ./...
pyflakes:
@echo Running pyflakes...
@pyflakes3 $(PY_FILES)
pydocstyle:
@echo Running pydocstyle...
@pydocstyle
pycodestyle:
@echo Running pycodestyle...
@pycodestyle $(PY_FILES)
codespell:
@echo Running codespell...
@codespell $(PY_FILES)
pylint:
@echo Running pylint...
@pylint $(PY_FILES)
ruff:
@echo Running ruff...
@ruff check $(PY_FILES)
isort:
@echo Running isort...
@isort --check-only --diff $(PY_FILES)
bandit:
@echo Running bandit...
@bandit --quiet -r .
lint: pycodestyle pydocstyle pyflakes pylint ruff isort codespell bandit
@echo Validating appstream data...
@appstreamcli validate --strict net.launchpad.email_reminder.metainfo.xml
$(APPNAME).tar.gz:
git archive --format=tar.gz --prefix=$(APPNAME)/ -o $@ HEAD
release: $(APPNAME).tar.gz
gpg -a --detach-sign $<
commitsign:
git commit -a -m "Bump version and changelog for release"
git tag -s $(APPNAME) -m "$(VERSION) release"
email-reminder-1.0.1/README 0000664 0000000 0000000 00000003244 15122360213 0015261 0 ustar 00root root 0000000 0000000 Email-Reminder
--------------
Email-Reminder allows users to define events that they want to be
reminded of by email. Possible events include birthdays,
anniversaries, and yearly events. Reminders can be sent on the day of
the event and a few days beforehand.
This package includes the cron job that checks for events and sends
reminders once a day, and a simple GUI that allows users to edit the
reminders they want to receive.
Installation
------------
See the INSTALL file.
Usage
-----
To add new reminders, use the "email-reminder-editor" program.
Reminders are automatically saved when the program is closed.
Use the "Test configuration" option in the "File" menu to force the
"send-reminders" script to run immediately.
Don't forget to set your name and email address under "Preferences" in
the "Edit" menu.
Sample files
------------
Sample configuration files are included in the examples directory.
"email-reminder.conf" is a sample configuration file for the
"send-reminders" program whereas "email-reminders" is a sample user
reminder list.
License
-------
Copyright (C) 2004-2025 by Francois Marier (francois@fmarier.org)
Email-Reminder is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
Email-Reminder is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
See the COPYING file for a copy of the GNU General Public License.
email-reminder-1.0.1/RELEASING 0000664 0000000 0000000 00000001703 15122360213 0015633 0 ustar 00root root 0000000 0000000 Preparing the build
===================
1- update version number in email-reminder-editor
2- edit Changes
If necessary, update the copyright year in:
- README
- email-reminder-editor
- email-reminder-editor.1
- cmd/collect-reminders/main.go
- cmd/send-reminders/main.go
- debian/copyright
Build instructions
==================
1- make clean
2- make
3- make test
4- make commitsign
5- make release
Public release
==============
1- upload the tarball to Launchpad (empty changelog):
lp-project-upload email-reminder VERSION email-reminder-VERSION.tar.gz
- Use the same text for the announcement and the release notes.
- Copy all lines from Changes into the changelog.
2- add a new announcement on https://launchpad.net/email-reminder/+announcements
3- create milestones (minor and patch) for the next release on Launchpad:
https://launchpad.net/email-reminder/trunk/+addmilestone
Repository
==========
Push the code and tags:
git push --follow-tags
email-reminder-1.0.1/TODO 0000664 0000000 0000000 00000000406 15122360213 0015066 0 ustar 00root root 0000000 0000000 - Update packaging from Perl to Golang
Possible improvements over the Perl version:
- use a DynamicUser in systemd service (https://0pointer.net/blog/dynamic-users-with-systemd.html)
- make strings localizable
- process all events concurrently using Goroutines
email-reminder-1.0.1/cmd/ 0000775 0000000 0000000 00000000000 15122360213 0015141 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/cmd/collect-reminders/ 0000775 0000000 0000000 00000000000 15122360213 0020554 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/cmd/collect-reminders/main.go 0000664 0000000 0000000 00000012553 15122360213 0022035 0 ustar 00root root 0000000 0000000 // Collects email reminders set by users for special occasions and moves
// them to the email-reminder spool directory.
//
// Email-reminder allows users to define events that they want to be
// reminded of by email.
//
// This program is meant to be invoked every day by a cron job or as the
// root user. It collects the reminder files from each user.
//
// # Copyright (C) 2023-2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/user"
"path/filepath"
"slices"
"strconv"
"strings"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/util"
)
const etcPasswd = "/etc/passwd"
const (
FieldUsername = iota
FieldPassword
FieldUid
FieldGid
FieldGECOS
FieldHomeDir
FieldShell
)
var nonInteractiveShells = []string{"/bin/false", "/sbin/nologin", "/usr/bin/git-shell", "/usr/sbin/nologin"}
type HomeDir struct {
Directory string
Uid int
}
func copyReminders(homeDir HomeDir, simulate bool, verbose bool) {
configFilename := config.GetUserConfigFilename(homeDir.Directory)
if configFilename == "" {
if verbose {
log.Printf("No reminders in '%s'\n", homeDir.Directory)
}
return
}
// OpenInRoot prevents symlink escapes outside homeDir.Directory
src, err := os.OpenInRoot(homeDir.Directory, configFilename)
if err != nil {
configFilePath := filepath.Join(homeDir.Directory, configFilename)
log.Printf("Could not read from '%s': %s\n", configFilePath, err)
return
}
defer src.Close()
// Validate ownership and file type on the *open* file descriptor to avoid TOCTOU races
if err := util.ValidateOpenFile(src, uint32(homeDir.Uid)); err != nil {
log.Printf("Skipping config file '%s': %s\n", src.Name(), err)
return
}
// TODO: enforce the 50MB limit in the system-wide config
destinationFilePath := filepath.Join(config.SpoolDir, strconv.Itoa(homeDir.Uid))
if simulate {
log.Printf("Simulating, not actually copying '%s' to '%s'\n", src.Name(), destinationFilePath)
return
}
dst, err := os.Create(destinationFilePath)
if err != nil {
log.Printf("Could not write to '%s': %s\n", destinationFilePath, err)
return
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
log.Printf("Could not copy '%s' to '%s': %s\n", src.Name(), dst.Name(), err)
os.Remove(destinationFilePath)
return
}
if verbose {
log.Printf("Copied '%s' to '%s'\n", src.Name(), dst.Name())
}
}
func localHomeDirs(passwd string, verbose bool) []HomeDir {
homeDirs := make([]HomeDir, 0, 2)
data, err := os.ReadFile(passwd)
if err != nil {
log.Printf("Could not open %s: %s\n", etcPasswd, err)
return homeDirs
}
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Split(line, ":")
if len(fields) == FieldShell+1 {
uid, err := strconv.Atoi(fields[FieldUid])
if err != nil {
if verbose {
log.Printf("Skipping invalid user %s with invalid UID %s\n", fields[FieldUsername], fields[FieldUid])
}
continue
}
if uid < 1000 || uid >= 60000 || slices.Contains(nonInteractiveShells, fields[FieldShell]) {
// This is likely a system user account, not a normal user account.
continue
}
if verbose {
log.Printf("Found %s (%d:%s) with homedir '%s'\n", fields[FieldUsername], uid, fields[FieldShell], fields[FieldHomeDir])
}
if err := util.ValidateHomeDirectory(fields[FieldHomeDir], uint32(uid)); err != nil {
if verbose {
log.Printf("Skipping user %s: %s\n", fields[FieldUsername], err)
}
continue
}
homeDirs = append(homeDirs, HomeDir{fields[FieldHomeDir], uid})
}
}
return homeDirs
}
func requireRoot(verbose bool) {
currentUser, err := user.Current()
if err != nil {
log.Fatalln(err)
}
if currentUser.Uid != "0" {
if verbose {
log.Printf("Current user is %s (%s)\n", currentUser.Username, currentUser.Uid)
}
log.Fatalln("This script must be run as root.")
}
}
func main() {
log.SetFlags(0)
simulate := flag.Bool("simulate", false, "do not actually copy any files")
verbose := flag.Bool("verbose", false, "print out information about what the program is doing")
version := flag.Bool("version", false, "display the version number")
// TODO: add short names too, either hacking it like in https://www.antoniojgutierrez.com/posts/2021-05-14-short-and-long-options-in-go-flags-pkg/
// or using another package like golang-github-pborman-getopt-dev in Debian
flag.Parse()
if *version {
fmt.Println("collect-reminders " + config.VersionNumber)
os.Exit(0)
}
requireRoot(*verbose)
homeDirs := localHomeDirs(etcPasswd, *verbose)
if *verbose {
log.Printf("Found these local home directories: %v\n", homeDirs)
}
for _, homeDir := range homeDirs {
copyReminders(homeDir, *simulate, *verbose)
}
}
email-reminder-1.0.1/cmd/send-reminders/ 0000775 0000000 0000000 00000000000 15122360213 0020060 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/cmd/send-reminders/main.go 0000664 0000000 0000000 00000020225 15122360213 0021334 0 ustar 00root root 0000000 0000000 // Send email reminders set by users for special occasions.
//
// Email-reminder allows users to define events that they want to be
// reminded of by email.
//
// This script is meant to be invoked every day by a cron job. It mails
// the actual reminders out.
//
// When run by the root user, it processes all of the spooled reminders.
// When run by a specific user, it only processes the reminders set by that
// user.
//
// # Copyright (C) 2024-2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package main
import (
"flag"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/events"
"launchpad.net/email-reminder/internal/util"
)
func processEvent(now time.Time, event events.Event, defaultRecipient util.EmailRecipient, conf config.Config, notifier Notifier) {
if conf.Verbose {
log.Printf("Processing %s", event)
}
if err := event.Validate(); err != nil {
log.Printf("Skipping invalid event '%s': %s", event, err)
return
}
recipients := event.GetRecipients(defaultRecipient, conf.MaxRecipientsPerEvent)
if len(recipients) == 0 {
log.Printf("Skipping '%s': no recipient email addresses configured", event)
return
}
for _, reminder := range event.Reminders {
isOccurring, when, err := event.IsOccurring(now, reminder)
if err != nil {
log.Printf("Cannot tell whether '%s' is occurring: %s", event, err)
continue
}
if !isOccurring {
continue
}
body, subject, err := event.ReminderMessage(now, when)
if err != nil {
log.Printf("Skipping '%s': %s", event, err)
break
}
if errs := notifier.Send(body, subject, recipients); len(errs) > 0 {
log.Printf("Failed to send reminder(s) for '%s': %v", event, errs)
notifier.SendDebug(now, event, when, errs, defaultRecipient)
}
break
}
}
func processFile(now time.Time, filename string, contents []byte, conf config.Config) {
if len(contents) > conf.MaxXMLSizeBytes {
log.Printf("Skipping %s: XML file too large (max %d bytes)\n", filename, conf.MaxXMLSizeBytes)
return
}
if conf.Verbose {
log.Printf("Extracting events from %s\n", filename)
}
user, err := events.LoadUserEvents(filename, contents, conf)
if err != nil {
log.Printf("Skipping %s: %s", filename, err)
return
}
if conf.Verbose {
log.Printf("%d events found in %s\n", len(user.Events), filename)
}
defaultRecipient := user.ToEmailRecipient()
notifier := &SmtpNotifier{Conf: conf}
for _, event := range user.Events {
processEvent(now, event, defaultRecipient, conf, notifier)
}
}
func processUserConfigFile(now time.Time, conf config.Config) {
if conf.Verbose {
log.Println("Processing only the current user's reminders")
}
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatalln("No HOME environment variable set")
}
configFilename := config.GetUserConfigFilename(homeDir)
if configFilename == "" {
log.Fatalln("No user config file found.")
}
configFilePath := filepath.Join(homeDir, configFilename)
file, err := os.OpenInRoot(homeDir, configFilename)
if err != nil {
log.Fatalf("Aborting due to unreadable %s: %s\n", configFilePath, err)
}
defer file.Close()
limitedReader := io.LimitReader(file, int64(conf.MaxXMLSizeBytes)+1) // one extra byte to detect truncated files
contents, err := io.ReadAll(limitedReader)
if err != nil {
log.Fatalf("Aborting due to unreadable %s: %s\n", configFilePath, err)
}
processFile(now, configFilePath, contents, conf)
}
func shouldProcessPath(path string, d fs.DirEntry, spoolDir string, walkErr error, conf config.Config) (process bool, err error) {
if walkErr != nil {
if path == spoolDir {
// If the spoolDir can't be opened, we can't process anything.
if conf.Verbose {
log.Println(walkErr)
}
return false, walkErr
}
// Skip files that cannot be opened
if conf.Verbose {
log.Printf("Skipping unreadable file %s: %s\n", path, walkErr)
}
return false, nil
}
if strings.HasPrefix(filepath.Base(path), ".") {
if d.IsDir() {
// Skip hidden dirs and return to the parent dir
return false, fs.SkipDir
}
return false, nil // Skip hidden files but continue with siblings
}
if d.IsDir() {
// Don't try to read directories, but keep recursing in them
return false, nil
}
return true, nil
}
func processSpooledFile(fullpath string, spoolDir string, now time.Time, conf config.Config) error {
relPath, err := filepath.Rel(spoolDir, fullpath)
if err != nil {
if conf.Verbose {
log.Printf("Skipping file %s: cannot determine relative path: %s\n", fullpath, err)
}
return nil
}
file, err := os.OpenInRoot(spoolDir, relPath)
if err != nil {
if conf.Verbose {
log.Printf("Skipping unreadable file %s: %s\n", fullpath, err)
}
return nil
}
defer file.Close()
limitedReader := io.LimitReader(file, int64(conf.MaxXMLSizeBytes)+1) // one extra byte to detect truncation
contents, err := io.ReadAll(limitedReader)
if err != nil {
if conf.Verbose {
log.Printf("Skipping unreadable file %s: %s\n", file.Name(), err)
}
return nil
}
// Start by deleting the file so that we don't end up in a loop if the file somehow crashes send-reminders:
// 1. opening the file
// 2. attempting to process it
// 3. crashing
// 4. opening the file again
// etc.
if conf.Verbose {
log.Printf("Deleting %s\n", file.Name())
}
if conf.Simulate {
log.Println("Simulating, not actually deleting the file")
} else {
if err := os.Remove(file.Name()); err != nil {
if conf.Verbose {
log.Printf("Unable to delete %s\n", file.Name())
}
// Without write access to the spoolDir, fall back to just the current user's reminders
// TODO: return nil instead and then only fall back if we've been unable to delete anything from the spoolDir
return err
}
}
processFile(now, file.Name(), contents, conf)
return nil
}
func processFiles(spoolDir string, conf config.Config) {
// Set a consistent time for all reminders
now := time.Now()
err := filepath.WalkDir(spoolDir, func(path string, d fs.DirEntry, err error) error {
process, walkErr := shouldProcessPath(path, d, spoolDir, err, conf)
if walkErr != nil {
return walkErr // can be fs.SkipDir or another error
}
if !process {
return nil
}
return processSpooledFile(path, spoolDir, now, conf)
})
if err != nil {
processUserConfigFile(now, conf)
}
}
func main() {
log.SetFlags(0)
simulate := flag.Bool("simulate", false, "does not actually send any emails out")
verbose := flag.Bool("verbose", false, "print out information about what the program is doing, including the full emails being sent out")
version := flag.Bool("version", false, "display the version number")
// TODO: add short names too, either hacking it like in https://www.antoniojgutierrez.com/posts/2021-05-14-short-and-long-options-in-go-flags-pkg/
// or using another package like golang-github-pborman-getopt-dev in Debian
flag.Parse()
if *version {
fmt.Println("send-reminders " + config.VersionNumber)
os.Exit(0)
}
conf := config.ReadSystemWideConfig(*simulate, *verbose)
// Check for root
currentUser, err := user.Current()
if err != nil {
log.Fatalln(err)
}
if currentUser.Uid == "0" {
log.Println("Warning: for security reasons, this script should not be run as root.")
} else if conf.Verbose {
log.Printf("Current user is %s (%s)\n", currentUser.Username, currentUser.Uid)
}
if !conf.SendReminders {
if conf.Verbose {
log.Printf("Nothing to do: reminders are disabled in system-wide configuration file")
}
os.Exit(0)
}
processFiles(config.SpoolDir, conf)
}
email-reminder-1.0.1/cmd/send-reminders/main_test.go 0000664 0000000 0000000 00000027650 15122360213 0022404 0 ustar 00root root 0000000 0000000 package main
import (
"errors"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"testing"
"time"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/events"
"launchpad.net/email-reminder/internal/util"
)
var cfg = config.Config{
MaxRecipientsPerEvent: 10000,
}
var defaultRecipient = util.EmailRecipient{Email: "default@example.com"}
// Hide any log output that processEvent may trigger
func discardLogs(t *testing.T) {
t.Helper()
original := log.Writer()
log.SetOutput(io.Discard)
t.Cleanup(func() {
log.SetOutput(original)
})
}
type mockNotifier struct {
sendFunc func(body, subject string, recipients []util.EmailRecipient) []error
sendDebugFunc func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient)
}
func (m *mockNotifier) Send(body, subject string, recipients []util.EmailRecipient) []error {
if m.sendFunc != nil {
return m.sendFunc(body, subject, recipients)
}
return nil
}
func (m *mockNotifier) SendDebug(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
if m.sendDebugFunc != nil {
m.sendDebugFunc(now, event, when, failures, defaultRecipient)
}
}
func TestProcessEventSkipsInvalidEvent(t *testing.T) {
discardLogs(t)
now := time.Now()
event := events.Event{Type: events.EventTypeBirthday}
called := false
notifier := &mockNotifier{
sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
called = true
return nil
},
}
processEvent(now, event, defaultRecipient, cfg, notifier)
if called {
t.Fatalf("expected invalid event to be skipped")
}
}
func TestProcessEventSendsReminderWhenOccurring(t *testing.T) {
discardLogs(t)
now := time.Date(2024, time.March, 10, 9, 0, 0, 0, time.UTC)
event := events.Event{
Type: events.EventTypeBirthday,
Name: "Alice",
Month: time.March,
Day: 10,
Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
}
sendCount := 0
debugCount := 0
notifier := &mockNotifier{
sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
sendCount++
if body == "" {
t.Fatalf("expected body to be populated")
}
if subject == "" {
t.Fatalf("expected subject to be populated")
}
if len(recipients) == 0 {
t.Fatalf("expected at least one recipient")
}
return nil
},
sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
debugCount++
},
}
processEvent(now, event, defaultRecipient, cfg, notifier)
if sendCount != 1 {
t.Fatalf("expected exactly one reminder to be sent, got %d", sendCount)
}
if debugCount != 0 {
t.Fatalf("expected no debug email to be sent")
}
}
func TestProcessEventSendsDebugOnFailure(t *testing.T) {
discardLogs(t)
now := time.Date(2024, time.March, 10, 9, 0, 0, 0, time.UTC)
event := events.Event{
Type: events.EventTypeBirthday,
Name: "Alice",
Month: time.March,
Day: 10,
Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
}
sendCount := 0
debugCount := 0
notifier := &mockNotifier{
sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
sendCount++
return []error{errors.New("boom")}
},
sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
debugCount++
if len(failures) != 1 {
t.Fatalf("expected to receive the send errors")
}
},
}
processEvent(now, event, defaultRecipient, cfg, notifier)
if sendCount != 1 {
t.Fatalf("expected a send attempt")
}
if debugCount != 1 {
t.Fatalf("expected a debug email to be triggered")
}
}
func TestProcessEventSkipsWhenNotOccurring(t *testing.T) {
discardLogs(t)
now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
event := events.Event{
Type: events.EventTypeBirthday,
Name: "Alice",
Month: time.March,
Day: 10,
Reminders: []events.Reminder{{Type: events.ReminderTypeSameDay}},
}
sendCount := 0
notifier := &mockNotifier{
sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
sendCount++
return nil
},
}
processEvent(now, event, defaultRecipient, cfg, notifier)
if sendCount != 0 {
t.Fatalf("expected no reminder to be sent, got %d", sendCount)
}
}
func TestProcessEventHandlesMultipleRemindersAndRecipients(t *testing.T) {
discardLogs(t)
now := time.Date(2024, time.March, 7, 9, 0, 0, 0, time.UTC)
event := events.Event{
Type: events.EventTypeBirthday,
Name: "Alice",
Month: time.March,
Day: 10,
Reminders: []events.Reminder{
{Type: events.ReminderTypeDaysBefore, Days: 3},
{Type: events.ReminderTypeSameDay},
},
Recipients: []events.Recipient{
{Name: "Bob", Email: "bob@example.com"},
{Name: "Carol", Email: "carol@example.com"},
},
}
sendCount := 0
debugCount := 0
var gotBody, gotSubject string
var gotRecipientsCount int
notifier := &mockNotifier{
sendFunc: func(body, subject string, recipients []util.EmailRecipient) []error {
sendCount++
gotBody = body
gotSubject = subject
gotRecipientsCount = len(recipients)
return nil
},
sendDebugFunc: func(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
debugCount++
},
}
processEvent(now, event, defaultRecipient, cfg, notifier)
if sendCount != 1 {
t.Fatalf("expected exactly one reminder to be sent, got %d", sendCount)
}
if debugCount != 0 {
t.Fatalf("expected no debug email to be sent, got %d", debugCount)
}
if gotSubject == "" {
t.Fatalf("expected subject to be populated")
}
if !strings.Contains(gotBody, "in 3 days") {
t.Fatalf("expected body to reference the first matching reminder, got %q", gotBody)
}
if gotRecipientsCount != 2 {
t.Fatalf("expected two recipients, got %d", gotRecipientsCount)
}
}
// Minimal testing mock of fs.DirEntry
type mockDirEntry struct {
name string
isDir bool
}
func (m mockDirEntry) Name() string { return m.name }
func (m mockDirEntry) IsDir() bool { return m.isDir }
func (m mockDirEntry) Type() fs.FileMode { return 0 }
func (m mockDirEntry) Info() (fs.FileInfo, error) { return nil, nil }
func TestShouldProcessPath(t *testing.T) {
spoolDir := "/var/spool/reminders"
tests := []struct {
name string
path string
dirEntry fs.DirEntry
walkErr error
wantProcess bool
wantErr error
}{
{
name: "regular file should be processed",
path: "/var/spool/reminders/user1",
dirEntry: mockDirEntry{name: "user1", isDir: false},
walkErr: nil,
wantProcess: true,
wantErr: nil,
},
{
name: "hidden file should be skipped",
path: "/var/spool/reminders/.hidden",
dirEntry: mockDirEntry{name: ".hidden", isDir: false},
walkErr: nil,
wantProcess: false,
wantErr: nil,
},
{
name: "hidden directory should be skipped with SkipDir",
path: "/var/spool/reminders/.cache",
dirEntry: mockDirEntry{name: ".cache", isDir: true},
walkErr: nil,
wantProcess: false,
wantErr: fs.SkipDir,
},
{
name: "regular directory should not be processed but continue",
path: "/var/spool/reminders/subdir",
dirEntry: mockDirEntry{name: "subdir", isDir: true},
walkErr: nil,
wantProcess: false,
wantErr: nil,
},
{
name: "error on spool dir should be fatal",
path: spoolDir,
dirEntry: mockDirEntry{name: "reminders", isDir: true},
walkErr: os.ErrPermission,
wantProcess: false,
wantErr: os.ErrPermission,
},
{
name: "error on file should be skipped",
path: "/var/spool/reminders/badfile",
dirEntry: mockDirEntry{name: "badfile", isDir: false},
walkErr: os.ErrPermission,
wantProcess: false,
wantErr: nil,
},
{
name: "nested regular file should be processed",
path: "/var/spool/reminders/subdir/user 2",
dirEntry: mockDirEntry{name: "user 2", isDir: false},
walkErr: nil,
wantProcess: true,
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
discardLogs(t)
conf := config.Config{}
gotProcess, gotErr := shouldProcessPath(tt.path, tt.dirEntry, spoolDir, tt.walkErr, conf)
if gotProcess != tt.wantProcess {
t.Errorf("process = %v, want %v", gotProcess, tt.wantProcess)
}
if tt.wantErr == nil {
if gotErr != nil {
t.Errorf("err = %v, want nil", gotErr)
}
} else if !errors.Is(gotErr, tt.wantErr) {
t.Errorf("err = %v, wantErr %v", gotErr, tt.wantErr)
}
})
}
}
func TestProcessSpooledFile(t *testing.T) {
discardLogs(t)
// Create a temporary directory and file for testing
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "testuser")
// Write valid XML content
validContent := `
`
if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
conf := config.Config{}
// Process the file (which should delete it)
err := processSpooledFile(testFile, tmpDir, now, conf)
if err != nil {
t.Fatalf("processSpoolFile failed: %v", err)
}
// Verify file was deleted
if _, err := os.Stat(testFile); !os.IsNotExist(err) {
t.Errorf("expected file to be deleted, but it still exists")
}
}
func TestProcessSpooledFileUnreadable(t *testing.T) {
discardLogs(t)
// Use a non-existent file path
nonExistentFile := "/tmp/this-file-should-not-exist-" + t.Name()
now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
conf := config.Config{}
// Should not return an error for unreadable files (logs and skips instead)
err := processSpooledFile(nonExistentFile, "/tmp", now, conf)
if err != nil {
t.Fatalf("expected no error for unreadable file, got: %v", err)
}
}
func TestProcessSpooledFileSimulate(t *testing.T) {
discardLogs(t)
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "testuser")
validContent := `
`
if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
conf := config.Config{Simulate: true}
err := processSpooledFile(testFile, tmpDir, now, conf)
if err != nil {
t.Fatalf("processSpoolFile failed: %v", err)
}
// In simulate mode, file should NOT be deleted
if _, err := os.Stat(testFile); os.IsNotExist(err) {
t.Errorf("expected file to NOT be deleted in simulate mode")
}
}
func TestProcessSpooledFilePermissionError(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("test requires non-root user")
}
discardLogs(t)
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "testuser")
validContent := `
`
if err := os.WriteFile(testFile, []byte(validContent), 0644); err != nil {
t.Fatalf("failed to create test file: %v", err)
}
// Make directory read-only to prevent deletion
if err := os.Chmod(tmpDir, 0555); err != nil {
t.Fatalf("failed to change directory permissions: %v", err)
}
t.Cleanup(func() { os.Chmod(tmpDir, 0755) })
now := time.Date(2024, time.March, 5, 9, 0, 0, 0, time.UTC)
conf := config.Config{}
// Should return error when unable to delete
err := processSpooledFile(testFile, tmpDir, now, conf)
if err == nil {
t.Fatalf("expected error when unable to delete file")
}
}
email-reminder-1.0.1/cmd/send-reminders/notifier.go 0000664 0000000 0000000 00000011261 15122360213 0022227 0 ustar 00root root 0000000 0000000 package main
import (
"encoding/json"
"fmt"
"log"
"net/smtp"
"os"
"runtime"
"strings"
"time"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/events"
"launchpad.net/email-reminder/internal/util"
)
type Notifier interface {
Send(body, subject string, recipients []util.EmailRecipient) []error
SendDebug(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient)
}
type SmtpNotifier struct {
Conf config.Config
}
func (n *SmtpNotifier) Send(body, subject string, recipients []util.EmailRecipient) []error {
var errs []error
for _, to := range recipients {
fullBody := util.FullBody(body, to, config.VersionNumber)
if err := sendEmail(fullBody, subject, to, n.Conf); err != nil {
if n.Conf.Verbose {
log.Printf("Failed to send reminder to %s: %v", to.NameAndEmail(), err)
}
errs = append(errs, err)
}
}
return errs
}
func (n *SmtpNotifier) SendDebug(now time.Time, event events.Event, when string, failures []error, defaultRecipient util.EmailRecipient) {
eventName := strings.TrimSpace(event.Name)
if eventName == "" {
eventName = event.String()
}
occurrenceLine := "Since this event is OCCURRING TODAY, you should really check your reminders manually."
if when != "today" {
occurrenceLine = fmt.Sprintf("Since this event is scheduled for %s, please double-check your reminders manually.", when)
}
if n.Conf.Verbose {
log.Printf("Sending debug email to %s for %s", defaultRecipient.Email, event)
}
body := fmt.Sprintf(`WARNING: Due to an error, the email reminder for the event "%s" could not be processed and all I could do was to let you know that there was a problem.
%s
Please forward this email to the email-reminder author so that this problem can be fixed in future versions:
Francois Marier
Thanks!
--------------------------------------------------------------
%s`, eventName, occurrenceLine, composeDebugInfo(now, event, failures))
subject := fmt.Sprintf("Email-reminder ERROR: %s", eventName)
if err := sendEmail(body, subject, defaultRecipient, n.Conf); err != nil {
log.Printf("Could not send debug email for %s: %v", event, err)
}
}
func sendEmail(body string, subject string, recipient util.EmailRecipient, conf config.Config) error {
msg := util.AssembleRawMessage(body, subject, recipient.NameAndEmail(), conf.MailFrom, config.VersionNumber)
if conf.Verbose {
log.Println(msg)
}
if conf.Simulate {
return nil
}
var auth smtp.Auth
if conf.SmtpUsername != "" && conf.SmtpPassword != "" {
auth = smtp.PlainAuth("", conf.SmtpUsername, conf.SmtpPassword, conf.SmtpServer)
}
if conf.SmtpSsl {
if err := util.SendMailImplicitTLS(conf.SmtpServer, auth, conf.MailFrom, []string{recipient.Email}, []byte(msg)); err != nil {
return fmt.Errorf("could not send '%s' email (TLS) to '%s': %w", subject, recipient.Email, err)
}
} else if err := util.SendMailPlaintext(conf.SmtpServer, auth, conf.MailFrom, []string{recipient.Email}, []byte(msg)); err != nil {
return fmt.Errorf("could not send '%s' email to '%s': %w", subject, recipient.Email, err)
}
return nil
}
func composeDebugInfo(now time.Time, event events.Event, failures []error) string {
info := []string{
fmt.Sprintf("Email-reminder: %s", config.VersionNumber),
fmt.Sprintf("Go: %s (%s/%s)", runtime.Version(), runtime.GOOS, runtime.GOARCH),
}
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
info = append(info, fmt.Sprintf("Hostname: '%s'", hostname))
}
if pathVar, ok := os.LookupEnv("PATH"); ok {
info = append(info, fmt.Sprintf("PATH: '%q'", pathVar))
} else {
info = append(info, "PATH: ")
}
if homeVar, ok := os.LookupEnv("HOME"); ok {
info = append(info, fmt.Sprintf("HOME: '%q'", homeVar))
} else {
info = append(info, "HOME: ")
}
if output, err := util.SecureExecCommand("/usr/bin/lsb_release", "-s", "-d"); err == nil {
if trimmed := strings.TrimSpace(string(output)); trimmed != "" {
info = append(info, fmt.Sprintf("OS: %s", trimmed))
}
}
if output, err := util.SecureExecCommand("/usr/bin/uname", "-a"); err == nil {
if trimmed := strings.TrimSpace(string(output)); trimmed != "" {
info = append(info, fmt.Sprintf("Kernel: %s", trimmed))
}
}
info = append(info, fmt.Sprintf("Time: %s", now.Format(time.RFC3339)))
info = append(info, "Error(s):")
for _, failure := range failures {
info = append(info, fmt.Sprintf("- %v", failure))
}
if data, err := json.MarshalIndent(event, "", " "); err == nil {
info = append(info, "Event:")
info = append(info, string(data))
} else {
info = append(info, fmt.Sprintf("Event: ", err))
}
return strings.Join(info, "\n")
}
email-reminder-1.0.1/collect-reminders.8 0000664 0000000 0000000 00000006624 15122360213 0020112 0 ustar 00root root 0000000 0000000 .\" -*- mode: troff; coding: utf-8 -*-
.\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
.ie n \{\
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "COLLECT-REMINDERS 1"
.TH COLLECT-REMINDERS 8 2025-10-02 "perl v5.40.1" "System Manager's Manual"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH NAME
collect\-reminders \- collect email reminders to be sent out
.SH SYNOPSIS
.IX Header "SYNOPSIS"
Collect email reminders set by users for special occasions and move
them to the email-reminder spool directory.
.SH DESCRIPTION
.IX Header "DESCRIPTION"
Email-reminder allows users to define events that they want to be
reminded of by email.
.PP
This script is meant to be invoked every day by a cron job or as the
root user. It collects the reminder files from each user.
.SH OPTIONS
.IX Header "OPTIONS"
.IP \fB\-\-help\fR 6
.IX Item "--help"
Displays basic usage message.
.IP \fB\-\-simulate\fR 6
.IX Item "--simulate"
Does not actually copy any files.
.IP \fB\-\-verbose\fR 6
.IX Item "--verbose"
Prints out information about what the program is doing, including the
full emails being sent out.
.IP \fB\-\-version\fR 6
.IX Item "--version"
Displays the version number.
.SH FILES
.IX Header "FILES"
\&\fI~/.config/email\-reminder/reminders.xml\fR, \fI/etc/email\-reminder.conf\fR
.SH AUTHOR
.IX Header "AUTHOR"
Francois Marier
.SH "SEE ALSO"
.IX Header "SEE ALSO"
email-reminder-editor, send-reminders
.SH COPYRIGHT
.IX Header "COPYRIGHT"
Copyright (C) 2004\-2025 by Francois Marier
.PP
Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.
.PP
Email-Reminder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
.PP
You should have received a copy of the GNU General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110\-1301, USA.
email-reminder-1.0.1/email-reminder-editor 0000775 0000000 0000000 00000035273 15122360213 0020514 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
"""
Email-Reminder Editor - edit special occasion reminders
Copyright (C) 2023-2025 by Francois Marier
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
"""
import argparse
import os
import pwd
import subprocess
import sys
from pathlib import Path
from PySide2.QtCore import QModelIndex, Qt
from PySide2.QtGui import QIcon, QKeySequence
from PySide2.QtWidgets import (QAbstractItemView, QApplication, QCheckBox,
QDialog, QHBoxLayout, QLabel, QLineEdit,
QMainWindow, QMenuBar, QMessageBox, QPushButton,
QSpinBox, QTableView, QTabWidget, QToolBar,
QVBoxLayout)
from EmailReminder.EventList import EventList
APP = QApplication(sys.argv)
CONFIG_FILE = Path.home() / '.config' / 'email-reminder' / 'reminders.xml'
LEGACY_CONFIG_FILE = Path.home() / '.email-reminders'
SEND_REMINDERS = '/usr/bin/send-reminders'
VERSION = '1.0.1' # source of truth for the version number everywhere
def get_user_config_file_path(verbose):
if CONFIG_FILE.exists():
return CONFIG_FILE
if LEGACY_CONFIG_FILE.exists():
return LEGACY_CONFIG_FILE
if verbose:
print("No events configuration found in legacy or preferred location.")
try:
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
except (OSError, PermissionError) as e:
print(f"Failed to create config directory: {e}. "
"Using legacy config file.")
return LEGACY_CONFIG_FILE
return CONFIG_FILE
class EventTab:
def __init__(self, model):
self.model = model
self.table = QTableView()
self.table.setModel(model)
self.table.setShowGrid(False)
self.table.verticalHeader().setVisible(False)
self.table.horizontalHeader().setStretchLastSection(True)
self.table.setCornerButtonEnabled(False)
self.table.setSelectionBehavior(QTableView.SelectRows)
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
self.table.setSortingEnabled(False) # TODO: enable this (bug 724121)
def getTable(self):
return self.table
def addEvent(self):
if self.model.append():
last = self.model.rowCount() - 1
index = self.model.index(last, 0)
self.table.setCurrentIndex(index)
self.table.scrollToBottom()
def deleteSelectedEvent(self):
indexes = self.table.selectionModel().selectedIndexes()
if indexes and indexes[0].isValid():
if self.model.delete(indexes[0].row()):
self.table.setCurrentIndex(QModelIndex())
def getSelectedEventReminders(self):
indexes = self.table.selectionModel().selectedIndexes()
if indexes and indexes[0].isValid():
return self.model.getReminders(indexes[0].row())
return None
def setSelectedEventReminders(self, values):
indexes = self.table.selectionModel().selectedIndexes()
if indexes and indexes[0].isValid():
self.model.setReminders(indexes[0].row(), values)
class TabWidget(QTabWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.eventTabs = []
def append(self, model):
event = EventTab(model)
self.eventTabs.append(event)
self.addTab(event.getTable(), model.LABEL)
def addEvent(self):
self.eventTabs[self.currentIndex()].addEvent()
def deleteEvent(self):
self.eventTabs[self.currentIndex()].deleteSelectedEvent()
def getEventReminders(self):
return self.eventTabs[self.currentIndex()].getSelectedEventReminders()
def setEventReminders(self, values):
self.eventTabs[self.currentIndex()].setSelectedEventReminders(values)
class EditRemindersDialog(QDialog):
def __init__(self, tabs, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tabs = tabs
self.setWindowTitle("Edit reminders")
self.event_name_label = QLabel("Current reminders for '':")
self.same_day_checkbox = QCheckBox("&Same day")
self.same_day_checkbox.setChecked(True)
days_in_advance_layout = QHBoxLayout()
self.days_in_advance_checkbox = QCheckBox("&Days in advance:")
self.days_in_advance_spinbox = QSpinBox()
self.days_in_advance_spinbox.setRange(1, 364)
self.days_in_advance_spinbox.setSingleStep(1)
self.days_in_advance_spinbox.setValue(1)
self.days_in_advance_spinbox.setDisabled(True)
self.days_in_advance_checkbox.stateChanged.connect(self.toggleSpinBox)
days_in_advance_layout.addWidget(self.days_in_advance_checkbox)
days_in_advance_layout.addWidget(self.days_in_advance_spinbox)
close_layout = QHBoxLayout()
close_button = QPushButton("Close")
close_button.clicked.connect(self.accept)
close_button.setDefault(True)
close_layout.addStretch()
close_layout.addWidget(close_button)
layout = QVBoxLayout()
layout.addWidget(self.event_name_label)
layout.addWidget(self.same_day_checkbox)
layout.addLayout(days_in_advance_layout)
layout.addLayout(close_layout)
self.setLayout(layout)
self.accepted.connect(self.save)
def toggleSpinBox(self):
self.days_in_advance_spinbox.setDisabled(
not self.days_in_advance_checkbox.isChecked())
def load(self):
reminders = self.tabs.getEventReminders()
if reminders:
self.event_name_label.setText(
f"Current reminders for '{reminders['name']}':")
self.same_day_checkbox.setChecked(reminders['sameday'])
self.days_in_advance_checkbox.setChecked(
reminders['daysinadvance'] > 0)
self.days_in_advance_spinbox.setValue(reminders['daysinadvance'])
return reminders is not None
def save(self):
values = {'sameday': self.same_day_checkbox.isChecked(),
'daysinadvance': 0}
if self.days_in_advance_checkbox.isChecked():
values['daysinadvance'] = self.days_in_advance_spinbox.value()
self.tabs.setEventReminders(values)
class PreferencesDialog(QDialog):
def __init__(self, events, *args, **kwargs):
super().__init__(*args, **kwargs)
self.events = events
self.setWindowTitle("Preferences")
name_layout = QHBoxLayout()
self.first_name_edit = QLineEdit()
self.last_name_edit = QLineEdit()
name_layout.addWidget(QLabel("Name:"))
name_layout.addWidget(self.first_name_edit)
name_layout.addWidget(self.last_name_edit)
email_layout = QHBoxLayout()
self.email_edit = QLineEdit()
email_layout.addWidget(QLabel("Email:"))
email_layout.addWidget(self.email_edit)
close_layout = QHBoxLayout()
close_button = QPushButton("Close")
close_button.clicked.connect(self.accept)
close_button.setDefault(True)
close_layout.addStretch()
close_layout.addWidget(close_button)
layout = QVBoxLayout()
layout.addWidget(
QLabel("Set the default recipient for the reminder emails:"))
layout.addLayout(name_layout)
layout.addLayout(email_layout)
layout.addLayout(close_layout)
self.setLayout(layout)
self.accepted.connect(self.save)
def load(self):
user = self.events.getUser()
if not user['first_name'] and not user['last_name']:
# Default to the full name of the OS account.
unixName = pwd.getpwuid(os.getuid())[4].split(',')[0]
user['first_name'] = unixName.split(' ')[0]
user['last_name'] = unixName.split(' ')[1]
self.events.setUser({
'first_name': user['first_name'],
'last_name': user['last_name'],
})
if not user['email']:
user['email'] = ''
if 'EMAIL' in os.environ:
user['email'] = os.environ['EMAIL']
self.events.setUser({
'email': user['email'],
})
self.first_name_edit.setText(user['first_name'])
self.last_name_edit.setText(user['last_name'])
self.email_edit.setText(user['email'])
def save(self):
self.events.setUser({
'first_name': self.first_name_edit.text(),
'last_name': self.last_name_edit.text(),
'email': self.email_edit.text(),
})
class MainWindow(QMainWindow):
def __init__(self, events, *args, **kwargs):
super().__init__(*args, **kwargs)
self.events = events
self.setWindowTitle("Email-Reminder Editor")
self.tabs = TabWidget()
for eventType in EventList.SUPPORTED_TYPES:
self.tabs.append(events.model(eventType))
self.tabs.setDocumentMode(True)
self.setCentralWidget(self.tabs)
self.addToolBar(MainToolbar(self, self.tabs))
self.setMenuBar(MainMenu(self, self.events, self.tabs))
self.preferences_dialog = PreferencesDialog(self.events)
self.edit_reminders_dialog = EditRemindersDialog(self.tabs)
def show_preferences(self):
self.preferences_dialog.load()
self.preferences_dialog.exec_()
def show_edit_reminders(self):
if self.edit_reminders_dialog.load():
self.edit_reminders_dialog.exec_()
def closeEvent(self, event):
user = self.events.getUser()
if user['email']:
event.accept()
return
# Warn the user about a missing email address.
confirmation_box = QMessageBox()
confirmation_box.setText("You will not receive any reminders since "
"you have not set your email address.")
confirmation_box.setInformativeText("Would you like to set your email "
"address in the preferences now "
"or quit?")
confirmation_box.setIcon(QMessageBox.Question)
confirmation_box.addButton("Open Preferences", QMessageBox.YesRole)
confirmation_box.addButton("Quit", QMessageBox.NoRole)
if confirmation_box.exec():
event.accept()
else:
event.ignore()
self.show_preferences()
class MainToolbar(QToolBar):
def __init__(self, window, tabs, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setMovable(False)
self.setFloatable(False)
self.setContextMenuPolicy(Qt.PreventContextMenu)
# Maintain the original look-and-feel.
self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
new_event_action = self.addAction(QIcon.fromTheme('document-new'),
'New')
new_event_action.triggered.connect(tabs.addEvent)
delete_event_action = self.addAction(QIcon.fromTheme('edit-delete'),
'Delete')
delete_event_action.triggered.connect(tabs.deleteEvent)
self.addSeparator()
edit_event_action = self.addAction('Edit reminders')
edit_event_action.triggered.connect(window.show_edit_reminders)
class MainMenu(QMenuBar):
def __init__(self, window, events, tabs, *args, **kwargs):
super().__init__(*args, **kwargs)
self.events = events
self.setNativeMenuBar(True)
file_menu = self.addMenu('File')
test_config_action = file_menu.addAction("Test configuration")
test_config_action.triggered.connect(self.runTest)
file_menu.addSeparator()
quit_action = file_menu.addAction("Quit")
quit_action.setShortcut(QKeySequence.Quit)
quit_action.triggered.connect(window.close)
edit_menu = self.addMenu('Edit')
new_event_action = edit_menu.addAction("New event")
new_event_action.setShortcut(QKeySequence.New)
new_event_action.triggered.connect(tabs.addEvent)
delete_event_action = edit_menu.addAction("Delete event")
delete_event_action.setShortcut(QKeySequence.Delete)
delete_event_action.triggered.connect(tabs.deleteEvent)
edit_event_action = edit_menu.addAction("Edit reminders...")
edit_event_action.setShortcut(QKeySequence("Ctrl+e"))
edit_event_action.triggered.connect(window.show_edit_reminders)
edit_menu.addSeparator()
preferences_event_action = edit_menu.addAction("Preferences...")
preferences_event_action.setShortcut(QKeySequence.Preferences)
preferences_event_action.triggered.connect(window.show_preferences)
def runTest(self):
warning_box = QMessageBox()
warning_box.setIcon(QMessageBox.Warning)
if not os.access(SEND_REMINDERS, os.X_OK):
warning_box.setText(f"Cannot run '{SEND_REMINDERS}'.")
warning_box.setInformativeText("Check your installation.")
warning_box.exec()
return
self.events.save()
result = subprocess.run([SEND_REMINDERS], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, check=False)
if result.stdout:
warning_box.setText(f"Error while running '{SEND_REMINDERS}':")
warning_box.setInformativeText(result.stdout.decode('utf-8'))
warning_box.exec()
def main():
parser = argparse.ArgumentParser(description="Simple editor for modifying "
"special occasion email reminders")
parser.add_argument('-s', '--simulate', dest='simulate',
action='store_true', help="don't save any changes")
parser.add_argument('-v', '--verbose', dest='verbose',
action='store_true', help="print more information")
parser.add_argument('-V', '--version', action='version',
version=f'Email-Reminder Editor {VERSION}')
args = parser.parse_args()
events = EventList(args.simulate, args.verbose)
if not events.load(get_user_config_file_path(args.verbose)):
return 1
QIcon.setThemeName('gnome') # TODO: remove (icon+name toolbar buttons)
window = MainWindow(events)
window.show()
status = APP.exec_()
events.save()
return status
sys.exit(main())
email-reminder-1.0.1/email-reminder-editor.1 0000664 0000000 0000000 00000013622 15122360213 0020642 0 ustar 00root root 0000000 0000000 .\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.29)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{
. if \nF \{
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "EMAIL-REMINDER-EDITOR 1"
.TH EMAIL-REMINDER-EDITOR 1 "2016-07-03" "perl v5.22.2" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
Email\-Reminder\-Editor \- edit special occasion reminders
.SH "SYNOPSIS"
.IX Header "SYNOPSIS"
Simple editor for modifying special-occasion email reminders.
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
Email-reminder allows users to define events that they want to be
reminded of by email. Possible events include birthdays,
anniversaries, and yearly events. Reminders can be sent on the day of
the event and a few days beforehand.
.PP
This is a simple editor that allows users to add/modify their
reminders. It saves changes automatically when the program is closed.
.SH "OPTIONS"
.IX Header "OPTIONS"
.IP "\fB\-\-help\fR" 6
.IX Item "--help"
Displays basic usage message.
.IP "\fB\-\-simulate\fR" 6
.IX Item "--simulate"
Does not actually save any changes.
.IP "\fB\-\-verbose\fR" 6
.IX Item "--verbose"
Prints out information about what the program is doing.
.IP "\fB\-\-version\fR" 6
.IX Item "--version"
Displays the version number.
.SH "FILES"
.IX Header "FILES"
\&\fI~/.config/email\-reminder/reminders.xml\fR
.SH "AUTHOR"
.IX Header "AUTHOR"
Francois Marier
.SH "SEE ALSO"
.IX Header "SEE ALSO"
collect-reminders, send-reminders
.SH "COPYRIGHT"
.IX Header "COPYRIGHT"
Copyright (C) 2004\-2025 by Francois Marier
.PP
Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the \s-1GNU\s0 General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.
.PP
Email-Reminder is distributed in the hope that it will be useful,
but \s-1WITHOUT ANY WARRANTY\s0; without even the implied warranty of
\&\s-1MERCHANTABILITY\s0 or \s-1FITNESS FOR A PARTICULAR PURPOSE. \s0 See the \s-1GNU\s0
General Public License for more details.
.PP
You should have received a copy of the \s-1GNU\s0 General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, \s-1MA
02110\-1301, USA.\s0
email-reminder-1.0.1/email-reminder.desktop 0000664 0000000 0000000 00000000532 15122360213 0020663 0 ustar 00root root 0000000 0000000 [Desktop Entry]
Name=Email-Reminder
Comment=Set/modify your personal email reminders
Comment[fr]=Ajouter et modifier vos rappels par courriel
Exec=/usr/bin/email-reminder-editor
Terminal=false
Type=Application
Categories=Utility;Calendar
StartupNotify=true
Keywords=friends;addressbook;mail;contact;anniversary;birthday;reminders;events;todolist
email-reminder-1.0.1/examples/ 0000775 0000000 0000000 00000000000 15122360213 0016214 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/examples/email-reminder-collect.service 0000664 0000000 0000000 00000001771 15122360213 0024121 0 ustar 00root root 0000000 0000000 [Unit]
Description=Collect email reminders
[Service]
Type=oneshot
User=root
Group=root
ExecStart=/usr/sbin/collect-reminders
ExecStartPost=/usr/bin/find /var/spool/email-reminder/ -name '.*' -prune -o -type f -exec /usr/bin/chown email-reminder {} +
# Security hardening
LockPersonality=true
MemoryDenyWriteExecute=true
NoNewPrivileges=true
ProtectClock=true
ProtectControlGroups=true
ProtectHostname=true
ProtectKernelLogs=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProcSubset=pid
RemoveIPC=true
RestrictNamespaces=true
RestrictRealtime=true
# Minimal list of syscalls
SystemCallArchitectures=native
SystemCallFilter=@system-service
# Restrict filesystem access
PrivateDevices=true
PrivateTmp=true
ProtectProc=invisible
ProtectSystem=strict
ReadWritePaths=/var/spool/email-reminder
RestrictSUIDSGID=true
UMask=0077
# No network needed
IPAddressDeny=any
PrivateNetwork=true
RestrictAddressFamilies=none
# Minimal capabilities needed for chown
AmbientCapabilities=
CapabilityBoundingSet=CAP_CHOWN
email-reminder-1.0.1/examples/email-reminder.conf 0000664 0000000 0000000 00000001754 15122360213 0021764 0 ustar 00root root 0000000 0000000 # /etc/email-reminder.conf
# Parameters for the send-reminders program
# Set to 0 to temporarily disable sending the emails out
# Default: 1
#send_reminders = 1
# Server to use to send the emails out
# Default: localhost
#smtp_server = localhost
# Whether to use implicit TLS on port 465 (smtp_ssl=1) or plaintext SMTP on port 25 (smtp_ssl=0)
# Default: 0
#smtp_ssl = 0
# If your SMTP server requires you to login, set these variables:
#smtp_username = john@example.com
#smtp_password = 1l0v33ma1lr3m1nd3r
# Emails will appear to come from this address
# NOTE: Some SMTP servers require that this is a valid address
# Default: root@localhost
#mail_from = root@localhost
# Maximum number of events allowed per user
# Default: 10000
#max_events_per_user = 10000
# Maximum number of recipients allowed per event
# Valid range: 1-10000
# Default: 200
#max_recipients_per_event = 200
# Maximum size of XML reminder files in megabytes (MB)
# Valid range: 1-1000000
# Default: 50
#max_xml_size_mb = 50
email-reminder-1.0.1/examples/email-reminder.service 0000664 0000000 0000000 00000002004 15122360213 0022464 0 ustar 00root root 0000000 0000000 [Unit]
Description=Send email reminders
After=network-online.target email-reminder-collect.service
Wants=network-online.target
Requires=email-reminder-collect.service
[Service]
Type=oneshot
User=email-reminder
Group=email-reminder
ExecStart=/usr/bin/send-reminders
# Security hardening
LockPersonality=true
MemoryDenyWriteExecute=true
NoNewPrivileges=true
ProtectClock=true
ProtectControlGroups=true
ProtectHostname=true
ProtectKernelLogs=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProcSubset=pid
RemoveIPC=true
RestrictNamespaces=true
RestrictRealtime=true
# Minimal list of syscalls
SystemCallArchitectures=native
SystemCallFilter=@system-service
# Restrict filesystem access
PrivateDevices=true
PrivateTmp=true
PrivateUsers=true
ProtectHome=true
ProtectProc=invisible
ProtectSystem=strict
ReadWritePaths=/var/spool/email-reminder
RestrictSUIDSGID=true
UMask=0077
# Network restrictions
RestrictAddressFamilies=AF_INET AF_INET6
# No special capabilities needed
AmbientCapabilities=
CapabilityBoundingSet=
email-reminder-1.0.1/examples/email-reminders 0000664 0000000 0000000 00000003641 15122360213 0021220 0 ustar 00root root 0000000 0000000
FrancoisMarierfrancois@fmarier.orgTrent Reznor17519655Normand L'Amour691930Bruno Blanchet2931964Prince CharlesLady Diana29719811Waitangi Day62St-Jean Baptiste46Rent12Garbage3
email-reminder-1.0.1/go.mod 0000664 0000000 0000000 00000000057 15122360213 0015506 0 ustar 00root root 0000000 0000000 module launchpad.net/email-reminder
go 1.24.0
email-reminder-1.0.1/internal/ 0000775 0000000 0000000 00000000000 15122360213 0016212 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/internal/config/ 0000775 0000000 0000000 00000000000 15122360213 0017457 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/internal/config/config.go 0000664 0000000 0000000 00000013527 15122360213 0021263 0 ustar 00root root 0000000 0000000 // # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package config
import (
"bufio"
_ "embed"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"launchpad.net/email-reminder/internal/util"
)
//go:embed version
var VersionNumber string
const (
LegacyUserConfigFile = ".email-reminders"
UserConfigDir = ".config/email-reminder"
UserConfigFile = "reminders.xml"
SpoolDir = "/var/spool/email-reminder"
systemWideConfigFile = "email-reminder.conf" // relative to /etc
)
type Config struct {
SmtpServer string
SmtpUsername string
SmtpPassword string
MailFrom string
SendReminders bool
SmtpSsl bool
// Limits to prevent resource exhaustion
MaxEventsPerUser int
MaxRecipientsPerEvent int
MaxXMLSizeBytes int
// Runtime flags
Simulate bool
Verbose bool
}
var smtpServerRegex = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9.\-]*[A-Za-z0-9])$`)
func readConfig(dir string, filename string) Config {
// Use the local machine's hostname so that the server name matches the self-signed cert that Debian creates for STARTTLS purposes.
hostname, err := os.Hostname()
if err != nil {
hostname = "localhost"
}
// Default values
config := Config{
SendReminders: true,
SmtpServer: hostname,
SmtpSsl: false,
SmtpUsername: "",
SmtpPassword: "",
MailFrom: "root@localhost",
MaxEventsPerUser: 10000,
MaxRecipientsPerEvent: 200,
MaxXMLSizeBytes: 50 * 1024 * 1024, // 50MB
}
file, err := os.OpenInRoot(dir, filename)
if err != nil {
log.Printf("failed to open system-wide config file in /etc: %v", err)
log.Println("Using default configuration values")
return config
}
defer file.Close()
if info, err := file.Stat(); err == nil {
permissions := info.Mode().Perm()
if permissions&0024 != 0 {
log.Printf("Warning: '%s' has insecure permissions: %o. This file could contain sensitive credentials and should be 640 at most.", file.Name(), permissions)
}
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// Strip out comments
tokens := strings.SplitN(scanner.Text(), "#", 2)
line := strings.TrimSpace(tokens[0])
if line == "" {
// Skip blank lines
continue
}
tokens = strings.Split(line, "=")
if len(tokens) != 2 {
// Stop processing invalid file
log.Printf("Ignoring invalid line in %s: %s", filename, line)
continue
}
key := strings.TrimSpace(tokens[0])
value := strings.TrimSpace(tokens[1])
switch key {
case "send_reminders":
b, err := util.ParseBool(value)
if err == nil {
config.SendReminders = b
}
case "smtp_server":
if smtpServerRegex.MatchString(value) {
config.SmtpServer = value
} else {
log.Printf("Ignoring invalid SMTP server '%s'", value)
}
case "smtp_ssl":
b, err := util.ParseBool(value)
if err == nil {
config.SmtpSsl = b
}
case "smtp_username":
if len(value) <= 128 {
config.SmtpUsername = value
} else {
log.Printf("Ignoring invalid SMTP username: length exceeds 128 characters")
}
case "smtp_password":
if len(value) <= 128 {
config.SmtpPassword = value
} else {
log.Printf("Ignoring invalid SMTP password: length exceeds 128 characters")
}
case "mail_from":
if err := util.ValidateEmail(value); err != nil {
log.Printf("Ignoring invalid mail_from '%s': %v", value, err)
} else {
config.MailFrom = value
}
case "max_events_per_user":
if n, err := strconv.Atoi(value); err != nil {
log.Printf("Ignoring invalid max_events_per_user '%s': %v", value, err)
} else if n <= 0 {
log.Printf("Ignoring invalid max_events_per_user '%s': must be positive and non-zero", value)
} else {
config.MaxEventsPerUser = n
}
case "max_recipients_per_event":
if n, err := strconv.Atoi(value); err != nil {
log.Printf("Ignoring invalid max_recipients_per_event '%s': %v", value, err)
} else if n <= 0 || n > 10_000 {
log.Printf("Ignoring invalid max_recipients_per_event '%s': must be between 1 and 10000 inclusively", value)
} else {
config.MaxRecipientsPerEvent = n
}
case "max_xml_size_mb":
if n, err := strconv.Atoi(value); err != nil {
log.Printf("Ignoring invalid max_xml_size_mb '%s': %v", value, err)
} else if n <= 0 || n > 1_000_000 {
log.Printf("Ignoring invalid max_xml_size_mb '%s': must be between 1 and 1M inclusively", value)
} else {
config.MaxXMLSizeBytes = n * 1024 * 1024
}
}
}
if err := scanner.Err(); err != nil {
log.Printf("Invalid system-wide config file %s: %s\n", filename, err)
}
return config
}
func ReadSystemWideConfig(simulate bool, verbose bool) Config {
config := readConfig("/etc", systemWideConfigFile)
config.Simulate = simulate
config.Verbose = verbose
return config
}
// Returns the name of the user's config file relative to homeDir or empty string if there isn't one
func GetUserConfigFilename(homeDir string) string {
preferredFilename := filepath.Join(UserConfigDir, UserConfigFile)
if _, err := os.Stat(filepath.Join(homeDir, preferredFilename)); err == nil {
return preferredFilename
}
if _, err := os.Stat(filepath.Join(homeDir, LegacyUserConfigFile)); err == nil {
return LegacyUserConfigFile
}
return ""
}
email-reminder-1.0.1/internal/config/config_test.go 0000664 0000000 0000000 00000034770 15122360213 0022325 0 ustar 00root root 0000000 0000000 package config
import (
"os"
"path/filepath"
"testing"
)
func TestReadConfig(t *testing.T) {
const defaultMailFrom = "root@localhost"
const defaultMaxEvents = 10000
const defaultMaxRecipients = 200
t.Run("NonExistentConfigFile", func(t *testing.T) {
config := readConfig("/nonexistent", "file.conf")
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected default MailFrom value to be '%s', got '%s'", defaultMailFrom, config.MailFrom)
}
})
t.Run("ValidConfigFile", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `# Test configuration file
send_reminders=false
smtp_server=mail.example.com # default
smtp_ssl=true
smtp_username=testuser # change?
smtp_password=testpass
mail_from=test@example.com
max_events_per_user=5000
max_recipients_per_event=150
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
if config.SendReminders != false {
t.Errorf("Expected SendReminders to be false, got %v", config.SendReminders)
}
if config.SmtpServer != "mail.example.com" {
t.Errorf("Expected SmtpServer to be 'mail.example.com', got '%s'", config.SmtpServer)
}
if config.SmtpSsl != true {
t.Errorf("Expected SmtpSsl to be true, got %v", config.SmtpSsl)
}
if config.SmtpUsername != "testuser" {
t.Errorf("Expected SmtpUsername to be 'testuser', got '%s'", config.SmtpUsername)
}
if config.SmtpPassword != "testpass" {
t.Errorf("Expected SmtpPassword to be 'testpass', got '%s'", config.SmtpPassword)
}
if config.MailFrom != "test@example.com" {
t.Errorf("Expected MailFrom to be 'test@example.com', got '%s'", config.MailFrom)
}
if config.MaxEventsPerUser != 5000 {
t.Errorf("Expected MaxEventsPerUser to be 5000, got %d", config.MaxEventsPerUser)
}
if config.MaxRecipientsPerEvent != 150 {
t.Errorf("Expected MaxRecipientsPerEvent to be 150, got %d", config.MaxRecipientsPerEvent)
}
})
t.Run("ValidConfigFileBooleans", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `# Test configuration file
send_reminders=no
smtp_ssl=yes
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
if config.SendReminders != false {
t.Errorf("Expected SendReminders to be false, got %v", config.SendReminders)
}
if config.SmtpSsl != true {
t.Errorf("Expected SmtpSsl to be true, got %v", config.SmtpSsl)
}
})
t.Run("ConfigWithCommentsAndWhitespace", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `# This is a comment
# Another comment
send_reminders = 1
smtp_server = localhost
# More comments with # marks in it too
smtp_ssl=0
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
if config.SendReminders != true {
t.Errorf("Expected SendReminders to be true, got %v", config.SendReminders)
}
if config.SmtpServer != "localhost" {
t.Errorf("Expected SmtpServer to be 'localhost', got '%s'", config.SmtpServer)
}
if config.SmtpSsl != false {
t.Errorf("Expected SmtpSsl to be false, got %v", config.SmtpSsl)
}
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected default MailFrom value to be '%s', got '%s'", defaultMailFrom, config.MailFrom)
}
})
t.Run("InvalidBooleanValues", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `send_reminders=invalid_bool
smtp_ssl=not_a_boolean
smtp_server=valid.server.com
max_xml_size_mb=1000
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Boolean values should remain default due to invalid input
if config.SendReminders != true {
t.Errorf("Expected SendReminders to be true (default due to invalid input), got %v", config.SendReminders)
}
if config.SmtpSsl != false {
t.Errorf("Expected SmtpSsl to be false (default due to invalid input), got %v", config.SmtpSsl)
}
// Valid string value should be set
if config.SmtpServer != "valid.server.com" {
t.Errorf("Expected SmtpServer to be 'valid.server.com', got '%s'", config.SmtpServer)
}
// Valid integer value should be set
const max_xml_bytes = 1_000 * 1024 * 1024
if config.MaxXMLSizeBytes != max_xml_bytes {
t.Errorf("Expected MaxXMLSizeBytes to be %d bytes, got %d bytes", max_xml_bytes, config.MaxXMLSizeBytes)
}
})
t.Run("InvalidLineFormat", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `smtp_server=valid.server.com
invalid_line_without_equal_sign
smtp_ssl==1
mail_from=test@example.com
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Should process the first valid line but stop at invalid line
if config.SmtpServer != "valid.server.com" {
t.Errorf("Expected SmtpServer to be 'valid.server.com', got '%s'", config.SmtpServer)
}
if config.SmtpSsl != false {
t.Errorf("Expected SmtpSsl to be false (default due to invalid input), got %v", config.SmtpSsl)
}
// The line after the invalid one should still be processed
if config.MailFrom != "test@example.com" {
t.Errorf("Expected MailFrom to be 'test@example.com', got '%s'", config.MailFrom)
}
})
t.Run("InvalidSmtpHostname", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
// Get the default hostname for comparison
hostname, err := os.Hostname()
if err != nil {
hostname = "localhost"
}
configContent := `smtp_server=.invalid.hostname
smtp_ssl=true
mail_from=test@localhost
`
err = os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Invalid SMTP hostname should be rejected and default value kept
if config.SmtpServer != hostname {
t.Errorf("Expected SmtpServer to be '%s' (default due to invalid hostname), got '%s'", hostname, config.SmtpServer)
}
// Other valid values should still be set
if config.SmtpSsl != true {
t.Errorf("Expected SmtpSsl to be true, got %v", config.SmtpSsl)
}
if config.MailFrom != "test@localhost" {
t.Errorf("Expected MailFrom to be 'test@localhost', got '%s'", config.MailFrom)
}
})
t.Run("InvalidMailFrom", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `mail_from=user@@example.com
max_events_per_user=-10
max_recipients_per_event=100000
max_xml_size_mb=0
smtp_server=mail.example.com
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Invalid mail_from should be rejected, default should be used
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected MailFrom to be default '%s', got '%s'", defaultMailFrom, config.MailFrom)
}
// Invalid max_events_per_user should be rejected, default should be used
if config.MaxEventsPerUser != defaultMaxEvents {
t.Errorf("Expected MaxEventsPerUser to be default %d, got '%d'", defaultMaxEvents, config.MaxEventsPerUser)
}
// Invalid max_recipients_per_event should be rejected, default should be used
if config.MaxRecipientsPerEvent != defaultMaxRecipients {
t.Errorf("Expected MaxRecipientsPerEvent to be default %d, got %d", defaultMaxRecipients, config.MaxRecipientsPerEvent)
}
// Invalid max_xml_size_mb should be rejected, default should be used
const defaultMaxXML = 50 * 1024 * 1024
if config.MaxXMLSizeBytes != defaultMaxXML {
t.Errorf("Expected MaxXMLSizeBytes to be default %d, got %d", defaultMaxXML, config.MaxXMLSizeBytes)
}
// Other valid values should still be set
if config.SmtpServer != "mail.example.com" {
t.Errorf("Expected SmtpServer to be 'mail.example.com', got '%s'", config.SmtpServer)
}
})
t.Run("MailFromWithDisplayName", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
// Try to use email with display name format
configContent := `mail_from=John Doe
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Display name format should be rejected, default should be used
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected MailFrom to be default '%s' due to display name format, got '%s'", defaultMailFrom, config.MailFrom)
}
})
t.Run("EmptyConfigFile", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
err := os.WriteFile(configFile, []byte(""), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// All values should be defaults
if config.SendReminders != true {
t.Errorf("Expected SendReminders to be true, got %v", config.SendReminders)
}
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected MailFrom to be '%s', got '%s'", defaultMailFrom, config.MailFrom)
}
})
t.Run("OnlyCommentsConfigFile", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
configContent := `# This is a comment
# Another comment
# Yet another comment
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// All values should be defaults
if config.SendReminders != true {
t.Errorf("Expected SendReminders to be true, got %v", config.SendReminders)
}
if config.MailFrom != defaultMailFrom {
t.Errorf("Expected MailFrom to be '%s', got '%s'", defaultMailFrom, config.MailFrom)
}
})
t.Run("SmtpUsernameTooLong", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
longUsername := string(make([]byte, 129)) // 129 characters
for i := range longUsername {
longUsername = string([]byte{byte('a' + (i % 26))}) + longUsername[1:]
}
configContent := `smtp_username=` + longUsername + `
smtp_password=validpass
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Username that's too long should be rejected, default (empty string) should be used
if config.SmtpUsername != "" {
t.Errorf("Expected SmtpUsername to be empty (default) due to excessive length, got '%s'", config.SmtpUsername)
}
// Other valid values should still be set
if config.SmtpPassword != "validpass" {
t.Errorf("Expected SmtpPassword to be 'validpass', got '%s'", config.SmtpPassword)
}
})
t.Run("SmtpPasswordTooLong", func(t *testing.T) {
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "test.conf")
longPassword := string(make([]byte, 129)) // 129 characters long
for i := range longPassword {
longPassword = string([]byte{byte('A' + (i % 26))}) + longPassword[1:]
}
configContent := `smtp_username=validuser
smtp_password=` + longPassword + `
`
err := os.WriteFile(configFile, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
config := readConfig(tmpDir, "test.conf")
// Password that's too long should be rejected, default (empty string) should be used
if config.SmtpPassword != "" {
t.Errorf("Expected SmtpPassword to be empty (default) due to excessive length, got '%s'", config.SmtpPassword)
}
// Other valid values should still be set
if config.SmtpUsername != "validuser" {
t.Errorf("Expected SmtpUsername to be 'validuser', got '%s'", config.SmtpUsername)
}
})
}
func TestGetUserConfigFilePath(t *testing.T) {
t.Run("NoConfigFiles", func(t *testing.T) {
tmpDir := t.TempDir()
path := GetUserConfigFilename(tmpDir)
if path != "" {
t.Errorf("Expected path to be empty, got '%s'", path)
}
})
t.Run("OnlyLegacyFile", func(t *testing.T) {
tmpDir := t.TempDir()
legacyPath := filepath.Join(tmpDir, LegacyUserConfigFile)
if err := os.WriteFile(legacyPath, []byte("legacy content"), 0644); err != nil {
t.Fatalf("Failed to create legacy config file: %v", err)
}
filename := GetUserConfigFilename(tmpDir)
if filename != LegacyUserConfigFile {
t.Errorf("Expected path to be '%s', got '%s'", LegacyUserConfigFile, filename)
}
})
t.Run("OnlyPreferredFile", func(t *testing.T) {
tmpDir := t.TempDir()
if err := os.MkdirAll(filepath.Join(tmpDir, UserConfigDir), 0755); err != nil {
t.Fatalf("Failed to create preferred config directory: %v", err)
}
preferredFilename := filepath.Join(UserConfigDir, UserConfigFile)
if err := os.WriteFile(filepath.Join(tmpDir, preferredFilename), []byte("preferred content"), 0644); err != nil {
t.Fatalf("Failed to create preferred config file: %v", err)
}
filename := GetUserConfigFilename(tmpDir)
if filename != preferredFilename {
t.Errorf("Expected path to be '%s', got '%s'", preferredFilename, filename)
}
})
t.Run("BothFilesExist", func(t *testing.T) {
tmpDir := t.TempDir()
// Create legacy file
legacyPath := filepath.Join(tmpDir, LegacyUserConfigFile)
if err := os.WriteFile(legacyPath, []byte("legacy content"), 0644); err != nil {
t.Fatalf("Failed to create legacy config file: %v", err)
}
// Create preferred file
if err := os.MkdirAll(filepath.Join(tmpDir, UserConfigDir), 0755); err != nil {
t.Fatalf("Failed to create preferred config directory: %v", err)
}
preferredFilename := filepath.Join(UserConfigDir, UserConfigFile)
if err := os.WriteFile(filepath.Join(tmpDir, preferredFilename), []byte("preferred content"), 0644); err != nil {
t.Fatalf("Failed to create preferred config file: %v", err)
}
filename := GetUserConfigFilename(tmpDir)
// Should prefer the new config file over the legacy one
if filename != preferredFilename {
t.Errorf("Expected path to be '%s' (preferred), got '%s'", preferredFilename, filename)
}
})
}
email-reminder-1.0.1/internal/events/ 0000775 0000000 0000000 00000000000 15122360213 0017516 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/internal/events/event.go 0000664 0000000 0000000 00000027723 15122360213 0021201 0 ustar 00root root 0000000 0000000 // # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package events
import (
"encoding/xml"
"fmt"
"log"
"strconv"
"strings"
"time"
"launchpad.net/email-reminder/internal/util"
)
const (
hoursPerDay = 24 * time.Hour
maxNameLength = 1024
maxEmailLength = 254
)
type EventType string
const (
EventTypeAnniversary EventType = "anniversary"
EventTypeBirthday EventType = "birthday"
EventTypeYearly EventType = "yearly"
EventTypeMonthly EventType = "monthly"
EventTypeWeekly EventType = "weekly"
)
func (et *EventType) UnmarshalText(text []byte) error {
v := strings.TrimSpace(strings.ToLower(string(text)))
switch v {
case string(EventTypeAnniversary):
*et = EventTypeAnniversary
case string(EventTypeBirthday):
*et = EventTypeBirthday
case string(EventTypeYearly):
*et = EventTypeYearly
case string(EventTypeMonthly):
*et = EventTypeMonthly
case string(EventTypeWeekly):
*et = EventTypeWeekly
default:
*et = EventType(v)
}
return nil
}
// Valid values: 0-6 for weekly events, 1-31 otherwise
type EventDay int
func (ed *EventDay) UnmarshalText(text []byte) error {
value := strings.TrimSpace(strings.ToLower(string(text)))
// Numeric values
if day, err := strconv.Atoi(value); err == nil {
*ed = EventDay(day)
return nil
}
// Handle textual day names (like Perl's Date::Manip ParseDate)
dayNames := map[string]int{
"sunday": 0,
"monday": 1,
"tuesday": 2,
"wednesday": 3,
"thursday": 4,
"friday": 5,
"saturday": 6,
"sun": 0,
"mon": 1,
"tue": 2,
"wed": 3,
"thu": 4,
"fri": 5,
"sat": 6,
}
if day, exists := dayNames[value]; exists {
*ed = EventDay(day)
return nil
}
*ed = EventDay(-1)
return fmt.Errorf("unrecognized day name: %s", value)
}
type Event struct {
XMLName xml.Name `xml:"event"`
Type EventType `xml:"type,attr"`
Name string `xml:"name"`
Email string `xml:"email,omitempty"`
PartnerName string `xml:"partner_name,omitempty"`
PartnerEmail string `xml:"partner_email,omitempty"`
Reminders []Reminder `xml:"reminders>reminder,omitempty"`
Recipients []Recipient `xml:"recipients>recipient,omitempty"`
Day EventDay `xml:"day,omitempty"`
Month time.Month `xml:"month,omitempty"`
Year int `xml:"year,omitempty"`
}
func (event Event) Validate() error {
if strings.TrimSpace(event.Name) == "" {
return fmt.Errorf("empty event name")
}
if len(event.Name) > maxNameLength {
return fmt.Errorf("event name exceeds maximum length of %d characters", maxNameLength)
}
if len(event.Email) > maxEmailLength {
return fmt.Errorf("email exceeds maximum length of %d characters", maxEmailLength)
}
if len(event.PartnerEmail) > maxEmailLength {
return fmt.Errorf("partner email exceeds maximum length of %d characters", maxEmailLength)
}
if event.Year < 0 {
return fmt.Errorf("%d is not a valid year", event.Year)
}
switch event.Type {
case EventTypeAnniversary:
if strings.TrimSpace(event.PartnerName) == "" {
return fmt.Errorf("empty partner name")
}
if len(event.PartnerName) > maxNameLength {
return fmt.Errorf("partner name exceeds maximum length of %d characters", maxNameLength)
}
fallthrough
case EventTypeBirthday, EventTypeYearly:
if event.Month < 1 || event.Month > 12 {
return fmt.Errorf("%d is not a valid month", event.Month)
}
fallthrough
case EventTypeMonthly:
if event.Day < 1 || event.Day > 31 {
return fmt.Errorf("%d is not a valid day", event.Day)
}
case EventTypeWeekly:
if event.Day < 0 || event.Day > 7 {
return fmt.Errorf("%d is not a valid day of the week", event.Day)
}
default:
return fmt.Errorf("unknown event type: %s", event.Type)
}
return nil
}
func (event Event) IsOccurring(now time.Time, reminder Reminder) (bool, string, error) {
target := now
when := ""
switch reminder.Type {
case ReminderTypeSameDay:
when = "today"
case ReminderTypeDaysBefore:
if reminder.Days <= 0 {
return false, "", fmt.Errorf("invalid reminder days: %d", reminder.Days)
}
target = target.Add(hoursPerDay * time.Duration(reminder.Days))
if reminder.Days == 1 {
when = fmt.Sprintf("tomorrow (%s)", target.Format("Mon Jan 2"))
} else {
when = fmt.Sprintf("in %d days (%s)", reminder.Days, target.Format("Mon Jan 2"))
}
default:
return false, "", fmt.Errorf("unknown reminder type: %s", reminder.Type)
}
switch event.Type {
case EventTypeAnniversary, EventTypeBirthday, EventTypeYearly:
return event.IsSameDay(target), when, nil
case EventTypeMonthly:
if int(event.Day) == target.Day() {
return true, when, nil
} else if int(event.Day) > 28 && util.IsLastDayOfTheMonth(target) {
// If it's not possible for a monthly event to occur this month because there
// aren't enough days in the month, then we assume the user wants this event
// to occur on the last day of the month.
return true, when, nil
}
return false, when, nil
case EventTypeWeekly:
return target.Weekday() == event.Day.DayOfTheWeek(), when, nil
default:
return false, when, fmt.Errorf("unknown event type: %s", event.Type)
}
}
func (event Event) GetOccurrence(now time.Time) (int, bool) {
if event.Year == 0 {
return 0, false
}
occurrence := now.Year() - event.Year
if now.Month() < event.Month {
// Haven't quite reached the anniversary month yet
occurrence -= 1
} else if now.Month() == event.Month && now.Day() < int(event.Day) {
// Handle Feb 29th events correctly
if !event.IsSameDay(now) {
// Haven't quite reached the anniversary day yet
occurrence -= 1
}
}
return occurrence, occurrence >= 0
}
func (event Event) GetRecipients(fallback util.EmailRecipient, maxRecipients int) []util.EmailRecipient {
to := []util.EmailRecipient{}
// Look for event-specific recipients
for _, recipient := range event.Recipients {
emailRecipient := recipient.ToEmailRecipient()
if emailRecipient.Email == "" {
log.Printf("Ignoring recipient %s: missing email address", recipient)
continue
}
if len(to) >= maxRecipients {
log.Printf("Warning: event '%s' has more than %d recipients, ignoring excess recipients", event.Name, maxRecipients)
break
}
to = append(to, emailRecipient)
}
if len(to) == 0 && fallback.Email != "" {
// Fall back to default destination email address if configured
to = []util.EmailRecipient{fallback}
}
return to
}
func (event Event) AnniversaryContact() string {
email := strings.TrimSpace(event.Email)
partnerEmail := strings.TrimSpace(event.PartnerEmail)
if email != "" && partnerEmail != "" {
return fmt.Sprintf("You can reach them at %s and %s respectively.", email, partnerEmail)
} else if email != "" {
return fmt.Sprintf("You can reach %s at %s.", strings.TrimSpace(event.Name), email)
} else if partnerEmail != "" {
return fmt.Sprintf("You can reach %s at %s.", strings.TrimSpace(event.PartnerName), partnerEmail)
}
return "" // No contact details for either person
}
func (event Event) ReminderMessage(now time.Time, occurringWhen string) (string, string, error) {
msg := ""
subject := strings.TrimSpace(event.Name)
name := strings.TrimSpace(event.Name)
switch event.Type {
case EventTypeAnniversary:
partnerName := strings.TrimSpace(event.PartnerName)
subject = fmt.Sprintf("Anniversary of %s and %s", name, partnerName)
anniversaryString := "anniversary"
specialName := ""
if occurrence, valid := event.GetOccurrence(now.UTC()); valid {
anniversaryString = fmt.Sprintf("%s anniversary", formatOrdinal(occurrence))
if s := anniversaryName(occurrence); s != "" {
specialName = fmt.Sprintf(" (%s)", s)
}
subject = fmt.Sprintf("%s of %s and %s", anniversaryString, name, partnerName)
}
msg = fmt.Sprintf(`I just want to remind you that the %s%s of %s and %s is %s.`, anniversaryString, specialName, name, partnerName, occurringWhen)
if contactString := event.AnniversaryContact(); contactString != "" {
msg += fmt.Sprintf("\n\n%s", contactString)
}
case EventTypeBirthday:
subject = fmt.Sprintf("%s's birthday", name)
age := "getting one year older"
if occurrence, valid := event.GetOccurrence(now.UTC()); valid {
age = fmt.Sprintf("turning %d", occurrence)
if occurringWhen == "today" {
subject = fmt.Sprintf("%s is now %d", name, occurrence)
}
}
email := strings.TrimSpace(event.Email)
fullName := name
if email != "" {
fullName = fmt.Sprintf("%s (%s)", name, email)
}
msg = fmt.Sprintf("I just want to remind you that %s is %s %s.", fullName, age, occurringWhen)
case EventTypeMonthly, EventTypeWeekly:
msg = fmt.Sprintf(`I just want to remind you of the following event %s:
%s`, occurringWhen, name)
case EventTypeYearly:
// Use supplied 'now' for deterministic testing instead of current system time
if occurrence, valid := event.GetOccurrence(now.UTC()); valid {
name = fmt.Sprintf("%s %s", formatOrdinal(occurrence+1), name)
}
msg = fmt.Sprintf(`I just want to remind you of the following event %s:
%s`, occurringWhen, name)
default:
return "", "", fmt.Errorf("unknown event type %s", event.Type)
}
return msg, subject, nil
}
func (event Event) String() string {
name := strings.TrimSpace(event.Name)
switch event.Type {
case EventTypeBirthday:
if event.Year > 0 {
return fmt.Sprintf("%s's birthday (%d-%02d-%02d)", name, event.Year, event.Month, int(event.Day))
}
return fmt.Sprintf("%s's birthday (%02d-%02d)", name, event.Month, int(event.Day))
case EventTypeAnniversary:
return fmt.Sprintf("%s's anniversary (%d-%02d-%02d)", name, event.Year, event.Month, int(event.Day))
case EventTypeMonthly:
return fmt.Sprintf("%s (monthly on day %d)", name, int(event.Day))
case EventTypeWeekly:
return fmt.Sprintf("%s (weekly on %s)", name, event.Day.DayOfTheWeek())
case EventTypeYearly:
return fmt.Sprintf("%s (yearly on %02d-%02d)", name, event.Month, int(event.Day))
default:
return fmt.Sprintf("%s (%s)", name, event.Type)
}
}
func (e Event) IsSameDay(now time.Time) bool {
if now.Month() == time.February && now.Day() == 28 && int(e.Day) == 29 {
// Feb 29th birthdays are typically celebrated on Feb 28th in non-leap years
return util.IsLastDayOfTheMonth(now)
}
return now.Month() == e.Month && now.Day() == int(e.Day)
}
func (e EventDay) DayOfTheWeek() time.Weekday {
day := int(e)
if day < 1 || day > 6 {
// Default to Sunday for out of range dates (both 0 and 7 are Sunday in cron)
return time.Sunday
}
return time.Weekday(day)
}
func anniversaryName(occurrence int) string {
// https://en.wikipedia.org/wiki/Wedding_anniversary#Traditional_anniversary_gifts
names := map[int]string{
1: "Paper",
2: "Cotton",
3: "Leather",
4: "Linen",
5: "Wood",
6: "Iron",
7: "Copper",
8: "Bronze",
9: "Pottery",
10: "Tin",
11: "Steel",
12: "Silk",
13: "Lace",
14: "Ivory",
15: "Crystal",
20: "Porcelain",
25: "Silver",
30: "Pearl",
35: "Coral",
40: "Ruby",
45: "Sapphire",
50: "Gold",
55: "Emerald",
60: "Diamond",
70: "Platinum",
}
if name, exists := names[occurrence]; exists {
return name
}
return ""
}
func formatOrdinal(n int) string {
lastTwoDigits := n % 100
if lastTwoDigits >= 11 && lastTwoDigits <= 13 {
return fmt.Sprintf("%dth", n)
}
switch n % 10 {
case 1:
return fmt.Sprintf("%dst", n)
case 2:
return fmt.Sprintf("%dnd", n)
case 3:
return fmt.Sprintf("%drd", n)
default:
return fmt.Sprintf("%dth", n)
}
}
email-reminder-1.0.1/internal/events/event_test.go 0000664 0000000 0000000 00000111326 15122360213 0022231 0 ustar 00root root 0000000 0000000 package events
import (
"fmt"
"testing"
"time"
"launchpad.net/email-reminder/internal/util"
)
const defaultMaxRecipients = 10000
var defaultRecipient = util.EmailRecipient{Email: "default@example.com"}
func TestGetOccurrence(t *testing.T) {
tests := []struct {
event Event
now time.Time
wantValue int
wantOccurred bool
}{
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 5, 15, 10, 0, 0, 0, time.UTC),
wantValue: 25,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 7, 20, 10, 0, 0, 0, time.UTC),
wantValue: 25,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 5, 10, 10, 0, 0, 0, time.UTC),
wantValue: 24,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 8,
Day: EventDay(15),
},
now: time.Date(2025, 5, 20, 10, 0, 0, 0, time.UTC),
wantValue: 24,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 2,
Day: EventDay(29),
},
now: time.Date(2025, 2, 28, 10, 0, 0, 0, time.UTC), // 2025 is not a leap year
wantValue: 25,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 2,
Day: EventDay(29),
},
now: time.Date(2024, 2, 28, 10, 0, 0, 0, time.UTC), // 2024 is a leap year
wantValue: 23,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 2,
Day: EventDay(29),
},
now: time.Date(2024, 2, 29, 10, 0, 0, 0, time.UTC), // 2024 is a leap year
wantValue: 24,
wantOccurred: true,
},
{
event: Event{
Type: "yearly",
Year: 2020,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 5, 15, 10, 0, 0, 0, time.UTC),
wantValue: 5,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2025,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 5, 15, 10, 0, 0, 0, time.UTC),
wantValue: 0,
wantOccurred: true,
},
{
event: Event{
Type: "birthday",
Year: 2025,
Month: 8,
Day: EventDay(15),
},
now: time.Date(2025, 5, 15, 10, 0, 0, 0, time.UTC),
wantValue: -1,
wantOccurred: false, // unborn person
},
{
event: Event{
Type: "birthday",
Year: 2000,
Month: 5,
Day: EventDay(15),
},
now: time.Date(2025, 3, 20, 10, 0, 0, 0, time.UTC),
wantValue: 24,
wantOccurred: true,
},
}
for i, tt := range tests {
gotValue, gotOccurred := tt.event.GetOccurrence(tt.now)
if gotValue != tt.wantValue {
t.Errorf("Test %d: GetOccurrence() gotValue = %v, want %v", i, gotValue, tt.wantValue)
}
if gotOccurred != tt.wantOccurred {
t.Errorf("Test %d: GetOccurrence() gotOccurred = %v, want %v", i, gotOccurred, tt.wantOccurred)
}
}
}
func TestGetRecipients(t *testing.T) {
tests := []struct {
name string
event Event
want []util.EmailRecipient
}{
{
name: "no recipients - use default email",
event: Event{
Name: "Test Event",
Recipients: []Recipient{},
},
want: []util.EmailRecipient{defaultRecipient},
},
{
name: "single recipient with name and email",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Name: "John Doe", Email: "john@example.com"},
},
},
want: []util.EmailRecipient{{Email: "john@example.com", FirstName: "John", LastName: "Doe"}},
},
{
name: "single recipient with email only",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Email: "jane@example.com"},
},
},
want: []util.EmailRecipient{{Email: "jane@example.com"}},
},
{
name: "multiple recipients",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Name: "John Doe", Email: "john@example.com"},
{Email: "jane@example.com"},
{Name: "Bob Smith", Email: "bob@example.com"},
},
},
want: []util.EmailRecipient{
{Email: "john@example.com", FirstName: "John", LastName: "Doe"},
{Email: "jane@example.com"},
{Email: "bob@example.com", FirstName: "Bob", LastName: "Smith"},
},
},
{
name: "recipient with empty email - should be ignored",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Name: "John Doe Smith", Email: "john@example.com"},
{Name: "Invalid", Email: ""},
{Email: "jane@example.com"},
},
},
want: []util.EmailRecipient{
{Email: "john@example.com", FirstName: "John", LastName: "Doe Smith"},
{Email: "jane@example.com"},
},
},
{
name: "all recipients invalid - use default email",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Name: "Invalid1", Email: ""},
{Name: "Invalid2", Email: " "},
},
},
want: []util.EmailRecipient{defaultRecipient},
},
{
name: "recipient with whitespace in name and email",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Name: " John Doe ", Email: " john@example.com "},
},
},
want: []util.EmailRecipient{{Email: "john@example.com", FirstName: "John", LastName: "Doe"}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.event.GetRecipients(defaultRecipient, defaultMaxRecipients)
if len(got) != len(tt.want) {
t.Errorf("GetRecipients() length = %d, want %d", len(got), len(tt.want))
return
}
for i, recipient := range got {
if recipient.Email != tt.want[i].Email {
t.Errorf("GetRecipients()[%d].Email = %s, want %s", i, recipient.Email, tt.want[i].Email)
}
if recipient.FirstName != tt.want[i].FirstName {
t.Errorf("GetRecipients()[%d].FirstName = %s, want %s", i, recipient.FirstName, tt.want[i].FirstName)
}
}
})
}
}
func TestGetRecipientsMaxLimit(t *testing.T) {
tests := []struct {
name string
event Event
maxRecipients int
wantCount int
}{
{
name: "within limit - 2 recipients with max 10",
event: Event{
Recipients: []Recipient{
{Email: "recipient1@example.com"},
{Email: "recipient2@example.com"},
},
},
maxRecipients: 10,
wantCount: 2,
},
{
name: "at limit - 2 recipients with max 2",
event: Event{
Recipients: []Recipient{
{Email: "recipient1@example.com"},
{Email: "recipient2@example.com"},
},
},
maxRecipients: 2,
wantCount: 2,
},
{
name: "exceeds limit - 5 recipients with max 3",
event: Event{
Name: "Test Event",
Recipients: []Recipient{
{Email: "recipient1@example.com"},
{Email: "recipient2@example.com"},
{Email: "recipient3@example.com"},
{Email: "recipient4@example.com"},
{Email: "recipient5@example.com"},
},
},
maxRecipients: 3,
wantCount: 3, // Only first 3 should be returned
},
{
name: "no recipients - fallback used",
event: Event{},
maxRecipients: 10,
wantCount: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.event.GetRecipients(defaultRecipient, tt.maxRecipients)
if len(got) != tt.wantCount {
t.Errorf("GetRecipients() returned %d recipients, want %d", len(got), tt.wantCount)
}
})
}
}
func TestAnniversaryContact(t *testing.T) {
tests := []struct {
name string
event Event
want string
}{
{
name: "both emails present",
event: Event{
Name: "John",
Email: " john@example.com",
PartnerName: "Jane",
PartnerEmail: " jane@example.com ",
},
want: "You can reach them at john@example.com and jane@example.com respectively.",
},
{
name: "only event email present",
event: Event{
Name: "John",
Email: " john@example.com",
PartnerName: "Jane",
PartnerEmail: "",
},
want: "You can reach John at john@example.com.",
},
{
name: "only partner email present",
event: Event{
Name: "John",
Email: "",
PartnerName: "Jane",
PartnerEmail: "jane@example.com ",
},
want: "You can reach Jane at jane@example.com.",
},
{
name: "no emails present",
event: Event{
Name: "John",
Email: "",
PartnerName: "Jane",
PartnerEmail: "",
},
want: "",
},
{
name: "empty strings for emails",
event: Event{
Name: "John",
Email: " ",
PartnerName: "Jane",
PartnerEmail: " ",
},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.event.AnniversaryContact()
if got != tt.want {
t.Errorf("AnniversaryContact() = %q, want %q", got, tt.want)
}
})
}
}
func TestEventValidate(t *testing.T) {
tests := []struct {
name string
event Event
wantValid bool
}{
// Valid events
{
name: "valid anniversary",
event: Event{
Type: "anniversary",
Name: "John",
PartnerName: "Jane",
Day: EventDay(15),
Month: 6,
Year: 2020,
},
wantValid: true,
},
{
name: "valid birthday",
event: Event{
Type: "birthday",
Name: "Alice",
Day: EventDay(1),
Month: 1,
},
wantValid: true,
},
{
name: "valid yearly",
event: Event{
Type: "yearly",
Name: "Company Anniversary",
Day: EventDay(31),
Month: 12,
},
wantValid: true,
},
{
name: "valid monthly",
event: Event{
Type: "monthly",
Name: "Monthly Review",
Day: EventDay(15),
},
wantValid: true,
},
{
name: "valid weekly on Sunday",
event: Event{
Type: "weekly",
Name: "Weekly Meeting",
Day: EventDay(0),
},
wantValid: true,
},
{
name: "valid weekly on Saturday",
event: Event{
Type: "weekly",
Name: "Weekly Meeting",
Day: EventDay(6),
},
wantValid: true,
},
// Invalid events - empty name
{
name: "empty name",
event: Event{
Type: "birthday",
Name: "",
Day: EventDay(15),
Month: 6,
},
wantValid: false,
},
{
name: "whitespace only name",
event: Event{
Type: "birthday",
Name: " \t\n ",
Day: EventDay(15),
Month: 6,
},
wantValid: false,
},
// Invalid events - anniversary specific validation
{
name: "anniversary with empty partner name",
event: Event{
Type: "anniversary",
Name: "John",
PartnerName: "",
Day: EventDay(15),
Month: 6,
},
wantValid: false,
},
{
name: "anniversary with whitespace only partner name",
event: Event{
Type: "anniversary",
Name: "John",
PartnerName: " \t\n ",
Day: EventDay(15),
Month: 6,
},
wantValid: false,
},
// Invalid events - bad day values for anniversary/birthday/yearly
{
name: "anniversary with day 0",
event: Event{
Type: "anniversary",
Name: "Test",
PartnerName: "Partner",
Day: EventDay(0),
Month: 6,
},
wantValid: false,
},
{
name: "birthday with day 32",
event: Event{
Type: "birthday",
Name: "Test",
Day: EventDay(32),
Month: 6,
},
wantValid: false,
},
// Invalid events - bad month values for anniversary/birthday/yearly
{
name: "anniversary with month 0",
event: Event{
Type: "anniversary",
Name: "Test",
PartnerName: "Partner",
Day: EventDay(15),
Month: 0,
},
wantValid: false,
},
{
name: "yearly with month 13",
event: Event{
Type: "yearly",
Name: "Test",
Day: EventDay(15),
Month: 13,
},
wantValid: false,
},
// Invalid events - bad day values for monthly
{
name: "monthly with day 0",
event: Event{
Type: "monthly",
Name: "Test",
Day: EventDay(0),
},
wantValid: false,
},
{
name: "monthly with day 32",
event: Event{
Type: "monthly",
Name: "Test",
Day: EventDay(32),
},
wantValid: false,
},
// Invalid events - unknown type
{
name: "unknown event type",
event: Event{
Type: "unknown",
Name: "Test",
Day: EventDay(15),
},
wantValid: false,
},
// Invalid events - negative year
{
name: "birthday with large negative year",
event: Event{
Type: "birthday",
Name: "Test",
Day: EventDay(15),
Month: 6,
Year: -9999,
},
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.event.Validate()
if tt.wantValid {
if err != nil {
t.Errorf("Validate() unexpected error = %v", err)
}
} else {
if err == nil {
t.Errorf("Validate() error = nil, want non-empty error")
} else if err.Error() == "" {
t.Errorf("Validate() error message is empty, want non-empty error message")
}
}
})
}
}
func TestIsOccurring(t *testing.T) {
tests := []struct {
name string
event Event
now time.Time
reminder Reminder
wantOccurring bool
wantWhen string
wantError bool
}{
// Same day and days before occurring tests
{
name: "anniversary same day",
event: Event{
Type: "anniversary",
Name: "Alice",
PartnerName: "Bob",
Day: EventDay(15),
Month: 6,
},
now: time.Date(2025, 6, 15, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "birthday 1 day before",
event: Event{
Type: "birthday",
Name: "John",
Day: EventDay(25),
Month: 12,
},
now: time.Date(2025, 12, 24, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "days before",
Days: 1,
},
wantOccurring: true,
wantWhen: "tomorrow (Thu Dec 25)",
wantError: false,
},
{
name: "birthday 42 days before (should fire)",
event: Event{
Type: "birthday",
Name: "Test Person",
Day: EventDay(14),
Month: 5,
Year: 1948,
},
now: time.Date(2011, 4, 2, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "days before",
Days: 42,
},
wantOccurring: true,
wantWhen: "in 42 days (Sat May 14)",
wantError: false,
},
{
name: "birthday 42 days before (should not fire)",
event: Event{
Type: "birthday",
Name: "Test Person",
Day: EventDay(14),
Month: 5,
Year: 1948,
},
now: time.Date(2011, 4, 1, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "days before",
Days: 42,
},
wantOccurring: false,
wantWhen: "in 42 days (Fri May 13)",
wantError: false,
},
{
name: "yearly same day",
event: Event{
Type: "yearly",
Name: "Annual Meeting",
Day: EventDay(10),
Month: 3,
},
now: time.Date(2025, 3, 10, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "monthly 2 days before",
event: Event{
Type: "monthly",
Name: "Monthly Report",
Day: EventDay(15),
},
now: time.Date(2025, 9, 13, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "days before",
Days: 2,
},
wantOccurring: true,
wantWhen: "in 2 days (Mon Sep 15)",
wantError: false,
},
{
name: "weekly 1 day before",
event: Event{
Type: "weekly",
Name: "Team Meeting",
Day: EventDay(1), // Monday
},
now: time.Date(2025, 9, 14, 10, 0, 0, 0, time.UTC), // Sunday
reminder: Reminder{
Type: "days before",
Days: 1,
},
wantOccurring: true,
wantWhen: "tomorrow (Mon Sep 15)",
wantError: false,
},
{
name: "weekly same day - Sunday",
event: Event{
Type: "weekly",
Name: "Sunday Service",
Day: EventDay(0), // Sunday
},
now: time.Date(2025, 9, 14, 10, 0, 0, 0, time.UTC), // Sunday
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
// Non-occurring tests
{
name: "birthday different day",
event: Event{
Type: "birthday",
Name: "Jane",
Day: EventDay(25),
Month: 12,
},
now: time.Date(2025, 12, 20, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "same day",
},
wantOccurring: false,
wantWhen: "today",
wantError: false,
},
{
name: "monthly different day",
event: Event{
Type: "monthly",
Name: "TPS Report",
Day: EventDay(15),
},
now: time.Date(2025, 9, 10, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "same day",
},
wantOccurring: false,
wantWhen: "today",
wantError: false,
},
{
name: "weekly different day",
event: Event{
Type: "weekly",
Name: "Garbage",
Day: EventDay(1), // Monday
},
now: time.Date(2025, 9, 16, 10, 0, 0, 0, time.UTC), // Tuesday
reminder: Reminder{
Type: "same day",
},
wantOccurring: false,
wantWhen: "today",
wantError: false,
},
// Edge cases
{
name: "monthly last day of February non-leap year",
event: Event{
Type: "monthly",
Name: "End of Month Report",
Day: EventDay(31), // Requested on 31st but February only has 28 days
},
now: time.Date(2025, 2, 28, 10, 0, 0, 0, time.UTC), // Last day of February in non-leap year
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "leap year February 29th birthday on Feb 28th",
event: Event{
Type: "birthday",
Name: "Leap Year Baby",
Day: EventDay(29),
Month: 2,
Year: 2024,
},
now: time.Date(2025, 2, 28, 10, 0, 0, 0, time.UTC), // 2025 is not a leap year
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "leap year February 29th birthday on actual Feb 29th",
event: Event{
Type: "birthday",
Name: "Leap Year Baby",
Day: EventDay(29),
Month: 2,
Year: 2024,
},
now: time.Date(2028, 2, 29, 10, 0, 0, 0, time.UTC), // 2028 is a leap year
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "anniversary Feb 29 celebrated on Feb 28 in non-leap year",
event: Event{
Type: "anniversary",
Name: "Alice",
PartnerName: "Bob",
Day: EventDay(29),
Month: 2,
Year: 2000, // leap year base
},
now: time.Date(2025, 2, 28, 10, 0, 0, 0, time.UTC), // Non-leap year Feb 28
reminder: Reminder{Type: "same day"},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
// Error cases
{
name: "invalid reminder type",
event: Event{
Type: "birthday",
Name: "Robert",
Day: EventDay(25),
Month: 12,
},
now: time.Date(2025, 12, 25, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "invalid",
},
wantOccurring: false,
wantWhen: "",
wantError: true,
},
{
name: "invalid event type",
event: Event{
Type: "invalid",
Name: "Invalid Event",
Day: EventDay(25),
},
now: time.Date(2025, 12, 25, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "same day",
},
wantOccurring: false,
wantWhen: "today",
wantError: true,
},
{
name: "days before with zero days",
event: Event{
Type: "birthday",
Name: "Alice",
Day: EventDay(25),
Month: 12,
},
now: time.Date(2025, 12, 25, 10, 0, 0, 0, time.UTC),
reminder: Reminder{
Type: "days before",
Days: 0,
},
wantOccurring: false,
wantWhen: "",
wantError: true,
},
// Additional weekly edge/fallback cases
{
name: "weekly day 7 treated as Sunday (same day reminder)",
event: Event{
Type: "weekly",
Name: "Overflow Weekly",
Day: EventDay(7), // out of normal range; should default to Sunday
},
now: time.Date(2025, 9, 14, 10, 0, 0, 0, time.UTC), // Sunday
reminder: Reminder{
Type: "same day",
},
wantOccurring: true,
wantWhen: "today",
wantError: false,
},
{
name: "weekly negative day treated as Sunday (days before reminder)",
event: Event{
Type: "weekly",
Name: "Negative Weekly",
Day: EventDay(-1), // negative; should default to Sunday
},
now: time.Date(2025, 9, 13, 10, 0, 0, 0, time.UTC), // Saturday
reminder: Reminder{
Type: "days before",
Days: 1,
},
wantOccurring: true, // Saturday + 1 day = Sunday (defaulted)
wantWhen: "tomorrow (Sun Sep 14)",
wantError: false,
},
{
name: "birthday with days before reminder crossing year and month boundaries in leap and non-leap years",
event: Event{
Type: "birthday",
Name: "John",
Day: EventDay(2),
Month: 3,
Year: 2000,
},
now: time.Date(2023, 12, 29, 10, 0, 0, 0, time.UTC), // 2023 is a non-leap year, 2024 is a leap year
reminder: Reminder{
Type: "days before",
Days: 64, // 33 days before Jan 31st, 29 more days before Feb 29th, 2 more days before March 2nd
},
wantOccurring: true,
wantWhen: "in 64 days (Sat Mar 2)",
wantError: false,
},
{
name: "monthly event on 31st crossing a month boundary",
event: Event{
Type: "monthly",
Name: "Monthly 31st Event",
Day: EventDay(31),
},
now: time.Date(2025, 2, 25, 10, 0, 0, 0, time.UTC), // non-leap year
reminder: Reminder{
Type: "days before",
Days: 34, // 3 days before Feb 28th, 31 more days before March 31st
},
wantOccurring: true,
wantWhen: "in 34 days (Mon Mar 31)",
wantError: false,
},
{
name: "yearly event with days before reminder crossing a month boundary on a leap year",
event: Event{
Type: "yearly",
Name: "Test Event",
Day: EventDay(31),
Month: 3, // March
Year: 2020,
},
now: time.Date(2024, 2, 28, 10, 0, 0, 0, time.UTC), // leap year
reminder: Reminder{
Type: "days before",
Days: 31,
},
wantOccurring: false, // Feb 28 + 31 days = March 30th due to leap year
wantWhen: "in 31 days (Sat Mar 30)",
wantError: false,
},
{
name: "monthly event on 31st with days before instead of same-day",
event: Event{
Type: "monthly",
Name: "Monthly Report",
Day: EventDay(31),
},
now: time.Date(2025, 4, 30, 10, 0, 0, 0, time.UTC), // last day of the month
reminder: Reminder{
Type: "days before",
Days: 1,
},
wantOccurring: false,
wantWhen: "tomorrow (Thu May 1)",
wantError: false,
},
{
name: "monthly event on 31st with days before on leap year",
event: Event{
Type: "monthly",
Name: "End of Month Report",
Day: EventDay(31),
},
now: time.Date(2024, 1, 29, 10, 0, 0, 0, time.UTC), // leap year
reminder: Reminder{
Type: "days before",
Days: 31, // 2 days before Jan 31st, 29 more days before Feb 29th
},
wantOccurring: true, // Feb 29th is the last day of the month
wantWhen: "in 31 days (Thu Feb 29)",
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
occurring, when, err := tt.event.IsOccurring(tt.now, tt.reminder)
if occurring != tt.wantOccurring {
t.Errorf("IsOccurring() occurring = %v, want %v", occurring, tt.wantOccurring)
}
if when != tt.wantWhen {
t.Errorf("IsOccurring() when = %q, want %q", when, tt.wantWhen)
}
if (err != nil) != tt.wantError {
t.Errorf("IsOccurring() error = %v, wantError %v", err, tt.wantError)
}
})
}
}
func TestReminderMessage(t *testing.T) {
defaultNow := time.Date(2025, 4, 15, 10, 0, 0, 0, time.UTC)
tests := []struct {
name string
event Event
occurringWhen string
now time.Time // Zero value means use defaultNow
wantMessage string
wantSubject string
wantError bool
}{
{
name: "anniversary comprehensive - occurrence, special name, both contacts",
event: Event{
Type: "anniversary",
Name: " Alice ", // Test whitespace trimming
PartnerName: "Bob",
Email: "alice@test.com",
PartnerEmail: "bob@test.com",
Year: 2000,
Month: 4,
Day: EventDay(13),
},
occurringWhen: "today",
wantMessage: "I just want to remind you that the 25th anniversary (Silver) of Alice and Bob is today.\n\nYou can reach them at alice@test.com and bob@test.com respectively.",
wantSubject: "25th anniversary of Alice and Bob",
wantError: false,
},
{
name: "anniversary without occurrence and partial contact info",
event: Event{
Type: "anniversary",
Name: "Charlie",
PartnerName: "Diana",
Email: "charlie@test.com", // Only one contact
},
occurringWhen: "tomorrow (Wed Apr 16)",
wantMessage: "I just want to remind you that the anniversary of Charlie and Diana is tomorrow (Wed Apr 16).\n\nYou can reach Charlie at charlie@test.com.",
wantSubject: "Anniversary of Charlie and Diana",
wantError: false,
},
{
name: "birthday comprehensive - age calculation before birthday in year, email, today timing",
event: Event{
Type: "birthday",
Name: "John ",
Email: "john@test.com",
Year: 2000,
Month: 9,
Day: EventDay(13),
},
occurringWhen: "today",
// defaultNow is April 15 2025, which is before the Sept 13 birthday, so John is not 25 yet
wantMessage: "I just want to remind you that John (john@test.com) is turning 24 today.",
wantSubject: "John is now 24",
wantError: false,
},
{
name: "birthday after birthday in year with today timing uses new age in subject",
event: Event{
Type: "birthday",
Name: "John",
Email: "john@test.com",
Year: 2000,
Month: 9,
Day: EventDay(13),
},
occurringWhen: "today",
now: time.Date(2025, 9, 14, 10, 0, 0, 0, time.UTC), // After/birthday date in the same year
wantMessage: "I just want to remind you that John (john@test.com) is turning 25 today.",
wantSubject: "John is now 25",
wantError: false,
},
{
name: "birthday without age and non-today timing",
event: Event{
Type: "birthday",
Name: "Jane",
},
occurringWhen: "in 2 days (Thu Apr 17)",
wantMessage: "I just want to remind you that Jane is getting one year older in 2 days (Thu Apr 17).",
wantSubject: "Jane's birthday",
wantError: false,
},
{
name: "yearly comprehensive - occurrence calculation",
event: Event{
Type: "yearly",
Name: "Company Founded",
Year: 2020,
Month: 4,
Day: EventDay(13),
},
occurringWhen: "today",
wantMessage: "I just want to remind you of the following event today:\n\n6th Company Founded",
wantSubject: "Company Founded",
wantError: false,
},
{
name: "yearly without occurrence",
event: Event{
Type: "yearly",
Name: "Memorial Day",
Month: 5,
Day: EventDay(30),
},
occurringWhen: "tomorrow (Wed Apr 16)",
wantMessage: "I just want to remind you of the following event tomorrow (Wed Apr 16):\n\nMemorial Day",
wantSubject: "Memorial Day",
wantError: false,
},
{
name: "monthly event",
event: Event{
Type: "monthly",
Name: " Team Meeting",
Day: EventDay(15),
},
occurringWhen: "today",
wantMessage: "I just want to remind you of the following event today:\n\nTeam Meeting",
wantSubject: "Team Meeting",
wantError: false,
},
{
name: "weekly event",
event: Event{
Type: "weekly",
Name: "Garbage Collection ",
Day: EventDay(1),
},
occurringWhen: "tomorrow (Wed Apr 16)",
wantMessage: "I just want to remind you of the following event tomorrow (Wed Apr 16):\n\nGarbage Collection",
wantSubject: "Garbage Collection",
wantError: false,
},
// Edge cases for date handling
{
name: "birthday Feb 29th in non-leap year",
event: Event{
Type: "birthday",
Name: "Leap Year Baby",
Year: 2000, // Born in leap year
Month: 2,
Day: EventDay(29),
},
occurringWhen: "today",
now: time.Date(2025, 2, 28, 10, 0, 0, 0, time.UTC), // Feb 28th in non-leap year 2025
wantMessage: "I just want to remind you that Leap Year Baby is turning 25 today.", // 2025 is non-leap year, so Feb 29th becomes Feb 28th
wantSubject: "Leap Year Baby is now 25",
wantError: false,
},
{
name: "monthly event 31st in 30-day month",
event: Event{
Type: "monthly",
Name: "End of Month Report",
Day: EventDay(31), // Set to 31st but testing in a 30-day month
},
occurringWhen: "today",
now: time.Date(2025, 9, 30, 10, 0, 0, 0, time.UTC), // Sept 30th (last day of 30-day month)
wantMessage: "I just want to remind you of the following event today:\n\nEnd of Month Report",
wantSubject: "End of Month Report",
wantError: false,
},
// Error case
{
name: "unknown event type",
event: Event{
Type: "invalid",
Name: "Test Event",
},
occurringWhen: "today",
wantMessage: "",
wantSubject: "",
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testNow := defaultNow
if !tt.now.IsZero() {
testNow = tt.now
}
gotMessage, gotSubject, err := tt.event.ReminderMessage(testNow, tt.occurringWhen)
if (err != nil) != tt.wantError {
t.Errorf("ReminderMessage() error = %v, wantError %v", err, tt.wantError)
return
}
if err != nil {
return // Don't check message/subject if we expected an error
}
if gotMessage != tt.wantMessage {
t.Errorf("ReminderMessage() gotMessage = %q, want %q", gotMessage, tt.wantMessage)
}
if gotSubject != tt.wantSubject {
t.Errorf("ReminderMessage() gotSubject = %q, want %q", gotSubject, tt.wantSubject)
}
})
}
}
func TestEventDayUnmarshalText(t *testing.T) {
tests := []struct {
input string
want EventDay
}{
{"0", EventDay(0)},
{"1", EventDay(1)},
{"15", EventDay(15)},
{"32", EventDay(32)},
{"100", EventDay(100)},
// Full day names
{"Sunday", EventDay(0)},
{"monday", EventDay(1)},
{"Tuesday ", EventDay(2)},
{"Wednesday", EventDay(3)},
{" Thursday ", EventDay(4)},
{"Friday", EventDay(5)},
{"SATURDAY", EventDay(6)},
// Common abbreviations
{"Sun", EventDay(0)},
{"Mon", EventDay(1)},
{"Tue", EventDay(2)},
{" Wed ", EventDay(3)},
{"Thu", EventDay(4)},
{"Fri", EventDay(5)},
{"Sat", EventDay(6)},
// Invalid inputs
{"invalid", EventDay(-1)},
{"-1", EventDay(-1)},
{"", EventDay(-1)},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
var ed EventDay
err := ed.UnmarshalText([]byte(tt.input))
if err != nil && (ed != -1 || tt.want != -1) {
t.Errorf("EventDay.UnmarshalText(%q) unexpected error: %v", tt.input, err)
}
if ed != tt.want {
t.Errorf("EventDay.UnmarshalText(%q) = %d, want %d", tt.input, ed, tt.want)
}
})
}
}
func TestIsSameDay(t *testing.T) {
tests := []struct {
name string
now time.Time
originalDay EventDay
originalMonth time.Month
want bool
}{
{
name: "exact match - regular date",
now: time.Date(2023, time.March, 15, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(15),
originalMonth: time.March,
want: true,
},
{
name: "different day same month",
now: time.Date(2023, time.March, 16, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(15),
originalMonth: time.March,
want: false,
},
{
name: "same day different month",
now: time.Date(2023, time.April, 15, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(15),
originalMonth: time.March,
want: false,
},
{
name: "Feb 29 birthday on Feb 28 in non-leap year",
now: time.Date(2023, time.February, 28, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(29),
originalMonth: time.February,
want: true,
},
{
name: "Feb 29 birthday on Feb 29 in leap year",
now: time.Date(2024, time.February, 29, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(29),
originalMonth: time.February,
want: true,
},
{
name: "Feb 29 birthday on Feb 28 in leap year (should not match)",
now: time.Date(2024, time.February, 28, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(29),
originalMonth: time.February,
want: false,
},
{
name: "regular Feb 28 birthday on Feb 28 in non-leap year",
now: time.Date(2023, time.February, 28, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(28),
originalMonth: time.February,
want: true,
},
{
name: "regular Feb 28 birthday on Feb 28 in leap year",
now: time.Date(2024, time.February, 28, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(28),
originalMonth: time.February,
want: true,
},
{
name: "Feb 27 should not match Feb 29 in non-leap year",
now: time.Date(2023, time.February, 27, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(29),
originalMonth: time.February,
want: false,
},
{
name: "March 1 should not match Feb 29 in non-leap year",
now: time.Date(2023, time.March, 1, 10, 30, 0, 0, time.UTC),
originalDay: EventDay(29),
originalMonth: time.February,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event := Event{
Day: tt.originalDay,
Month: tt.originalMonth,
}
result := event.IsSameDay(tt.now)
if result != tt.want {
t.Errorf("Event{Day: %d, Month: %v}.IsSameDay(%v) = %v, want %v",
tt.originalDay, tt.originalMonth, tt.now, result, tt.want)
}
})
}
}
func TestEventDayDayOfTheWeek(t *testing.T) {
tests := []struct {
day EventDay
want time.Weekday
}{
{EventDay(1), time.Monday},
{EventDay(2), time.Tuesday},
{EventDay(6), time.Saturday},
// Sunday cases (0 and 7 should both become Sunday)
{EventDay(0), time.Sunday}, // already 0 in Go
{EventDay(7), time.Sunday}, // cron-style
// Out of range values should default to Sunday
{EventDay(-1), time.Sunday},
{EventDay(8), time.Sunday},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("day_%d", tt.day), func(t *testing.T) {
got := tt.day.DayOfTheWeek()
if got != tt.want {
t.Errorf("EventDay(%d).DayOfTheWeek() = %v, want %v", tt.day, got, tt.want)
}
})
}
}
func TestEventTypeUnmarshalText(t *testing.T) {
tests := []struct {
input string
want EventType
}{
{"anniversary", EventTypeAnniversary},
{"birthday", EventTypeBirthday},
{"yearly", EventTypeYearly},
{"monthly", EventTypeMonthly},
{"weekly", EventTypeWeekly},
{"BIRTHDAY", EventTypeBirthday},
{" Anniversary ", EventTypeAnniversary},
{"unknown", EventType("unknown")},
{"", EventType("")},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
var et EventType
err := et.UnmarshalText([]byte(tt.input))
if err != nil {
t.Errorf("EventType.UnmarshalText(%q) unexpected error: %v", tt.input, err)
}
if et != tt.want {
t.Errorf("EventType.UnmarshalText(%q) = %q, want %q", tt.input, et, tt.want)
}
})
}
}
func TestAnniversaryName(t *testing.T) {
tests := []struct {
occurrence int
want string
}{
// Test a few representative values
{1, "Paper"},
{25, "Silver"},
{50, "Gold"},
{70, "Platinum"},
// Test degenerate cases
{0, ""},
{-1, ""},
{16, ""}, // year without special name
{100, ""}, // year without special name
}
for _, tt := range tests {
got := anniversaryName(tt.occurrence)
if got != tt.want {
t.Errorf("anniversaryName(%d) = %q, want %q", tt.occurrence, got, tt.want)
}
}
}
func TestFormatOrdinal(t *testing.T) {
tests := []struct {
input int
want string
}{
// Test the special cases for 11th, 12th, 13th
{11, "11th"},
{12, "12th"},
{13, "13th"},
{111, "111th"},
{112, "112th"},
{113, "113th"},
// Test 1st endings
{1, "1st"},
{21, "21st"},
{31, "31st"},
{101, "101st"},
{121, "121st"},
// Test 2nd endings
{2, "2nd"},
{22, "22nd"},
{32, "32nd"},
{102, "102nd"},
{122, "122nd"},
// Test 3rd endings
{3, "3rd"},
{23, "23rd"},
{33, "33rd"},
{103, "103rd"},
{123, "123rd"},
// Test th endings for other numbers
{0, "0th"},
{4, "4th"},
{5, "5th"},
{6, "6th"},
{7, "7th"},
{8, "8th"},
{9, "9th"},
{10, "10th"},
{14, "14th"},
{20, "20th"},
{28, "28th"},
{100, "100th"},
{109, "109th"},
{1000, "1000th"},
}
for _, tt := range tests {
result := formatOrdinal(tt.input)
if result != tt.want {
t.Errorf("formatOrdinal(%d) = %s; want %s", tt.input, result, tt.want)
}
}
}
email-reminder-1.0.1/internal/events/recipient.go 0000664 0000000 0000000 00000003172 15122360213 0022032 0 ustar 00root root 0000000 0000000 // # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package events
import (
"encoding/xml"
"log"
"strings"
"launchpad.net/email-reminder/internal/util"
)
type Recipient struct {
XMLName xml.Name `xml:"recipient"`
Name string `xml:"name,attr,omitempty"`
Email string `xml:"email,attr"`
}
// Splits Name into FirstName/LastName when needed
func (r Recipient) ToEmailRecipient() util.EmailRecipient {
email := strings.TrimSpace(r.Email)
if err := util.ValidateEmail(email); err != nil {
log.Printf("Rejecting invalid email '%s': %s\n", email, err)
email = ""
}
first := ""
last := ""
name := strings.TrimSpace(r.Name)
if name != "" && len(name) < 255 { // ignore excessively long names
parts := strings.Fields(name)
if len(parts) > 0 {
first = parts[0]
}
if len(parts) > 1 {
last = strings.Join(parts[1:], " ")
}
}
return util.EmailRecipient{Email: email, FirstName: first, LastName: last}
}
email-reminder-1.0.1/internal/events/recipient_test.go 0000664 0000000 0000000 00000005325 15122360213 0023073 0 ustar 00root root 0000000 0000000 package events
import (
"testing"
"launchpad.net/email-reminder/internal/util"
)
func TestRecipientToEmailRecipient(t *testing.T) {
tests := []struct {
name string
recipient Recipient
want util.EmailRecipient
}{
{
name: "recipient with first and last name",
recipient: Recipient{
Name: "John Doe",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "recipient with three-part name",
recipient: Recipient{
Name: "John Doe Smith",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe Smith",
},
},
{
name: "recipient with single name",
recipient: Recipient{
Name: "John",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "",
},
},
{
name: "recipient with email only",
recipient: Recipient{
Name: "",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "",
LastName: "",
},
},
{
name: "recipient with invalid email",
recipient: Recipient{
Name: "John Doe",
Email: "john@",
},
want: util.EmailRecipient{
Email: "",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "recipient with whitespace in name",
recipient: Recipient{
Name: " John Doe ",
Email: " john@example.com ",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "recipient with whitespace-only name",
recipient: Recipient{
Name: " ",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "",
LastName: "",
},
},
{
name: "recipient with multiple spaces between names",
recipient: Recipient{
Name: "John Doe Smith",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe Smith",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.recipient.ToEmailRecipient()
if got.Email != tt.want.Email {
t.Errorf("ToEmailRecipient().Email = %q, want %q", got.Email, tt.want.Email)
}
if got.FirstName != tt.want.FirstName {
t.Errorf("ToEmailRecipient().FirstName = %q, want %q", got.FirstName, tt.want.FirstName)
}
if got.LastName != tt.want.LastName {
t.Errorf("ToEmailRecipient().LastName = %q, want %q", got.LastName, tt.want.LastName)
}
})
}
}
email-reminder-1.0.1/internal/events/reminder.go 0000664 0000000 0000000 00000002613 15122360213 0021654 0 ustar 00root root 0000000 0000000 // # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package events
import (
"encoding/xml"
"strings"
)
type ReminderType string
const (
ReminderTypeSameDay ReminderType = "same day"
ReminderTypeDaysBefore ReminderType = "days before"
)
func (rt *ReminderType) UnmarshalText(text []byte) error {
v := strings.TrimSpace(strings.ToLower(string(text)))
switch v {
case string(ReminderTypeSameDay):
*rt = ReminderTypeSameDay
case string(ReminderTypeDaysBefore):
*rt = ReminderTypeDaysBefore
default:
*rt = ReminderType(v)
}
return nil
}
type Reminder struct {
XMLName xml.Name `xml:"reminder"`
Type ReminderType `xml:"type,attr"`
Days int `xml:",chardata"`
}
email-reminder-1.0.1/internal/events/reminder_test.go 0000664 0000000 0000000 00000001421 15122360213 0022707 0 ustar 00root root 0000000 0000000 package events
import (
"testing"
)
func TestReminderTypeUnmarshalText(t *testing.T) {
tests := []struct {
input string
want ReminderType
}{
{"same day", ReminderTypeSameDay},
{"SAME DAY", ReminderTypeSameDay},
{" same day ", ReminderTypeSameDay},
{"days before", ReminderTypeDaysBefore},
{"DAYS BEFORE", ReminderTypeDaysBefore},
{"unknown", ReminderType("unknown")},
{"", ReminderType("")},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
var rt ReminderType
err := rt.UnmarshalText([]byte(tt.input))
if err != nil {
t.Errorf("ReminderType.UnmarshalText(%q) unexpected error: %v", tt.input, err)
}
if rt != tt.want {
t.Errorf("ReminderType.UnmarshalText(%q) = %q, want %q", tt.input, rt, tt.want)
}
})
}
}
email-reminder-1.0.1/internal/events/user.go 0000664 0000000 0000000 00000003602 15122360213 0021024 0 ustar 00root root 0000000 0000000 // # Copyright (C) 2025 Francois Marier
//
// Email-Reminder is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of the
// License, or (at your option) any later version.
//
// Email-Reminder is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Email-Reminder; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.
package events
import (
"encoding/xml"
"fmt"
"log"
"strings"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/util"
)
type User struct {
XMLName xml.Name `xml:"email-reminder_user"`
FirstName string `xml:"first_name,omitempty"`
LastName string `xml:"last_name,omitempty"`
Email string `xml:"email"`
Events []Event `xml:"events>event,omitempty"`
}
func (u User) ToEmailRecipient() util.EmailRecipient {
email := strings.TrimSpace(u.Email)
if err := util.ValidateEmail(email); err != nil {
log.Printf("Rejecting invalid email '%s': %s\n", email, err)
email = ""
}
return util.EmailRecipient{Email: email, FirstName: strings.TrimSpace(u.FirstName), LastName: strings.TrimSpace(u.LastName)}
}
func LoadUserEvents(filename string, contents []byte, conf config.Config) (User, error) {
v := User{}
err := xml.Unmarshal(contents, &v)
if err != nil {
return v, fmt.Errorf("error parsing XML: %w", err)
}
if len(v.Events) > conf.MaxEventsPerUser {
return v, fmt.Errorf("too many events (%d), maximum allowed is %d", len(v.Events), conf.MaxEventsPerUser)
}
return v, nil
}
email-reminder-1.0.1/internal/events/user_test.go 0000664 0000000 0000000 00000026360 15122360213 0022071 0 ustar 00root root 0000000 0000000 package events
import (
"testing"
"launchpad.net/email-reminder/internal/config"
"launchpad.net/email-reminder/internal/util"
)
func TestUserToEmailRecipient(t *testing.T) {
tests := []struct {
name string
user User
want util.EmailRecipient
}{
{
name: "user with all fields populated",
user: User{
FirstName: "John",
LastName: "Doe",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "user with email only",
user: User{
FirstName: "",
LastName: "",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "",
LastName: "",
},
},
{
name: "user with first name only",
user: User{
FirstName: "John",
LastName: "",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "",
},
},
{
name: "user with last name only",
user: User{
FirstName: "",
LastName: "Doe",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "",
LastName: "Doe",
},
},
{
name: "user with whitespace in all fields",
user: User{
FirstName: " John ",
LastName: " Doe ",
Email: " john@example.com ",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "user with whitespace-only first name",
user: User{
FirstName: " ",
LastName: "Doe",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "",
LastName: "Doe",
},
},
{
name: "user with whitespace-only last name",
user: User{
FirstName: "John",
LastName: " ",
Email: "john@example.com",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "",
},
},
{
name: "user with whitespace-only email",
user: User{
FirstName: "John",
LastName: "Doe",
Email: " ",
},
want: util.EmailRecipient{
Email: "",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "user with invalid email",
user: User{
FirstName: "John",
LastName: "Doe",
Email: "john@",
},
want: util.EmailRecipient{
Email: "",
FirstName: "John",
LastName: "Doe",
},
},
{
name: "user with tabs and newlines",
user: User{
FirstName: "\t\nJohn\n\t",
LastName: "\tDoe\n",
Email: "\njohn@example.com\t",
},
want: util.EmailRecipient{
Email: "john@example.com",
FirstName: "John",
LastName: "Doe",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.user.ToEmailRecipient()
if got.Email != tt.want.Email {
t.Errorf("ToEmailRecipient().Email = %q, want %q", got.Email, tt.want.Email)
}
if got.FirstName != tt.want.FirstName {
t.Errorf("ToEmailRecipient().FirstName = %q, want %q", got.FirstName, tt.want.FirstName)
}
if got.LastName != tt.want.LastName {
t.Errorf("ToEmailRecipient().LastName = %q, want %q", got.LastName, tt.want.LastName)
}
})
}
}
func TestLoadUserEvents(t *testing.T) {
tests := []struct {
name string
filename string
contents []byte
wantErr bool
validate func(*testing.T, User)
}{
{
name: "valid XML with all fields",
filename: "test.xml",
contents: []byte(`
JohnDoejohn@example.comAlice's Birthday2025-03-15`),
wantErr: false,
validate: func(t *testing.T, u User) {
if u.FirstName != "John" {
t.Errorf("FirstName = %q, want %q", u.FirstName, "John")
}
if u.LastName != "Doe" {
t.Errorf("LastName = %q, want %q", u.LastName, "Doe")
}
if u.Email != "john@example.com" {
t.Errorf("Email = %q, want %q", u.Email, "john@example.com")
}
if len(u.Events) != 1 {
t.Errorf("Events length = %d, want %d", len(u.Events), 1)
}
},
},
{
name: "valid XML with minimal fields",
filename: "minimal.xml",
contents: []byte(`
user@example.com`),
wantErr: false,
validate: func(t *testing.T, u User) {
if u.FirstName != "" {
t.Errorf("FirstName = %q, want empty", u.FirstName)
}
if u.LastName != "" {
t.Errorf("LastName = %q, want empty", u.LastName)
}
if u.Email != "user@example.com" {
t.Errorf("Email = %q, want %q", u.Email, "user@example.com")
}
if len(u.Events) != 0 {
t.Errorf("Events length = %d, want %d", len(u.Events), 0)
}
},
},
{
name: "invalid XML - malformed",
filename: "invalid.xml",
contents: []byte(`test@example.comtest@example.com`),
wantErr: true,
},
{
name: "invalid XML - not well-formed",
filename: "invalid3.xml",
contents: []byte(`not xml at all`),
wantErr: true,
},
{
name: "Billion Laughs attack - nested entity expansion",
filename: "billion-laughs.xml",
contents: []byte(`
]>
&lol9;`),
wantErr: true,
},
{
name: "XML bomb - large entity reference",
filename: "xml-bomb.xml",
contents: []byte(`
]>
&bomb;&bomb;&bomb;&bomb;&bomb;&bomb;&bomb;&bomb;&bomb;&bomb;`),
wantErr: true,
},
{
name: "Quadratic blowup attack",
filename: "quadratic.xml",
contents: []byte(`
]>
&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;`),
wantErr: true,
},
{
name: "empty XML file",
filename: "empty.xml",
contents: []byte(``),
wantErr: true,
},
{
name: "valid XML with special characters",
filename: "special.xml",
contents: []byte(`
JoséO'Brien-Müllerjosé@example.com`),
wantErr: false,
validate: func(t *testing.T, u User) {
if u.FirstName != "José" {
t.Errorf("FirstName = %q, want %q", u.FirstName, "José")
}
if u.LastName != "O'Brien-Müller" {
t.Errorf("LastName = %q, want %q", u.LastName, "O'Brien-Müller")
}
},
},
{
name: "XML with Unicode noncharacters",
filename: "nonchar.xml",
contents: []byte("\n\n Test\uFFFE\n User\uFFFF\n test@example.com\n"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conf := config.Config{
MaxEventsPerUser: 10000,
MaxRecipientsPerEvent: 200,
}
got, err := LoadUserEvents(tt.filename, tt.contents, conf)
if tt.wantErr {
if err == nil {
t.Errorf("LoadUserEvents() error = nil, wantErr %v", tt.wantErr)
}
return
}
if err != nil {
t.Errorf("LoadUserEvents() unexpected error = %v", err)
return
}
if tt.validate != nil {
tt.validate(t, got)
}
})
}
}
func TestLoadUserEventsMaxLimit(t *testing.T) {
tests := []struct {
name string
filename string
contents []byte
maxEvents int
wantErr bool
}{
{
name: "within limit - 2 events with max 10",
filename: "test.xml",
maxEvents: 10,
contents: []byte(`
test@example.comAlice2025-03-15Bob2025-04-20`),
wantErr: false,
},
{
name: "at limit - 2 events with max 2",
filename: "test.xml",
maxEvents: 2,
contents: []byte(`
test@example.comAlice2025-03-15Bob2025-04-20`),
wantErr: false,
},
{
name: "exceeds limit - 3 events with max 2",
filename: "test.xml",
maxEvents: 2,
contents: []byte(`
test@example.comAlice2025-03-15Bob2025-04-20Charlie2025-05-10`),
wantErr: true,
},
{
name: "no events - within any limit",
filename: "test.xml",
maxEvents: 1,
contents: []byte(`
test@example.com`),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conf := config.Config{
MaxEventsPerUser: tt.maxEvents,
MaxRecipientsPerEvent: 200,
}
_, err := LoadUserEvents(tt.filename, tt.contents, conf)
if tt.wantErr {
if err == nil {
t.Errorf("LoadUserEvents() error = nil, wantErr %v", tt.wantErr)
}
} else {
if err != nil {
t.Errorf("LoadUserEvents() unexpected error = %v", err)
}
}
})
}
}
email-reminder-1.0.1/internal/util/ 0000775 0000000 0000000 00000000000 15122360213 0017167 5 ustar 00root root 0000000 0000000 email-reminder-1.0.1/internal/util/util.go 0000664 0000000 0000000 00000022022 15122360213 0020471 0 ustar 00root root 0000000 0000000 package util
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"log"
"mime"
"mime/quotedprintable"
"net"
"net/mail"
"net/smtp"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
)
type EmailRecipient struct {
Email string
FirstName string // optional
LastName string // optional
}
func ParseBool(value string) (bool, error) {
switch strings.ToLower(value) {
case "no":
return false, nil
case "yes":
return true, nil
default:
return strconv.ParseBool(value)
}
}
// SecureExecCommand executes a command only if the binary has secure permissions.
// It validates that the executable is owned by root and not writable by group or others,
// and enforces a 5-second timeout to prevent hanging on malicious executables.
// This mitigates command injection vulnerabilities by ensuring system binaries haven't been compromised.
func SecureExecCommand(path string, args ...string) ([]byte, error) {
info, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("cannot stat executable: %w", err)
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return nil, fmt.Errorf("cannot get file ownership info")
}
// Check ownership and permissions
if stat.Uid != 0 {
return nil, fmt.Errorf("executable not owned by root (owner: %d)", stat.Uid)
}
if permissions := info.Mode().Perm(); permissions&0022 != 0 {
return nil, fmt.Errorf("executable is writable by non-owner (mode: %o)", permissions)
}
// Execute with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, path, args...)
return cmd.Output()
}
// ValidateEmail validates email addresses using RFC5322 via mail.ParseAddress(),
// while also accepting local delivery formats supported by local mail servers.
func ValidateEmail(email string) error {
if email == "" {
return fmt.Errorf("email address is empty")
}
// RFC 3696 Errata 1690 specifies a maximum email address length of 254 characters
// https://www.rfc-editor.org/errata/eid1690
if len(email) > 254 {
return fmt.Errorf("email address exceeds maximum length of 254 characters")
}
// Normalize addresses accepted by Postfix for RFC5322 parsing
normalized := email
if !strings.Contains(email, "@") {
// Bare username (e.g., "root") - add @localhost for parsing
normalized = email + "@localhost"
} else if strings.HasPrefix(email, "@") {
// @hostname format (e.g., "@example.com") - add dummy local part for parsing
normalized = "dummy.user" + email
}
addr, err := mail.ParseAddress(normalized) // RFC5322
if err != nil {
return fmt.Errorf("invalid email format: %w", err)
}
// Ensure no display name was included
if addr.Address != normalized {
return fmt.Errorf("email address contains unexpected formatting")
}
return nil
}
func IsLastDayOfTheMonth(now time.Time) bool {
tomorrow := now.AddDate(0, 0, 1)
return tomorrow.Month() != now.Month()
}
// Formatted email address suitable for the To header (e.g., "John Doe "), or just the email if no name is present
func (e EmailRecipient) NameAndEmail() string {
// Combine first and last names
name := strings.TrimSpace(strings.Join([]string{e.FirstName, e.LastName}, " "))
if name == "" && e.Email == "" {
return ""
}
address := mail.Address{Name: name, Address: e.Email}
return address.String()
}
func AssembleRawMessage(body string, subject string, recipient string, sender string, appVersion string) string {
var msg strings.Builder
// Headers
fmt.Fprintf(&msg, "From: Email-Reminder <%s>\r\n", sender)
fmt.Fprintf(&msg, "To: %s\r\n", recipient)
fmt.Fprintf(&msg, "Subject: %s\r\n", mime.QEncoding.Encode("UTF-8", subject))
msg.WriteString("X-Auto-Response-Suppress: All\r\n") // suppress MS Exchange OOO replies
msg.WriteString("Content-Language: en\r\n")
fmt.Fprintf(&msg, "User-Agent: email-reminder/%s\r\n", appVersion)
msg.WriteString("MIME-Version: 1.0\r\n")
msg.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
msg.WriteString("Content-Disposition: inline\r\n")
msg.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
body = strings.ReplaceAll(body, "\n", "\r\n") // required by RFC822
var qpBody bytes.Buffer
w := quotedprintable.NewWriter(&qpBody)
w.Write([]byte(body))
w.Close()
msg.WriteString("\r\n")
msg.WriteString(qpBody.String())
return msg.String()
}
// SendMailPlaintext sends email via plain SMTP on port 25 without any TLS/STARTTLS.
// This is useful for localhost connections where STARTTLS might fail due to certificate mismatches.
func SendMailPlaintext(host string, auth smtp.Auth, from string, to []string, msg []byte) error {
conn, err := net.Dial("tcp", net.JoinHostPort(host, "25"))
if err != nil {
return fmt.Errorf("failed to establish connection: %w", err)
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("failed to create SMTP client: %w", err)
}
if auth != nil {
if ok, _ := client.Extension("AUTH"); ok {
if err := client.Auth(auth); err != nil {
return fmt.Errorf("failed to authenticate with SMTP server: %w", err)
}
}
}
if err := client.Mail(from); err != nil {
return fmt.Errorf("MAIL command failed for %s: %w", from, err)
}
for _, recipient := range to {
if err := client.Rcpt(recipient); err != nil {
return fmt.Errorf("RCPT command failed for %s: %w", recipient, err)
}
}
data, err := client.Data()
if err != nil {
return fmt.Errorf("DATA command failed: %w", err)
}
if _, err := data.Write(msg); err != nil {
return fmt.Errorf("failed to write message body: %w", err)
}
if err := data.Close(); err != nil {
return fmt.Errorf("failed to close message body: %w", err)
}
if err := client.Quit(); err != nil {
return fmt.Errorf("failed to terminate SMTP session: %w", err)
}
return nil
}
// Loosely based on https://gist.github.com/chrisgillis/10888032
func SendMailImplicitTLS(host string, auth smtp.Auth, from string, to []string, msg []byte) error {
conn, err := tls.Dial("tcp", net.JoinHostPort(host, "465"), &tls.Config{
ServerName: host,
MinVersion: tls.VersionTLS12,
})
if err != nil {
return fmt.Errorf("failed to establish TLS connection: %w", err)
}
defer conn.Close()
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("failed to create SMTP client: %w", err)
}
if auth != nil {
if ok, _ := client.Extension("AUTH"); ok {
if err := client.Auth(auth); err != nil {
return fmt.Errorf("failed to authenticate with SMTP server: %w", err)
}
}
}
if err := client.Mail(from); err != nil {
return fmt.Errorf("MAIL command failed for %s: %w", from, err)
}
for _, recipient := range to {
if err := client.Rcpt(recipient); err != nil {
return fmt.Errorf("RCPT command failed for %s: %w", recipient, err)
}
}
data, err := client.Data()
if err != nil {
return fmt.Errorf("DATA command failed: %w", err)
}
if _, err := data.Write(msg); err != nil {
return fmt.Errorf("failed to write message body: %w", err)
}
if err := data.Close(); err != nil {
return fmt.Errorf("failed to close message body: %w", err)
}
if err := client.Quit(); err != nil {
return fmt.Errorf("failed to terminate SMTP session: %w", err)
}
return nil
}
// Ensure that the home directory is owned by the expected user
func ValidateHomeDirectory(homePath string, expectedUid uint32) error {
info, err := os.Lstat(homePath) // Use Lstat to detect symlinks
if err != nil {
return fmt.Errorf("cannot access home directory '%s': %w", homePath, err)
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("home directory '%s' is a symlink", homePath)
}
if !info.IsDir() {
return fmt.Errorf("home directory '%s' is not a directory", homePath)
}
if stat, ok := info.Sys().(*syscall.Stat_t); ok { // Only works on UNIX
if stat.Uid != expectedUid {
return fmt.Errorf("home directory '%s' is not owned by uid %d (actual owner: %d)", homePath, expectedUid, stat.Uid)
}
} else {
log.Printf("cannot get ownership information for '%s'", homePath)
}
return nil
}
// ValidateOpenFile checks that an already-open file is owned by the expected user
// and is a regular file (not a device, socket, symlink, etc.).
func ValidateOpenFile(file *os.File, expectedUid uint32) error {
info, err := file.Stat()
if err != nil {
return fmt.Errorf("cannot stat file '%s': %w", file.Name(), err)
}
stat, ok := info.Sys().(*syscall.Stat_t) // Only works on UNIX
if !ok {
return fmt.Errorf("cannot get ownership information for '%s'", file.Name())
}
if stat.Uid != expectedUid {
return fmt.Errorf("file '%s' is not owned by uid %d (actual owner: %d)", file.Name(), expectedUid, stat.Uid)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("'%s' is not a regular file (mode: %s)", file.Name(), info.Mode().Type())
}
return nil
}
// Complete email body with friendly greeting and footer
func FullBody(body string, recipient EmailRecipient, version string) string {
firstName := recipient.FirstName
if firstName == "" {
firstName = "there"
}
return fmt.Sprintf(`Hi %s,
%s
Have a good day!
--
Sent by Email-Reminder %s
https://launchpad.net/email-reminder`, firstName, body, version)
}
email-reminder-1.0.1/internal/util/util_test.go 0000664 0000000 0000000 00000042563 15122360213 0021544 0 ustar 00root root 0000000 0000000 package util
import (
"fmt"
"io"
"net/mail"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func validateEmailMessage(t *testing.T, rawMessage string, wantEmptyBody bool) {
t.Helper()
msg, err := mail.ReadMessage(strings.NewReader(rawMessage))
if err != nil {
t.Errorf("Failed to parse email message: %v", err)
return
}
requiredHeaders := []string{"From", "To", "Subject", "MIME-Version", "Content-Type"}
for _, header := range requiredHeaders {
if msg.Header.Get(header) == "" {
t.Errorf("Missing required header: %s", header)
}
}
body, err := io.ReadAll(msg.Body)
if err != nil {
t.Errorf("Failed to read body from parsed message: %v", err)
}
if !wantEmptyBody && len(body) == 0 {
t.Errorf("Empty body")
}
}
func TestEmailRecipient_NameAndEmail(t *testing.T) {
tests := []struct {
recipient EmailRecipient
want string
}{
{recipient: EmailRecipient{Email: ""}, want: ""},
{recipient: EmailRecipient{Email: "john.doe@example.com", FirstName: "John", LastName: "Doe"}, want: "\"John Doe\" "},
{recipient: EmailRecipient{Email: "john@example.com", FirstName: "John"}, want: "\"John\" "},
{recipient: EmailRecipient{Email: "doe@example.com", LastName: "Doe"}, want: "\"Doe\" "},
{recipient: EmailRecipient{Email: "test@example.com"}, want: ""},
{recipient: EmailRecipient{Email: "john.doe@example.com", FirstName: "John", LastName: "Doe Smith"}, want: "\"John Doe Smith\" "},
{recipient: EmailRecipient{Email: "rene@example.com", FirstName: "René"}, want: "=?utf-8?q?Ren=C3=A9?= "},
{recipient: EmailRecipient{Email: "john.garcia@example.com", FirstName: "John", LastName: "García"}, want: "=?utf-8?q?John_Garc=C3=ADa?= "},
{recipient: EmailRecipient{Email: "party@example.com", FirstName: "🎉"}, want: "=?utf-8?q?=F0=9F=8E=89?= "},
}
for _, tt := range tests {
if got := tt.recipient.NameAndEmail(); got != tt.want {
t.Errorf("NameAndEmail() = %q, want %q", got, tt.want)
}
}
}
func TestIsLastDayOfTheMonth(t *testing.T) {
tests := []struct {
name string
date time.Time
want bool
}{
{
name: "last day of January (31st)",
date: time.Date(2023, time.January, 31, 10, 30, 0, 0, time.UTC),
want: true,
},
{
name: "not last day of January (30th)",
date: time.Date(2023, time.January, 30, 10, 30, 0, 0, time.UTC),
want: false,
},
{
name: "last day of February in non-leap year (28th)",
date: time.Date(2023, time.February, 28, 10, 30, 0, 0, time.UTC),
want: true,
},
{
name: "not last day of February in non-leap year (27th)",
date: time.Date(2023, time.February, 27, 10, 30, 0, 0, time.UTC),
want: false,
},
{
name: "last day of February in leap year (29th)",
date: time.Date(2024, time.February, 29, 10, 30, 0, 0, time.UTC),
want: true,
},
{
name: "not last day of February in leap year (28th)",
date: time.Date(2024, time.February, 28, 10, 30, 0, 0, time.UTC),
want: false,
},
{
name: "first day of month (1st)",
date: time.Date(2023, time.March, 1, 10, 30, 0, 0, time.UTC),
want: false,
},
{
name: "middle of month (15th)",
date: time.Date(2023, time.March, 15, 10, 30, 0, 0, time.UTC),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := IsLastDayOfTheMonth(tt.date)
if result != tt.want {
t.Errorf("IsLastDayOfTheMonth(%v) = %v, want %v",
tt.date, result, tt.want)
}
})
}
}
func TestParseBool(t *testing.T) {
tests := []struct {
value string
want bool
wantError bool
}{
// Accepted values
{
value: "yes",
want: true,
wantError: false,
},
{
value: "YES",
want: true,
wantError: false,
},
{
value: "Yes",
want: true,
wantError: false,
},
{
value: "no",
want: false,
wantError: false,
},
{
value: "NO",
want: false,
wantError: false,
},
{
value: "No",
want: false,
wantError: false,
},
{
value: "true",
want: true,
wantError: false,
},
{
value: "false",
want: false,
wantError: false,
},
{
value: "1",
want: true,
wantError: false,
},
{
value: "0",
want: false,
wantError: false,
},
{
value: "t",
want: true,
wantError: false,
},
{
value: "f",
want: false,
wantError: false,
},
{
value: "TRUE",
want: true,
wantError: false,
},
{
value: "FALSE",
want: false,
wantError: false,
},
// Errors
{
value: "invalid",
want: false,
wantError: true,
},
{
value: "",
want: false,
wantError: true,
},
{
value: "123",
want: false,
wantError: true,
},
{
value: " ",
want: false,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.value, func(t *testing.T) {
result, err := ParseBool(tt.value)
if tt.wantError {
if err == nil {
t.Errorf("ParseBool(%q) expected error, but got none", tt.value)
}
} else {
if err != nil {
t.Errorf("ParseBool(%q) unexpected error: %v", tt.value, err)
}
}
if result != tt.want {
t.Errorf("ParseBool(%q) = %v, want %v", tt.value, result, tt.want)
}
})
}
}
func TestValidateEmail(t *testing.T) {
tests := []struct {
email string
wantError bool
}{
// Valid email addresses (RFC5322)
{
email: "root@localhost",
wantError: false,
},
{
email: "admin@mail.example.com",
wantError: false,
},
{
email: "user123@example.com",
wantError: false,
},
{
email: "first.last@example.com",
wantError: false,
},
{
email: "user+tag@example.com",
wantError: false,
},
{
email: "user_name@example.com",
wantError: false,
},
// Valid local-only addresses (for local Postfix delivery)
{
email: "user123",
wantError: false,
},
{
email: "first.last",
wantError: false,
},
{
email: "user_name",
wantError: false,
},
{
email: "test-user",
wantError: false,
},
{
email: "mail.example.com", // becomes mail.example.com@localhost
wantError: false,
},
{
email: "domain!user", // becomes user@domain (legacy UUCP mapping)
wantError: false,
},
// Some mail servers accept emails without a local part
{
email: "@localhost",
wantError: false,
},
{
email: "@mail.example.com",
wantError: false,
},
// Invalid email addresses
{
email: "",
wantError: true,
},
{
email: "root@",
wantError: true,
},
{
email: "@",
wantError: true,
},
{
email: "user @example.com",
wantError: true,
},
{
email: "user@example.com\nBcc: attacker@evil.com",
wantError: true,
},
{
email: "user@example.com\rBcc: attacker@evil.com",
wantError: true,
},
{
email: "user@example.com\x00",
wantError: true,
},
{
email: "user@@example.com",
wantError: true,
},
{
email: "John Doe ",
wantError: true,
},
// Length boundary tests
{
// 254 bytes: valid (maximum allowed length)
email: fmt.Sprintf("%s@%s.com", strings.Repeat("a", 64), strings.Repeat("b", 185)),
wantError: false,
},
{
// 255 bytes: invalid (exceeds maximum allowed length)
email: fmt.Sprintf("%s@%s.com", strings.Repeat("a", 64), strings.Repeat("b", 186)),
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.email, func(t *testing.T) {
err := ValidateEmail(tt.email)
if tt.wantError {
if err == nil {
t.Errorf("ValidateEmail(%q) expected error, but got none", tt.email)
}
} else {
if err != nil {
t.Errorf("ValidateEmail(%q) unexpected error: %v", tt.email, err)
}
}
})
}
}
func TestAssembleRawMessage(t *testing.T) {
const (
defaultVersion = "0.0.1"
fixedHeadersFormat = "X-Auto-Response-Suppress: All\r\n" +
"Content-Language: en\r\n" +
"User-Agent: email-reminder/%s\r\n" +
"MIME-Version: 1.0\r\n" +
"Content-Type: text/plain; charset=UTF-8\r\n" +
"Content-Disposition: inline\r\n" +
"Content-Transfer-Encoding: quoted-printable\r\n"
)
tests := []struct {
name string
body string
subject string
recipient string
sender string
appVersion string
want string
}{
{
name: "simple message",
body: "This is a test message.",
subject: "Test Subject",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: defaultVersion,
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: Test Subject\r\n"+
fixedHeadersFormat+
"\r\nThis is a test message.",
defaultVersion,
),
},
{
name: "multi-line body",
body: "Line 1\nLine 2\nLine 3",
subject: "Multi-line",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: defaultVersion,
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: Multi-line\r\n"+
fixedHeadersFormat+
"\r\nLine 1\r\nLine 2\r\nLine 3",
defaultVersion,
),
},
{
name: "unicode subject",
body: "Test with unicode subject",
subject: "Tëst Sübject with émojis 🎉",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: defaultVersion,
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: =?UTF-8?q?T=C3=ABst_S=C3=BCbject_with_=C3=A9mojis_=F0=9F=8E=89?=\r\n"+
fixedHeadersFormat+
"\r\nTest with unicode subject",
defaultVersion,
),
},
{
name: "special characters in body",
body: "Body with special chars: äöü & < > \"",
subject: "Special Chars",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: defaultVersion,
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: Special Chars\r\n"+
fixedHeadersFormat+
"\r\nBody with special chars: =C3=A4=C3=B6=C3=BC & < > \"",
defaultVersion,
),
},
{
name: "empty body",
body: "",
subject: "Empty Body",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: defaultVersion,
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: Empty Body\r\n"+
fixedHeadersFormat+
"\r\n",
defaultVersion,
),
},
{
name: "long line that needs quoted-printable encoding",
body: "This is a very long line that exceeds the typical 76 character limit for email lines and should be properly encoded using quoted-printable encoding to ensure proper email delivery.",
subject: "Long Line Test",
recipient: "test@example.com",
sender: "sender@example.com",
appVersion: "1.2.3-test",
want: fmt.Sprintf(
"From: Email-Reminder \r\n"+
"To: test@example.com\r\n"+
"Subject: Long Line Test\r\n"+
fixedHeadersFormat+
"\r\nThis is a very long line that exceeds the typical 76 character limit for em=\r\n"+
"ail lines and should be properly encoded using quoted-printable encoding to=\r\n"+
" ensure proper email delivery.",
"1.2.3-test",
),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := AssembleRawMessage(tt.body, tt.subject, tt.recipient, tt.sender, tt.appVersion)
// Validate that the result is a properly formatted email message
validateEmailMessage(t, result, len(tt.body) == 0)
// Also check that it matches expected output
if result != tt.want {
t.Errorf("AssembleRawMessage() = %q, want %q", result, tt.want)
}
})
}
}
func TestValidateHomeDirectory(t *testing.T) {
tempDir := t.TempDir()
// Test case 1: Valid directory
err := ValidateHomeDirectory(tempDir, uint32(os.Getuid()))
if err != nil {
t.Errorf("ValidateHomeDirectory() for valid directory failed: %v", err)
}
// Test case 2: Non-existent directory
err = ValidateHomeDirectory("/non/existent/path", uint32(os.Getuid()))
if err == nil {
t.Error("ValidateHomeDirectory() should fail for non-existent directory")
}
// Test case 3: Create a symlink to test symlink detection
symlinkPath := filepath.Join(tempDir, "symlink")
targetPath := filepath.Join(tempDir, "target")
os.Mkdir(targetPath, 0755)
err = os.Symlink(targetPath, symlinkPath)
if err != nil {
t.Fatalf("Failed to create test symlink: %v", err)
}
err = ValidateHomeDirectory(symlinkPath, uint32(os.Getuid()))
if err == nil {
t.Error("ValidateHomeDirectory() should fail for symlink")
}
if !strings.Contains(err.Error(), "symlink") {
t.Errorf("Error message should mention symlink, got: %v", err)
}
// Test case 4: Wrong owner (we can't easily test this without root permissions,
// but we can test the error handling by passing an invalid UID)
err = ValidateHomeDirectory(tempDir, uint32(0xFFFFFFFF)) // Use max uint32 as invalid UID
if err == nil {
t.Error("ValidateHomeDirectory() should fail for wrong owner")
}
}
func TestValidateOpenFile(t *testing.T) {
// Test case 1: Correctly owned regular file
tempFile := filepath.Join(t.TempDir(), "testfile")
file, err := os.Create(tempFile)
if err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
defer file.Close()
err = ValidateOpenFile(file, uint32(os.Getuid()))
if err != nil {
t.Errorf("ValidateOpenFile() for correctly owned file failed: %v", err)
}
// Test case 2: Wrong owner
err = ValidateOpenFile(file, uint32(0xFFFFFFFF)) // Use max uint32 as invalid UID
if err == nil {
t.Error("ValidateOpenFile() should fail for wrong owner")
}
if !strings.Contains(err.Error(), "not owned by uid") {
t.Errorf("Error message should mention ownership, got: %v", err)
}
// Test case 3: Not a regular file (directory)
tempDir := t.TempDir()
dirFile, err := os.Open(tempDir)
if err != nil {
t.Fatalf("Failed to open temp directory: %v", err)
}
defer dirFile.Close()
err = ValidateOpenFile(dirFile, uint32(os.Getuid()))
if err == nil {
t.Error("ValidateOpenFile() should fail for directory")
}
if !strings.Contains(err.Error(), "not a regular file") {
t.Errorf("Error message should mention regular file, got: %v", err)
}
}
func TestFullBody(t *testing.T) {
tests := []struct {
name string
body string
recipient EmailRecipient
version string
want string
}{
{
name: "without a name",
body: "Your appointment is scheduled for 2pm.",
recipient: EmailRecipient{Email: "someone@example.com"},
version: "0.8.3",
want: `Hi there,
Your appointment is scheduled for 2pm.
Have a good day!
--
Sent by Email-Reminder 0.8.3
https://launchpad.net/email-reminder`,
},
{
name: "with only a last name",
body: "Test message",
recipient: EmailRecipient{FirstName: "", LastName: "Smith", Email: "smith@example.com"},
version: "1.0.0",
want: `Hi there,
Test message
Have a good day!
--
Sent by Email-Reminder 1.0.0
https://launchpad.net/email-reminder`,
},
{
name: "with name and multiline body",
body: "Line 1\nLine 2\nLine 3",
recipient: EmailRecipient{FirstName: "Alice", Email: "alice@example.com"},
version: "0.8.3",
want: `Hi Alice,
Line 1
Line 2
Line 3
Have a good day!
--
Sent by Email-Reminder 0.8.3
https://launchpad.net/email-reminder`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := FullBody(tt.body, tt.recipient, tt.version)
if got != tt.want {
t.Errorf("FullBody() = %q, want %q", got, tt.want)
}
})
}
}
func TestSecureExecCommand(t *testing.T) {
// Test with a legitimate system binary (should exist and be owned by root)
t.Run("valid_system_binary", func(t *testing.T) {
// Try /bin/echo which should be safe and available on most systems
output, err := SecureExecCommand("/bin/echo", "test")
if err != nil {
// This might fail if /bin/echo doesn't exist or isn't owned by root
// which is acceptable for this security-focused test
t.Logf("Expected error for system binary (may not be root-owned in test environment): %v", err)
return
}
if len(output) == 0 {
t.Error("Expected non-empty output from /bin/echo")
}
})
t.Run("nonexistent_binary", func(t *testing.T) {
_, err := SecureExecCommand("/nonexistent/binary")
if err == nil {
t.Error("Expected error for nonexistent binary")
}
if !strings.Contains(err.Error(), "cannot stat executable") {
t.Errorf("Expected 'cannot stat executable' error, got: %v", err)
}
})
t.Run("non_root_owned_binary", func(t *testing.T) {
// Create a temporary executable owned by the current user
tmpDir := t.TempDir()
tmpScript := filepath.Join(tmpDir, "test_script")
// Create a simple shell script
content := []byte("#!/bin/sh\necho test\n")
if err := os.WriteFile(tmpScript, content, 0755); err != nil {
t.Fatalf("Failed to create test script: %v", err)
}
// Try to execute it - should fail because it's not owned by root
_, err := SecureExecCommand(tmpScript)
if err == nil {
t.Error("Expected error for non-root owned binary")
}
if !strings.Contains(err.Error(), "not owned by root") {
t.Errorf("Expected 'not owned by root' error, got: %v", err)
}
})
}
email-reminder-1.0.1/net.launchpad.email_reminder.metainfo.xml 0000664 0000000 0000000 00000003105 15122360213 0024417 0 ustar 00root root 0000000 0000000
net.launchpad.email_reminderEmail-ReminderSend event reminders by emailCC0-1.0GPL-3.0-or-laterFrançois Marier
Email-reminder allows users to define events that they want to be reminded of by email. Possible events include birthdays, anniversaries, and yearly events. Reminders can be sent on the day of the event and/or a few days beforehand.
email-reminder.desktop
List of yearly events along with the reminders dialog box
List of weekly events along with the preferences dialog box
https://screenshots.debian.net/screenshot/email-reminder/337https://launchpad.net/email-reminderhttps://bugs.launchpad.net/email-reminderhttps://answers.launchpad.net/email-reminder
email-reminder-1.0.1/send-reminders.1 0000664 0000000 0000000 00000007200 15122360213 0017376 0 ustar 00root root 0000000 0000000 .\" -*- mode: troff; coding: utf-8 -*-
.\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
.ie n \{\
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.nr rF 0
.if \n(.g .if rF .nr rF 1
.if (\n(rF:(\n(.g==0)) \{\
. if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
. \}
.\}
.rr rF
.\" ========================================================================
.\"
.IX Title "SEND-REMINDERS 1"
.TH SEND-REMINDERS 1 2025-10-18 "perl v5.40.1" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH NAME
send\-reminders \- send email reminders for special occasions
.SH SYNOPSIS
.IX Header "SYNOPSIS"
Send email reminders set by users for special-occasion email reminders.
.SH DESCRIPTION
.IX Header "DESCRIPTION"
Email-reminder allows users to define events that they want to be
reminded of by email. Possible events include birthdays,
anniversaries, and yearly events. Reminders can be sent on the day of
the event and a few days beforehand.
.PP
This script is meant to be invoked every day by a cron job. It mails
the actual reminders out.
.PP
When run by the root user, it processes all of the spooled reminders.
When run by a specific user, it only processes reminders set by that
user.
.SH OPTIONS
.IX Header "OPTIONS"
.IP \fB\-\-help\fR 6
.IX Item "--help"
Displays basic usage message.
.IP \fB\-\-simulate\fR 6
.IX Item "--simulate"
Does not actually send any emails out.
.IP \fB\-\-verbose\fR 6
.IX Item "--verbose"
Prints out information about what the program is doing, including the
full emails being sent out.
.IP \fB\-\-version\fR 6
.IX Item "--version"
Displays the version number.
.SH FILES
.IX Header "FILES"
\&\fI~/.config/email\-reminder/reminders.xml\fR, \fI/etc/email\-reminder.conf\fR
.SH AUTHOR
.IX Header "AUTHOR"
Francois Marier
.SH "SEE ALSO"
.IX Header "SEE ALSO"
email-reminder-editor, collect-reminders
.SH COPYRIGHT
.IX Header "COPYRIGHT"
Copyright (C) 2004\-2025 by Francois Marier
.PP
Email-Reminder is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.
.PP
Email-Reminder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
.PP
You should have received a copy of the GNU General Public License
along with Email-Reminder; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110\-1301, USA.