chore(*): drop everything that is not required for Tvix

Co-Authored-By: edef <edef@edef.eu>
Co-Authored-By: Ryan Lahfa <raito@lix.systems>
Change-Id: I9817214c3122e49d694c5e41818622a08d9dfe45
This commit is contained in:
Florian Klink 2025-01-05 17:12:30 +01:00
parent bd91cac1f3
commit df4500ea2b
2905 changed files with 34 additions and 493328 deletions

View file

@ -1,3 +0,0 @@
/target/
**/*.rs.bk
Cargo.lock

View file

@ -1,6 +0,0 @@
[package]
name = "defer"
version = "0.1.0"
authors = ["Vincent Ambo <tazjin@gmail.com>"]
[dependencies]

View file

@ -1,53 +0,0 @@
defer in Rust
=============
After a Hacker News discussion about implementing Go's `defer` keyword in C++,
I stumbled upon [this comment](https://news.ycombinator.com/item?id=15523589)
and more specifically this response to it by "Occivink":
> There's plenty of one-time cases where you don't want to declare an entire
> class but still enjoy scope-based functions.
Specificall the "don't want to declare an entire class" suggests that languages
like C++ have high friction for explaining your desired invariant (cleanup is
run when `$thing` is destroyed) to the compiler.
It seems like most languages either hand-wave this away (*cough* Java *cough*)
or use what seems like a workaround (`defer`).
Rust has the so-called `Drop` trait, which is a typeclass that contains a single
method with no return value that is run when a variable is dropped (i.e. goes out
of scope).
This works fine for most general cases - i.e. closing file handlers - but can
get complicated if other use-cases of `defer` are considered:
* returning an error-value by mutating a reference in the enclosing scope (oh boy)
* deferring a decision about when/whether to run cleanup to the caller
While thinking about how to do this with the `Drop` trait I realised that `defer`
can actually be trivially implemented in Rust, using `Drop`.
A simple implementation of `defer` can be seen in [defer.rs](examples/defer.rs),
an implementation using shared mutable state for error returns is in the file
[defer-with-error.rs](examples/defer-with-error.rs) and an implementation that
allows cleanup to be *cancelled* (don't _actually_ do this, it leaks a pointer)
is in [undefer.rs](examples/undefer.rs).
Whether any of this is actually useful is not up to me to decide. I haven't
actually had a real-life need for this.
You can run the examples with `cargo run --example defer`, etc.
## Notes
* `Drop` is not guaranteed to run in case of panics or program aborts, if you
need support for that check out [scopeguard](https://github.com/bluss/scopeguard)
* `undefer` could be implemented safely by, for example, carrying a boolean that
by default causes execution to happen but can be flipped to disable it
## Further reading:
* [The Pain Of Real Linear Types in Rust](https://gankro.github.io/blah/linear-rust/)
* [Go's defer](https://tour.golang.org/flowcontrol/12)
* [Rust's Drop](https://doc.rust-lang.org/std/ops/trait.Drop.html)

View file

@ -1,72 +0,0 @@
// Go's defer in Rust, with error value return.
use std::rc::Rc;
use std::sync::RwLock;
struct Defer<F: Fn()> {
f: F,
}
impl<F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
// Convenience type synonym. This is a reference-counted smart pointer to
// a shareable, mutable variable.
// Rust does not allow willy-nilly mutation of shared variables, so explicit
// write-locking must be performed.
type ErrorHandle<T> = Rc<RwLock<Option<T>>>;
///////////////////
// Usage example //
///////////////////
#[derive(Debug)] // Debug trait for some default way to print the type.
enum Error {
DropError,
}
fn main() {
// Create a place to store the error.
let drop_err: ErrorHandle<Error> = Default::default(); // create empty error
// Introduce an arbitrary scope block (so that we still have control after
// the defer runs):
{
let mut i = 1;
// Rc types are safe to clone and share for multiple ownership.
let err_handle = drop_err.clone();
// Call defer and let the closure own the cloned handle to the error:
let token = defer(move || {
// do something!
println!("Value is: {}", i);
// ... oh no, it went wrong!
*err_handle.write().unwrap() = Some(Error::DropError);
});
i += 1;
println!("Value is: {}", i);
// token goes out of scope here - drop() is called.
}
match *drop_err.read().unwrap() {
Some(ref err) => println!("Oh no, an error occured: {:?}!", err),
None => println!("Phew, everything went well."),
};
}
// Prints:
// Value is: 2
// Value is: 1
// Oh no, an error occured: DropError!

View file

@ -1,31 +0,0 @@
// Go's defer in Rust!
struct Defer<F: Fn()> {
f: F,
}
impl<F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
fn main() {
let mut i = 1;
// Calling it "token" ... could be something else. The lifetime of this
// controls when the action is run.
let _token = defer(move || println!("Value is: {}", i));
i += 1;
println!("Value is: {}", i);
}
// Prints:
// Value is: 2
// Value is: 1

View file

@ -1,40 +0,0 @@
// Go's defer in Rust, with a little twist!
struct Defer<F: Fn()> {
f: F,
}
impl<F: Fn()> Drop for Defer<F> {
fn drop(&mut self) {
(self.f)()
}
}
// Only added this for Go-syntax familiarity ;-)
fn defer<F: Fn()>(f: F) -> Defer<F> {
Defer { f }
}
// Changed your mind about the defer?
// (Note: This leaks the closure! Don't actually do this!)
fn undefer<F: Fn()>(token: Defer<F>) {
use std::mem;
mem::forget(token);
}
fn main() {
let mut i = 1;
// Calling it "token" ... could be something else. The lifetime of this
// controls when the action is run.
let token = defer(move || println!("Value is: {}", i));
i += 1;
println!("Value is: {}", i);
// Oh, now I changed my mind about the previous defer:
undefer(token);
}
// Prints:
// Value is: 2

View file

@ -1 +0,0 @@
*.elc

View file

@ -1,11 +0,0 @@
elblog
======
This is a simple blogging software written in Emacs Lisp.
The idea is that it should be able to do most of the things [my actual blog][]
does at the moment.
No documentation exists for now besides the commit messages, but it works!
[my actual blog]: https://www.tazj.in/

View file

@ -1,37 +0,0 @@
<style type="text/css">
body {
margin: 40px auto;
max-width: 800px;
line-height: 1.6;
font-size: 18px;
color: #383838;
padding: 0 10px
}
h1, h2, h3 {
line-height: 1.2
}
.footer {
text-align: right;
}
.lod {
text-align: center;
}
.unstyled-link {
color: inherit;
text-decoration: none;
}
.uncoloured-link {
color: inherit;
}
.date {
text-align: right;
font-style: italic;
float: right;
}
.inline {
display: inline;
}
.navigation {
text-align: center;
}
</style>

View file

@ -1,123 +0,0 @@
;;; blog.el --- A simple org-mode & elnode blog software.
;;; -*- lexical-binding: t; -*-
(require 'dash)
(require 'elnode)
(require 'f)
(require 'ht)
;; Definition of customization options
(defgroup elblog nil
"Configuration for the Emacs Lisp blog software"
:link '(url-link "https://github.com/tazjin/elblog"))
(defcustom elblog-port 8010
"Port to run elblog's HTTP server on"
:group 'elblog
:type 'integer)
(defcustom elblog-host "localhost"
"Host for elblog's HTTP server to listen on"
:group 'elblog
:type 'string)
(defcustom elblog-title "Elblog"
"Title text for this elblog instance"
:group 'elblog
:type 'string)
(defcustom elblog-article-directory nil
"Directory in which elblog articles are stored"
:group 'elblog
:type 'string)
(defcustom elblog-additional-routes '()
"Additional Elnode routes to register in the Elblog instance"
:group 'elblog
:type '(alist :key-type regexp :value-type function))
;; Declare user-configurable variables needed at runtime.
(defvar elblog-articles (ht-create)
"A hash-table of blog articles. This is used for looking up articles from
URL fragments as well as for rendering the index.")
;; HTML templating setup
(defun template-preamble ()
"Templates the preamble snippet with the correct blog title."
(format (f-read-text "preamble.html") elblog-title))
(defun configure-org-html-export ()
"Configure org-mode settings for elblog's HTML templating to work correctly."
(setq org-html-postamble t)
(setq org-html-doctype "html5")
(setq org-html-head-include-scripts nil)
(setq org-html-style-default (f-read-text "blog.css"))
(setq org-html-preamble-format `(("en" ,(template-preamble))))
(setq org-html-postamble-format `(("en" ,(f-read-text "postamble.html")))))
;; Article fetching & rendering functions
(defun render-org-buffer (input-buffer &optional force)
"Renders an org-mode buffer as HTML and returns the name of the output buffer."
(letrec ((output-buffer (concat (buffer-name input-buffer) "-rendered"))
;; Don't re-render articles unless forced.
(must-render (or force
(not (get-buffer output-buffer)))))
(if (and input-buffer must-render)
(with-current-buffer input-buffer
(org-export-to-buffer 'html output-buffer nil nil t)))
(if input-buffer output-buffer nil)))
(defun get-buffer-string (buffer)
"Returns the contents of the specified buffer as a string."
(with-current-buffer (get-buffer buffer)
(buffer-string)))
(defvar-local article-not-found
'(404 . "<html><body><p>Oh no, the article was not found.</p></body></html>"))
(defvar-local text-html '("Content-Type" . "text/html"))
(defun render-article (article)
"Renders an article, if it exists."
(letrec ((rendered (-some->>
(ht-get elblog-articles article)
(concat elblog-article-directory)
(find-file)
(render-org-buffer))))
(if rendered `(200 . ,(get-buffer-string rendered))
article-not-found)))
(defun blog-post-handler (httpcon)
"This handler servers a blog post from the configured blog post directory."
(let ((response (render-article (elnode-http-mapping httpcon 1))))
(elnode-http-start httpcon (car response) text-html)
(elnode-http-return httpcon (cdr response))))
;; Web server implementation
(defvar elblog-routes
'(("^.*//\\(.*\\)" . blog-post-handler))
"The default routes available in elblog. They can be extended by the user
by setting the elblog-additional-routes customize option.")
(defun elblog-handler (httpcon)
(elnode-hostpath-dispatcher
httpcon
(-concat elblog-additional-routes elblog-routes)))
(defun start-elblog ()
(interactive)
(configure-org-html-export)
(elnode-start 'elblog-handler
:port elblog-port
:host elblog-host))
(defun stop-elblog ()
(interactive)
(elnode-stop elblog-port))
(provide 'elblog)

View file

@ -1,9 +0,0 @@
<hr>
<footer><p class="footer">Served with <a class="uncoloured-link" href="https://github.com/tazjin/elblog">Emacs</a>.</p>
<p class="footer">
<a class="uncoloured-link" href="https://twitter.com/tazjin">Twitter</a>
|
<a class="uncoloured-link" href="mailto:blog@tazj.in">Mail</a>
</p>
<p class="lod">ಠ_ಠ</p>
</footer>

View file

@ -1,6 +0,0 @@
<header>
<h1>
<a class="unstyled-link" href="/">%s</a>
</h1>
<hr>
</header>

View file

@ -1,20 +0,0 @@
A SERMON ON ETHICS AND LOVE
===========================
One day Mal-2 asked the messenger spirit Saint Gulik to approach the Goddess and request Her presence for some desperate advice. Shortly afterwards the radio came on by itself, and an ethereal female Voice said **YES?**
"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a heavy burden from my heart!"
**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.**
"I am filled with fear and tormented with terrible visions of pain. Everywhere people are hurting one another, the planet is rampant with injustices, whole societies plunder groups of their own people, mothers imprison sons, children perish while brothers war. O, woe."
**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?**
"But nobody Wants it! Everybody hates it."
**OH. WELL, THEN *STOP*.**
At which moment She turned herself into an aspirin commercial and left The Polyfather stranded alone with his species.
SINISTER DEXTER HAS A BROKEN SPIROMETER.

View file

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

View file

@ -1,96 +0,0 @@
# Gemma
Gemma is a simple application to track *recurring* tasks, named after Gemma
Hartley who [wrote an article][] about task distribution issues in households.
## Background
(Skip this if you just want the technical bits)
Gemma's article launched a discussion in my friend circle about what causes an
uneven distribution of household workload. I theorised that this is not so much
a gender issue, but mostly a discoverability issue.
Usually one person in a household is aware of what needs to be done, but in many
cases the "overhead" of delegating the tasks would actually take more time than
simply doing the task.
I theorise further that the person (or people) who do a smaller share of the
household work would often do the work if they had a convenient way to become
aware of what needs to be done. Many times the "household manager" has the
function of tracking non-obvious tasks like when bedsheets were last changed -
shouldn't it be possible to actually distribute this information somehow?
## The Project
This project is an initial attempt at sketching out a little application that
aids with reminding users of recurring tasks. Some basic ideas:
* The system should be blame-free.
* There should be as little usage overhead as possible so that people actually
do use it.
* It should work mostly passively without much user interaction.
I believe that the basic (*very* simple) idea behind Gemma solves these issues.
Unfortunately my living situation changed before I actually got to test this out
in a real-life situation involving multiple people, but feedback from other
potential test subjects would be welcome! :)
## Overview
Gemma is a Common Lisp application in which a list of recurring tasks is
declared, together with the *maximum interval* at which they should be completed
(in days). Example:
```lisp
;; Bathroom tasks
(deftask bathroom/wipe-mirror 7)
(deftask bathroom/wipe-counter 7)
;; Bedroom tasks
(deftask bedroom/change-sheets 7)
(deftask bedroom/vacuum 10)
;; Kitchen tasks
(deftask kitchen/trash 3)
(deftask kitchen/wipe-counters 3)
(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!")
;; Entire place
(deftask clean-windows 60)
```
These tasks are marked with their last completion time and tracked by Gemma. A
simple Elm-based frontend application displays the tasks sorted by their
"urgency" and features a button to mark a task as completed:
![Gemma screenshot](http://i.imgur.com/n7FFMJH.png)
Marking a task as completed resets its counter and moves it to the bottom of the
task list.
In theory this *should be it*, the frontend is made available to household
members in some easily accessible place (e.g. an old phone glued to the fridge!)
and people should attempt to develop a habit of checking what needs to be done
occasionally.
The "household manager" still exists as a role of the household because someone
is entering the tasks into the application, but if my theory about people not
actually being actively *unwilling* to do tasks is correct this could help a
lot.
## Usage
(*Note*: Gemma is alpha software so the below is clearly not the final goal)
Right now using this is non-trivial, but I'll eventually make a better
distribution. Basically you need to know Common Lisp (in which case you'll know
how to get the backend running) and have `elm-reactor` installed to run the
development version of the frontend application.
Gemma is configured via a configuration file that should be located either at
`/etc/gemma/config.lisp` or at a custom location specified via the environment
variable `GEMMA_CONFIG`. Have a look at the `config.lisp` file in the repository
root for an example.
[wrote an article]: http://www.harpersbazaar.com/culture/features/a12063822/emotional-labor-gender-equality/

View file

@ -1,21 +0,0 @@
;; Example configuration file for Gemma
(config :port 4242
:data-dir "/tmp/gemma/")
(deftask bathroom/wipe-mirror 7)
(deftask bathroom/wipe-counter 7)
;; Bedroom tasks
(deftask bedroom/change-sheets 7)
(deftask bedroom/vacuum 10)
;; Kitchen tasks
(deftask kitchen/normal-trash 3)
(deftask kitchen/green-trash 5)
(deftask kitchen/blue-trash 5)
(deftask kitchen/wipe-counters 3)
(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!")
;; Entire place
(deftask clean-windows 60)

View file

@ -1,56 +0,0 @@
{ depot, ... }:
let
inherit (depot.third_party.elmPackages_0_18) cacert iana-etc libredirect stdenv runCommand writeText elmPackages;
frontend = stdenv.mkDerivation {
name = "gemma-frontend.html";
src = ./frontend;
buildInputs = [ cacert iana-etc elmPackages.elm ];
# The individual Elm packages this requires are not packaged and I
# can't be bothered to do that now, so lets open the escape hatch:
outputHashAlgo = "sha256";
outputHash = "000xhds5bsig3kbi7dhgbv9h7myacf34bqvw7avvz7m5mwnqlqg7";
phases = [ "unpackPhase" "buildPhase" ];
buildPhase = ''
export NIX_REDIRECTS=/etc/protocols=${iana-etc}/etc/protocols \
LD_PRELOAD=${libredirect}/lib/libredirect.so
export SYSTEM_CERTIFICATE_PATH=${cacert}/etc/ssl/certs
mkdir .home && export HOME="$PWD/.home"
elm-make --yes Main.elm --output $out
'';
};
injectFrontend = writeText "gemma-frontend.lisp" ''
(in-package :gemma)
(setq *static-file-location* "${runCommand "frontend" {} ''
mkdir -p $out
cp ${frontend} $out/index.html
''}/")
'';
in
depot.nix.buildLisp.program {
name = "gemma";
deps = with depot.third_party.lisp; [
cl-json
cl-prevalence
hunchentoot
local-time
];
srcs = [
./src/gemma.lisp
injectFrontend
];
# depends on SBCL
brokenOn = [
"ccl"
"ecl"
];
}

View file

@ -1,221 +0,0 @@
-- Copyright (C) 2016-2017 Vincent Ambo <mail@tazj.in>
--
-- This file is part of Gemma.
--
-- Gemma 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.
module Main exposing (..)
import Html exposing (Html, text, div, span)
import Html.Attributes exposing (style)
import Json.Decode exposing (..)
import Http
import Time
-- Material design imports
import Material
import Material.Card as Card
import Material.Color as Color
import Material.Grid exposing (grid, cell, size, Device(..))
import Material.Layout as Layout
import Material.Scheme as Scheme
import Material.Options as Options
import Material.Elevation as Elevation
import Material.Button as Button
-- API interface to Gemma
type alias Task =
{ name : String
, description : Maybe String
, remaining : Int
}
emptyStringFilter s =
if s == "" then
Nothing
else
Just s
decodeEmptyString : Decoder (Maybe String)
decodeEmptyString =
map emptyStringFilter string
decodeTask : Decoder Task
decodeTask =
map3 Task
(field "name" string)
(field "description" decodeEmptyString)
(field "remaining" int)
loadTasks : Cmd Msg
loadTasks =
let
request =
Http.get "/tasks" (list decodeTask)
in
Http.send NewTasks request
completeTask : Task -> Cmd Msg
completeTask task =
let
request =
Http.getString
(String.concat
[ "/complete?task="
, task.name
]
)
in
Http.send (\_ -> LoadTasks) request
-- Elm architecture implementation
type Msg
= None
| LoadTasks
| NewTasks (Result Http.Error (List Task))
| Mdl (Material.Msg Msg)
| Complete Task
type alias Model =
{ tasks : List Task
, error : Maybe String
, mdl : Material.Model
}
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LoadTasks ->
( model, loadTasks )
Complete task ->
( model, completeTask task )
NewTasks (Ok tasks) ->
( { model | tasks = tasks, error = Nothing }, Cmd.none )
NewTasks (Err err) ->
( { model | error = Just (toString err) }, Cmd.none )
_ ->
( model, Cmd.none )
-- View implementation
white =
Color.text Color.white
taskColor : Task -> Color.Hue
taskColor task =
if task.remaining > 2 then
Color.Green
else if task.remaining < 0 then
Color.Red
else
Color.Yellow
within : Task -> String
within task =
if task.remaining < 0 then
"This task is overdue!"
else if task.remaining > 2 then
String.concat
[ "Relax, this task has "
, toString task.remaining
, " days left before it is due."
]
else
String.concat
[ "This task should be completed within "
, toString task.remaining
, " days. Consider doing it now!"
]
renderTask : Model -> Task -> Html Msg
renderTask model task =
Card.view
[ Color.background (Color.color (taskColor task) Color.S800)
, Elevation.e3
]
[ Card.title [] [ Card.head [ white ] [ text task.name ] ]
, Card.text [ white ]
[ text (Maybe.withDefault "" task.description)
, Html.br [] []
, text (within task)
]
, Card.actions
[ Card.border ]
[ Button.render Mdl
[ 0 ]
model.mdl
[ white, Button.ripple, Button.accent, Options.onClick (Complete task) ]
[ text "Completed" ]
]
]
gemmaView : Model -> Html Msg
gemmaView model =
grid []
(List.map (\t -> cell [ size All 4 ] [ renderTask model t ])
model.tasks
)
view : Model -> Html Msg
view model =
gemmaView model |> Scheme.top
-- subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Material.subscriptions Mdl model
, Time.every (15 * Time.second) (\_ -> LoadTasks)
]
main : Program Never Model Msg
main =
let
model =
{ tasks = []
, error = Nothing
, mdl = Material.model
}
in
Html.program
{ init = ( model, Cmd.batch [ loadTasks, Material.init Mdl ] )
, view = view
, update = update
, subscriptions = subscriptions
}

View file

@ -1,17 +0,0 @@
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"elm-lang/http": "1.0.0 <= v < 2.0.0",
"debois/elm-mdl": "8.1.0 <= v < 9.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}

View file

@ -1,192 +0,0 @@
;; Copyright (C) 2016-2020 Vincent Ambo <mail@tazj.in>
;;
;; This file is part of Gemma.
;;
;; Gemma 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.
(defpackage gemma
(:use :cl
:local-time
:cl-json)
(:import-from :sb-posix :getenv)
(:shadowing-import-from :sb-posix :getcwd)
(:export :start-gemma :config :main))
(in-package :gemma)
;; TODO: Store an average of how many days it was between task
;; completions. Some of the current numbers are just guesses
;; anyways.
(defmacro in-case-of (x &body body)
"Evaluate BODY if X is non-nil, binding the value of X to IT."
`(let ((it ,x))
(when it ,@body)))
;; Set default configuration parameters
(defvar *gemma-port* 4242
"Port on which the Gemma web server listens.")
(defvar *gemma-acceptor* nil
"Hunchentoot acceptor for Gemma's web server.")
(defvar *static-file-location* "frontend/"
"Folder from which to serve static assets. If built inside of Nix,
the path is injected during the build.")
(defvar *p-tasks* nil
"All tasks registered in this Gemma instance.")
(defun initialise-persistence (data-dir)
(setq *p-tasks* (cl-prevalence:make-prevalence-system data-dir))
;; Initialise database ID counter
(or (> (length (cl-prevalence:find-all-objects *p-tasks* 'task)) 0)
(cl-prevalence:tx-create-id-counter *p-tasks*)))
(defun config (&key port data-dir)
"Configuration function for use in the Gemma configuration file."
(in-package :gemma)
(in-case-of port (defparameter *gemma-port* it))
(initialise-persistence (or data-dir "data/")))
;;
;; Define task management system
;;
(defclass task ()
((id :reader id
:initarg :id)
;; (Unique) name of the task
(name :type symbol
:initarg :name
:accessor name-of)
;; Maximum completion interval
(days :type integer
:initarg :days
:accessor days-of)
;; Optional description
(description :type string
:initarg :description
:accessor description-of)
;; Last completion time
(done-at :type timestamp
:initarg :done-at
:accessor last-done-at)))
(defmacro deftask (task-name days &optional description)
(unless (get-task task-name)
`(progn (cl-prevalence:tx-create-object
*p-tasks*
'task
(quote ((name ,task-name)
(days ,days)
(description ,(or description ""))
(done-at ,(now)))))
(cl-prevalence:snapshot *p-tasks*))))
(defun get-task (name)
(cl-prevalence:find-object-with-slot *p-tasks* 'task 'name name))
(defun list-tasks ()
(cl-prevalence:find-all-objects *p-tasks* 'task))
(defun days-remaining (task)
"Returns the number of days remaining before the supplied TASK reaches its
maximum interval."
(let* ((expires-at (timestamp+ (last-done-at task)
(days-of task) :day))
(secs-until-expiry (timestamp-difference expires-at (now))))
(round (/ secs-until-expiry 60 60 24))))
(defun sort-tasks (tasks)
"Sorts TASKS in descending order by number of days remaining."
(sort (copy-list tasks)
(lambda (t1 t2) (< (days-remaining t1)
(days-remaining t2)))))
(defun complete-task (name &optional at)
"Mark the task with NAME as completed, either now or AT specified time."
(cl-prevalence:tx-change-object-slots *p-tasks* 'task
(id (get-task name))
`((done-at ,(or at (now)))))
(cl-prevalence:snapshot *p-tasks*))
;;
;; Define web API
;;
(defun response-for (task)
"Create a response object to be JSON encoded for TASK."
`((:name . ,(name-of task))
(:description . ,(description-of task))
(:remaining . ,(days-remaining task))))
(defun start-gemma ()
(in-package :gemma)
;; Load configuration
(load (pathname (or (getenv "GEMMA_CONFIG")
"/etc/gemma/config.lisp")))
;; Set up web server
(setq *gemma-acceptor* (make-instance 'hunchentoot:easy-acceptor
:port *gemma-port*
:document-root *static-file-location*))
(hunchentoot:start *gemma-acceptor*)
;; Task listing handler
(hunchentoot:define-easy-handler
(get-tasks :uri "/tasks") ()
(setf (hunchentoot:content-type*) "application/json")
(setf (hunchentoot:header-out "Access-Control-Allow-Origin") "*")
(encode-json-to-string
;; Construct a frontend-friendly representation of the tasks.
(mapcar #'response-for (sort-tasks (list-tasks)))))
;; Task completion handler
(hunchentoot:define-easy-handler
(complete-task-handler :uri "/complete") (task)
(setf (hunchentoot:content-type*) "application/json")
(let* ((key (find-symbol (camel-case-to-lisp task) "GEMMA")))
(format t "Marking task ~A as completed" key)
(complete-task key)
(encode-json-to-string (response-for (get-task key))))))
(defun main ()
"This function serves as the entrypoint for ASDF-built executables.
It joins the Hunchentoot server thread to keep the process running
for as long as the server is alive."
(start-gemma)
(sb-thread:join-thread
(find-if (lambda (th)
(string= (sb-thread:thread-name th)
(format nil "hunchentoot-listener-*:~A" *gemma-port*)))
(sb-thread:list-all-threads))))
;; Experimentation / testing stuff
(defun randomise-completion-times ()
"Set some random completion timestamps for all tasks"
(mapcar
(lambda (task)
(complete-task (name-of task)
(timestamp- (now)
(random 14)
:day)))
(cl-prevalence:find-all-objects *p-tasks* 'task)))
(defun clear-all-tasks ()
(mapcar (lambda (task) (cl-prevalence:tx-delete-object *p-tasks* 'task (id task)))
(cl-prevalence:find-all-objects *p-tasks* 'task)))
;; (randomise-completion-times)

View file

@ -1,34 +0,0 @@
# iDual light control
This folder contains some tooling for controlling iDual LED lights
(which use infrared controls) using a "Broadlink RM Pro" infrared
controller.
The supported colour codes of the iDual remote are stored in
`codes.txt`.
The point of this is to make it possible for me to automate my lights
in the morning, so that I can actually get out of bed.
## Capturing codes
Capturing codes is relatively easy, assuming that the broadlink device
is set up:
```python
import broadlink
import base64
devices = broadlink.discover(timeout=5)
devices[0].auth()
```
For each code, the procedure is as follows:
```python
devices[0].find_rf_packet()
# wait until this returns True
devices[0].check_data()
# this will return the code
```

View file

@ -1,25 +0,0 @@
{ depot, pkgs, lib, ... }:
let
inherit (pkgs) python3 python3Packages;
opts = {
pname = "idualctl";
version = "0.1";
src = ./.;
propagatedBuildInputs = [
depot.third_party.python.broadlink
];
};
package = python3Packages.buildPythonPackage opts;
script = python3Packages.buildPythonApplication opts;
in
depot.nix.readTree.drvTargets {
inherit script;
python = python3.withPackages (_: [ package ]);
setAlarm = pkgs.writeShellScriptBin "set-alarm" ''
echo "setting an alarm for ''${1}"
${pkgs.systemd}/bin/systemd-run --user --on-calendar="''${1} Europe/London" --unit=light-alarm.service
'';
}

View file

@ -1,65 +0,0 @@
import base64
import broadlink
import time
import sys
commands = {
# system commands
'on' : 'JgBIAAABK5AVERQ2FBEUERQSFBEUERQSFBEUNhQ2FDUUNhQ2FDYUNRU1FBIUERQRFBIUERQRFBIUERQ2FDYUNRQ2FDYUNhQ1FQANBQ==',
'off' : 'JgBIAAABLJAUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQRFDYUERQSFBEUERQSFBEUNhQRFDYUNhQ2FDUUNhQ2FAANBQ==',
'darker' : 'JgBIAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFBIUERQRFDYUEhQRFBEVNRQ2FDYUNhQRFDYUNhQ1FQANBQ==',
'brighter' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUERQ2FBEUEhQRFBEUEhQ1FTUUEhQ1FTUUNhQ2FAANBQ==',
# presets
'candle' : 'JgBQAAABKZISExI4EhMSFBITEhQRFBITEhQROBI4EjgSOBE4EjgSOBI4ERQSExIUEjgRFBITEhQSExI4EjgROBIUEjcSOBI4EgAFJgABKUkSAA0FAAAAAAAAAAA=',
'bulb' : 'JgBYAAABK5AUERQ2FBEVERQRFBEVERQRFBEVNRQ2FDYUNRU1FDYUNhQRFDYUNRURFBEUEhQRFBEUNhQRFREUNhQ1FDYUNhQ2FAAFIwABKkgVAAxOAAErRxUADQU=',
'sun' : 'JgBQAAABLI8VERQ2FBEUERURFBEUEhQRFBEUNhQ2FDYUNRU1FTUUNhQSFDUUEhQ2FBEUERURFBEUNhQSFDUUEhQ2FDUVNRQ2FAAFJQABK0cVAA0FAAAAAAAAAAA=',
'cold' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FTUUEhQRFBEUEhQRFBIUERQRFDYUNhQ2FDYUNRQ2FAAFJAABK0cVAA0FAAAAAAAAAAA=',
'eve_dark' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQSFDUUEhQRFBIUNRQSFDUUNhQSFDUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=',
'eve_fade' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ1FDYUNhQRFDYUERQSFBEUEhQRFBEUNhQSEzYUNhQ2FAANBQ==',
'reading' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNhQ1FDYUEhQ1FBIUERQRFBIUERQSFDUUEhQ1FTUUNhQ2FAAFJAABK0YVAA0FAAAAAAAAAAA=',
'yoga' : 'JgBYAAABLI8VERQ1FREUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRURFBEUNhQRFBIUERMSExMTNxM2ExMTNxM2EzcTNxM3EwAFJQABKkgTAAxRAAErRxUADQU=',
'morning' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FDYUERURFDUVERQRFBIUERQRFTUUNhQRFDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=',
'colours' : 'JgBQAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQSFBEUERQ2FDYUERQSFBEUNhQ1FTUUEhQRFDYUNRU1FAAFJAABKkcVAA0FAAAAAAAAAAA=',
'random' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSExIUNhQ1EzcTNxM3EzYTNxMTEhMTNxM2ExMTEhMSExMTNxM2ExMTEhM3EzcTNhM3EwAFJQABK0cVAA0FAAAAAAAAAAA=',
'island' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRURFBEUEhQRFBEUEhQ1FREUNhQ1FDYUNhQ2FAAFIwABK0cVAA0FAAAAAAAAAAA=',
'forest' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FTUUNhQ2FDUVNRQSFBEUNhQRFDYUERQSFBEUNhQ2FBEUNhQRFDYUNhQ1FQAFIwABK0cVAA0FAAAAAAAAAAA=',
'ocean' : 'JgBQAAABK5AUEhQ1FREUERQSFBEUERQRFREUNhQ1FTUUNhQ2FDUVNRQ2FBEUEhQ1FTUUEhQRFBEUEhQ1FTUUEhQRFDYUNRU1FAAFJAABK0cVAA0FAAAAAAAAAAA=',
'fire' : 'JgBQAAABK5AUERQ2FBEUEhQRFBEUEhQRFBEUNhQ2FDUVNRQ2FDYUNRU1FBIUNRU1FBIUERQRFBIUERQ2FBEUEhQ1FTUUNhQ2FAAFIwABLEYVAA0FAAAAAAAAAAA=',
'love' : 'JgBQAAABL5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFDUUNhQSFBEUERQSFBEUNhQRFBIUNRQ2FDYUNhQ1FAAFJAABK0cVAA0FAAAAAAAAAAA=',
# colour commands
'red' : 'JgBIAAABK5AUERQ2FBEUEhQRFBEVERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUNhQ1FREUERQSFBEUNhQRFBIUERQ2FDUVNRQ2FAANBQ==',
'yellow' : 'JgBIAAABLI8UEhQ2FBEUERQSFBEUEhMSFBEUNhQ2FDUUNhQ2FDYUNRQ2FDYUNhQRFBIUERQRFBIUERQSExIUNhQ1FDYUNhQ2FAANBQ==',
'green' : 'JgBIAAABK5AUEhQ1FREUERQSFBEUERQSFBEUNhQ1FDYUNhQ2FDUVNRQSFBEUERQ2FBIUERQRFBIUNRU1FDYUERQ2FDYUNhQ1FQANBQ==',
'blue' : 'JgBIAAABK5AUERQ2FBEUEhQRFBITEhQRFBEUNhQ2FDYUNRQ2FDYUNhQ2ExIUNhQRFDYUERQSExIUERQ2FBEUNhQSEzYUNhQ2FAANBQ==',
'saturate' : 'JgBIAAABK5AUERQ2FBEUEhQRFBIUERQRFBEUNhQ2FDYUNRU1FDYUNhQRFDYUERQ2FDYUERQSFBEUNhQRFDYUERQSFDUUNhQ2FAANBQ==',
'desaturate' : 'JgBIAAABLI8VERQ2FBEUERQSFBEUERURFBEUNhQ1FTUUNhQ2FDYUNRQ2FDYUNhQ1FREUERQSFBEUERQSFBEUERQ2FDYUNhQ1FQANBQ==',
}
def cmd(name):
return base64.b64decode(commands[name])
class LightController:
def __init__(self):
self.devices = broadlink.discover(timeout=10, max_devices=2)
if self.devices == []:
raise Exception('no devices found')
for device in self.devices:
device.auth()
def send_cmd(self, name, iterations=5):
"Send a command, repeatedly for reliability"
packet = cmd(name)
for i in range(iterations):
for device in self.devices:
device.send_data(packet)
def wakey(self):
"Turn on the lights in the morning, try repeatedly for reasons."
print('Turning on the lights. Wakey, wakey!')
for i in range(5):
self.send_cmd('random')
time.sleep(0.3)
self.send_cmd('on')
time.sleep(0.3)

View file

@ -1,39 +0,0 @@
#!/usr/bin/env python
import idual
import sys
def help():
print('Available commands:')
for cmd in idual.commands:
print('- ' + cmd)
sys.exit(0)
def handle(ctrl, cmd):
if cmd == 'help':
help()
elif cmd == 'wakey':
ctrl.wakey()
sys.exit(0)
elif cmd == 'on':
print('Turning on the lights')
ctrl.send_cmd(cmd)
elif cmd == 'off':
print('Turning off the lights')
ctrl.send_cmd(cmd)
elif cmd in idual.commands:
print('Sending ' + cmd + '-command')
ctrl.send_cmd(cmd)
else:
print('unknown command \'' + cmd + '\'')
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) == 1:
help()
print('Initialising light controller')
ctrl = idual.LightController()
for cmd in sys.argv[1:]:
handle(ctrl, cmd)

View file

@ -1,15 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='idualctl',
version='0.1',
author='Vincent Ambo',
author_email='mail@tazj.in',
url='https://git.tazj.in/about/fun/idual',
packages=['idual'],
scripts = ['idualctl'],
install_requires=['broadlink>=0.13.2'],
include_package_data=True,
)

View file

@ -1 +0,0 @@
eval "$(lorri direnv)"

View file

@ -1,30 +0,0 @@
dist
dist-*
build/
cabal-dev
*.o
*.hi
*.hie
*.chi
*.chs.h
*.dyn_o
*.dyn_hi
.hpc
.hsenv
.cabal-sandbox/
cabal.sandbox.config
*.prof
*.aux
*.hp
*.eventlog
.stack-work/
cabal.project.local
cabal.project.local~
.HTF/
.ghc.environment.*
# from nix-build
result
# grr
*_flymake.hs

View file

@ -1,19 +0,0 @@
diff --git a/src/NLP/POS/LiteralTagger.hs b/src/NLP/POS/LiteralTagger.hs
index 913bee8..3c2f71d 100644
--- a/src/NLP/POS/LiteralTagger.hs
+++ b/src/NLP/POS/LiteralTagger.hs
@@ -1,4 +1,4 @@
-{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE OverloadedStrings, PackageImports #-}
module NLP.POS.LiteralTagger
( tag
, tagSentence
@@ -27,7 +27,7 @@ import NLP.FullStop (segment)
import NLP.Types ( tagUNK, Sentence, TaggedSentence(..), applyTags
, Tag, POSTagger(..), CaseSensitive(..), tokens, showTok)
import Text.Regex.TDFA
-import Text.Regex.TDFA.Text (compile)
+import "regex-tdfa" Text.Regex.TDFA.Text (compile)
taggerID :: ByteString
taggerID = pack "NLP.POS.LiteralTagger"

View file

@ -1,13 +0,0 @@
{ depot ? (import ../../../. { })
, pkgs ? depot.third_party.nixpkgs
, ...
}:
let
basePkg = pkgs.haskellPackages.callPackage ./pkg.nix { };
in
pkgs.haskell.lib.overrideSrc basePkg {
src = depot.third_party.gitignoreSource ./.;
version = "canon";
}

View file

@ -1,4 +0,0 @@
cradle:
cabal:
- path: './app'
component: 'exe:owothia'

View file

@ -1,53 +0,0 @@
cabal-version: 2.2
name: owothia
version: 0.0.1.0
executable owothia
main-is: Main.hs
build-depends: base
, relude
, irc-client
, lens
, chatter
, containers
, text
, bytestring
, random
, envy
mixins: base hiding (Prelude)
, relude (Relude as Prelude)
hs-source-dirs:
src
default-extensions:
BlockArguments
ConstraintKinds
DataKinds
DeriveAnyClass
DeriveGeneric
DerivingStrategies
DerivingVia
FlexibleContexts
FlexibleInstances
FunctionalDependencies
GADTSyntax
GeneralizedNewtypeDeriving
KindSignatures
LambdaCase
MultiWayIf
NoStarIsType
OverloadedStrings
PolyKinds
RankNTypes
ScopedTypeVariables
TupleSections
TypeApplications
TypeFamilies
TypeOperators
ViewPatterns
ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N -O2
default-language: Haskell2010

View file

@ -1,34 +0,0 @@
{ mkDerivation
, base
, bytestring
, chatter
, containers
, envy
, irc-client
, lens
, lib
, random
, relude
, text
}:
mkDerivation {
pname = "owothia";
version = "0.0.1.0";
src = ./.;
isLibrary = false;
isExecutable = true;
executableHaskellDepends = [
base
bytestring
chatter
containers
envy
irc-client
lens
random
relude
text
];
license = "unknown";
hydraPlatforms = lib.platforms.none;
}

View file

@ -1,40 +0,0 @@
diff --git a/Text/Regex/TDFA/Text.hs b/Text/Regex/TDFA/Text.hs
index c4ef9db..9299272 100644
--- a/Text/Regex/TDFA/Text.hs
+++ b/Text/Regex/TDFA/Text.hs
@@ -38,13 +38,6 @@ import Text.Regex.TDFA.NewDFA.Uncons(Uncons(uncons))
import qualified Text.Regex.TDFA.NewDFA.Engine as Engine(execMatch)
import qualified Text.Regex.TDFA.NewDFA.Tester as Tester(matchTest)
-instance Extract T.Text where
- before = T.take; after = T.drop; empty = T.empty
-
-instance Uncons T.Text where
- {- INLINE uncons #-}
- uncons = T.uncons
-
instance RegexContext Regex T.Text T.Text where
match = polymatch
matchM = polymatchM
diff --git a/Text/Regex/TDFA/Text/Lazy.hs b/Text/Regex/TDFA/Text/Lazy.hs
index 73ca4a0..52958fb 100644
--- a/Text/Regex/TDFA/Text/Lazy.hs
+++ b/Text/Regex/TDFA/Text/Lazy.hs
@@ -38,17 +38,10 @@ import Text.Regex.TDFA.NewDFA.Uncons(Uncons(uncons))
import qualified Text.Regex.TDFA.NewDFA.Engine as Engine(execMatch)
import qualified Text.Regex.TDFA.NewDFA.Tester as Tester(matchTest)
-instance Extract L.Text where
- before = L.take . toEnum; after = L.drop . toEnum; empty = L.empty
-
instance RegexContext Regex L.Text L.Text where
match = polymatch
matchM = polymatchM
-instance Uncons L.Text where
- {- INLINE uncons #-}
- uncons = L.uncons
-
instance RegexMaker Regex CompOption ExecOption L.Text where
makeRegexOptsM c e source = makeRegexOptsM c e (L.unpack source)

View file

@ -1,22 +0,0 @@
{ pkgs ? (import ../../../. { }).third_party, ... }:
let
inherit (pkgs)
haskellPackages
haskell
gitignoreSource
;
in
(haskellPackages.extend (haskell.lib.packageSourceOverrides {
owothia = gitignoreSource ./.;
})).shellFor {
packages = p: [ p.owothia ];
withHoogle = true;
doBenchmark = true;
buildInputs = with haskellPackages; [
cabal-install
hlint
haskell-language-server
];
}

View file

@ -1,168 +0,0 @@
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Network.IRC.Client
import Control.Lens
import NLP.POS
import NLP.Types (POSTagger)
import qualified NLP.Types.Tags as Tags
import NLP.Types.Tree
import qualified NLP.Corpora.Conll as Conll
import NLP.Corpora.Conll (Tag)
import qualified Data.ByteString as BS
import System.Random
import System.Envy
import System.IO as S
import Data.Maybe
import Data.Foldable (traverse_)
import qualified Data.Text
--------------------------------------------------------------------------------
data Config = Config
{ _owoChance :: Int
, _ircServer :: ByteString
, _ircPort :: Int
, _ircServerPassword :: Maybe Text
, _nickservPassword :: Maybe Text
, _ircNick :: Maybe Text
, _ircIdent :: Maybe Text
, _ircChannels :: [Text]
}
deriving stock (Show, Eq, Generic)
makeLenses ''Config
instance Var [Text] where
toVar ts = show ts
fromVar s = readMaybe s >>= (pure . map Data.Text.pack)
instance FromEnv Config where
fromEnv _ =
Config <$> env "OWO_CHANCE"
<*> env "IRC_SERVER"
<*> env "IRC_PORT"
<*> envMaybe "IRC_SERVER_PASSWORD"
<*> envMaybe "NICKSERV_PASSWORD"
<*> envMaybe "IRC_NICK"
<*> envMaybe "IRC_IDENT"
<*> env "IRC_CHANNELS"
stopWord :: Text -> Bool
stopWord "'s" = True
stopWord "\"" = True
stopWord "is" = True
stopWord "are" = True
stopWord "am" = True
stopWord "were" = True
stopWord "was" = True
stopWord "be" = True
stopWord _ = False
pickVerb :: POS Tag -> Maybe Text
pickVerb (POS Conll.VB (Token verb)) = Just verb
pickVerb (POS Conll.VBD (Token verb)) = Just verb
pickVerb (POS Conll.VBG (Token verb)) = Just verb
pickVerb (POS Conll.VBN (Token verb)) = Just verb
pickVerb (POS Conll.VBZ (Token verb)) = Just verb
pickVerb _ = Nothing
pickNoun :: POS Tag -> Maybe Text
pickNoun (POS Conll.NN (Token noun)) = Just noun
pickNoun _ = Nothing
randomPOS
:: Tags.Tag tag
=> (POS tag -> Maybe Text)
-> POSTagger tag
-> Text
-> IO (Maybe Text)
randomPOS pickPOS tagger s = do
let candidates
= filter (not . stopWord)
. mapMaybe pickPOS
$ tag tagger s >>= \(TaggedSent ps) -> ps
i <- randomRIO (0, length candidates - 1)
pure $ candidates ^? ix i
doOwo :: MonadIO m => Config -> m Bool
doOwo conf = do
n <- liftIO (randomRIO @Int (0, conf ^. owoChance))
pure $ n == 0
data OwoType = Noun | Verb
deriving stock (Show, Eq)
instance Random OwoType where
random = over _1 (bool Noun Verb) . random
randomR = const random
vowels :: [Char]
vowels = "aeiou"
article :: Text -> Text
article (x :< _) | x `elem` vowels = "an"
article _ = "a"
owo :: OwoType -> Text -> Text
owo Noun n = mconcat
[ "I'm "
, article n
, " "
, n
, if "o" `Data.Text.isSuffixOf` n
then "wo"
else " owo"
]
owo Verb v = v <> " me owo"
pickOwo :: OwoType -> POS Tag -> Maybe Text
pickOwo Verb = pickVerb
pickOwo Noun = pickNoun
randomOwo :: OwoType -> POSTagger Tag -> Text -> IO (Maybe Text)
randomOwo = randomPOS . pickOwo
owothiaHandler :: Config -> Text -> IORef Bool -> POSTagger Tag -> EventHandler s
owothiaHandler conf nick state tagger = EventHandler Just $ \src ev -> do
hasIdentified <- readIORef state
when (not hasIdentified) $ do
nickservAuth
traverse_ (send . Join) (conf ^. ircChannels)
writeIORef state True
when ("You are now identified" `BS.isInfixOf` (ev ^. raw)) $
traverse_ (send . Join) (conf ^. ircChannels)
case (src, ev ^. message) of
(Channel chan nick, Privmsg _ (Right m)) -> do
willOwo <- doOwo conf
when willOwo $ owoMessage chan m
_ -> pure()
pure ()
where
owoMessage chan m = do
owoType <- liftIO randomIO
mWord <- liftIO $ randomOwo owoType tagger m
for_ mWord $ \word -> send $ Privmsg chan $ Right $ owo owoType word
nickservAuthMsg = "IDENTIFY " <> nick <> " " <> fromJust (conf ^. nickservPassword)
nickservAuth = send $ Privmsg "NickServ" $ Right nickservAuthMsg
main :: IO ()
main = do
conf <- either fail pure =<< decodeEnv
tagger <- defaultTagger
state <- newIORef $ not . isJust $ (conf ^. nickservPassword)
S.hSetBuffering stdout LineBuffering
let nick = fromMaybe "owothia" (conf ^. ircNick)
conn =
plainConnection (conf ^. ircServer) (conf ^. ircPort)
& realname .~ "Owothia Revströwö"
& password .~ (conf ^. ircServerPassword)
& username .~ fromMaybe "owothia" (conf ^. ircIdent)
& logfunc .~ stdoutLogger
cfg =
defaultInstanceConfig nick
& channels .~ (conf ^. ircChannels)
& handlers %~ (owothiaHandler conf nick state tagger : )
runClient conn cfg ()

View file

@ -1,5 +0,0 @@
/target
irc.toml
paroxysm-irc.toml
paroxysm.toml
**/*.rs.bk

1881
fun/paroxysm/Cargo.lock generated

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,31 +0,0 @@
[package]
authors = ["eeeeeta <eta@theta.eu.org>"]
edition = "2018"
name = "paroxysm"
version = "0.1.0"
[dependencies]
chrono = "0.4"
config = "0.9"
crimp = { path = "../../net/crimp" }
env_logger = "0.7"
failure = "0.1"
irc = "0.13"
lazy_static = "1.4"
log = "0.4"
rand = "0.7"
regex = "1.3"
serde = { version = "1.0", features = [ "derive" ] }
[dependencies.diesel]
features = [ "postgres", "chrono", "r2d2" ]
version = "1.4"
# Add bogus dependency on any version of pq-sys, so we can force the pkg-config
# flag since pg_config reports an incorrect libdir in pkgs.libpq
# https://github.com/NixOS/nixpkgs/pull/359659#issuecomment-2660995914
# https://github.com/NixOS/nixpkgs/pull/382380
# https://github.com/sgrif/pq-sys/issues/75
[dependencies.pq-sys]
features = [ "pkg-config" ]
version = "*"

View file

@ -1 +0,0 @@
eta

View file

@ -1,19 +0,0 @@
paroxysm
========
`paroxysm` is a bot for [internet relay chat
(IRC)](https://en.wikipedia.org/wiki/Internet_Relay_Chat) that lets you store
small pieces of information, called *factoids*, and retrieve them later. It's
useful for organising frequently-used information to avoid repeating oneself in
a busy chatroom, as well as making little todo lists or notes to self in a
private chatroom.
It was directly inspired by the
[LearnDB](https://github.com/crawl/sequell/blob/master/docs/learndb.md)
functionality offered in `##crawl` on chat.freenode.net, and uses similar
syntax.
## Usage instructions
Will come soon; the project is very much still in beta, and is subject to
change.

View file

@ -1,10 +0,0 @@
{ pkgs, ... }:
let
cargoNix = import ./Cargo.nix {
inherit pkgs;
nixpkgs = pkgs.path;
};
in
cargoNix.rootCrate.build

View file

@ -1,7 +0,0 @@
{ depot, pkgs, ... }:
pkgs.dockerTools.buildLayeredImage {
name = "paroxysm";
contents = [ depot.fun.paroxysm ];
config.Entrypoint = [ "${depot.fun.paroxysm}/bin/paroxysm" ];
}

View file

@ -1,2 +0,0 @@
DROP TABLE entries;
DROP TABLE keywords;

View file

@ -1,15 +0,0 @@
CREATE TABLE keywords (
id SERIAL PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
chan VARCHAR NOT NULL,
UNIQUE(name, chan)
);
CREATE TABLE entries (
id SERIAL PRIMARY KEY,
keyword_id INT NOT NULL REFERENCES keywords ON DELETE CASCADE,
idx INT NOT NULL,
text VARCHAR NOT NULL,
creation_ts TIMESTAMP NOT NULL,
created_by VARCHAR NOT NULL
);

View file

@ -1 +0,0 @@
-- This file should undo anything in `up.sql`

View file

@ -1 +0,0 @@
ALTER TABLE keywords DROP CONSTRAINT IF EXISTS keywords_name_key;

View file

@ -1,12 +0,0 @@
use serde::Deserialize;
use std::collections::HashSet;
#[derive(Deserialize)]
pub struct Config {
pub database_url: String,
pub irc_config_path: String,
#[serde(default)]
pub admins: HashSet<String>,
#[serde(default)]
pub log_filter: Option<String>,
}

View file

@ -1,219 +0,0 @@
use crate::models::{Entry, Keyword, NewEntry, NewKeyword};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use failure::{format_err, Error};
use std::borrow::Cow;
/// Maximum number of times we'll follow a `see: ` pointer.
const RECURSION_LIMIT: usize = 5;
pub struct KeywordDetails {
pub keyword: Keyword,
pub entries: Vec<Entry>,
}
impl KeywordDetails {
pub fn learn(&mut self, nick: &str, text: &str, dbc: &PgConnection) -> Result<usize, Error> {
let now = ::chrono::Utc::now().naive_utc();
let ins = NewEntry {
keyword_id: self.keyword.id,
idx: (self.entries.len() + 1) as _,
text,
creation_ts: now,
created_by: nick,
};
let new = {
use crate::schema::entries;
::diesel::insert_into(entries::table)
.values(ins)
.get_result(dbc)?
};
self.entries.push(new);
Ok(self.entries.len())
}
pub fn process_moves(&mut self, moves: &[(i32, i32)], dbc: &PgConnection) -> Result<(), Error> {
for (oid, new_idx) in moves {
{
use crate::schema::entries::dsl::*;
::diesel::update(entries.filter(id.eq(oid)))
.set(idx.eq(new_idx))
.execute(dbc)?;
}
}
self.entries = Self::get_entries(self.keyword.id, dbc)?;
Ok(())
}
pub fn swap(&mut self, idx_a: usize, idx_b: usize, dbc: &PgConnection) -> Result<(), Error> {
let mut moves = vec![];
for ent in self.entries.iter() {
if ent.idx == idx_a as i32 {
moves.push((ent.id, idx_b as i32));
}
if ent.idx == idx_b as i32 {
moves.push((ent.id, idx_a as i32));
}
}
if moves.len() != 2 {
Err(format_err!("Invalid swap operation."))?;
}
self.process_moves(&moves, dbc)?;
Ok(())
}
pub fn update(&mut self, idx: usize, val: &str, dbc: &PgConnection) -> Result<(), Error> {
let ent = self
.entries
.get_mut(idx.saturating_sub(1))
.ok_or(format_err!("No such element to update."))?;
{
use crate::schema::entries::dsl::*;
::diesel::update(entries.filter(id.eq(ent.id)))
.set(text.eq(val))
.execute(dbc)?;
}
ent.text = val.to_string();
Ok(())
}
pub fn delete(&mut self, idx: usize, dbc: &PgConnection) -> Result<(), Error> {
// step 1: delete the element
{
let ent = self
.entries
.get(idx.saturating_sub(1))
.ok_or(format_err!("No such element to delete."))?;
{
use crate::schema::entries::dsl::*;
::diesel::delete(entries.filter(id.eq(ent.id))).execute(dbc)?;
}
}
// step 2: move all the elements in front of it back one
let mut moves = vec![];
for ent in self.entries.iter() {
if idx > ent.idx as _ {
moves.push((ent.id, ent.idx.saturating_sub(1)));
}
}
self.process_moves(&moves, dbc)?;
Ok(())
}
pub fn add_zwsp_to_name(name: &str) -> Option<String> {
let second_index = name.char_indices().nth(1).map(|(i, _)| i)?;
let (start, end) = name.split_at(second_index);
Some(format!("{}{}", start, end))
}
pub fn format_entry(&self, idx: usize) -> Option<String> {
self.format_entry_colours(idx, true)
}
pub fn format_entry_colours(&self, idx: usize, with_colours: bool) -> Option<String> {
if let Some(ent) = self.entries.get(idx.saturating_sub(1)) {
let gen_clr = if self.keyword.chan == "*" && with_colours {
"\x0307"
} else {
""
};
let zwsp_name = Self::add_zwsp_to_name(&self.keyword.name)
.unwrap_or_else(|| self.keyword.name.clone());
Some(format!(
"{}{}{name}{}[{idx}/{total}]{}: {text} {}[{date}]{}",
if with_colours { "\x02" } else { "" },
gen_clr,
if with_colours { "\x0f\x0315" } else { "" },
if with_colours { "\x0f" } else { "" },
if with_colours { "\x0f\x0314" } else { "" },
if with_colours { "\x0f" } else { "" },
name = zwsp_name,
idx = idx,
total = self.entries.len(),
text = ent.text,
date = ent.creation_ts.date()
))
} else {
None
}
}
pub fn get_or_create(word: &str, c: &str, dbc: &PgConnection) -> Result<Self, Error> {
if let Some(ret) = Self::get(word, c, dbc)? {
Ok(ret)
} else {
Ok(Self::create(word, c, dbc)?)
}
}
pub fn create(word: &str, c: &str, dbc: &PgConnection) -> Result<Self, Error> {
let val = NewKeyword {
name: word,
chan: c,
};
let ret: Keyword = {
use crate::schema::keywords;
::diesel::insert_into(keywords::table)
.values(val)
.get_result(dbc)?
};
Ok(KeywordDetails {
keyword: ret,
entries: vec![],
})
}
fn get_entries(kid: i32, dbc: &PgConnection) -> Result<Vec<Entry>, Error> {
let entries: Vec<Entry> = {
use crate::schema::entries::dsl::*;
entries
.filter(keyword_id.eq(kid))
.order_by(idx.asc())
.load(dbc)?
};
Ok(entries)
}
fn get_inner<'a, T: Into<Cow<'a, str>>>(
word: T,
c: &str,
dbc: &PgConnection,
recursion_count: usize,
) -> Result<Option<Self>, Error> {
let word = word.into();
let keyword: Option<Keyword> = {
use crate::schema::keywords::dsl::*;
keywords
.filter(name.ilike(word).and(chan.eq(c).or(chan.eq("*"))))
.first(dbc)
.optional()?
};
if let Some(k) = keyword {
let entries = Self::get_entries(k.id, dbc)?;
if let Some(e0) = entries.get(0) {
if e0.text.starts_with("see: ") {
if recursion_count > RECURSION_LIMIT {
// Oh dear.
Err(format_err!("Halt. You're having a bit too much fun."))?
}
let new_word = e0.text.replace("see: ", "");
return Self::get_inner(new_word, c, dbc, recursion_count + 1);
}
}
Ok(Some(KeywordDetails {
keyword: k,
entries,
}))
} else {
Ok(None)
}
}
pub fn get<'a, T: Into<Cow<'a, str>>>(
word: T,
c: &str,
dbc: &PgConnection,
) -> Result<Option<Self>, Error> {
Self::get_inner(word, c, dbc, 0)
}
}

View file

@ -1,395 +0,0 @@
// TODO(tazjin): Upgrade to a Diesel version with public derive
// macros.
#[macro_use]
extern crate diesel;
use crate::cfg::Config;
use crate::keyword::KeywordDetails;
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool};
use failure::{format_err, Error};
use irc::client::prelude::*;
use lazy_static::lazy_static;
use log::{debug, info, warn};
use rand::rngs::ThreadRng;
use rand::{thread_rng, Rng};
use regex::{Captures, Regex};
use std::collections::HashMap;
use std::fmt::Display;
mod cfg;
mod keyword;
mod models;
mod schema;
lazy_static! {
static ref LEARN_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*):\s*(?P<val>.*)"#).unwrap();
static ref QUERY_RE: Regex =
Regex::new(r#"^\?\?\s*(?P<subj>[^\[:]*)(?P<idx>\[[^\]]+\])?"#).unwrap();
static ref QLAST_RE: Regex = Regex::new(r#"^\?\?\s*(?P<subj>[^\[:]*)!"#).unwrap();
static ref INCREMENT_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*)(?P<incrdecr>\+\+|\-\-)"#).unwrap();
static ref MOVE_RE: Regex =
Regex::new(r#"^\?\?(?P<gen>!)?\s*(?P<subj>[^\[:]*)(?P<idx>\[[^\]]+\])->(?P<new_idx>.*)"#)
.unwrap();
}
pub struct App {
client: IrcClient,
pg: Pool<ConnectionManager<PgConnection>>,
rng: ThreadRng,
cfg: Config,
last_msgs: HashMap<String, HashMap<String, String>>,
}
impl App {
pub fn report_error<T: Display>(
&mut self,
nick: &str,
chan: &str,
msg: T,
) -> Result<(), Error> {
self.client
.send_notice(nick, format!("[{}] \x0304Error:\x0f {}", chan, msg))?;
Ok(())
}
pub fn keyword_from_captures(
&mut self,
learn: &::regex::Captures,
nick: &str,
chan: &str,
) -> Result<KeywordDetails, Error> {
let db = self.pg.get()?;
debug!("Fetching keyword for captures: {:?}", learn);
let subj = &learn["subj"];
let learn_chan = if learn.name("gen").is_some() {
"*"
} else {
chan
};
if !chan.starts_with("#") && learn_chan != "*" {
Err(format_err!("Only general entries may be taught via PM."))?;
}
debug!("Fetching keyword '{}' for chan {}", subj, learn_chan);
let kwd = KeywordDetails::get_or_create(subj, learn_chan, &db)?;
if kwd.keyword.chan == "*" && !self.cfg.admins.contains(nick) {
Err(format_err!(
"Only administrators can create or modify general entries."
))?;
}
Ok(kwd)
}
pub fn handle_move(
&mut self,
target: &str,
nick: &str,
chan: &str,
mv: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let idx = &mv["idx"];
let idx = match idx[1..(idx.len() - 1)].parse::<usize>() {
Ok(i) => i,
Err(e) => Err(format_err!("Could not parse index: {}", e))?,
};
let new_idx = match mv["new_idx"].parse::<i32>() {
Ok(i) => i,
Err(e) => Err(format_err!("Could not parse target index: {}", e))?,
};
let mut kwd = self.keyword_from_captures(&mv, nick, chan)?;
if new_idx < 0 {
kwd.delete(idx, &db)?;
self.client.send_notice(
target,
format!("\x02{}\x0f: Deleted entry {}.", kwd.keyword.name, idx),
)?;
} else {
kwd.swap(idx, new_idx as _, &db)?;
self.client.send_notice(
target,
format!(
"\x02{}\x0f: Swapped entries {} and {}.",
kwd.keyword.name, idx, new_idx
),
)?;
}
Ok(())
}
pub fn handle_learn(
&mut self,
target: &str,
nick: &str,
chan: &str,
learn: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let val = &learn["val"];
let mut kwd = self.keyword_from_captures(&learn, nick, chan)?;
let idx = kwd.learn(nick, val, &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
Ok(())
}
pub fn handle_insert_last_quote(
&mut self,
target: &str,
nick: &str,
chan: &str,
qlast: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let nick_to_grab = &qlast["subj"].to_ascii_lowercase();
let mut kwd = self.keyword_from_captures(&qlast, nick, chan)?;
let chan_lastmsgs = self
.last_msgs
.entry(chan.to_string())
.or_insert(HashMap::new());
// Use `nick` here, so things like "grfn: see glittershark" work.
let val = if let Some(last) = chan_lastmsgs.get(nick_to_grab) {
if last.starts_with("\x01ACTION ") {
// Yes, this is inefficient, but it's better than writing some hacky CTCP parsing
// code I guess (also, characters are hard, so just blindly slicing
// seems like a bad idea)
format!(
"* {} {}",
nick_to_grab,
last.replace("\x01ACTION ", "").replace("\x01", "")
)
} else {
format!("<{}> {}", nick_to_grab, last)
}
} else {
Err(format_err!("I dunno what {} said...", kwd.keyword.name))?
};
let idx = kwd.learn(nick, &val, &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
Ok(())
}
pub fn handle_increment(
&mut self,
target: &str,
nick: &str,
chan: &str,
icr: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let mut kwd = self.keyword_from_captures(&icr, nick, chan)?;
let is_incr = &icr["incrdecr"] == "++";
let now = chrono::Utc::now().naive_utc().date();
let mut idx = None;
for (i, ent) in kwd.entries.iter().enumerate() {
if ent.creation_ts.date() == now {
if let Ok(val) = ent.text.parse::<i32>() {
let val = if is_incr { val + 1 } else { val - 1 };
idx = Some((i + 1, val));
}
}
}
if let Some((i, val)) = idx {
kwd.update(i, &val.to_string(), &db)?;
self.client
.send_notice(target, kwd.format_entry(i).unwrap())?;
} else {
let val = if is_incr { 1 } else { -1 };
let idx = kwd.learn(nick, &val.to_string(), &db)?;
self.client
.send_notice(target, kwd.format_entry(idx).unwrap())?;
}
Ok(())
}
pub fn handle_query(
&mut self,
target: &str,
_nick: &str,
chan: &str,
query: Captures,
) -> Result<(), Error> {
let db = self.pg.get()?;
let subj = &query["subj"];
let idx = match query.name("idx") {
Some(i) => {
let i = i.as_str();
match &i[1..(i.len() - 1)] {
"*" => Some(-1),
x => x.parse::<usize>().map(|x| x as i32).ok(),
}
}
None => None,
};
debug!("Querying {} with idx {:?}", subj, idx);
match KeywordDetails::get(subj, chan, &db)? {
Some(kwd) => {
if let Some(mut idx) = idx {
if idx == -1 {
// 'get all entries' ('*' parses into this)
// step 1: make a blob of all the quotes
let mut data_to_upload = String::new();
for i in 0..kwd.entries.len() {
data_to_upload
.push_str(&kwd.format_entry_colours(i + 1, false).unwrap());
data_to_upload.push('\n');
}
// step 2: attempt to POST it to eta's pastebin
// TODO(eta): make configurable
let response = crimp::Request::put("https://eta.st/lx/upload")
.user_agent("paroxysm/0.0.2 crimp/0.2")?
.header("Linx-Expiry", "7200")? // 2 hours
.body("text/plain", data_to_upload.as_bytes())
.timeout(std::time::Duration::from_secs(2))?
.send()?
.as_string()?;
// step 3: tell the world about it
if response.status != 200 {
Err(format_err!(
"upload returned {}: {}",
response.status,
response.body
))?
}
self.client.send_notice(
target,
format!(
"\x02{}\x0f: uploaded {} quotes to \x02\x0311{}\x0f (will expire in \x0224\x0f hours)",
subj,
kwd.entries.len(),
response.body
)
)?;
} else {
if idx == 0 {
idx = 1;
}
if let Some(ent) = kwd.format_entry(idx as _) {
self.client.send_notice(target, ent)?;
} else {
let pluralised = if kwd.entries.len() == 1 {
"entry"
} else {
"entries"
};
self.client.send_notice(
target,
format!(
"\x02{}\x0f: only has \x02\x0304{}\x0f {}",
subj,
kwd.entries.len(),
pluralised
),
)?;
}
}
} else {
let entry = if kwd.entries.len() < 2 {
1 // because [1, 1) does not a range make
} else {
self.rng.gen_range(1, kwd.entries.len())
};
if let Some(ent) = kwd.format_entry(entry) {
self.client.send_notice(target, ent)?;
} else {
self.client
.send_notice(target, format!("\x02{}\x0f: no entries yet", subj))?;
}
}
}
None => {
// If someone just posts "??????????", don't spam the channel with
// an error message (but do allow joke entries to appear if set).
if !subj.chars().all(|c| c == '?' || c == ' ') {
self.client
.send_notice(target, format!("\x02{}\x0f: never heard of it", subj))?;
}
}
}
Ok(())
}
pub fn handle_privmsg(&mut self, from: &str, chan: &str, msg: &str) -> Result<(), Error> {
let nick = from.split("!").next().ok_or(format_err!(
"Received PRIVMSG from a source without nickname (failed to split n!u@h)"
))?;
let target = if chan.starts_with("#") { chan } else { nick };
debug!("[{}] <{}> {}", chan, nick, msg);
if let Some(learn) = LEARN_RE.captures(msg) {
self.handle_learn(target, nick, chan, learn)?;
} else if let Some(qlast) = QLAST_RE.captures(msg) {
self.handle_insert_last_quote(target, nick, chan, qlast)?;
} else if let Some(mv) = MOVE_RE.captures(msg) {
self.handle_move(target, nick, chan, mv)?;
} else if let Some(icr) = INCREMENT_RE.captures(msg) {
self.handle_increment(target, nick, chan, icr)?;
} else if let Some(query) = QUERY_RE.captures(msg) {
self.handle_query(target, nick, chan, query)?;
} else {
let chan_lastmsgs = self
.last_msgs
.entry(chan.to_string())
.or_insert(HashMap::new());
chan_lastmsgs.insert(nick.to_string().to_ascii_lowercase(), msg.to_string());
}
Ok(())
}
pub fn handle_msg(&mut self, m: Message) -> Result<(), Error> {
match m.command {
Command::PRIVMSG(channel, message) => {
if let Some(src) = m.prefix {
if let Err(e) = self.handle_privmsg(&src, &channel, &message) {
warn!("error handling command in {} (src {}): {}", channel, src, e);
if let Some(nick) = src.split("!").next() {
self.report_error(nick, &channel, e)?;
}
}
}
}
Command::INVITE(nick, channel) => {
if self.cfg.admins.contains(&nick) {
info!("Joining {} after admin invite", channel);
self.client.send_join(channel)?;
}
}
_ => {}
}
Ok(())
}
}
fn main() -> Result<(), Error> {
println!("[+] loading configuration");
let default_log_filter = "paroxysm=info".to_string();
let mut settings = config::Config::default();
settings.merge(config::Environment::with_prefix("PARX"))?;
let cfg: Config = settings.try_into()?;
let env = env_logger::Env::new()
.default_filter_or(cfg.log_filter.clone().unwrap_or(default_log_filter));
env_logger::init_from_env(env);
info!("paroxysm starting up");
info!("connecting to database at {}", cfg.database_url);
let pg = Pool::new(ConnectionManager::new(&cfg.database_url))?;
info!("connecting to IRC using config {}", cfg.irc_config_path);
let client = IrcClient::new(&cfg.irc_config_path)?;
client.identify()?;
let st = client.stream();
let mut app = App {
client,
pg,
cfg,
rng: thread_rng(),
last_msgs: HashMap::new(),
};
info!("running!");
st.for_each_incoming(|m| {
if let Err(e) = app.handle_msg(m) {
warn!("Error processing message: {}", e);
}
})?;
Ok(())
}

View file

@ -1,36 +0,0 @@
use crate::schema::{entries, keywords};
use chrono::NaiveDateTime;
#[derive(Queryable)]
pub struct Keyword {
pub id: i32,
pub name: String,
pub chan: String,
}
#[derive(Queryable)]
pub struct Entry {
pub id: i32,
pub keyword_id: i32,
pub idx: i32,
pub text: String,
pub creation_ts: NaiveDateTime,
pub created_by: String,
}
#[derive(Insertable)]
#[table_name = "keywords"]
pub struct NewKeyword<'a> {
pub name: &'a str,
pub chan: &'a str,
}
#[derive(Insertable)]
#[table_name = "entries"]
pub struct NewEntry<'a> {
pub keyword_id: i32,
pub idx: i32,
pub text: &'a str,
pub creation_ts: NaiveDateTime,
pub created_by: &'a str,
}

View file

@ -1,18 +0,0 @@
table! {
entries (id) {
id -> Int4,
keyword_id -> Int4,
idx -> Int4,
text -> Varchar,
creation_ts -> Timestamp,
created_by -> Varchar,
}
}
table! {
keywords (id) {
id -> Int4,
name -> Varchar,
chan -> Varchar,
}
}

View file

@ -1,2 +0,0 @@
.idea/
quinistry

View file

@ -1,63 +0,0 @@
Quinistry
=========
*A simple Docker registry quine.*
## What?
This is an example project for a from-scratch implementation of an HTTP server compatible with the [Docker Registry V2][]
protocol.
It serves a single image called `quinistry:latest` which is a Docker image that runs quinistry itself, therefore it is a
sort of Docker registry [quine][].
The official documentation does not contain enough information to actually implement this protocol (which I assume is
intentional), but a bit of trial&error lead there anyways. I've added comments to parts of the code to clear up things
that may be helpful to other developers in the future.
## Example
```
# Run quinistry:
vincent@urdhva ~/go/src/github.com/tazjin/quinistry (git)-[master] % ./quinistry
2017/03/16 14:11:56 Starting quinistry
# Pull the quinistry image from itself:
vincent@urdhva ~ % docker pull localhost:8080/quinistry
Using default tag: latest
latest: Pulling from quinistry
7bf1a8b18466: Already exists
Digest: sha256:d5cd4490901ef04b4e28e4ccc03a1d25fe3461200cf4d7166aab86fcd495e22e
Status: Downloaded newer image for localhost:8080/quinistry:latest
# Quinistry will log:
2017/03/16 14:14:03 Acknowleding V2 API: GET /v2/
2017/03/16 14:14:03 Serving manifest: GET /v2/quinistry/manifests/latest
2017/03/16 14:14:03 Serving config: GET /v2/quinistry/blobs/sha256:fbb165c48849de16017aa398aa9bb08fd1c00eaa7c150b6c2af37312913db279
# Run the downloaded image:
vincent@urdhva ~ % docker run -p 8090:8080 localhost:8080/quinistry
2017/03/16 13:15:18 Starting quinistry
# And download it again from itself:
vincent@urdhva ~ % docker pull localhost:8090/quinistry
Using default tag: latest
latest: Pulling from quinistry
7bf1a8b18466: Already exists
Digest: sha256:11141d95ddce0bac9ffa32ab1e8bc94748ed923e87762c68858dc41d11a46d3f
Status: Downloaded newer image for localhost:8090/quinistry:latest
```
## Building
Quinistry creates a Docker image that only contains a statically linked `main` binary. As this package makes use of
`net/http`, Go will (by default) link against `libc` for DNS resolution and create a dynamic binary instead.
To disable this, `build` the project with `-tags netgo`:
```
go build -tags netgo
```
[Docker Registry V2]: https://docs.docker.com/registry/spec/api/
[quine]: https://en.wikipedia.org/wiki/Quine_(computing)

View file

@ -1,12 +0,0 @@
package main
// HTTP content types
const ImageConfigMediaType string = "application/vnd.docker.container.image.v1+json"
const ManifestMediaType string = "application/vnd.docker.distribution.manifest.v2+json"
const LayerMediaType string = "application/vnd.docker.image.rootfs.diff.tar.gzip"
// HTTP header names
const ContentType string = "Content-Type"
const DigestHeader string = "Docker-Content-Digest"

View file

@ -1,11 +0,0 @@
{ depot, ... }:
depot.nix.buildGo.program {
name = "quinistry";
srcs = [
./const.go
./image.go
./main.go
./types.go
];
}

View file

@ -1,150 +0,0 @@
// The code in this file creates a Docker image layer containing the binary of the
// application itself.
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"time"
)
// This function creates a Docker-image digest (i.e. SHA256 hash with
// algorithm-specification prefix)
func Digest(b []byte) string {
hash := sha256.New()
hash.Write(b)
return fmt.Sprintf("sha256:%x", hash.Sum(nil))
}
func GetImageOfCurrentExecutable() Image {
binary := getCurrentBinary()
tarArchive := createTarArchive(&map[string][]byte{
"/main": binary,
})
configJson, configElem := createConfig([]string{Digest(tarArchive)})
compressed := gzipArchive("Quinistry image", tarArchive)
manifest := createManifest(&configElem, &compressed)
manifestJson, _ := json.Marshal(manifest)
return Image{
Layer: compressed,
LayerDigest: Digest(compressed),
Manifest: manifestJson,
ManifestDigest: Digest(manifestJson),
Config: configJson,
ConfigDigest: Digest(configJson),
}
}
func getCurrentBinary() []byte {
path, _ := os.Executable()
file, _ := ioutil.ReadFile(path)
return file
}
func createTarArchive(files *map[string][]byte) []byte {
buf := new(bytes.Buffer)
w := tar.NewWriter(buf)
for name, file := range *files {
hdr := &tar.Header{
Name: name,
// Everything is executable \o/
Mode: 0755,
Size: int64(len(file)),
}
w.WriteHeader(hdr)
w.Write(file)
}
if err := w.Close(); err != nil {
log.Fatalln(err)
os.Exit(1)
}
return buf.Bytes()
}
func gzipArchive(name string, archive []byte) []byte {
buf := new(bytes.Buffer)
w := gzip.NewWriter(buf)
w.Name = name
w.Write(archive)
if err := w.Close(); err != nil {
log.Fatalln(err)
os.Exit(1)
}
return buf.Bytes()
}
func createConfig(layerDigests []string) (configJson []byte, elem Element) {
now := time.Now()
imageConfig := &ImageConfig{
Cmd: []string{"/main"},
Env: []string{"PATH=/"},
}
rootFs := RootFs{
DiffIds: layerDigests,
Type: "layers",
}
history := []History{
{
Created: now,
CreatedBy: "Quinistry magic",
},
}
config := Config{
Created: now,
Author: "tazjin",
Architecture: "amd64",
Os: "linux",
Config: imageConfig,
RootFs: rootFs,
History: history,
}
configJson, _ = json.Marshal(config)
elem = Element{
MediaType: ImageConfigMediaType,
Size: len(configJson),
Digest: Digest(configJson),
}
return
}
func createManifest(config *Element, layer *[]byte) Manifest {
layers := []Element{
{
MediaType: LayerMediaType,
Size: len(*layer),
// Layers must contain the digest of the *gzipped* layer.
Digest: Digest(*layer),
},
}
return Manifest{
SchemaVersion: 2,
MediaType: ManifestMediaType,
Config: *config,
Layers: layers,
}
}

View file

@ -1,27 +0,0 @@
# This is a child quinistry, running via an image served off the parent.
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: quinistry-gen2
labels:
k8s-app: quinistry
quinistry/role: child
quinistry/generation: '2'
spec:
template:
metadata:
labels:
k8s-app: quinistry
quinistry/role: child
quinistry/generation: '2'
spec:
containers:
- name: quinistry
# Bootstrap via Docker Hub (or any other registry)
image: localhost:5000/quinistry
ports:
- name: registry
containerPort: 8080
# Incremented hostPort,
hostPort: 5001

View file

@ -1,27 +0,0 @@
# This is a bootstrapped Quinistry DaemonSet. The initial image
# comes from Docker Hub
---
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: quinistry
labels:
k8s-app: quinistry
quinistry/role: parent
quinistry/generation: '1'
spec:
template:
metadata:
labels:
k8s-app: quinistry
quinistry/role: parent
quinistry/generation: '1'
spec:
containers:
- name: quinistry
# Bootstrap via Docker Hub (or any other registry)
image: tazjin/quinistry
ports:
- name: registry
containerPort: 8080
hostPort: 5000

View file

@ -1,57 +0,0 @@
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
log.Println("Starting quinistry")
image := GetImageOfCurrentExecutable()
layerUri := fmt.Sprintf("/v2/quinistry/blobs/%s", image.LayerDigest)
configUri := fmt.Sprintf("/v2/quinistry/blobs/%s", image.ConfigDigest)
log.Fatal(http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Acknowledge that we speak V2
if r.RequestURI == "/v2/" {
logRequest("Acknowleding V2 API", r)
fmt.Fprintln(w)
return
}
// Serve manifest
if r.RequestURI == "/v2/quinistry/manifests/latest" {
logRequest("Serving manifest", r)
w.Header().Set(ContentType, ManifestMediaType)
w.Header().Add(DigestHeader, image.ManifestDigest)
w.Write(image.Manifest)
return
}
// Serve actual image layer
if r.RequestURI == layerUri {
logRequest("Serving image layer blob", r)
w.Header().Add(DigestHeader, image.LayerDigest)
w.Write(image.Layer)
return
}
// Serve image config
if r.RequestURI == configUri {
logRequest("Serving config", r)
w.Header().Set("Content-Type", ImageConfigMediaType)
w.Header().Set(DigestHeader, image.ConfigDigest)
w.Write(image.Config)
return
}
log.Printf("Unhandled request: %v\n", *r)
})))
}
func logRequest(msg string, r *http.Request) {
log.Printf("%s: %s %s\n", msg, r.Method, r.RequestURI)
}

View file

@ -1,79 +0,0 @@
package main
import "time"
// This type represents the rootfs-key of the Docker image config.
// It specifies the digest (i.e. usually SHA256 hash) of the tar'ed, but NOT
// compressed image layers.
type RootFs struct {
// The digests of the non-compressed FS layers.
DiffIds []string `json:"diff_ids"`
// Type should always be set to "layers"
Type string `json:"type"`
}
// This type represents an entry in the Docker image config's history key.
// Every history element "belongs" to a filesystem layer.
type History struct {
Created time.Time `json:"created"`
CreatedBy string `json:"created_by"`
}
// This type represents runtime-configuration for the Docker image.
// A lot of possible keys are omitted here, see:
// https://github.com/docker/docker/blob/master/image/spec/v1.2.md#image-json-description
type ImageConfig struct {
Cmd []string
Env []string
}
// This type represents the Docker image configuration
type Config struct {
Created time.Time `json:"created"`
Author string `json:"author"`
// Architecture should be "amd64"
Architecture string `json:"architecture"`
// OS should be "linux"
Os string `json:"os"`
// Configuration can be set to 'nil', in which case all options have to be
// supplied at container launch time.
Config *ImageConfig `json:"config"`
// Filesystem layers and history elements have to be in the same order.
RootFs RootFs `json:"rootfs"`
History []History `json:"history"`
}
// This type represents any manifest
type Element struct {
MediaType string `json:"mediaType"`
Size int `json:"size"`
Digest string `json:"digest"`
}
// This type represents a Docker image manifest as used by the registry
// protocol V2.
type Manifest struct {
SchemaVersion int `json:"schemaVersion"` // Must be 2
MediaType string `json:"mediaType"` // Use ManifestMediaType const
Config Element `json:"config"`
Layers []Element `json:"layers"`
}
// A really "dumb" representation of an image, with its data blob and related
// metadata.
// Note: This is not a registry API type.
type Image struct {
Layer []byte
LayerDigest string
Manifest []byte
ManifestDigest string
Config []byte
ConfigDigest string
}

View file

@ -1 +0,0 @@
ben

View file

@ -1,7 +0,0 @@
{ pkgs, ... }:
pkgs.buildGoModule {
name = "tvl-ebooks";
vendorHash = "sha256:1p7bazh2vbhvvm559bcvfff9s4yy4q9jmklxr3sfp97inwpv6hzy";
src = ./.;
}

View file

@ -1,170 +0,0 @@
package main
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"sync"
"time"
"github.com/go-redis/redis"
"gopkg.in/irc.v3"
)
var messageBeat chan bool
var firstMessage chan bool
var client *irc.Client
var safeLock sync.Mutex
func main() {
nick := flag.String("nick", "NONE", "the ircnick you want")
from := flag.String("ip", "[::1]", "src address")
flag.Parse()
localAddrDialier := &net.Dialer{
LocalAddr: &net.TCPAddr{
IP: net.ParseIP(*from),
Port: 0,
},
}
conn, err := tls.DialWithDialer(localAddrDialier, "tcp", "chat.freenode.net:6697", &tls.Config{})
if err != nil {
log.Fatalln(err)
}
messageBeat = make(chan bool)
firstMessage = make(chan bool, 10)
go ircKeepalive()
redisc := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
go func() {
for {
time.Sleep(time.Second)
r := redisc.Ping()
if r.Err() != nil {
redisc = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
}
redisc.Set(fmt.Sprintf("alive-%s", *nick), "yes", time.Second*5)
}
}()
if *nick == "NONE" {
log.Fatalf("You must set a nick")
}
go func() {
<-firstMessage
for {
psub := redisc.Subscribe(fmt.Sprintf("irc-%s", *nick))
for {
msg, err := psub.ReceiveMessage()
if err != nil {
break
}
client.WriteMessage(&irc.Message{
Command: "PRIVMSG",
Params: []string{
"##tvl-ebooks",
msg.Payload,
},
})
}
time.Sleep(time.Second * 10)
}
}()
go func() {
<-firstMessage
for {
psub := redisc.Subscribe(fmt.Sprintf("raw-irc-%s", *nick))
for {
msg, err := psub.ReceiveMessage()
if err != nil {
break
}
im := irc.Message{}
err = json.Unmarshal([]byte(msg.Payload), &im)
if err == nil {
client.WriteMessage(&im)
}
}
time.Sleep(time.Second * 10)
}
}()
seenMsgBefore := false
config := irc.ClientConfig{
Nick: *nick,
User: *nick,
Name: fmt.Sprintf("%s Ebooks", *nick),
Handler: irc.HandlerFunc(func(c *irc.Client, m *irc.Message) {
b, _ := json.Marshal(m)
log.Printf("%#v", string(b))
messageBeat <- true
if !seenMsgBefore {
firstMessage <- true
seenMsgBefore = true
}
res := redisc.Publish("ebook", string(b))
if res.Err() != nil {
log.Printf("Publish error! %#v", err)
}
if m.Command == "001" {
// 001 is a welcome event, so we join channels there
c.Write("JOIN ##tvl-ebooks")
}
// else if m.Command == "PRIVMSG" && c.FromChannel(m) {
// // // Create a handler on all messages.
// // c.WriteMessage(&irc.Message{
// // Command: "PRIVMSG",
// // Params: []string{
// // m.Params[0],
// // m.Trailing(),
// // },
// // })
// }
}),
}
// Create the client
client = irc.NewClient(conn, config)
err = client.Run()
if err != nil {
log.Fatalln(err)
}
}
func ircKeepalive() {
tt := time.NewTimer(time.Second)
lastPing := time.Now()
for {
select {
case <-tt.C:
if time.Since(lastPing) > time.Minute*5 {
log.Fatalf("It's been too long since the last IRC message, blowing up")
}
break
case <-messageBeat:
lastPing = time.Now()
}
}
}

View file

@ -1,8 +0,0 @@
module github.com/benjojo/tvl-ebooks
go 1.14
require (
github.com/go-redis/redis v6.15.9+incompatible
gopkg.in/irc.v3 v3.1.3
)

View file

@ -1,11 +0,0 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/irc.v3 v3.1.3 h1:yeTiJ365882L8h4AnBKYfesD92y5R5ZhGiylu9DfcPY=
gopkg.in/irc.v3 v3.1.3/go.mod h1:shO2gz8+PVeS+4E6GAny88Z0YVVQSxQghdrMVGQsR9s=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View file

@ -1,99 +0,0 @@
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/go-redis/redis"
"gopkg.in/irc.v3"
)
var messageBeat chan bool
func main() {
conn, err := tls.Dial("tcp", "bnc.irccloud.com:6697", nil)
if err != nil {
log.Fatalln(err)
}
messageBeat = make(chan bool)
go ircKeepalive()
redisc := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
go func() {
for {
time.Sleep(time.Second)
r := redisc.Ping()
if r.Err() != nil {
redisc = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
}
}
}()
config := irc.ClientConfig{
Nick: "Benjojo",
Pass: os.Getenv("IRCCLOUD"),
User: "Benjojo",
Name: "Ben Cox",
Handler: irc.HandlerFunc(func(c *irc.Client, m *irc.Message) {
b, _ := json.Marshal(m)
// log.Printf("%#v", string(b))
messageBeat <- true
res := redisc.Publish("irccloud", string(b))
if res.Err() != nil {
log.Printf("Publish error! %#v", err)
}
// if m.Command == "001" {
// // 001 is a welcome event, so we join channels there
// // c.Write("JOIN #bot-test-chan")
// } else if m.Command == "PRIVMSG" && c.FromChannel(m) {
// // // Create a handler on all messages.
// // c.WriteMessage(&irc.Message{
// // Command: "PRIVMSG",
// // Params: []string{
// // m.Params[0],
// // m.Trailing(),
// // },
// // })
// }
}),
}
// Create the client
client := irc.NewClient(conn, config)
err = client.Run()
if err != nil {
log.Fatalln(err)
}
}
func ircKeepalive() {
tt := time.NewTimer(time.Second)
lastPing := time.Now()
for {
select {
case <-tt.C:
if time.Since(lastPing) > time.Minute*5 {
log.Fatalf("It's been too long since the last IRC message, blowing up")
}
break
case <-messageBeat:
lastPing = time.Now()
}
}
}

View file

@ -1,26 +0,0 @@
package main
import (
"crypto/rand"
"log"
"net"
)
func main() {
// 2a0c:2f07:29:9999:6564:5298:8413:4652
ip := net.ParseIP("2a0c:2f07:29::")
rand.Read(ip[6:])
if ip[7] > 0xaa {
ip[4] = 0x03
ip[5] = 0x84
if ip[7] > 0xdd {
ip[4] = 0x08
ip[5] = 0x64
}
}
log.Printf("%s\n", ip)
//
}

View file

@ -1,246 +0,0 @@
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"strconv"
"strings"
"time"
"github.com/go-redis/redis"
)
type incomingIRC struct {
Command string `json:"Command"`
Host string `json:"Host"`
Name string `json:"Name"`
Params []string `json:"Params"`
User string `json:"User"`
}
var suppressionUsernames map[string]bool
var noMkov map[string]bool
func main() {
redisc := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
fireaway := make(chan incomingIRC, 10)
suppressionUsernames = make(map[string]bool)
suppressionList := redisc.HGetAll("suppressionList")
suppressionListA, _ := suppressionList.Result()
suppressionListMap, _ := stringMaptoIntMap(suppressionListA)
for v, _ := range suppressionListMap {
suppressionUsernames[v] = true
suppressionUsernames[strings.ToLower(v)] = true
}
noMkov = make(map[string]bool)
noMkovRedis := redisc.HGetAll("nomkov")
noMkovRedisA, _ := noMkovRedis.Result()
noMkovMap, _ := stringMaptoIntMap(noMkovRedisA)
for v, _ := range noMkovMap {
noMkov[v] = true
noMkov[strings.ToLower(v)] = true
}
go func() {
for {
irccloudFeed := redisc.Subscribe("irccloud")
for {
msg, err := irccloudFeed.ReceiveMessage()
if err != nil {
break
}
imsg := incomingIRC{}
err = json.Unmarshal([]byte(msg.Payload), &imsg)
if err != nil {
log.Printf("Json decoding error from irccloud feed %s", err)
continue
}
if imsg.Command == "PRIVMSG" {
if len(imsg.Params) == 2 {
if imsg.Params[0] == "##tvl" || imsg.Params[0] == "##tvlbot" {
fireaway <- imsg
}
}
}
}
time.Sleep(time.Second)
}
}()
for msg := range fireaway {
// Learn
learnFromMessage(msg, redisc)
msg2 := generateMesasge(msg, redisc)
// Check if we have a active log in for that user
ttl := redisc.TTL("alive-" + msg.Name + "-eb")
ttld, err := ttl.Result()
if err == nil {
redisc.Publish("irc-"+msg.Name+"-eb", msg2)
if ttld == 0 || ttld.Seconds() == -2 {
redisc.Publish("irc-tvlebooks-eb", "<"+fmt.Sprintf("%s.%s", string(msg.Name[0]), msg.Name[1:])+"-eb> "+msg2)
}
} else {
redisc.Publish("irc-tvlebooks-eb", "<"+fmt.Sprintf("%s.%s", string(msg.Name[0]), msg.Name[1:])+"-eb> "+msg2)
}
}
}
func generateMesasge(msg incomingIRC, redisc *redis.Client) string {
text := msg.Params[1]
username := strings.ToLower(msg.Name)
suppressionUsernames[username] = true
suppressionUsernames[username+":"] = true
suppressionUsernames[msg.Name] = true
suppressionUsernames[msg.Name+":"] = true
redisc.HIncrBy("suppressionList", msg.Name, 1)
text = strings.ToLower(text)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ".", "", -1)
text = strings.Replace(text, "!", "", -1)
text = strings.Replace(text, "?", "", -1)
words := strings.Split(text, " ")
lastWord := propwords(msg.Name, words[0], redisc)
if noMkov[username] {
lastWord = blockoutWord(lastWord)
words[0] = blockoutWord(words[0])
}
lastWord = filterHighlights(lastWord)
if lastWord == "_END_" {
if noMkov[username] {
return blockoutWord(words[0])
}
return words[0]
}
outputMsg := words[0] + " " + lastWord + " "
for {
lastWord = propwords(username, lastWord, redisc)
if lastWord == "" || lastWord == "_END_" {
return outputMsg
}
if noMkov[username] {
lastWord = blockoutWord(lastWord)
}
lastWord = filterHighlights(lastWord)
outputMsg += lastWord + " "
if len(outputMsg) > 100 {
return outputMsg
}
}
}
// filterHighlights: tries to prevent highlights by checking against
// a map called suppressionUsernames
func filterHighlights(in string) string {
for username := range suppressionUsernames {
if strings.Contains(in, username) {
if len(in) < 2 {
in = fmt.Sprintf("%s.%s", string(in[0]), in[1:])
return in
}
}
}
return in
}
func blockoutWord(in string) string {
block := ""
for i := 0; i < len(in); i++ {
block += "█"
}
return block
}
func propwords(username string, start string, redisc *redis.Client) string {
userHash := redisc.HGetAll(fmt.Sprintf("%s-%s", username, start))
userHashMap, err := userHash.Result()
if err != nil {
genericHash := redisc.HGetAll(fmt.Sprintf("generic-%s", start))
userHashMap, err = genericHash.Result()
}
userIntHashMap, totalVectors := stringMaptoIntMap(userHashMap)
if totalVectors == 0 {
return ""
}
targetRand := rand.Intn(totalVectors)
progresRand := 0
for k, v := range userIntHashMap {
progresRand += v
if targetRand > progresRand {
return k
}
}
for k, _ := range userIntHashMap {
return k
}
return ""
}
func stringMaptoIntMap(in map[string]string) (outMap map[string]int, total int) {
outMap = make(map[string]int)
for k, v := range in {
i, err := strconv.ParseInt(v, 10, 64)
if err != nil {
continue
}
total += int(i)
outMap[k] = int(i)
}
return outMap, total
}
func learnFromMessage(msg incomingIRC, redisc *redis.Client) {
text := msg.Params[1]
text = strings.ToLower(text)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ".", "", -1)
text = strings.Replace(text, "!", "", -1)
text = strings.Replace(text, "?", "", -1)
words := strings.Split(text, " ")
username := msg.Name
for k, word := range words {
// HINCRBY myhash field 1
nextWord := "_END_"
if len(words)-1 != k {
nextWord = words[k+1]
}
if !noMkov[username] {
redisc.HIncrBy(fmt.Sprintf("%s-%s", username, word), nextWord, 1)
}
redisc.HIncrBy(fmt.Sprintf("generic-%s", word), nextWord, 1)
}
}

View file

@ -1,174 +0,0 @@
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"github.com/go-redis/redis"
)
type incomingIRC struct {
Command string `json:"Command"`
Host string `json:"Host"`
Name string `json:"Name"`
Params []string `json:"Params"`
User string `json:"User"`
}
var quicklogMatch = regexp.MustCompile(`<(\w+)> (.+)`)
func main() {
redisc := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("127.0.0.1:%d", 6379),
Password: "", // no password set
DB: 0, // use default DB
})
fireaway := make(chan incomingIRC, 10)
go func() {
f, err := os.Open("tvl.txt")
if err != nil {
log.Printf("aaa %v", err)
os.Exit(0)
}
bio := bufio.NewReader(f)
for {
line, _, err := bio.ReadLine()
if err != nil {
break
}
sline := string(line)
offset := strings.Index(sline, "]")
notime := sline[offset+1:]
if quicklogMatch.MatchString(notime) {
bits := quicklogMatch.FindAllStringSubmatch(notime, -1)
if len(bits) != 0 {
if len(bits[0]) != 0 {
a := make([]string, 2)
a[1] = bits[0][2]
ic := incomingIRC{
Name: bits[0][1],
Params: a,
}
log.Printf("aa %#v", ic)
fireaway <- ic
}
}
}
}
}()
for msg := range fireaway {
// Learn
learnFromMessage(msg, redisc)
// os.Exit(0)
}
}
func generateMesasge(msg incomingIRC, redisc *redis.Client) string {
text := msg.Params[1]
username := msg.Name
text = strings.ToLower(text)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ".", "", -1)
text = strings.Replace(text, "!", "", -1)
text = strings.Replace(text, "?", "", -1)
words := strings.Split(text, " ")
lastWord := propwords(username, words[0], redisc)
outputMsg := words[0] + " " + lastWord + " "
for {
lastWord = propwords(username, words[0], redisc)
if lastWord == "" || lastWord == "_END_" {
return outputMsg
}
outputMsg += lastWord + " "
if len(outputMsg) > 100 {
return outputMsg
}
}
}
func propwords(username string, start string, redisc *redis.Client) string {
userHash := redisc.HGetAll(fmt.Sprintf("%s-%s", username, start))
userHashMap, err := userHash.Result()
if err != nil {
genericHash := redisc.HGetAll(fmt.Sprintf("generic-%s", start))
userHashMap, err = genericHash.Result()
}
userIntHashMap, totalVectors := stringMaptoIntMap(userHashMap)
targetRand := rand.Intn(totalVectors)
progresRand := 0
for k, v := range userIntHashMap {
progresRand += v
if targetRand > progresRand {
return k
}
}
for k, _ := range userIntHashMap {
return k
}
return ""
}
func stringMaptoIntMap(in map[string]string) (outMap map[string]int, total int) {
outMap = make(map[string]int)
for k, v := range in {
i, err := strconv.ParseInt(v, 10, 64)
if err != nil {
continue
}
total += int(i)
outMap[k] = int(i)
}
return outMap, total
}
func learnFromMessage(msg incomingIRC, redisc *redis.Client) {
text := msg.Params[1]
text = strings.ToLower(text)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ",", "", -1)
text = strings.Replace(text, ".", "", -1)
text = strings.Replace(text, "!", "", -1)
text = strings.Replace(text, "?", "", -1)
words := strings.Split(text, " ")
username := msg.Name
for k, word := range words {
// HINCRBY myhash field 1
nextWord := "_END_"
if len(words)-1 != k {
nextWord = words[k+1]
}
redisc.HIncrBy(fmt.Sprintf("%s-%s", username, word), nextWord, 1)
redisc.HIncrBy(fmt.Sprintf("generic-%s", word), nextWord, 1)
}
}

View file

@ -1,21 +0,0 @@
{ depot, pkgs, ... }:
let
inherit (depot.third_party) gopkgs;
uggc = depot.nix.buildGo.program {
name = "uggc";
srcs = [
./main.go
];
deps = [
gopkgs."github.com".pkg.browser.gopkg
];
};
in
uggc.overrideAttrs (old: {
buildCommand = old.buildCommand + ''
install -D ${./uggc.desktop} $out/share/applications/uggc.desktop
sed "s|@out@|$out|g" -i $out/share/applications/uggc.desktop
'';
})

View file

@ -1,38 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/pkg/browser"
)
func rot13(r rune) rune {
if 'a' <= r && r <= 'm' {
return r + ('n' - 'a')
} else if 'n' <= r && r <= 'z' {
return r - ('n' - 'a')
}
if 'A' <= r && r <= 'M' {
return r + ('N' - 'A')
} else if 'N' <= r && r <= 'Z' {
return r - ('N' - 'A')
}
return r
}
func main() {
if len(os.Args) == 0 {
fmt.Println("usage: uggc [rot13-encoded URL]")
return
}
urlText := strings.Join(os.Args[1:], " ")
corrected := strings.Map(rot13, urlText)
err := browser.OpenURL(corrected)
if err != nil {
fmt.Println("could not launch browser:", err)
}
}

View file

@ -1,7 +0,0 @@
[Desktop Entry]
Type=Application
Name=Rot13 URL Handler
Exec=@out@/bin/uggc
StartupNotify=false
MimeType=x-scheme-handler/uggc;
MimeType=x-scheme-handler/uggcf;

View file

@ -1,23 +0,0 @@
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\uggc]
"URL Protocol"=""
@="URL:Rot13 HTTP URL Protocol"
[HKEY_CLASSES_ROOT\uggcf]
"URL Protocol"=""
@="URL:Rot13 HTTPS URL Protocol"
[HKEY_CLASSES_ROOT\uggc\shell]
[HKEY_CLASSES_ROOT\uggcf\shell]
[HKEY_CLASSES_ROOT\uggc\shell\open]
[HKEY_CLASSES_ROOT\uggcf\shell\open]
[HKEY_CLASSES_ROOT\uggc\shell\open\command]
@="\"C:\\Program Files\\uggc\\uggc.exe\" \"%1\""
[HKEY_CLASSES_ROOT\uggcf\shell\open\command]
@="\"C:\\Program Files\\uggc\\uggc.exe\" \"%1\""

View file

@ -1,35 +0,0 @@
Watchblob - WatchGuard VPN on Linux
===================================
This tiny helper tool makes it possible to use WatchGuard / Firebox / <<whatever
they are actually called>> VPNs that use multi-factor authentication on Linux.
Rather than using OpenVPN's built-in dynamic challenge/response protocol, WatchGuard
has opted for a separate implementation negotiating credentials outside of the
OpenVPN protocol, which makes it impossible to start those connections solely by
using the `openvpn` CLI and configuration files.
What this application does has been reverse-engineered from the "WatchGuard Mobile VPN
with SSL" application on OS X.
I've published a [blog post](https://www.tazj.in/en/1486830338) describing the process
and what is actually going on in this protocol.
## Installation
Make sure you have Go installed and `GOPATH` configured, then simply
`go get github.com/tazjin/watchblob/...`.
## Usage
Right now the usage is very simple. Make sure you have the correct OpenVPN client
config ready (this is normally supplied by the WatchGuard UI) simply run:
```
watchblob vpnserver.somedomain.org username p4ssw0rd
```
The server responds with a challenge which is displayed to the user, wait until you
receive the SMS code or whatever and enter it. `watchblob` then completes the
credential negotiation and you may proceed to log in with OpenVPN using your username
and *the OTP token* (**not** your password) as credentials.

View file

@ -1,13 +0,0 @@
{ depot, ... }:
depot.nix.buildGo.program {
name = "watchblob";
srcs = [
./main.go
./urls.go
];
deps = with depot.third_party; [
gopkgs."golang.org".x.crypto.ssh.terminal.gopkg
];
}

View file

@ -1,108 +0,0 @@
package main
import (
"bufio"
"encoding/xml"
"fmt"
"golang.org/x/crypto/ssh/terminal"
"net/http"
"os"
"strings"
"syscall"
)
// The XML response returned by the WatchGuard server
type Resp struct {
Action string `xml:"action"`
LogonStatus int `xml:"logon_status"`
LogonId int `xml:"logon_id"`
Error string `xml:"errStr"`
Challenge string `xml:"chaStr"`
}
func main() {
args := os.Args[1:]
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "Usage: watchblob <vpn-host>")
os.Exit(1)
}
host := args[0]
username, password, err := readCredentials()
if err != nil {
fmt.Fprintf(os.Stderr, "Could not read credentials: %v\n", err)
}
fmt.Printf("Requesting challenge from %s as user %s\n", host, username)
challenge, err := triggerChallengeResponse(&host, &username, &password)
if err != nil || challenge.LogonStatus != 4 {
fmt.Fprintln(os.Stderr, "Did not receive challenge from server")
fmt.Fprintf(os.Stderr, "Response: %v\nError: %v\n", challenge, err)
os.Exit(1)
}
token := getToken(&challenge)
err = logon(&host, &challenge, &token)
if err != nil {
fmt.Fprintf(os.Stderr, "Logon failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Login succeeded, you may now (quickly) authenticate OpenVPN with %s as your password\n", token)
}
func readCredentials() (string, string, error) {
fmt.Printf("Username: ")
reader := bufio.NewReader(os.Stdin)
username, err := reader.ReadString('\n')
fmt.Printf("Password: ")
password, err := terminal.ReadPassword(syscall.Stdin)
fmt.Println()
// If an error occured, I don't care about which one it is.
return strings.TrimSpace(username), strings.TrimSpace(string(password)), err
}
func triggerChallengeResponse(host *string, username *string, password *string) (r Resp, err error) {
return request(templateUrl(host, templateChallengeTriggerUri(username, password)))
}
func getToken(challenge *Resp) string {
fmt.Println(challenge.Challenge)
reader := bufio.NewReader(os.Stdin)
token, _ := reader.ReadString('\n')
return strings.TrimSpace(token)
}
func logon(host *string, challenge *Resp, token *string) (err error) {
resp, err := request(templateUrl(host, templateResponseUri(challenge.LogonId, token)))
if err != nil {
return
}
if resp.LogonStatus != 1 {
err = fmt.Errorf("Challenge/response authentication failed: %v", resp)
}
return
}
func request(url string) (r Resp, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
decoder := xml.NewDecoder(resp.Body)
err = decoder.Decode(&r)
return
}

View file

@ -1,96 +0,0 @@
package main
import (
"encoding/xml"
"reflect"
"testing"
)
func TestUnmarshalChallengeRespones(t *testing.T) {
var testXml string = `
<?xml version="1.0" encoding="UTF-8"?>
<resp>
<action>sslvpn_logon</action>
<logon_status>4</logon_status>
<auth-domain-list>
<auth-domain>
<name>RADIUS</name>
</auth-domain>
</auth-domain-list>
<logon_id>441</logon_id>
<chaStr>Enter Your 6 Digit Passcode </chaStr>
</resp>`
var r Resp
xml.Unmarshal([]byte(testXml), &r)
expected := Resp{
Action: "sslvpn_logon",
LogonStatus: 4,
LogonId: 441,
Challenge: "Enter Your 6 Digit Passcode ",
}
assertEqual(t, expected, r)
}
func TestUnmarshalLoginError(t *testing.T) {
var testXml string = `
<?xml version="1.0" encoding="UTF-8"?>
<resp>
<action>sslvpn_logon</action>
<logon_status>2</logon_status>
<auth-domain-list>
<auth-domain>
<name>RADIUS</name>
</auth-domain>
</auth-domain-list>
<errStr>501</errStr>
</resp>`
var r Resp
xml.Unmarshal([]byte(testXml), &r)
expected := Resp{
Action: "sslvpn_logon",
LogonStatus: 2,
Error: "501",
}
assertEqual(t, expected, r)
}
func TestUnmarshalLoginSuccess(t *testing.T) {
var testXml string = `
<?xml version="1.0" encoding="UTF-8"?>
<resp>
<action>sslvpn_logon</action>
<logon_status>1</logon_status>
<auth-domain-list>
<auth-domain>
<name>RADIUS</name>
</auth-domain>
</auth-domain-list>
</resp>
`
var r Resp
xml.Unmarshal([]byte(testXml), &r)
expected := Resp{
Action: "sslvpn_logon",
LogonStatus: 1,
}
assertEqual(t, expected, r)
}
func assertEqual(t *testing.T, expected interface{}, result interface{}) {
if !reflect.DeepEqual(expected, result) {
t.Errorf(
"Unmarshaled values did not match.\nExpected: %v\nResult: %v\n",
expected, result,
)
t.Fail()
}
}

View file

@ -1,37 +0,0 @@
package main
import (
"fmt"
"net/url"
"strconv"
)
const urlFormat string = "https://%s%s"
const uriFormat = "/?%s"
func templateChallengeTriggerUri(username *string, password *string) string {
v := url.Values{}
v.Set("action", "sslvpn_logon")
v.Set("style", "fw_logon_progress.xsl")
v.Set("fw_logon_type", "logon")
v.Set("fw_domain", "Firebox-DB")
v.Set("fw_username", *username)
v.Set("fw_password", *password)
return fmt.Sprintf(uriFormat, v.Encode())
}
func templateResponseUri(logonId int, token *string) string {
v := url.Values{}
v.Set("action", "sslvpn_logon")
v.Set("style", "fw_logon_progress.xsl")
v.Set("fw_logon_type", "response")
v.Set("response", *token)
v.Set("fw_logon_id", strconv.Itoa(logonId))
return fmt.Sprintf(uriFormat, v.Encode())
}
func templateUrl(baseUrl *string, uri string) string {
return fmt.Sprintf(urlFormat, *baseUrl, uri)
}

View file

@ -1,14 +0,0 @@
{ depot, ... }:
depot.nix.buildLisp.program {
name = "wc";
srcs = [
./wc.lisp
];
deps = with depot.third_party.lisp; [
unix-opts
iterate
];
}

View file

@ -1,34 +0,0 @@
(defpackage wc
(:use #:cl #:iterate)
(:export :main))
(in-package :wc)
(declaim (optimize (speed 3) (safety 0)))
(defun main ()
(let ((filename (cadr (opts:argv)))
(space (char-code #\Space))
(newline (char-code #\Newline)))
(with-open-file (file-stream filename :element-type '(unsigned-byte 8))
(iter
(for byte in-stream file-stream using #'read-byte)
(for previous-byte previous byte)
(for is-newline = (eql newline byte))
;; Count each byte
(sum 1 into bytes)
;; Count every newline
(counting is-newline into newlines)
;; Count every "word", unless the preceding character already
;; was a space or we are at the beginning of the file.
(when (or (eql space previous-byte)
(eql newline previous-byte)
(not previous-byte))
(next-iteration))
(counting (or is-newline (eql space byte))
into words)
(declare (fixnum bytes newlines words))
(finally (format t " ~A ~A ~A ~A~%" newlines words bytes filename))))))

View file

@ -1 +0,0 @@
sterni

View file

@ -1,91 +0,0 @@
(defpackage 🕰.bin
(:shadow :describe)
(:use :cl :opts)
(:import-from :uiop :quit)
(:import-from :local-time
:now :timestamp-subtimezone :+utc-zone+
:*default-timezone* :define-timezone)
(:import-from :klatre :format-dottime-offset)
(:import-from :🕰 :)
(:export :🚂))
(in-package :🕰.bin)
(declaim (optimize (safety 3)))
(opts:define-opts
(:name :help
:description "Print this help text"
:short #\h
:long "help")
(:name :dot-time
:description "Use pseudo dot-time format (implies -u)"
:short #\d
:long "dot-time")
(:name :utc
:description "Display time in UTC instead of local time"
:short #\u
:long "utc")
(:name :no-newline
:description "Don't print a trailing newline"
:short #\n
:long "no-newline"))
(defun make-slash-terminated (str)
(if (eq (char str (1- (length str))) #\/)
str
(concatenate 'string str "/")))
; TODO(sterni): upstream this into local-time
(defun setup-default-timezone ()
(let* ((tz (remove #\: (uiop:getenv "TZ") :count 1))
(tz-dir (uiop:getenv "TZDIR"))
(tz-file (if (and tz tz-dir)
(merge-pathnames
(pathname tz)
(pathname (make-slash-terminated tz-dir)))
(pathname "/etc/localtime"))))
(handler-case
(define-timezone *default-timezone* tz-file :load t)
(t () (setf *default-timezone* +utc-zone+)))))
(defun 🚂 ()
(let ((ts (now)))
(multiple-value-bind (options free-args)
(handler-case (opts:get-opts)
; only handle subset of conditions that can happen here
(opts:unknown-option (c)
(format t "error: unknown option ~s~%" (opts:option c))
(quit 100)))
; check if we have any free args we don't know what to do with
(when (> (length free-args) 0)
(write-string "error: unexpected command line argument(s): ")
(loop for arg in free-args
do (progn (write-string arg) (write-char #\space)))
(write-char #\newline)
(quit 100))
; print help and exit
(when (getf options :help)
(opts:describe :usage-of "🕰️")
(quit 0))
; reinit *default-timezone* as it is cached from compilation
(setup-default-timezone)
; dot-time implies UTC, naturally
(when (getf options :dot-time)
(setf (getf options :utc) t))
; print clock face
(format t "~A" ( ts (if (getf options :utc)
local-time:+utc-zone+
local-time:*default-timezone*)))
; render dot-time offset if necessary
(when (getf options :dot-time)
(multiple-value-bind (offset-secs _dst _name)
(timestamp-subtimezone ts local-time:*default-timezone*)
(write-string
(format-dottime-offset (round (/ offset-secs 3600))))))
; write newline if necessary
(when (not (getf options :no-newline))
(write-char #\newline)))))

View file

@ -1,44 +0,0 @@
{ depot, ... }:
let
inherit (depot.nix)
buildLisp
;
lib = buildLisp.library {
name = "lib🕰";
deps = [
depot.third_party.lisp.local-time
];
srcs = [
./lib.lisp
];
};
bin = buildLisp.program {
name = "🕰";
deps = [
depot.third_party.lisp.unix-opts
depot.lisp.klatre
{
default = buildLisp.bundled "asdf";
sbcl = buildLisp.bundled "uiop";
}
lib
];
srcs = [
./bin.lisp
];
main = "🕰.bin:🚂";
brokenOn = [
"ecl" # refuses to create non-ASCII paths even on POSIX…
];
};
in
bin // {
inherit lib;
}

View file

@ -1,32 +0,0 @@
(defpackage 🕰
(:use :cl)
(:import-from :local-time
:timestamp-subtimezone :*default-timezone* :sec-of)
(:export :))
(in-package :🕰)
(declaim (optimize (safety 3)))
(defparameter *clock-emojis*
(vector #\🕛 #\🕧 ; 00:00 - 00:30
#\🕐 #\🕜 ; 01:00 - 01:30
#\🕑 #\🕝 ; 00:00 - 00:30
#\🕒 #\🕞 ; 00:00 - 00:30
#\🕓 #\🕟 ; 00:00 - 00:30
#\🕔 #\🕠 ; 00:00 - 00:30
#\🕕 #\🕡 ; 00:00 - 00:30
#\🕖 #\🕢 ; 00:00 - 00:30
#\🕗 #\🕣 ; 00:00 - 00:30
#\🕘 #\🕤 ; 00:00 - 00:30
#\🕙 #\🕥 ; 00:00 - 00:30
#\🕚 #\🕦)) ; 11:00 - 11:30
(defun (timestamp &optional (tz *default-timezone*))
"Convert a LOCAL-TIME:TIMESTAMP into the nearest Unicode clock face.
Use TZ (which defaults to LOCAL-TIME:*DEFAULT-TIMEZONE*) to determine
the UTC offset to factor when determining the local clock face."
(let* ((offset (multiple-value-bind (offset-secs _dst _name)
(timestamp-subtimezone timestamp tz)
offset-secs))
(secs (+ (sec-of timestamp) offset)))
(elt *clock-emojis* (mod (round (/ secs 1800)) 24))))