Compare commits
180 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46c0039a16 | ||
|
|
d5497908bb | ||
|
|
dac88391c1 | ||
|
|
a46a520bca | ||
|
|
04719f8dee | ||
|
|
113053a9e3 | ||
|
|
7cfe909644 | ||
|
|
01a1d981cf | ||
|
|
e7f8fc93e4 | ||
|
|
b45ca6f2c0 | ||
|
|
be17294dc2 | ||
|
|
7eaa92cb20 | ||
|
|
3001e57bcc | ||
|
|
43a2acb756 | ||
|
|
bcc424f2aa | ||
|
|
ec7e58a6a2 | ||
|
|
9a0f1f22b8 | ||
|
|
d6762276f5 | ||
|
|
41514cd557 | ||
|
|
63a29380a9 | ||
|
|
eeb378cfdc | ||
|
|
7a23779d07 | ||
|
|
29628a66a6 | ||
|
|
020c058805 | ||
|
|
8a625ef786 | ||
|
|
3bc8ff0104 | ||
|
|
11b5ac49c0 | ||
|
|
f553cdb282 | ||
|
|
6b46eb46e2 | ||
|
|
7280ae1ebc | ||
|
|
873c57b3d8 | ||
|
|
c8c53eed07 | ||
|
|
6779d9dd1f | ||
|
|
85939618c8 | ||
|
|
fe5734d9f0 | ||
|
|
6a7e9071b6 | ||
|
|
68d881291c | ||
|
|
66c749d5f0 | ||
|
|
534fca0d3b | ||
|
|
b6120cf6d7 | ||
|
|
09bf13bd70 | ||
|
|
9315829bc4 | ||
|
|
85b4abde6c | ||
|
|
edb6b0cf06 | ||
|
|
f24855ca9a | ||
|
|
ddd5ce2c21 | ||
|
|
e3dfea1991 | ||
|
|
fa9d6444f5 | ||
|
|
2c1989beb0 | ||
|
|
f266afa1de | ||
|
|
5639cf7a0f | ||
|
|
a1f513f6a5 | ||
|
|
1e8421e8ce | ||
|
|
4346f55b29 | ||
|
|
92f48fbbea | ||
|
|
200dd25ffa | ||
|
|
534b93e142 | ||
|
|
02f8a32b46 | ||
|
|
9cb48dbb60 | ||
|
|
bd09fb4c54 | ||
|
|
63206f8581 | ||
|
|
de0c41ec3b | ||
|
|
eaefb436d6 | ||
|
|
5843de5dfc | ||
|
|
6abda93a14 | ||
|
|
281faeff3b | ||
|
|
01d21165e9 | ||
|
|
e8688fed4b | ||
|
|
5ef83a7ba0 | ||
|
|
06b4d9c83b | ||
|
|
196c86d12b | ||
|
|
b45f95e392 | ||
|
|
aacdda94e1 | ||
|
|
ee34770610 | ||
|
|
b950e9da95 | ||
|
|
3ce333819f | ||
|
|
1f60791bad | ||
|
|
f966b2f9d7 | ||
|
|
d6fbccab55 | ||
|
|
d5be5d3e8c | ||
|
|
98c1ab9e86 | ||
|
|
b437a87266 | ||
|
|
9a56c24dbe | ||
|
|
808b63eaa1 | ||
|
|
3a009eac9d | ||
|
|
e2c419c021 | ||
|
|
6fb4bdc001 | ||
|
|
802ef17cb4 | ||
|
|
c9f1b02251 | ||
|
|
40fbce07db | ||
|
|
aa9764848a | ||
|
|
fc16b0531a | ||
|
|
94b70fbcb9 | ||
|
|
ab3cc47e27 | ||
|
|
a3ce12585b | ||
|
|
829e8f6ea6 | ||
|
|
fd71589f60 | ||
|
|
37fafd09e7 | ||
|
|
be50af0a7a | ||
|
|
da8f90d388 | ||
|
|
f1fac8da75 | ||
|
|
faa7de9f37 | ||
|
|
d0d1f9e5c7 | ||
|
|
4cc53633d8 | ||
|
|
4a3a0de198 | ||
|
|
048d17c365 | ||
|
|
0f495b881a | ||
|
|
3daa590732 | ||
|
|
dadb6419ee | ||
|
|
4fcb3891a2 | ||
|
|
0f57bd147c | ||
|
|
cd80c7ebd8 | ||
|
|
069d66263d | ||
|
|
6fbbb0c7b5 | ||
|
|
90ba341323 | ||
|
|
acb0bdf619 | ||
|
|
246061829b | ||
|
|
7ba268887b | ||
|
|
29f2196376 | ||
|
|
62f4d9963e | ||
|
|
07a1fe3acb | ||
|
|
1c8747f06f | ||
|
|
ae7bfb2c97 | ||
|
|
1e7ae885b4 | ||
|
|
9d37217eba | ||
|
|
e3debf4315 | ||
|
|
ccccae9aad | ||
|
|
28f4e1e55e | ||
|
|
8616be12a2 | ||
|
|
052ab7d411 | ||
|
|
6ca63cc0e9 | ||
|
|
f0edf0610e | ||
|
|
ee5b5c6edd | ||
|
|
4663c3b724 | ||
|
|
1193ddc65f | ||
|
|
d4330e86ac | ||
|
|
1b8ebab5f3 | ||
|
|
b6af28de33 | ||
|
|
e327e52766 | ||
|
|
7b8185c2a7 | ||
|
|
71af1af001 | ||
|
|
9af64bf3dd | ||
|
|
093154fa6c | ||
|
|
c247984ca9 | ||
|
|
2a05715107 | ||
|
|
cb69f18c39 | ||
|
|
fde5fda635 | ||
|
|
21990398c6 | ||
|
|
bbbab8d2ef | ||
|
|
ad057c12c0 | ||
|
|
e3bc92e158 | ||
|
|
45f94ead8b | ||
|
|
a56e1bf36d | ||
|
|
fa8a7ce43e | ||
|
|
e4c34a20e6 | ||
|
|
6a0dd08375 | ||
|
|
0d7039d034 | ||
|
|
8280e5b0ad | ||
|
|
ae97fbe025 | ||
|
|
6d7fec5337 | ||
|
|
ba2f6e08cd | ||
|
|
ffe0c72a5a | ||
|
|
52136030be | ||
|
|
a481f4c448 | ||
|
|
9b171dee8b | ||
|
|
c0ee174b13 | ||
|
|
fff535ca1a | ||
|
|
26390b9ad1 | ||
|
|
cc752cf797 | ||
|
|
4d48c5dc34 | ||
|
|
b9b53bcdf0 | ||
|
|
a1385f6785 | ||
|
|
d453db89a7 | ||
|
|
43c9a92748 | ||
|
|
c01c94c64c | ||
|
|
7adb0e4f2f | ||
|
|
0170f673bd | ||
|
|
86a16e3944 | ||
|
|
c9124cb5eb | ||
|
|
644ffa1420 |
22
.github/workflows/test.yaml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: test
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: '1.17.x'
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
- name: Install dependencies
|
||||
run: sudo apt update && sudo apt install -y python3-pip curl
|
||||
- name: Build docs (required for tests)
|
||||
run: make docs
|
||||
- name: Run tests, formatting, vetting and linting
|
||||
run: make check
|
||||
- name: Run coverage
|
||||
run: make coverage
|
||||
- name: Upload coverage to codecov.io
|
||||
run: make coverage-upload
|
||||
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
||||
dist/
|
||||
build/
|
||||
.idea/
|
||||
server/docs/
|
||||
tools/fbsend/fbsend
|
||||
*.iml
|
||||
|
||||
@@ -2,17 +2,42 @@ before:
|
||||
hooks:
|
||||
- go mod download
|
||||
builds:
|
||||
- binary: ntfy
|
||||
-
|
||||
id: ntfy
|
||||
binary: ntfy
|
||||
env:
|
||||
- CGO_ENABLED=1 # required for go-sqlite3
|
||||
goos:
|
||||
- linux
|
||||
goarch:
|
||||
- amd64
|
||||
tags: [sqlite_omit_load_extension,osusergo,netgo]
|
||||
ldflags:
|
||||
- "-linkmode=external -extldflags=-static -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}"
|
||||
goos: [linux]
|
||||
goarch: [amd64]
|
||||
-
|
||||
id: ntfy_armv7
|
||||
binary: ntfy
|
||||
env:
|
||||
- CGO_ENABLED=1 # required for go-sqlite3
|
||||
- CC=arm-linux-gnueabi-gcc # apt install gcc-arm-linux-gnueabi
|
||||
tags: [sqlite_omit_load_extension,osusergo,netgo]
|
||||
ldflags:
|
||||
- "-linkmode=external -extldflags=-static -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}"
|
||||
goos: [linux]
|
||||
goarch: [arm]
|
||||
goarm: [7]
|
||||
-
|
||||
id: ntfy_arm64
|
||||
binary: ntfy
|
||||
env:
|
||||
- CGO_ENABLED=1 # required for go-sqlite3
|
||||
- CC=aarch64-linux-gnu-gcc # apt install gcc-aarch64-linux-gnu
|
||||
tags: [sqlite_omit_load_extension,osusergo,netgo]
|
||||
ldflags:
|
||||
- "-linkmode=external -extldflags=-static -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}}"
|
||||
goos: [linux]
|
||||
goarch: [arm64]
|
||||
nfpms:
|
||||
-
|
||||
package_name: ntfy
|
||||
file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Arch }}"
|
||||
homepage: https://heckel.io/ntfy
|
||||
maintainer: Philipp C. Heckel <philipp.heckel@gmail.com>
|
||||
description: Simple pub-sub notification service
|
||||
@@ -22,12 +47,24 @@ nfpms:
|
||||
- rpm
|
||||
bindir: /usr/bin
|
||||
contents:
|
||||
- src: config/config.yml
|
||||
dst: /etc/ntfy/config.yml
|
||||
- src: server/server.yml
|
||||
dst: /etc/ntfy/server.yml
|
||||
type: config
|
||||
- src: config/ntfy.service
|
||||
- src: server/ntfy.service
|
||||
dst: /lib/systemd/system/ntfy.service
|
||||
- src: client/client.yml
|
||||
dst: /etc/ntfy/client.yml
|
||||
type: config
|
||||
- src: client/ntfy-client.service
|
||||
dst: /lib/systemd/system/ntfy-client.service
|
||||
- dst: /var/cache/ntfy
|
||||
type: dir
|
||||
- dst: /usr/share/ntfy/logo.png
|
||||
src: server/static/img/ntfy.png
|
||||
scripts:
|
||||
preinstall: "scripts/preinst.sh"
|
||||
postinstall: "scripts/postinst.sh"
|
||||
preremove: "scripts/prerm.sh"
|
||||
postremove: "scripts/postrm.sh"
|
||||
archives:
|
||||
-
|
||||
@@ -35,8 +72,10 @@ archives:
|
||||
files:
|
||||
- LICENSE
|
||||
- README.md
|
||||
- config/config.yml
|
||||
- config/ntfy.service
|
||||
- server/server.yml
|
||||
- server/ntfy.service
|
||||
- client/client.yml
|
||||
- client/ntfy-client.service
|
||||
replacements:
|
||||
386: i386
|
||||
amd64: x86_64
|
||||
@@ -51,10 +90,35 @@ changelog:
|
||||
- '^docs:'
|
||||
- '^test:'
|
||||
dockers:
|
||||
- dockerfile: Dockerfile
|
||||
ids:
|
||||
- ntfy
|
||||
- image_templates:
|
||||
- &amd64_image "binwiederhier/ntfy:{{ .Tag }}-amd64"
|
||||
use: buildx
|
||||
dockerfile: Dockerfile
|
||||
goarch: amd64
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- image_templates:
|
||||
- &arm64v8_image "binwiederhier/ntfy:{{ .Tag }}-arm64v8"
|
||||
use: buildx
|
||||
dockerfile: Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm64/v8"
|
||||
- image_templates:
|
||||
- &armv7_image "binwiederhier/ntfy:{{ .Tag }}-armv7"
|
||||
use: buildx
|
||||
dockerfile: Dockerfile
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm/v7"
|
||||
docker_manifests:
|
||||
- name_template: "binwiederhier/ntfy:latest"
|
||||
image_templates:
|
||||
- "binwiederhier/ntfy:latest"
|
||||
- "binwiederhier/ntfy:{{ .Tag }}"
|
||||
- "binwiederhier/ntfy:v{{ .Major }}.{{ .Minor }}"
|
||||
- *amd64_image
|
||||
- *arm64v8_image
|
||||
- *armv7_image
|
||||
- name_template: "binwiederhier/ntfy:{{ .Tag }}"
|
||||
image_templates:
|
||||
- *amd64_image
|
||||
- *arm64v8_image
|
||||
- *armv7_image
|
||||
|
||||
2
LICENSE
@@ -186,7 +186,7 @@
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2021 Philipp C. Heckel
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
340
LICENSE.GPLv2
Normal file
@@ -0,0 +1,340 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) 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
|
||||
this service 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 make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. 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.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the 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 a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE 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.
|
||||
|
||||
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
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
ntfy
|
||||
Copyright (C) 2021 Philipp C. Heckel
|
||||
|
||||
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 2 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, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision 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, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This 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.
|
||||
|
||||
70
Makefile
@@ -1,4 +1,3 @@
|
||||
GO=$(shell which go)
|
||||
VERSION := $(shell git describe --tag)
|
||||
|
||||
.PHONY:
|
||||
@@ -38,79 +37,100 @@ help:
|
||||
@echo " make install-lint - Install golint"
|
||||
|
||||
|
||||
# Documentation
|
||||
docs-deps: .PHONY
|
||||
pip3 install -r requirements.txt
|
||||
|
||||
docs: docs-deps
|
||||
mkdocs build
|
||||
|
||||
# Test/check targets
|
||||
|
||||
check: test fmt-check vet lint staticcheck
|
||||
|
||||
test: .PHONY
|
||||
$(GO) test ./...
|
||||
go test -v $(shell go list ./... | grep -vE 'ntfy/(test|examples|tools)')
|
||||
|
||||
race: .PHONY
|
||||
$(GO) test -race ./...
|
||||
go test -race $(shell go list ./... | grep -vE 'ntfy/(test|examples|tools)')
|
||||
|
||||
coverage:
|
||||
mkdir -p build/coverage
|
||||
$(GO) test -race -coverprofile=build/coverage/coverage.txt -covermode=atomic ./...
|
||||
$(GO) tool cover -func build/coverage/coverage.txt
|
||||
go test -race -coverprofile=build/coverage/coverage.txt -covermode=atomic $(shell go list ./... | grep -vE 'ntfy/(test|examples|tools)')
|
||||
go tool cover -func build/coverage/coverage.txt
|
||||
|
||||
coverage-html:
|
||||
mkdir -p build/coverage
|
||||
$(GO) test -race -coverprofile=build/coverage/coverage.txt -covermode=atomic ./...
|
||||
$(GO) tool cover -html build/coverage/coverage.txt
|
||||
go test -race -coverprofile=build/coverage/coverage.txt -covermode=atomic $(shell go list ./... | grep -vE 'ntfy/(test|examples|tools)')
|
||||
go tool cover -html build/coverage/coverage.txt
|
||||
|
||||
coverage-upload:
|
||||
cd build/coverage && (curl -s https://codecov.io/bash | bash)
|
||||
|
||||
|
||||
# Lint/formatting targets
|
||||
|
||||
fmt:
|
||||
$(GO) fmt ./...
|
||||
gofmt -s -w .
|
||||
|
||||
fmt-check:
|
||||
test -z $(shell gofmt -l .)
|
||||
|
||||
vet:
|
||||
$(GO) vet ./...
|
||||
go vet ./...
|
||||
|
||||
lint:
|
||||
which golint || $(GO) get -u golang.org/x/lint/golint
|
||||
$(GO) list ./... | grep -v /vendor/ | xargs -L1 golint -set_exit_status
|
||||
which golint || go get -u golang.org/x/lint/golint
|
||||
go list ./... | grep -v /vendor/ | xargs -L1 golint -set_exit_status
|
||||
|
||||
staticcheck: .PHONY
|
||||
rm -rf build/staticcheck
|
||||
which staticcheck || go get honnef.co/go/tools/cmd/staticcheck
|
||||
which staticcheck || go install honnef.co/go/tools/cmd/staticcheck@latest
|
||||
mkdir -p build/staticcheck
|
||||
ln -s "$(GO)" build/staticcheck/go
|
||||
ln -s "go" build/staticcheck/go
|
||||
PATH="$(PWD)/build/staticcheck:$(PATH)" staticcheck ./...
|
||||
rm -rf build/staticcheck
|
||||
|
||||
|
||||
# Building targets
|
||||
|
||||
build: .PHONY
|
||||
goreleaser build --rm-dist
|
||||
build-deps: docs
|
||||
which arm-linux-gnueabi-gcc || { echo "ERROR: ARMv6/v7 cross compiler not installed. On Ubuntu, run: apt install gcc-arm-linux-gnueabi"; exit 1; }
|
||||
which aarch64-linux-gnu-gcc || { echo "ERROR: ARM64 cross compiler not installed. On Ubuntu, run: apt install gcc-aarch64-linux-gnu"; exit 1; }
|
||||
|
||||
build-snapshot:
|
||||
goreleaser build --snapshot --rm-dist
|
||||
build: build-deps
|
||||
goreleaser build --rm-dist --debug
|
||||
|
||||
build-snapshot: build-deps
|
||||
goreleaser build --snapshot --rm-dist --debug
|
||||
|
||||
build-simple: clean
|
||||
mkdir -p dist/ntfy_linux_amd64
|
||||
export CGO_ENABLED=1
|
||||
$(GO) build \
|
||||
go build \
|
||||
-o dist/ntfy_linux_amd64/ntfy \
|
||||
-tags sqlite_omit_load_extension,osusergo,netgo \
|
||||
-ldflags \
|
||||
"-s -w -X main.version=$(VERSION) -X main.commit=$(shell git rev-parse --short HEAD) -X main.date=$(shell date +%s)"
|
||||
"-linkmode=external -extldflags=-static -s -w -X main.version=$(VERSION) -X main.commit=$(shell git rev-parse --short HEAD) -X main.date=$(shell date +%s)"
|
||||
|
||||
clean: .PHONY
|
||||
rm -rf dist build
|
||||
rm -rf dist build server/docs
|
||||
|
||||
|
||||
# Releasing targets
|
||||
|
||||
release:
|
||||
goreleaser release --rm-dist
|
||||
release-check-tags:
|
||||
$(eval LATEST_TAG := $(shell git describe --abbrev=0 --tags | cut -c2-))
|
||||
if ! grep -q $(LATEST_TAG) docs/install.md; then\
|
||||
echo "ERROR: Must update docs/install.md with latest tag first.";\
|
||||
exit 1;\
|
||||
fi
|
||||
|
||||
release-snapshot:
|
||||
goreleaser release --snapshot --skip-publish --rm-dist
|
||||
release: build-deps release-check-tags check
|
||||
goreleaser release --rm-dist --debug
|
||||
|
||||
release-snapshot: build-deps
|
||||
goreleaser release --snapshot --skip-publish --rm-dist --debug
|
||||
|
||||
|
||||
# Installing targets
|
||||
@@ -122,4 +142,4 @@ install:
|
||||
install-deb:
|
||||
sudo systemctl stop ntfy || true
|
||||
sudo apt-get purge ntfy || true
|
||||
sudo dpkg -i dist/*.deb
|
||||
sudo dpkg -i dist/ntfy_*_linux_amd64.deb
|
||||
|
||||
194
README.md
@@ -1,185 +1,57 @@
|
||||

|
||||
|
||||
# ntfy - simple HTTP-based pub-sub
|
||||
# ntfy.sh | Send push notifications to your phone or desktop via PUT/POST
|
||||
[](https://github.com/binwiederhier/ntfy/releases/latest)
|
||||
[](https://pkg.go.dev/heckel.io/ntfy)
|
||||
[](https://github.com/binwiederhier/ntfy/actions)
|
||||
[](https://goreportcard.com/report/github.com/binwiederhier/ntfy)
|
||||
[](https://codecov.io/gh/binwiederhier/ntfy)
|
||||
[](https://discord.gg/cT7ECsZj9w)
|
||||
[](https://ntfy.statuspage.io/)
|
||||
|
||||
**ntfy** (pronounce: *notify*) is a simple HTTP-based [pub-sub](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) notification service.
|
||||
It allows you to **send notifications to your phone or desktop via scripts** from any computer, entirely **without signup or cost**.
|
||||
It's also open source (as you can plainly see) if you want to run your own.
|
||||
|
||||
I run a free version of it at **[ntfy.sh](https://ntfy.sh)**, and there's an [Android app](https://play.google.com/store/apps/details?id=io.heckel.ntfy)
|
||||
I run a free version of it at **[ntfy.sh](https://ntfy.sh)**, and there's an [open source](https://github.com/binwiederhier/ntfy-android) [Android app](https://play.google.com/store/apps/details?id=io.heckel.ntfy)
|
||||
too.
|
||||
|
||||
## Usage
|
||||
<p>
|
||||
<img src="server/static/img/screenshot-curl.png" height="180">
|
||||
<img src="server/static/img/screenshot-web-detail.png" height="180">
|
||||
<img src="server/static/img/screenshot-phone-main.jpg" height="180">
|
||||
<img src="server/static/img/screenshot-phone-detail.jpg" height="180">
|
||||
<img src="server/static/img/screenshot-phone-notification.jpg" height="180">
|
||||
</p>
|
||||
|
||||
### Publishing messages
|
||||
## **[Documentation](https://ntfy.sh/docs/)**
|
||||
|
||||
Publishing messages can be done via PUT or POST using. Topics are created on the fly by subscribing or publishing to them.
|
||||
Because there is no sign-up, **the topic is essentially a password**, so pick something that's not easily guessable.
|
||||
|
||||
Here's an example showing how to publish a message using `curl`:
|
||||
|
||||
```
|
||||
curl -d "long process is done" ntfy.sh/mytopic
|
||||
```
|
||||
|
||||
Here's an example in JS with `fetch()` (see [full example](examples)):
|
||||
|
||||
```
|
||||
fetch('https://ntfy.sh/mytopic', {
|
||||
method: 'POST', // PUT works too
|
||||
body: 'Hello from the other side.'
|
||||
})
|
||||
```
|
||||
|
||||
### Subscribe to a topic
|
||||
You can create and subscribe to a topic either in this web UI, or in your own app by subscribing to an
|
||||
[EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource), a JSON feed, or raw feed.
|
||||
|
||||
#### Subscribe via web
|
||||
If you subscribe to a topic via this web UI in the field below, messages published to any subscribed topic
|
||||
will show up as **desktop notification**.
|
||||
|
||||
You can try this easily on **[ntfy.sh](https://ntfy.sh)**.
|
||||
|
||||
#### Subscribe via phone
|
||||
You can use the [Ntfy Android App](https://play.google.com/store/apps/details?id=io.heckel.ntfy) to receive
|
||||
notifications directly on your phone. Just like the server, this app is also [open source](https://github.com/binwiederhier/ntfy-android).
|
||||
|
||||
#### Subscribe via your app, or via the CLI
|
||||
Using [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) in JS, you can consume
|
||||
notifications like this (see [full example](examples)):
|
||||
|
||||
```javascript
|
||||
const eventSource = new EventSource('https://ntfy.sh/mytopic/sse');<br/>
|
||||
eventSource.onmessage = (e) => {<br/>
|
||||
// Do something with e.data<br/>
|
||||
};
|
||||
```
|
||||
|
||||
You can also use the same `/sse` endpoint via `curl` or any other HTTP library:
|
||||
|
||||
```
|
||||
$ curl -s ntfy.sh/mytopic/sse
|
||||
event: open
|
||||
data: {"id":"weSj9RtNkj","time":1635528898,"event":"open","topic":"mytopic"}
|
||||
|
||||
data: {"id":"p0M5y6gcCY","time":1635528909,"event":"message","topic":"mytopic","message":"Hi!"}
|
||||
|
||||
event: keepalive
|
||||
data: {"id":"VNxNIg5fpt","time":1635528928,"event":"keepalive","topic":"test"}
|
||||
```
|
||||
|
||||
To consume JSON instead, use the `/json` endpoint, which prints one message per line:
|
||||
|
||||
```
|
||||
$ curl -s ntfy.sh/mytopic/json
|
||||
{"id":"SLiKI64DOt","time":1635528757,"event":"open","topic":"mytopic"}
|
||||
{"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Hi!"}
|
||||
{"id":"DGUDShMCsc","time":1635528787,"event":"keepalive","topic":"mytopic"}
|
||||
```
|
||||
|
||||
Or use the `/raw` endpoint if you need something super simple (empty lines are keepalive messages):
|
||||
|
||||
```
|
||||
$ curl -s ntfy.sh/mytopic/raw
|
||||
|
||||
This is a notification
|
||||
```
|
||||
|
||||
#### Message buffering and polling
|
||||
Messages are buffered in memory for a few hours to account for network interruptions of subscribers.
|
||||
You can read back what you missed by using the `since=...` query parameter. It takes either a
|
||||
duration (e.g. `10m` or `30s`) or a Unix timestamp (e.g. `1635528757`):
|
||||
|
||||
```
|
||||
$ curl -s "ntfy.sh/mytopic/json?since=10m"
|
||||
# Same output as above, but includes messages from up to 10 minutes ago
|
||||
```
|
||||
|
||||
You can also just poll for messages if you don't like the long-standing connection using the `poll=1`
|
||||
query parameter. The connection will end after all available messages have been read. This parameter has to be
|
||||
combined with `since=`.
|
||||
|
||||
```
|
||||
$ curl -s "ntfy.sh/mytopic/json?poll=1&since=10m"
|
||||
# Returns messages from up to 10 minutes ago and ends the connection
|
||||
```
|
||||
|
||||
## Examples
|
||||
There are a few usage examples in the [examples](examples) directory. I'm sure there are tons of other ways to use it.
|
||||
|
||||
## Installation
|
||||
Please check out the [releases page](https://github.com/binwiederhier/ntfy/releases) for binaries and
|
||||
deb/rpm packages.
|
||||
|
||||
1. Install ntfy using one of the methods described below
|
||||
2. Then (optionally) edit `/etc/ntfy/config.yml`
|
||||
3. Then just run it with `ntfy` (or `systemctl start ntfy` when using the deb/rpm).
|
||||
|
||||
### Binaries and packages
|
||||
**Debian/Ubuntu** (*from a repository*)**:**
|
||||
```bash
|
||||
curl -sSL https://archive.heckel.io/apt/pubkey.txt | sudo apt-key add -
|
||||
sudo apt install apt-transport-https
|
||||
sudo sh -c "echo 'deb [arch=amd64] https://archive.heckel.io/apt debian main' > /etc/apt/sources.list.d/archive.heckel.io.list"
|
||||
sudo apt update
|
||||
sudo apt install ntfy
|
||||
```
|
||||
|
||||
**Debian/Ubuntu** (*manual install*)**:**
|
||||
```bash
|
||||
sudo apt install tmux
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.2.0/ntfy_1.2.0_amd64.deb
|
||||
dpkg -i ntfy_1.2.0_amd64.deb
|
||||
```
|
||||
|
||||
**Fedora/RHEL/CentOS:**
|
||||
```bash
|
||||
rpm -ivh https://github.com/binwiederhier/ntfy/releases/download/v1.2.0/ntfy_1.2.0_amd64.rpm
|
||||
```
|
||||
|
||||
**Docker:**
|
||||
```bash
|
||||
docker run --rm -it binwiederhier/ntfy
|
||||
```
|
||||
|
||||
**Go:**
|
||||
```bash
|
||||
go get -u heckel.io/ntfy
|
||||
```
|
||||
|
||||
**Manual install** (*any x86_64-based Linux*)**:**
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.2.0/ntfy_1.2.0_linux_x86_64.tar.gz
|
||||
sudo tar -C /usr/bin -zxf ntfy_1.2.0_linux_x86_64.tar.gz ntfy
|
||||
./ntfy
|
||||
```
|
||||
|
||||
## Building
|
||||
Building ntfy is simple. Here's how you do it:
|
||||
|
||||
```
|
||||
make build-simple
|
||||
# Builds to dist/ntfy_linux_amd64/ntfy
|
||||
```
|
||||
|
||||
To build releases, I use [GoReleaser](https://goreleaser.com/). If you have that installed, you can run `make build` or
|
||||
`make build-snapshot`.
|
||||
|
||||
## TODO
|
||||
- add HTTPS
|
||||
- make limits configurable
|
||||
[Getting started](https://ntfy.sh/docs/) |
|
||||
[Android/iOS](https://ntfy.sh/docs/subscribe/phone/) |
|
||||
[API](https://ntfy.sh/docs/publish/) |
|
||||
[Install / Self-hosting](https://ntfy.sh/docs/install/) |
|
||||
[Building](https://ntfy.sh/docs/develop/)
|
||||
|
||||
## Contributing
|
||||
I welcome any and all contributions. Just create a PR or an issue.
|
||||
|
||||
## Contact me
|
||||
You can directly contact me **[on Discord](https://discord.gg/cT7ECsZj9w)**, or via the [GitHub issues](https://github.com/binwiederhier/ntfy/issues),
|
||||
or find more contact information [on my website](https://heckel.io/about).
|
||||
|
||||
## License
|
||||
Made with ❤️ by [Philipp C. Heckel](https://heckel.io), distributed under the [Apache License 2.0](LICENSE).
|
||||
Made with ❤️ by [Philipp C. Heckel](https://heckel.io).
|
||||
The project is dual licensed under the [Apache License 2.0](LICENSE) and the [GPLv2 License](LICENSE.GPLv2).
|
||||
|
||||
Third party libraries and resources:
|
||||
* [github.com/urfave/cli/v2](https://github.com/urfave/cli/v2) (MIT) is used to drive the CLI
|
||||
* [Mixkit sound](https://mixkit.co/free-sound-effects/notification/) (Mixkit Free License) used as notification sound
|
||||
* [Lato Font](https://www.latofonts.com/) (OFL) is used as a font in the Web UI
|
||||
* [GoReleaser](https://goreleaser.com/) (MIT) is used to create releases
|
||||
* [go-smtp](https://github.com/emersion/go-smtp) (MIT) is used to receive e-mails
|
||||
* [stretchr/testify](https://github.com/stretchr/testify) (MIT) is used for unit and integration tests
|
||||
* [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3) (MIT) is used to provide the persistent message cache
|
||||
* [Firebase Admin SDK](https://github.com/firebase/firebase-admin-go) (Apache 2.0) is used to send FCM messages
|
||||
* [github/gemoji](https://github.com/github/gemoji) (MIT) is used for emoji support (specifically the [emoji.json](https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json) file)
|
||||
* [Lightbox with vanilla JS](https://yossiabramov.com/blog/vanilla-js-lightbox)
|
||||
* [Statically linking go-sqlite3](https://www.arp242.net/static-go.html)
|
||||
|
||||
257
client/client.go
Normal file
@@ -0,0 +1,257 @@
|
||||
// Package client provides a ntfy client to publish and subscribe to topics
|
||||
package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"heckel.io/ntfy/util"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Event type constants
|
||||
const (
|
||||
MessageEvent = "message"
|
||||
KeepaliveEvent = "keepalive"
|
||||
OpenEvent = "open"
|
||||
)
|
||||
|
||||
const (
|
||||
maxResponseBytes = 4096
|
||||
)
|
||||
|
||||
// Client is the ntfy client that can be used to publish and subscribe to ntfy topics
|
||||
type Client struct {
|
||||
Messages chan *Message
|
||||
config *Config
|
||||
subscriptions map[string]*subscription
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Message is a struct that represents a ntfy message
|
||||
type Message struct { // TODO combine with server.message
|
||||
ID string
|
||||
Event string
|
||||
Time int64
|
||||
Topic string
|
||||
Message string
|
||||
Title string
|
||||
Priority int
|
||||
Tags []string
|
||||
|
||||
// Additional fields
|
||||
TopicURL string
|
||||
SubscriptionID string
|
||||
Raw string
|
||||
}
|
||||
|
||||
type subscription struct {
|
||||
ID string
|
||||
topicURL string
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// New creates a new Client using a given Config
|
||||
func New(config *Config) *Client {
|
||||
return &Client{
|
||||
Messages: make(chan *Message, 50), // Allow reading a few messages
|
||||
config: config,
|
||||
subscriptions: make(map[string]*subscription),
|
||||
}
|
||||
}
|
||||
|
||||
// Publish sends a message to a specific topic, optionally using options.
|
||||
//
|
||||
// A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
|
||||
// (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
|
||||
// config (e.g. mytopic -> https://ntfy.sh/mytopic).
|
||||
//
|
||||
// To pass title, priority and tags, check out WithTitle, WithPriority, WithTagsList, WithDelay, WithNoCache,
|
||||
// WithNoFirebase, and the generic WithHeader.
|
||||
func (c *Client) Publish(topic, message string, options ...PublishOption) (*Message, error) {
|
||||
topicURL := c.expandTopicURL(topic)
|
||||
req, _ := http.NewRequest("POST", topicURL, strings.NewReader(message))
|
||||
for _, option := range options {
|
||||
if err := option(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("unexpected response %d from server", resp.StatusCode)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := toMessage(string(b), topicURL, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Poll queries a topic for all (or a limited set) of messages. Unlike Subscribe, this method only polls for
|
||||
// messages and does not subscribe to messages that arrive after this call.
|
||||
//
|
||||
// A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
|
||||
// (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
|
||||
// config (e.g. mytopic -> https://ntfy.sh/mytopic).
|
||||
//
|
||||
// By default, all messages will be returned, but you can change this behavior using a SubscribeOption.
|
||||
// See WithSince, WithSinceAll, WithSinceUnixTime, WithScheduled, and the generic WithQueryParam.
|
||||
func (c *Client) Poll(topic string, options ...SubscribeOption) ([]*Message, error) {
|
||||
ctx := context.Background()
|
||||
messages := make([]*Message, 0)
|
||||
msgChan := make(chan *Message)
|
||||
errChan := make(chan error)
|
||||
topicURL := c.expandTopicURL(topic)
|
||||
options = append(options, WithPoll())
|
||||
go func() {
|
||||
err := performSubscribeRequest(ctx, msgChan, topicURL, "", options...)
|
||||
close(msgChan)
|
||||
errChan <- err
|
||||
}()
|
||||
for m := range msgChan {
|
||||
messages = append(messages, m)
|
||||
}
|
||||
return messages, <-errChan
|
||||
}
|
||||
|
||||
// Subscribe subscribes to a topic to listen for newly incoming messages. The method starts a connection in the
|
||||
// background and returns new messages via the Messages channel.
|
||||
//
|
||||
// A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
|
||||
// (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
|
||||
// config (e.g. mytopic -> https://ntfy.sh/mytopic).
|
||||
//
|
||||
// By default, only new messages will be returned, but you can change this behavior using a SubscribeOption.
|
||||
// See WithSince, WithSinceAll, WithSinceUnixTime, WithScheduled, and the generic WithQueryParam.
|
||||
//
|
||||
// The method returns a unique subscriptionID that can be used in Unsubscribe.
|
||||
//
|
||||
// Example:
|
||||
// c := client.New(client.NewConfig())
|
||||
// subscriptionID := c.Subscribe("mytopic")
|
||||
// for m := range c.Messages {
|
||||
// fmt.Printf("New message: %s", m.Message)
|
||||
// }
|
||||
func (c *Client) Subscribe(topic string, options ...SubscribeOption) string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
subscriptionID := util.RandomString(10)
|
||||
topicURL := c.expandTopicURL(topic)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
c.subscriptions[subscriptionID] = &subscription{
|
||||
ID: subscriptionID,
|
||||
topicURL: topicURL,
|
||||
cancel: cancel,
|
||||
}
|
||||
go handleSubscribeConnLoop(ctx, c.Messages, topicURL, subscriptionID, options...)
|
||||
return subscriptionID
|
||||
}
|
||||
|
||||
// Unsubscribe unsubscribes from a topic that has been previously subscribed to using the unique
|
||||
// subscriptionID returned in Subscribe.
|
||||
func (c *Client) Unsubscribe(subscriptionID string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
sub, ok := c.subscriptions[subscriptionID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
delete(c.subscriptions, subscriptionID)
|
||||
sub.cancel()
|
||||
}
|
||||
|
||||
// UnsubscribeAll unsubscribes from a topic that has been previously subscribed with Subscribe.
|
||||
// If there are multiple subscriptions matching the topic, all of them are unsubscribed from.
|
||||
//
|
||||
// A topic can be either a full URL (e.g. https://myhost.lan/mytopic), a short URL which is then prepended https://
|
||||
// (e.g. myhost.lan -> https://myhost.lan), or a short name which is expanded using the default host in the
|
||||
// config (e.g. mytopic -> https://ntfy.sh/mytopic).
|
||||
func (c *Client) UnsubscribeAll(topic string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
topicURL := c.expandTopicURL(topic)
|
||||
for _, sub := range c.subscriptions {
|
||||
if sub.topicURL == topicURL {
|
||||
delete(c.subscriptions, sub.ID)
|
||||
sub.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) expandTopicURL(topic string) string {
|
||||
if strings.HasPrefix(topic, "http://") || strings.HasPrefix(topic, "https://") {
|
||||
return topic
|
||||
} else if strings.Contains(topic, "/") {
|
||||
return fmt.Sprintf("https://%s", topic)
|
||||
}
|
||||
return fmt.Sprintf("%s/%s", c.config.DefaultHost, topic)
|
||||
}
|
||||
|
||||
func handleSubscribeConnLoop(ctx context.Context, msgChan chan *Message, topicURL, subcriptionID string, options ...SubscribeOption) {
|
||||
for {
|
||||
// TODO The retry logic is crude and may lose messages. It should record the last message like the
|
||||
// Android client, use since=, and do incremental backoff too
|
||||
if err := performSubscribeRequest(ctx, msgChan, topicURL, subcriptionID, options...); err != nil {
|
||||
log.Printf("Connection to %s failed: %s", topicURL, err.Error())
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Printf("Connection to %s exited", topicURL)
|
||||
return
|
||||
case <-time.After(10 * time.Second): // TODO Add incremental backoff
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func performSubscribeRequest(ctx context.Context, msgChan chan *Message, topicURL string, subscriptionID string, options ...SubscribeOption) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/json", topicURL), nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, option := range options {
|
||||
if err := option(req); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
m, err := toMessage(scanner.Text(), topicURL, subscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.Event == MessageEvent {
|
||||
msgChan <- m
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toMessage(s, topicURL, subscriptionID string) (*Message, error) {
|
||||
var m *Message
|
||||
if err := json.NewDecoder(strings.NewReader(s)).Decode(&m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.TopicURL = topicURL
|
||||
m.SubscriptionID = subscriptionID
|
||||
m.Raw = s
|
||||
return m, nil
|
||||
}
|
||||
36
client/client.yml
Normal file
@@ -0,0 +1,36 @@
|
||||
# ntfy client config file
|
||||
|
||||
# Base URL used to expand short topic names in the "ntfy publish" and "ntfy subscribe" commands.
|
||||
# If you self-host a ntfy server, you'll likely want to change this.
|
||||
#
|
||||
# default-host: https://ntfy.sh
|
||||
|
||||
# Subscriptions to topics and their actions. This option is primarily used by the systemd service,
|
||||
# or if you cann "ntfy subscribe --from-config" directly.
|
||||
#
|
||||
# Example:
|
||||
# subscribe:
|
||||
# - topic: mytopic
|
||||
# command: /usr/local/bin/mytopic-triggered.sh
|
||||
# - topic: myserver.com/anothertopic
|
||||
# command: 'echo "$message"'
|
||||
# if:
|
||||
# priority: high,urgent
|
||||
#
|
||||
# Variables:
|
||||
# Variable Aliases Description
|
||||
# --------------- --------------------- -----------------------------------
|
||||
# $NTFY_ID $id Unique message ID
|
||||
# $NTFY_TIME $time Unix timestamp of the message delivery
|
||||
# $NTFY_TOPIC $topic Topic name
|
||||
# $NTFY_MESSAGE $message, $m Message body
|
||||
# $NTFY_TITLE $title, $t Message title
|
||||
# $NTFY_PRIORITY $priority, $prio, $p Message priority (1=min, 5=max)
|
||||
# $NTFY_TAGS $tags, $tag, $ta Message tags (comma separated list)
|
||||
# $NTFY_RAW $raw Raw JSON message
|
||||
#
|
||||
# Filters ('if:'):
|
||||
# You can filter 'message', 'title', 'priority' (comma-separated list, logical OR)
|
||||
# and 'tags' (comma-separated list, logical AND). See https://ntfy.sh/docs/subscribe/api/#filter-messages.
|
||||
#
|
||||
# subscribe:
|
||||
110
client/client_test.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package client_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/require"
|
||||
"heckel.io/ntfy/client"
|
||||
"heckel.io/ntfy/test"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClient_Publish_Subscribe(t *testing.T) {
|
||||
s, port := test.StartServer(t)
|
||||
defer test.StopServer(t, s, port)
|
||||
c := client.New(newTestConfig(port))
|
||||
|
||||
subscriptionID := c.Subscribe("mytopic")
|
||||
time.Sleep(time.Second)
|
||||
|
||||
msg, err := c.Publish("mytopic", "some message")
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "some message", msg.Message)
|
||||
|
||||
msg, err = c.Publish("mytopic", "some other message",
|
||||
client.WithTitle("some title"),
|
||||
client.WithPriority("high"),
|
||||
client.WithTags([]string{"tag1", "tag 2"}))
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "some other message", msg.Message)
|
||||
require.Equal(t, "some title", msg.Title)
|
||||
require.Equal(t, []string{"tag1", "tag 2"}, msg.Tags)
|
||||
require.Equal(t, 4, msg.Priority)
|
||||
|
||||
msg, err = c.Publish("mytopic", "some delayed message",
|
||||
client.WithDelay("25 hours"))
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "some delayed message", msg.Message)
|
||||
require.True(t, time.Now().Add(24*time.Hour).Unix() < msg.Time)
|
||||
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
msg = nextMessage(c)
|
||||
require.NotNil(t, msg)
|
||||
require.Equal(t, "some message", msg.Message)
|
||||
|
||||
msg = nextMessage(c)
|
||||
require.NotNil(t, msg)
|
||||
require.Equal(t, "some other message", msg.Message)
|
||||
require.Equal(t, "some title", msg.Title)
|
||||
require.Equal(t, []string{"tag1", "tag 2"}, msg.Tags)
|
||||
require.Equal(t, 4, msg.Priority)
|
||||
|
||||
msg = nextMessage(c)
|
||||
require.Nil(t, msg)
|
||||
|
||||
c.Unsubscribe(subscriptionID)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
msg, err = c.Publish("mytopic", "a message that won't be received")
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "a message that won't be received", msg.Message)
|
||||
|
||||
msg = nextMessage(c)
|
||||
require.Nil(t, msg)
|
||||
}
|
||||
|
||||
func TestClient_Publish_Poll(t *testing.T) {
|
||||
s, port := test.StartServer(t)
|
||||
defer test.StopServer(t, s, port)
|
||||
c := client.New(newTestConfig(port))
|
||||
|
||||
msg, err := c.Publish("mytopic", "some message", client.WithNoFirebase(), client.WithTagsList("tag1,tag2"))
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "some message", msg.Message)
|
||||
require.Equal(t, []string{"tag1", "tag2"}, msg.Tags)
|
||||
|
||||
msg, err = c.Publish("mytopic", "this won't be cached", client.WithNoCache())
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "this won't be cached", msg.Message)
|
||||
|
||||
msg, err = c.Publish("mytopic", "some delayed message", client.WithDelay("20 min"))
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "some delayed message", msg.Message)
|
||||
|
||||
messages, err := c.Poll("mytopic")
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 1, len(messages))
|
||||
require.Equal(t, "some message", messages[0].Message)
|
||||
|
||||
messages, err = c.Poll("mytopic", client.WithScheduled())
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 2, len(messages))
|
||||
require.Equal(t, "some message", messages[0].Message)
|
||||
require.Equal(t, "some delayed message", messages[1].Message)
|
||||
}
|
||||
|
||||
func newTestConfig(port int) *client.Config {
|
||||
c := client.NewConfig()
|
||||
c.DefaultHost = fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
return c
|
||||
}
|
||||
|
||||
func nextMessage(c *client.Client) *client.Message {
|
||||
select {
|
||||
case m := <-c.Messages:
|
||||
return m
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
42
client/config.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"gopkg.in/yaml.v2"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultBaseURL is the base URL used to expand short topic names
|
||||
DefaultBaseURL = "https://ntfy.sh"
|
||||
)
|
||||
|
||||
// Config is the config struct for a Client
|
||||
type Config struct {
|
||||
DefaultHost string `yaml:"default-host"`
|
||||
Subscribe []struct {
|
||||
Topic string `yaml:"topic"`
|
||||
Command string `yaml:"command"`
|
||||
If map[string]string `yaml:"if"`
|
||||
} `yaml:"subscribe"`
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config struct for a Client
|
||||
func NewConfig() *Config {
|
||||
return &Config{
|
||||
DefaultHost: DefaultBaseURL,
|
||||
Subscribe: nil,
|
||||
}
|
||||
}
|
||||
|
||||
// LoadConfig loads the Client config from a yaml file
|
||||
func LoadConfig(filename string) (*Config, error) {
|
||||
b, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := NewConfig()
|
||||
if err := yaml.Unmarshal(b, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
36
client/config_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package client_test
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/require"
|
||||
"heckel.io/ntfy/client"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfig_Load(t *testing.T) {
|
||||
filename := filepath.Join(t.TempDir(), "client.yml")
|
||||
require.Nil(t, os.WriteFile(filename, []byte(`
|
||||
default-host: http://localhost
|
||||
subscribe:
|
||||
- topic: no-command
|
||||
- topic: echo-this
|
||||
command: 'echo "Message received: $message"'
|
||||
- topic: alerts
|
||||
command: notify-send -i /usr/share/ntfy/logo.png "Important" "$m"
|
||||
if:
|
||||
priority: high,urgent
|
||||
`), 0600))
|
||||
|
||||
conf, err := client.LoadConfig(filename)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "http://localhost", conf.DefaultHost)
|
||||
require.Equal(t, 3, len(conf.Subscribe))
|
||||
require.Equal(t, "no-command", conf.Subscribe[0].Topic)
|
||||
require.Equal(t, "", conf.Subscribe[0].Command)
|
||||
require.Equal(t, "echo-this", conf.Subscribe[1].Topic)
|
||||
require.Equal(t, `echo "Message received: $message"`, conf.Subscribe[1].Command)
|
||||
require.Equal(t, "alerts", conf.Subscribe[2].Topic)
|
||||
require.Equal(t, `notify-send -i /usr/share/ntfy/logo.png "Important" "$m"`, conf.Subscribe[2].Command)
|
||||
require.Equal(t, "high,urgent", conf.Subscribe[2].If["priority"])
|
||||
}
|
||||
12
client/ntfy-client.service
Normal file
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=ntfy client
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=ntfy
|
||||
Group=ntfy
|
||||
ExecStart=/usr/bin/ntfy subscribe --config /etc/ntfy/client.yml --from-config
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
142
client/options.go
Normal file
@@ -0,0 +1,142 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RequestOption is a generic request option that can be added to Client calls
|
||||
type RequestOption = func(r *http.Request) error
|
||||
|
||||
// PublishOption is an option that can be passed to the Client.Publish call
|
||||
type PublishOption = RequestOption
|
||||
|
||||
// SubscribeOption is an option that can be passed to a Client.Subscribe or Client.Poll call
|
||||
type SubscribeOption = RequestOption
|
||||
|
||||
// WithTitle adds a title to a message
|
||||
func WithTitle(title string) PublishOption {
|
||||
return WithHeader("X-Title", title)
|
||||
}
|
||||
|
||||
// WithPriority adds a priority to a message. The priority can be either a number (1=min, 5=max),
|
||||
// or the corresponding names (see util.ParsePriority).
|
||||
func WithPriority(priority string) PublishOption {
|
||||
return WithHeader("X-Priority", priority)
|
||||
}
|
||||
|
||||
// WithTagsList adds a list of tags to a message. The tags parameter must be a comma-separated list
|
||||
// of tags. To use a slice, use WithTags instead
|
||||
func WithTagsList(tags string) PublishOption {
|
||||
return WithHeader("X-Tags", tags)
|
||||
}
|
||||
|
||||
// WithTags adds a list of a tags to a message
|
||||
func WithTags(tags []string) PublishOption {
|
||||
return WithTagsList(strings.Join(tags, ","))
|
||||
}
|
||||
|
||||
// WithDelay instructs the server to send the message at a later date. The delay parameter can be a
|
||||
// Unix timestamp, a duration string or a natural langage string. See https://ntfy.sh/docs/publish/#scheduled-delivery
|
||||
// for details.
|
||||
func WithDelay(delay string) PublishOption {
|
||||
return WithHeader("X-Delay", delay)
|
||||
}
|
||||
|
||||
// WithEmail instructs the server to also send the message to the given e-mail address
|
||||
func WithEmail(email string) PublishOption {
|
||||
return WithHeader("X-Email", email)
|
||||
}
|
||||
|
||||
// WithNoCache instructs the server not to cache the message server-side
|
||||
func WithNoCache() PublishOption {
|
||||
return WithHeader("X-Cache", "no")
|
||||
}
|
||||
|
||||
// WithNoFirebase instructs the server not to forward the message to Firebase
|
||||
func WithNoFirebase() PublishOption {
|
||||
return WithHeader("X-Firebase", "no")
|
||||
}
|
||||
|
||||
// WithSince limits the number of messages returned from the server. The parameter since can be a Unix
|
||||
// timestamp (see WithSinceUnixTime), a duration (WithSinceDuration) the word "all" (see WithSinceAll).
|
||||
func WithSince(since string) SubscribeOption {
|
||||
return WithQueryParam("since", since)
|
||||
}
|
||||
|
||||
// WithSinceAll instructs the server to return all messages for the given topic from the server
|
||||
func WithSinceAll() SubscribeOption {
|
||||
return WithSince("all")
|
||||
}
|
||||
|
||||
// WithSinceDuration instructs the server to return all messages since the given duration ago
|
||||
func WithSinceDuration(since time.Duration) SubscribeOption {
|
||||
return WithSinceUnixTime(time.Now().Add(-1 * since).Unix())
|
||||
}
|
||||
|
||||
// WithSinceUnixTime instructs the server to return only messages newer or equal to the given timestamp
|
||||
func WithSinceUnixTime(since int64) SubscribeOption {
|
||||
return WithSince(fmt.Sprintf("%d", since))
|
||||
}
|
||||
|
||||
// WithPoll instructs the server to close the connection after messages have been returned. Don't use this option
|
||||
// directly. Use Client.Poll instead.
|
||||
func WithPoll() SubscribeOption {
|
||||
return WithQueryParam("poll", "1")
|
||||
}
|
||||
|
||||
// WithScheduled instructs the server to also return messages that have not been sent yet, i.e. delayed/scheduled
|
||||
// messages (see WithDelay). The messages will have a future date.
|
||||
func WithScheduled() SubscribeOption {
|
||||
return WithQueryParam("scheduled", "1")
|
||||
}
|
||||
|
||||
// WithFilter is a generic subscribe option meant to be used to filter for certain messages only
|
||||
func WithFilter(param, value string) SubscribeOption {
|
||||
return WithQueryParam(param, value)
|
||||
}
|
||||
|
||||
// WithMessageFilter instructs the server to only return messages that match the exact message
|
||||
func WithMessageFilter(message string) SubscribeOption {
|
||||
return WithQueryParam("message", message)
|
||||
}
|
||||
|
||||
// WithTitleFilter instructs the server to only return messages with a title that match the exact string
|
||||
func WithTitleFilter(title string) SubscribeOption {
|
||||
return WithQueryParam("title", title)
|
||||
}
|
||||
|
||||
// WithPriorityFilter instructs the server to only return messages with the matching priority. Not that messages
|
||||
// without priority also implicitly match priority 3.
|
||||
func WithPriorityFilter(priority int) SubscribeOption {
|
||||
return WithQueryParam("priority", fmt.Sprintf("%d", priority))
|
||||
}
|
||||
|
||||
// WithTagsFilter instructs the server to only return messages that contain all of the given tags
|
||||
func WithTagsFilter(tags []string) SubscribeOption {
|
||||
return WithQueryParam("tags", strings.Join(tags, ","))
|
||||
}
|
||||
|
||||
// WithHeader is a generic option to add headers to a request
|
||||
func WithHeader(header, value string) RequestOption {
|
||||
return func(r *http.Request) error {
|
||||
if value != "" {
|
||||
r.Header.Set(header, value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithQueryParam is a generic option to add query parameters to a request
|
||||
func WithQueryParam(param, value string) RequestOption {
|
||||
return func(r *http.Request) error {
|
||||
if value != "" {
|
||||
q := r.URL.Query()
|
||||
q.Add(param, value)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
72
cmd/app.go
@@ -2,82 +2,44 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/urfave/cli/v2"
|
||||
"github.com/urfave/cli/v2/altsrc"
|
||||
"heckel.io/ntfy/config"
|
||||
"heckel.io/ntfy/server"
|
||||
"heckel.io/ntfy/util"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultClientRootConfigFile = "/etc/ntfy/client.yml"
|
||||
defaultClientUserConfigFile = "~/.config/ntfy/client.yml"
|
||||
)
|
||||
|
||||
// New creates a new CLI application
|
||||
func New() *cli.App {
|
||||
flags := []cli.Flag{
|
||||
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/config.yml", DefaultText: "/etc/ntfy/config.yml", Usage: "config file"},
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-http", Aliases: []string{"l"}, EnvVars: []string{"NTFY_LISTEN_HTTP"}, Value: config.DefaultListenHTTP, Usage: "ip:port used to as listen address"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "firebase-key-file", Aliases: []string{"F"}, EnvVars: []string{"NTFY_FIREBASE_KEY_FILE"}, Usage: "Firebase credentials file; if set additionally publish to FCM topic"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "cache-duration", Aliases: []string{"b"}, EnvVars: []string{"NTFY_CACHE_DURATION"}, Value: config.DefaultCacheDuration, Usage: "buffer messages for this time to allow `since` requests"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "keepalive-interval", Aliases: []string{"k"}, EnvVars: []string{"NTFY_KEEPALIVE_INTERVAL"}, Value: config.DefaultKeepaliveInterval, Usage: "default interval of keepalive messages"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "manager-interval", Aliases: []string{"m"}, EnvVars: []string{"NTFY_MANAGER_INTERVAL"}, Value: config.DefaultManagerInterval, Usage: "default interval of for message pruning and stats printing"}),
|
||||
}
|
||||
return &cli.App{
|
||||
Name: "ntfy",
|
||||
Usage: "Simple pub-sub notification service",
|
||||
UsageText: "ntfy [OPTION..]",
|
||||
HideHelp: true,
|
||||
HideVersion: true,
|
||||
EnableBashCompletion: true,
|
||||
UseShortOptionHandling: true,
|
||||
Reader: os.Stdin,
|
||||
Writer: os.Stdout,
|
||||
ErrWriter: os.Stderr,
|
||||
Action: execRun,
|
||||
Before: initConfigFileInputSource("config", flags),
|
||||
Flags: flags,
|
||||
Action: execMainApp,
|
||||
Before: initConfigFileInputSource("config", flagsServe), // DEPRECATED, see deprecation notice
|
||||
Flags: flagsServe, // DEPRECATED, see deprecation notice
|
||||
Commands: []*cli.Command{
|
||||
cmdServe,
|
||||
cmdPublish,
|
||||
cmdSubscribe,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func execRun(c *cli.Context) error {
|
||||
// Read all the options
|
||||
listenHTTP := c.String("listen-http")
|
||||
firebaseKeyFile := c.String("firebase-key-file")
|
||||
cacheFile := c.String("cache-file")
|
||||
cacheDuration := c.Duration("cache-duration")
|
||||
keepaliveInterval := c.Duration("keepalive-interval")
|
||||
managerInterval := c.Duration("manager-interval")
|
||||
|
||||
// Check values
|
||||
if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
|
||||
return errors.New("if set, FCM key file must exist")
|
||||
} else if keepaliveInterval < 5*time.Second {
|
||||
return errors.New("keepalive interval cannot be lower than five seconds")
|
||||
} else if managerInterval < 5*time.Second {
|
||||
return errors.New("manager interval cannot be lower than five seconds")
|
||||
} else if cacheDuration < managerInterval {
|
||||
return errors.New("cache duration cannot be lower than manager interval")
|
||||
}
|
||||
|
||||
// Run server
|
||||
conf := config.New(listenHTTP)
|
||||
conf.FirebaseKeyFile = firebaseKeyFile
|
||||
conf.CacheFile = cacheFile
|
||||
conf.CacheDuration = cacheDuration
|
||||
conf.KeepaliveInterval = keepaliveInterval
|
||||
conf.ManagerInterval = managerInterval
|
||||
s, err := server.New(conf)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := s.Run(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
log.Printf("Exiting.")
|
||||
return nil
|
||||
func execMainApp(c *cli.Context) error {
|
||||
fmt.Fprintln(c.App.ErrWriter, "\x1b[1;33mDeprecation notice: Please run the server using 'ntfy serve'; see 'ntfy -h' for help.\x1b[0m")
|
||||
fmt.Fprintln(c.App.ErrWriter, "\x1b[1;33mThis way of running the server will be removed March 2022. See https://ntfy.sh/docs/deprecations/ for details.\x1b[0m")
|
||||
return execServe(c)
|
||||
}
|
||||
|
||||
// initConfigFileInputSource is like altsrc.InitInputSourceWithContext and altsrc.NewYamlSourceFromFlagFunc, but checks
|
||||
|
||||
37
cmd/app_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/urfave/cli/v2"
|
||||
"heckel.io/ntfy/client"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// This only contains helpers so far
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
log.SetOutput(io.Discard)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func newTestApp() (*cli.App, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {
|
||||
var stdin, stdout, stderr bytes.Buffer
|
||||
app := New()
|
||||
app.Reader = &stdin
|
||||
app.Writer = &stdout
|
||||
app.ErrWriter = &stderr
|
||||
return app, &stdin, &stdout, &stderr
|
||||
}
|
||||
|
||||
func toMessage(t *testing.T, s string) *client.Message {
|
||||
var m *client.Message
|
||||
if err := json.NewDecoder(strings.NewReader(s)).Decode(&m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
99
cmd/publish.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/urfave/cli/v2"
|
||||
"heckel.io/ntfy/client"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var cmdPublish = &cli.Command{
|
||||
Name: "publish",
|
||||
Aliases: []string{"pub", "send", "trigger"},
|
||||
Usage: "Send message via a ntfy server",
|
||||
UsageText: "ntfy send [OPTIONS..] TOPIC [MESSAGE]",
|
||||
Action: execPublish,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
|
||||
&cli.StringFlag{Name: "title", Aliases: []string{"t"}, Usage: "message title"},
|
||||
&cli.StringFlag{Name: "priority", Aliases: []string{"p"}, Usage: "priority of the message (1=min, 2=low, 3=default, 4=high, 5=max)"},
|
||||
&cli.StringFlag{Name: "tags", Aliases: []string{"tag", "T"}, Usage: "comma separated list of tags and emojis"},
|
||||
&cli.StringFlag{Name: "delay", Aliases: []string{"at", "in", "D"}, Usage: "delay/schedule message"},
|
||||
&cli.StringFlag{Name: "email", Aliases: []string{"e-mail", "mail", "e"}, Usage: "also send to e-mail address"},
|
||||
&cli.BoolFlag{Name: "no-cache", Aliases: []string{"C"}, Usage: "do not cache message server-side"},
|
||||
&cli.BoolFlag{Name: "no-firebase", Aliases: []string{"F"}, Usage: "do not forward message to Firebase"},
|
||||
&cli.BoolFlag{Name: "quiet", Aliases: []string{"q"}, Usage: "do print message"},
|
||||
},
|
||||
Description: `Publish a message to a ntfy server.
|
||||
|
||||
Examples:
|
||||
ntfy publish mytopic This is my message # Send simple message
|
||||
ntfy send myserver.com/mytopic "This is my message" # Send message to different default host
|
||||
ntfy pub -p high backups "Backups failed" # Send high priority message
|
||||
ntfy pub --tags=warning,skull backups "Backups failed" # Add tags/emojis to message
|
||||
ntfy pub --delay=10s delayed_topic Laterzz # Delay message by 10s
|
||||
ntfy pub --at=8:30am delayed_topic Laterzz # Send message at 8:30am
|
||||
ntfy pub -e phil@example.com alerts 'App is down!' # Also send email to phil@example.com
|
||||
ntfy trigger mywebhook # Sending without message, useful for webhooks
|
||||
|
||||
Please also check out the docs on publishing messages. Especially for the --tags and --delay options,
|
||||
it has incredibly useful information: https://ntfy.sh/docs/publish/.
|
||||
|
||||
The default config file for all client commands is /etc/ntfy/client.yml (if root user),
|
||||
or ~/.config/ntfy/client.yml for all other users.`,
|
||||
}
|
||||
|
||||
func execPublish(c *cli.Context) error {
|
||||
if c.NArg() < 1 {
|
||||
return errors.New("must specify topic, type 'ntfy publish --help' for help")
|
||||
}
|
||||
conf, err := loadConfig(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
title := c.String("title")
|
||||
priority := c.String("priority")
|
||||
tags := c.String("tags")
|
||||
delay := c.String("delay")
|
||||
email := c.String("email")
|
||||
noCache := c.Bool("no-cache")
|
||||
noFirebase := c.Bool("no-firebase")
|
||||
quiet := c.Bool("quiet")
|
||||
topic := c.Args().Get(0)
|
||||
message := ""
|
||||
if c.NArg() > 1 {
|
||||
message = strings.Join(c.Args().Slice()[1:], " ")
|
||||
}
|
||||
var options []client.PublishOption
|
||||
if title != "" {
|
||||
options = append(options, client.WithTitle(title))
|
||||
}
|
||||
if priority != "" {
|
||||
options = append(options, client.WithPriority(priority))
|
||||
}
|
||||
if tags != "" {
|
||||
options = append(options, client.WithTagsList(tags))
|
||||
}
|
||||
if delay != "" {
|
||||
options = append(options, client.WithDelay(delay))
|
||||
}
|
||||
if email != "" {
|
||||
options = append(options, client.WithEmail(email))
|
||||
}
|
||||
if noCache {
|
||||
options = append(options, client.WithNoCache())
|
||||
}
|
||||
if noFirebase {
|
||||
options = append(options, client.WithNoFirebase())
|
||||
}
|
||||
cl := client.New(conf)
|
||||
m, err := cl.Publish(topic, message, options...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !quiet {
|
||||
fmt.Fprintln(c.App.Writer, strings.TrimSpace(m.Raw))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
36
cmd/publish_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/require"
|
||||
"heckel.io/ntfy/test"
|
||||
"heckel.io/ntfy/util"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCLI_Publish_Subscribe_Poll_Real_Server(t *testing.T) {
|
||||
testMessage := util.RandomString(10)
|
||||
|
||||
app, _, _, _ := newTestApp()
|
||||
require.Nil(t, app.Run([]string{"ntfy", "publish", "ntfytest", "ntfy unit test " + testMessage}))
|
||||
|
||||
app2, _, stdout, _ := newTestApp()
|
||||
require.Nil(t, app2.Run([]string{"ntfy", "subscribe", "--poll", "ntfytest"}))
|
||||
require.Contains(t, stdout.String(), testMessage)
|
||||
}
|
||||
|
||||
func TestCLI_Publish_Subscribe_Poll(t *testing.T) {
|
||||
s, port := test.StartServer(t)
|
||||
defer test.StopServer(t, s, port)
|
||||
topic := fmt.Sprintf("http://127.0.0.1:%d/mytopic", port)
|
||||
|
||||
app, _, stdout, _ := newTestApp()
|
||||
require.Nil(t, app.Run([]string{"ntfy", "publish", topic, "some message"}))
|
||||
m := toMessage(t, stdout.String())
|
||||
require.Equal(t, "some message", m.Message)
|
||||
|
||||
app2, _, stdout, _ := newTestApp()
|
||||
require.Nil(t, app2.Run([]string{"ntfy", "subscribe", "--poll", topic}))
|
||||
m = toMessage(t, stdout.String())
|
||||
require.Equal(t, "some message", m.Message)
|
||||
}
|
||||
145
cmd/serve.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
"github.com/urfave/cli/v2/altsrc"
|
||||
"heckel.io/ntfy/server"
|
||||
"heckel.io/ntfy/util"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
var flagsServe = []cli.Flag{
|
||||
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: "/etc/ntfy/server.yml", DefaultText: "/etc/ntfy/server.yml", Usage: "config file"},
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "base-url", Aliases: []string{"B"}, EnvVars: []string{"NTFY_BASE_URL"}, Usage: "externally visible base URL for this host (e.g. https://ntfy.sh)"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-http", Aliases: []string{"l"}, EnvVars: []string{"NTFY_LISTEN_HTTP"}, Value: server.DefaultListenHTTP, Usage: "ip:port used to as HTTP listen address"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "listen-https", Aliases: []string{"L"}, EnvVars: []string{"NTFY_LISTEN_HTTPS"}, Usage: "ip:port used to as HTTPS listen address"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "key-file", Aliases: []string{"K"}, EnvVars: []string{"NTFY_KEY_FILE"}, Usage: "private key file, if listen-https is set"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "cert-file", Aliases: []string{"E"}, EnvVars: []string{"NTFY_CERT_FILE"}, Usage: "certificate file, if listen-https is set"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "firebase-key-file", Aliases: []string{"F"}, EnvVars: []string{"NTFY_FIREBASE_KEY_FILE"}, Usage: "Firebase credentials file; if set additionally publish to FCM topic"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "cache-file", Aliases: []string{"C"}, EnvVars: []string{"NTFY_CACHE_FILE"}, Usage: "cache file used for message caching"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "cache-duration", Aliases: []string{"b"}, EnvVars: []string{"NTFY_CACHE_DURATION"}, Value: server.DefaultCacheDuration, Usage: "buffer messages for this time to allow `since` requests"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "keepalive-interval", Aliases: []string{"k"}, EnvVars: []string{"NTFY_KEEPALIVE_INTERVAL"}, Value: server.DefaultKeepaliveInterval, Usage: "interval of keepalive messages"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "manager-interval", Aliases: []string{"m"}, EnvVars: []string{"NTFY_MANAGER_INTERVAL"}, Value: server.DefaultManagerInterval, Usage: "interval of for message pruning and stats printing"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-addr", EnvVars: []string{"NTFY_SMTP_SENDER_ADDR"}, Usage: "SMTP server address (host:port) for outgoing emails"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-user", EnvVars: []string{"NTFY_SMTP_SENDER_USER"}, Usage: "SMTP user (if e-mail sending is enabled)"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-pass", EnvVars: []string{"NTFY_SMTP_SENDER_PASS"}, Usage: "SMTP password (if e-mail sending is enabled)"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-sender-from", EnvVars: []string{"NTFY_SMTP_SENDER_FROM"}, Usage: "SMTP sender address (if e-mail sending is enabled)"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-listen", EnvVars: []string{"NTFY_SMTP_SERVER_LISTEN"}, Usage: "SMTP server address (ip:port) for incoming emails, e.g. :25"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-domain", EnvVars: []string{"NTFY_SMTP_SERVER_DOMAIN"}, Usage: "SMTP domain for incoming e-mail, e.g. ntfy.sh"}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{Name: "smtp-server-addr-prefix", EnvVars: []string{"NTFY_SMTP_SERVER_ADDR_PREFIX"}, Usage: "SMTP email address prefix for topics to prevent spam (e.g. 'ntfy-')"}),
|
||||
altsrc.NewIntFlag(&cli.IntFlag{Name: "global-topic-limit", Aliases: []string{"T"}, EnvVars: []string{"NTFY_GLOBAL_TOPIC_LIMIT"}, Value: server.DefaultGlobalTopicLimit, Usage: "total number of topics allowed"}),
|
||||
altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-subscription-limit", EnvVars: []string{"NTFY_VISITOR_SUBSCRIPTION_LIMIT"}, Value: server.DefaultVisitorSubscriptionLimit, Usage: "number of subscriptions per visitor"}),
|
||||
altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-request-limit-burst", EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_BURST"}, Value: server.DefaultVisitorRequestLimitBurst, Usage: "initial limit of requests per visitor"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "visitor-request-limit-replenish", EnvVars: []string{"NTFY_VISITOR_REQUEST_LIMIT_REPLENISH"}, Value: server.DefaultVisitorRequestLimitReplenish, Usage: "interval at which burst limit is replenished (one per x)"}),
|
||||
altsrc.NewIntFlag(&cli.IntFlag{Name: "visitor-email-limit-burst", EnvVars: []string{"NTFY_VISITOR_EMAIL_LIMIT_BURST"}, Value: server.DefaultVisitorEmailLimitBurst, Usage: "initial limit of e-mails per visitor"}),
|
||||
altsrc.NewDurationFlag(&cli.DurationFlag{Name: "visitor-email-limit-replenish", EnvVars: []string{"NTFY_VISITOR_EMAIL_LIMIT_REPLENISH"}, Value: server.DefaultVisitorEmailLimitReplenish, Usage: "interval at which burst limit is replenished (one per x)"}),
|
||||
altsrc.NewBoolFlag(&cli.BoolFlag{Name: "behind-proxy", Aliases: []string{"P"}, EnvVars: []string{"NTFY_BEHIND_PROXY"}, Value: false, Usage: "if set, use X-Forwarded-For header to determine visitor IP address (for rate limiting)"}),
|
||||
}
|
||||
|
||||
var cmdServe = &cli.Command{
|
||||
Name: "serve",
|
||||
Usage: "Run the ntfy server",
|
||||
UsageText: "ntfy serve [OPTIONS..]",
|
||||
Action: execServe,
|
||||
Flags: flagsServe,
|
||||
Before: initConfigFileInputSource("config", flagsServe),
|
||||
Description: `Run the ntfy server and listen for incoming requests
|
||||
|
||||
The command will load the configuration from /etc/ntfy/server.yml. Config options can
|
||||
be overridden using the command line options.
|
||||
|
||||
Examples:
|
||||
ntfy serve # Starts server in the foreground (on port 80)
|
||||
ntfy serve --listen-http :8080 # Starts server with alternate port`,
|
||||
}
|
||||
|
||||
func execServe(c *cli.Context) error {
|
||||
if c.NArg() > 0 {
|
||||
return errors.New("no arguments expected, see 'ntfy serve --help' for help")
|
||||
}
|
||||
|
||||
// Read all the options
|
||||
baseURL := c.String("base-url")
|
||||
listenHTTP := c.String("listen-http")
|
||||
listenHTTPS := c.String("listen-https")
|
||||
keyFile := c.String("key-file")
|
||||
certFile := c.String("cert-file")
|
||||
firebaseKeyFile := c.String("firebase-key-file")
|
||||
cacheFile := c.String("cache-file")
|
||||
cacheDuration := c.Duration("cache-duration")
|
||||
keepaliveInterval := c.Duration("keepalive-interval")
|
||||
managerInterval := c.Duration("manager-interval")
|
||||
smtpSenderAddr := c.String("smtp-sender-addr")
|
||||
smtpSenderUser := c.String("smtp-sender-user")
|
||||
smtpSenderPass := c.String("smtp-sender-pass")
|
||||
smtpSenderFrom := c.String("smtp-sender-from")
|
||||
smtpServerListen := c.String("smtp-server-listen")
|
||||
smtpServerDomain := c.String("smtp-server-domain")
|
||||
smtpServerAddrPrefix := c.String("smtp-server-addr-prefix")
|
||||
globalTopicLimit := c.Int("global-topic-limit")
|
||||
visitorSubscriptionLimit := c.Int("visitor-subscription-limit")
|
||||
visitorRequestLimitBurst := c.Int("visitor-request-limit-burst")
|
||||
visitorRequestLimitReplenish := c.Duration("visitor-request-limit-replenish")
|
||||
visitorEmailLimitBurst := c.Int("visitor-email-limit-burst")
|
||||
visitorEmailLimitReplenish := c.Duration("visitor-email-limit-replenish")
|
||||
behindProxy := c.Bool("behind-proxy")
|
||||
|
||||
// Check values
|
||||
if firebaseKeyFile != "" && !util.FileExists(firebaseKeyFile) {
|
||||
return errors.New("if set, FCM key file must exist")
|
||||
} else if keepaliveInterval < 5*time.Second {
|
||||
return errors.New("keepalive interval cannot be lower than five seconds")
|
||||
} else if managerInterval < 5*time.Second {
|
||||
return errors.New("manager interval cannot be lower than five seconds")
|
||||
} else if cacheDuration > 0 && cacheDuration < managerInterval {
|
||||
return errors.New("cache duration cannot be lower than manager interval")
|
||||
} else if keyFile != "" && !util.FileExists(keyFile) {
|
||||
return errors.New("if set, key file must exist")
|
||||
} else if certFile != "" && !util.FileExists(certFile) {
|
||||
return errors.New("if set, certificate file must exist")
|
||||
} else if listenHTTPS != "" && (keyFile == "" || certFile == "") {
|
||||
return errors.New("if listen-https is set, both key-file and cert-file must be set")
|
||||
} else if smtpSenderAddr != "" && (baseURL == "" || smtpSenderUser == "" || smtpSenderPass == "" || smtpSenderFrom == "") {
|
||||
return errors.New("if smtp-sender-addr is set, base-url, smtp-sender-user, smtp-sender-pass and smtp-sender-from must also be set")
|
||||
} else if smtpServerListen != "" && smtpServerDomain == "" {
|
||||
return errors.New("if smtp-server-listen is set, smtp-server-domain must also be set")
|
||||
}
|
||||
|
||||
// Run server
|
||||
conf := server.NewConfig()
|
||||
conf.BaseURL = baseURL
|
||||
conf.ListenHTTP = listenHTTP
|
||||
conf.ListenHTTPS = listenHTTPS
|
||||
conf.KeyFile = keyFile
|
||||
conf.CertFile = certFile
|
||||
conf.FirebaseKeyFile = firebaseKeyFile
|
||||
conf.CacheFile = cacheFile
|
||||
conf.CacheDuration = cacheDuration
|
||||
conf.KeepaliveInterval = keepaliveInterval
|
||||
conf.ManagerInterval = managerInterval
|
||||
conf.SMTPSenderAddr = smtpSenderAddr
|
||||
conf.SMTPSenderUser = smtpSenderUser
|
||||
conf.SMTPSenderPass = smtpSenderPass
|
||||
conf.SMTPSenderFrom = smtpSenderFrom
|
||||
conf.SMTPServerListen = smtpServerListen
|
||||
conf.SMTPServerDomain = smtpServerDomain
|
||||
conf.SMTPServerAddrPrefix = smtpServerAddrPrefix
|
||||
conf.GlobalTopicLimit = globalTopicLimit
|
||||
conf.VisitorSubscriptionLimit = visitorSubscriptionLimit
|
||||
conf.VisitorRequestLimitBurst = visitorRequestLimitBurst
|
||||
conf.VisitorRequestLimitReplenish = visitorRequestLimitReplenish
|
||||
conf.VisitorEmailLimitBurst = visitorEmailLimitBurst
|
||||
conf.VisitorEmailLimitReplenish = visitorEmailLimitReplenish
|
||||
conf.BehindProxy = behindProxy
|
||||
s, err := server.New(conf)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := s.Run(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
log.Printf("Exiting.")
|
||||
return nil
|
||||
}
|
||||
237
cmd/subscribe.go
Normal file
@@ -0,0 +1,237 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/urfave/cli/v2"
|
||||
"heckel.io/ntfy/client"
|
||||
"heckel.io/ntfy/util"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var cmdSubscribe = &cli.Command{
|
||||
Name: "subscribe",
|
||||
Aliases: []string{"sub"},
|
||||
Usage: "Subscribe to one or more topics on a ntfy server",
|
||||
UsageText: "ntfy subscribe [OPTIONS..] [TOPIC]",
|
||||
Action: execSubscribe,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
|
||||
&cli.StringFlag{Name: "since", Aliases: []string{"s"}, Usage: "return events since `SINCE` (Unix timestamp, or all)"},
|
||||
&cli.BoolFlag{Name: "from-config", Aliases: []string{"C"}, Usage: "read subscriptions from config file (service mode)"},
|
||||
&cli.BoolFlag{Name: "poll", Aliases: []string{"p"}, Usage: "return events and exit, do not listen for new events"},
|
||||
&cli.BoolFlag{Name: "scheduled", Aliases: []string{"sched", "S"}, Usage: "also return scheduled/delayed events"},
|
||||
&cli.BoolFlag{Name: "verbose", Aliases: []string{"v"}, Usage: "print verbose output"},
|
||||
},
|
||||
Description: `Subscribe to a topic from a ntfy server, and either print or execute a command for
|
||||
every arriving message. There are 3 modes in which the command can be run:
|
||||
|
||||
ntfy subscribe TOPIC
|
||||
This prints the JSON representation of every incoming message. It is useful when you
|
||||
have a command that wants to stream-read incoming JSON messages. Unless --poll is passed,
|
||||
this command stays open forever.
|
||||
|
||||
Examples:
|
||||
ntfy subscribe mytopic # Prints JSON for incoming messages for ntfy.sh/mytopic
|
||||
ntfy sub home.lan/backups # Subscribe to topic on different server
|
||||
ntfy sub --poll home.lan/backups # Just query for latest messages and exit
|
||||
|
||||
ntfy subscribe TOPIC COMMAND
|
||||
This executes COMMAND for every incoming messages. The message fields are passed to the
|
||||
command as environment variables:
|
||||
|
||||
Variable Aliases Description
|
||||
--------------- --------------------- -----------------------------------
|
||||
$NTFY_ID $id Unique message ID
|
||||
$NTFY_TIME $time Unix timestamp of the message delivery
|
||||
$NTFY_TOPIC $topic Topic name
|
||||
$NTFY_MESSAGE $message, $m Message body
|
||||
$NTFY_TITLE $title, $t Message title
|
||||
$NTFY_PRIORITY $priority, $prio, $p Message priority (1=min, 5=max)
|
||||
$NTFY_TAGS $tags, $tag, $ta Message tags (comma separated list)
|
||||
$NTFY_RAW $raw Raw JSON message
|
||||
|
||||
Examples:
|
||||
ntfy sub mytopic 'notify-send "$m"' # Execute command for incoming messages
|
||||
ntfy sub topic1 /my/script.sh # Execute script for incoming messages
|
||||
|
||||
ntfy subscribe --from-config
|
||||
Service mode (used in ntfy-client.service). This reads the config file (/etc/ntfy/client.yml
|
||||
or ~/.config/ntfy/client.yml) and sets up subscriptions for every topic in the "subscribe:"
|
||||
block (see config file).
|
||||
|
||||
Examples:
|
||||
ntfy sub --from-config # Read topics from config file
|
||||
ntfy sub --config=/my/client.yml --from-config # Read topics from alternate config file
|
||||
|
||||
The default config file for all client commands is /etc/ntfy/client.yml (if root user),
|
||||
or ~/.config/ntfy/client.yml for all other users.`,
|
||||
}
|
||||
|
||||
func execSubscribe(c *cli.Context) error {
|
||||
// Read config and options
|
||||
conf, err := loadConfig(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cl := client.New(conf)
|
||||
since := c.String("since")
|
||||
poll := c.Bool("poll")
|
||||
scheduled := c.Bool("scheduled")
|
||||
fromConfig := c.Bool("from-config")
|
||||
topic := c.Args().Get(0)
|
||||
command := c.Args().Get(1)
|
||||
if !fromConfig {
|
||||
conf.Subscribe = nil // wipe if --from-config not passed
|
||||
}
|
||||
var options []client.SubscribeOption
|
||||
if since != "" {
|
||||
options = append(options, client.WithSince(since))
|
||||
}
|
||||
if poll {
|
||||
options = append(options, client.WithPoll())
|
||||
}
|
||||
if scheduled {
|
||||
options = append(options, client.WithScheduled())
|
||||
}
|
||||
if topic == "" && len(conf.Subscribe) == 0 {
|
||||
return errors.New("must specify topic, type 'ntfy subscribe --help' for help")
|
||||
}
|
||||
|
||||
// Execute poll or subscribe
|
||||
if poll {
|
||||
return doPoll(c, cl, conf, topic, command, options...)
|
||||
}
|
||||
return doSubscribe(c, cl, conf, topic, command, options...)
|
||||
}
|
||||
|
||||
func doPoll(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
|
||||
for _, s := range conf.Subscribe { // may be nil
|
||||
if err := doPollSingle(c, cl, s.Topic, s.Command, options...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if topic != "" {
|
||||
if err := doPollSingle(c, cl, topic, command, options...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func doPollSingle(c *cli.Context, cl *client.Client, topic, command string, options ...client.SubscribeOption) error {
|
||||
messages, err := cl.Poll(topic, options...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range messages {
|
||||
printMessageOrRunCommand(c, m, command)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func doSubscribe(c *cli.Context, cl *client.Client, conf *client.Config, topic, command string, options ...client.SubscribeOption) error {
|
||||
commands := make(map[string]string) // Subscription ID -> command
|
||||
for _, s := range conf.Subscribe { // May be nil
|
||||
topicOptions := append(make([]client.SubscribeOption, 0), options...)
|
||||
for filter, value := range s.If {
|
||||
topicOptions = append(topicOptions, client.WithFilter(filter, value))
|
||||
}
|
||||
subscriptionID := cl.Subscribe(s.Topic, topicOptions...)
|
||||
commands[subscriptionID] = s.Command
|
||||
}
|
||||
if topic != "" {
|
||||
subscriptionID := cl.Subscribe(topic, options...)
|
||||
commands[subscriptionID] = command
|
||||
}
|
||||
for m := range cl.Messages {
|
||||
command, ok := commands[m.SubscriptionID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
printMessageOrRunCommand(c, m, command)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printMessageOrRunCommand(c *cli.Context, m *client.Message, command string) {
|
||||
if command != "" {
|
||||
runCommand(c, command, m)
|
||||
} else {
|
||||
fmt.Fprintln(c.App.Writer, m.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
func runCommand(c *cli.Context, command string, m *client.Message) {
|
||||
if err := runCommandInternal(c, command, m); err != nil {
|
||||
fmt.Fprintf(c.App.ErrWriter, "Command failed: %s\n", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func runCommandInternal(c *cli.Context, command string, m *client.Message) error {
|
||||
scriptFile, err := createTmpScript(command)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(scriptFile)
|
||||
verbose := c.Bool("verbose")
|
||||
if verbose {
|
||||
log.Printf("[%s] Executing: %s (for message: %s)", util.ShortTopicURL(m.TopicURL), command, m.Raw)
|
||||
}
|
||||
cmd := exec.Command("sh", "-c", scriptFile)
|
||||
cmd.Stdin = c.App.Reader
|
||||
cmd.Stdout = c.App.Writer
|
||||
cmd.Stderr = c.App.ErrWriter
|
||||
cmd.Env = envVars(m)
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func createTmpScript(command string) (string, error) {
|
||||
scriptFile := fmt.Sprintf("%s/ntfy-subscribe-%s.sh.tmp", os.TempDir(), util.RandomString(10))
|
||||
script := fmt.Sprintf("#!/bin/sh\n%s", command)
|
||||
if err := os.WriteFile(scriptFile, []byte(script), 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return scriptFile, nil
|
||||
}
|
||||
|
||||
func envVars(m *client.Message) []string {
|
||||
env := os.Environ()
|
||||
env = append(env, envVar(m.ID, "NTFY_ID", "id")...)
|
||||
env = append(env, envVar(m.Topic, "NTFY_TOPIC", "topic")...)
|
||||
env = append(env, envVar(fmt.Sprintf("%d", m.Time), "NTFY_TIME", "time")...)
|
||||
env = append(env, envVar(m.Message, "NTFY_MESSAGE", "message", "m")...)
|
||||
env = append(env, envVar(m.Title, "NTFY_TITLE", "title", "t")...)
|
||||
env = append(env, envVar(fmt.Sprintf("%d", m.Priority), "NTFY_PRIORITY", "priority", "prio", "p")...)
|
||||
env = append(env, envVar(strings.Join(m.Tags, ","), "NTFY_TAGS", "tags", "tag", "ta")...)
|
||||
env = append(env, envVar(m.Raw, "NTFY_RAW", "raw")...)
|
||||
return env
|
||||
}
|
||||
|
||||
func envVar(value string, vars ...string) []string {
|
||||
env := make([]string, 0)
|
||||
for _, v := range vars {
|
||||
env = append(env, fmt.Sprintf("%s=%s", v, value))
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func loadConfig(c *cli.Context) (*client.Config, error) {
|
||||
filename := c.String("config")
|
||||
if filename != "" {
|
||||
return client.LoadConfig(filename)
|
||||
}
|
||||
u, _ := user.Current()
|
||||
configFile := defaultClientRootConfigFile
|
||||
if u.Uid != "0" {
|
||||
configFile = util.ExpandHome(defaultClientUserConfigFile)
|
||||
}
|
||||
if s, _ := os.Stat(configFile); s != nil {
|
||||
return client.LoadConfig(configFile)
|
||||
}
|
||||
return client.NewConfig(), nil
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
// Package config provides the main configuration
|
||||
package config
|
||||
|
||||
import (
|
||||
"golang.org/x/time/rate"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Defines default config settings
|
||||
const (
|
||||
DefaultListenHTTP = ":80"
|
||||
DefaultCacheDuration = 12 * time.Hour
|
||||
DefaultKeepaliveInterval = 30 * time.Second
|
||||
DefaultManagerInterval = time.Minute
|
||||
)
|
||||
|
||||
// Defines all the limits
|
||||
// - request limit: max number of PUT/GET/.. requests (here: 50 requests bucket, replenished at a rate of one per 10 seconds)
|
||||
// - global topic limit: max number of topics overall
|
||||
// - subscription limit: max number of subscriptions (active HTTP connections) per per-visitor/IP
|
||||
var (
|
||||
defaultGlobalTopicLimit = 5000
|
||||
defaultVisitorRequestLimit = rate.Every(10 * time.Second)
|
||||
defaultVisitorRequestLimitBurst = 50
|
||||
defaultVisitorSubscriptionLimit = 30
|
||||
)
|
||||
|
||||
// Config is the main config struct for the application. Use New to instantiate a default config struct.
|
||||
type Config struct {
|
||||
ListenHTTP string
|
||||
FirebaseKeyFile string
|
||||
CacheFile string
|
||||
CacheDuration time.Duration
|
||||
KeepaliveInterval time.Duration
|
||||
ManagerInterval time.Duration
|
||||
GlobalTopicLimit int
|
||||
VisitorRequestLimit rate.Limit
|
||||
VisitorRequestLimitBurst int
|
||||
VisitorSubscriptionLimit int
|
||||
}
|
||||
|
||||
// New instantiates a default new config
|
||||
func New(listenHTTP string) *Config {
|
||||
return &Config{
|
||||
ListenHTTP: listenHTTP,
|
||||
FirebaseKeyFile: "",
|
||||
CacheFile: "",
|
||||
CacheDuration: DefaultCacheDuration,
|
||||
KeepaliveInterval: DefaultKeepaliveInterval,
|
||||
ManagerInterval: DefaultManagerInterval,
|
||||
GlobalTopicLimit: defaultGlobalTopicLimit,
|
||||
VisitorRequestLimit: defaultVisitorRequestLimit,
|
||||
VisitorRequestLimitBurst: defaultVisitorRequestLimitBurst,
|
||||
VisitorSubscriptionLimit: defaultVisitorSubscriptionLimit,
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
# ntfy config file
|
||||
|
||||
# Listen address for the HTTP web server
|
||||
# Format: <hostname>:<port>
|
||||
#
|
||||
# listen-http: ":80"
|
||||
|
||||
# If set, also publish messages to a Firebase Cloud Messaging (FCM) topic for your app.
|
||||
# This is optional and only required to support Android apps (which don't allow background services anymore).
|
||||
#
|
||||
# firebase-key-file: <filename>
|
||||
|
||||
# If set, messages are cached in a local SQLite database instead of only in-memory. This
|
||||
# allows for service restarts without losing messages in support of the since= parameter.
|
||||
#
|
||||
# cache-file: <filename>
|
||||
|
||||
# Duration for which messages will be buffered before they are deleted.
|
||||
# This is required to support the "since=..." and "poll=1" parameter.
|
||||
#
|
||||
# cache-duration: 12h
|
||||
|
||||
# Interval in which keepalive messages are sent to the client. This is to prevent
|
||||
# intermediaries closing the connection for inactivity.
|
||||
#
|
||||
# keepalive-interval: 30s
|
||||
|
||||
# Interval in which the manager prunes old messages, deletes topics and prints the stats.
|
||||
#
|
||||
# manager-interval: 1m
|
||||
435
docs/config.md
Normal file
@@ -0,0 +1,435 @@
|
||||
# Configuring the ntfy server
|
||||
The ntfy server can be configured in three ways: using a config file (typically at `/etc/ntfy/server.yml`,
|
||||
see [server.yml](https://github.com/binwiederhier/ntfy/blob/main/config/server.yml)), via command line arguments
|
||||
or using environment variables.
|
||||
|
||||
## Quick start
|
||||
By default, simply running `ntfy serve` will start the server at port 80. No configuration needed. Batteries included 😀.
|
||||
If everything works as it should, you'll see something like this:
|
||||
```
|
||||
$ ntfy serve
|
||||
2021/11/30 19:59:08 Listening on :80
|
||||
```
|
||||
|
||||
You can immediately start [publishing messages](publish.md), or subscribe via the [Android app](subscribe/phone.md),
|
||||
[the web UI](subscribe/web.md), or simply via [curl or your favorite HTTP client](subscribe/api.md). To configure
|
||||
the server further, check out the [config options table](#config-options) or simply type `ntfy --help` to
|
||||
get a list of [command line options](#command-line-options).
|
||||
|
||||
## Message cache
|
||||
If desired, ntfy can temporarily keep notifications in an in-memory or an on-disk cache. Caching messages for a short period
|
||||
of time is important to allow [phones](subscribe/phone.md) and other devices with brittle Internet connections to be able to retrieve
|
||||
notifications that they may have missed.
|
||||
|
||||
By default, ntfy keeps messages **in-memory for 12 hours**, which means that **cached messages do not survive an application
|
||||
restart**. You can override this behavior using the following config settings:
|
||||
|
||||
* `cache-file`: if set, ntfy will store messages in a SQLite based cache (default is empty, which means in-memory cache).
|
||||
**This is required if you'd like messages to be retained across restarts**.
|
||||
* `cache-duration`: defines the duration for which messages are stored in the cache (default is `12h`).
|
||||
|
||||
You can also entirely disable the cache by setting `cache-duration` to `0`. When the cache is disabled, messages are only
|
||||
passed on to the connected subscribers, but never stored on disk or even kept in memory longer than is needed to forward
|
||||
the message to the subscribers.
|
||||
|
||||
Subscribers can retrieve cached messaging using the [`poll=1` parameter](subscribe/api.md#poll-for-messages), as well as the
|
||||
[`since=` parameter](subscribe/api.md#fetch-cached-messages).
|
||||
|
||||
## E-mail notifications
|
||||
To allow forwarding messages via e-mail, you can configure an **SMTP server for outgoing messages**. Once configured,
|
||||
you can set the `X-Email` header to [send messages via e-mail](publish.md#e-mail-notifications) (e.g.
|
||||
`curl -d "hi there" -H "X-Email: phil@example.com" ntfy.sh/mytopic`).
|
||||
|
||||
As of today, only SMTP servers with PLAIN auth and STARTLS are supported. To enable e-mail sending, you must set the
|
||||
following settings:
|
||||
|
||||
* `base-url` is the root URL for the ntfy server; this is needed for e-mail footer
|
||||
* `smtp-sender-addr` is the hostname:port of the SMTP server
|
||||
* `smtp-sender-user` and `smtp-sender-pass` are the username and password of the SMTP user
|
||||
* `smtp-sender-from` is the e-mail address of the sender
|
||||
|
||||
Here's an example config using [Amazon SES](https://aws.amazon.com/ses/) for outgoing mail (this is how it is
|
||||
configured for `ntfy.sh`):
|
||||
|
||||
=== "/etc/ntfy/server.yml"
|
||||
``` yaml
|
||||
base-url: "https://ntfy.sh"
|
||||
smtp-sender-addr: "email-smtp.us-east-2.amazonaws.com:587"
|
||||
smtp-sender-user: "AKIDEADBEEFAFFE12345"
|
||||
smtp-sender-pass: "Abd13Kf+sfAk2DzifjafldkThisIsNotARealKeyOMG."
|
||||
smtp-sender-from: "ntfy@ntfy.sh"
|
||||
```
|
||||
|
||||
Please also refer to the [rate limiting](#rate-limiting) settings below, specifically `visitor-email-limit-burst`
|
||||
and `visitor-email-limit-burst`. Setting these conservatively is necessary to avoid abuse.
|
||||
|
||||
## E-mail publishing
|
||||
To allow publishing messages via e-mail, ntfy can run a lightweight **SMTP server for incoming messages**. Once configured,
|
||||
users can [send emails to a topic e-mail address](publish.md#e-mail-publishing) (e.g. `mytopic@ntfy.sh` or
|
||||
`myprefix-mytopic@ntfy.sh`) to publish messages to a topic. This is useful for e-mail based integrations such as for
|
||||
statuspage.io (though these days most services also support webhooks and HTTP calls).
|
||||
|
||||
To configure the SMTP server, you must at least set `smtp-server-listen` and `smtp-server-domain`:
|
||||
|
||||
* `smtp-server-listen` defines the IP address and port the SMTP server will listen on, e.g. `:25` or `1.2.3.4:25`
|
||||
* `smtp-server-domain` is the e-mail domain, e.g. `ntfy.sh`
|
||||
* `smtp-server-addr-prefix` is an optional prefix for the e-mail addresses to prevent spam. If set to `ntfy-`, for instance,
|
||||
only e-mails to `ntfy-$topic@ntfy.sh` will be accepted. If this is not set, all emails to `$topic@ntfy.sh` will be
|
||||
accepted (which may obviously be a spam problem).
|
||||
|
||||
Here's an example config (this is how it is configured for `ntfy.sh`):
|
||||
|
||||
=== "/etc/ntfy/server.yml"
|
||||
``` yaml
|
||||
smtp-server-listen: ":25"
|
||||
smtp-server-domain: "ntfy.sh"
|
||||
smtp-server-addr-prefix: "ntfy-"
|
||||
```
|
||||
|
||||
In addition to configuring the ntfy server, you have to create two DNS records (an [MX record](https://en.wikipedia.org/wiki/MX_record)
|
||||
and a corresponding A record), so incoming mail will find its way to your server. Here's an example of how `ntfy.sh` is
|
||||
configured (in [Amazon Route 53](https://aws.amazon.com/route53/)):
|
||||
|
||||
<figure markdown>
|
||||
{ width=600 }
|
||||
<figcaption>DNS records for incoming mail</figcaption>
|
||||
</figure>
|
||||
|
||||
## Behind a proxy (TLS, etc.)
|
||||
!!! warning
|
||||
If you are running ntfy behind a proxy, you must set the `behind-proxy` flag. Otherwise, all visitors are
|
||||
[rate limited](#rate-limiting) as if they are one.
|
||||
|
||||
It may be desirable to run ntfy behind a proxy (e.g. nginx, HAproxy or Apache), so you can provide TLS certificates
|
||||
using Let's Encrypt using certbot, or simply because you'd like to share the ports (80/443) with other services.
|
||||
Whatever your reasons may be, there are a few things to consider.
|
||||
|
||||
If you are running ntfy behind a proxy, you should set the `behind-proxy` flag. This will instruct the
|
||||
[rate limiting](#rate-limiting) logic to use the `X-Forwarded-For` header as the primary identifier for a visitor,
|
||||
as opposed to the remote IP address. If the `behind-proxy` flag is not set, all visitors will
|
||||
be counted as one, because from the perspective of the ntfy server, they all share the proxy's IP address.
|
||||
|
||||
=== "/etc/ntfy/server.yml"
|
||||
``` yaml
|
||||
# Tell ntfy to use "X-Forwarded-For" to identify visitors
|
||||
behind-proxy: true
|
||||
```
|
||||
|
||||
### TLS/SSL
|
||||
ntfy supports HTTPS/TLS by setting the `listen-https` [config option](#config-options). However, if you
|
||||
are behind a proxy, it is recommended that TLS/SSL termination is done by the proxy itself (see below).
|
||||
|
||||
I highly recommend using [certbot](https://certbot.eff.org/). I use it with the [dns-route53 plugin](https://certbot-dns-route53.readthedocs.io/en/stable/),
|
||||
which lets you use [AWS Route 53](https://aws.amazon.com/route53/) as the challenge. That's much easier than using the
|
||||
HTTP challenge. I've found [this guide](https://nandovieira.com/using-lets-encrypt-in-development-with-nginx-and-aws-route53) to
|
||||
be incredibly helpful.
|
||||
|
||||
### nginx/Apache2
|
||||
For your convenience, here's a working config that'll help configure things behind a proxy. In this
|
||||
example, ntfy runs on `:2586` and we proxy traffic to it. We also redirect HTTP to HTTPS for GET requests against a topic
|
||||
or the root domain:
|
||||
|
||||
=== "nginx (/etc/nginx/sites-*/ntfy)"
|
||||
```
|
||||
server {
|
||||
listen 80;
|
||||
server_name ntfy.sh;
|
||||
|
||||
location / {
|
||||
# Redirect HTTP to HTTPS, but only for GET topic addresses, since we want
|
||||
# it to work with curl without the annoying https:// prefix
|
||||
set $redirect_https "";
|
||||
if ($request_method = GET) {
|
||||
set $redirect_https "yes";
|
||||
}
|
||||
if ($request_uri ~* "^/[-_a-z0-9]{0,64}$") {
|
||||
set $redirect_https "${redirect_https}yes";
|
||||
}
|
||||
if ($redirect_https = "yesyes") {
|
||||
return 302 https://$http_host$request_uri$is_args$query_string;
|
||||
}
|
||||
|
||||
proxy_pass http://127.0.0.1:2586;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_redirect off;
|
||||
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_connect_timeout 1m;
|
||||
proxy_send_timeout 1m;
|
||||
proxy_read_timeout 1m;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name ntfy.sh;
|
||||
|
||||
ssl_session_cache builtin:1000 shared:SSL:10m;
|
||||
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
|
||||
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/ntfy.sh/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/ntfy.sh/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:2586;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_buffering off;
|
||||
proxy_redirect off;
|
||||
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_connect_timeout 1m;
|
||||
proxy_send_timeout 1m;
|
||||
proxy_read_timeout 1m;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Apache2 (/etc/apache2/sites-*/ntfy.conf)"
|
||||
```
|
||||
<VirtualHost *:80>
|
||||
ServerName ntfy.sh
|
||||
|
||||
SetEnv proxy-nokeepalive 1
|
||||
SetEnv proxy-sendchunked 1
|
||||
|
||||
ProxyPass / http://127.0.0.1:2586/
|
||||
ProxyPassReverse / http://127.0.0.1:2586/
|
||||
|
||||
# Higher than the max message size of 512k
|
||||
LimitRequestBody 102400
|
||||
|
||||
# Redirect HTTP to HTTPS, but only for GET topic addresses, since we want
|
||||
# it to work with curl without the annoying https:// prefix
|
||||
RewriteEngine on
|
||||
RewriteCond %{REQUEST_METHOD} GET
|
||||
RewriteRule ^/([-_A-Za-z0-9]{0,64})$ https://%{SERVER_NAME}/$1 [R,L]
|
||||
</VirtualHost>
|
||||
|
||||
<VirtualHost *:443>
|
||||
ServerName ntfy.sh
|
||||
|
||||
SSLEngine on
|
||||
SSLCertificateFile /etc/letsencrypt/live/ntfy.sh/fullchain.pem
|
||||
SSLCertificateKeyFile /etc/letsencrypt/live/ntfy.sh/privkey.pem
|
||||
Include /etc/letsencrypt/options-ssl-apache.conf
|
||||
|
||||
SetEnv proxy-nokeepalive 1
|
||||
SetEnv proxy-sendchunked 1
|
||||
|
||||
ProxyPass / http://127.0.0.1:2586/
|
||||
ProxyPassReverse / http://127.0.0.1:2586/
|
||||
|
||||
# Higher than the max message size of 512k
|
||||
LimitRequestBody 102400
|
||||
|
||||
# Redirect HTTP to HTTPS, but only for GET topic addresses, since we want
|
||||
# it to work with curl without the annoying https:// prefix
|
||||
RewriteEngine on
|
||||
RewriteCond %{REQUEST_METHOD} GET
|
||||
RewriteRule ^/([-_A-Za-z0-9]{0,64})$ https://%{SERVER_NAME}/$1 [R,L]
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
## Firebase (FCM)
|
||||
!!! info
|
||||
Using Firebase is **optional** and only works if you modify and [build your own Android .apk](develop.md#android-app).
|
||||
For a self-hosted instance, it's easier to just not bother with FCM.
|
||||
|
||||
[Firebase Cloud Messaging (FCM)](https://firebase.google.com/docs/cloud-messaging) is the Google approved way to send
|
||||
push messages to Android devices. FCM is the only method that an Android app can receive messages without having to run a
|
||||
[foreground service](https://developer.android.com/guide/components/foreground-services).
|
||||
|
||||
For the main host [ntfy.sh](https://ntfy.sh), the [ntfy Android app](subscribe/phone.md) uses Firebase to send messages
|
||||
to the device. For other hosts, instant delivery is used and FCM is not involved.
|
||||
|
||||
To configure FCM for your self-hosted instance of the ntfy server, follow these steps:
|
||||
|
||||
1. Sign up for a [Firebase account](https://console.firebase.google.com/)
|
||||
2. Create a Firebase app and download the key file (e.g. `myapp-firebase-adminsdk-...json`)
|
||||
3. Place the key file in `/etc/ntfy`, set the `firebase-key-file` in `server.yml` accordingly and restart the ntfy server
|
||||
4. Build your own Android .apk following [these instructions](develop.md#android-app)
|
||||
|
||||
Example:
|
||||
```
|
||||
# If set, also publish messages to a Firebase Cloud Messaging (FCM) topic for your app.
|
||||
# This is optional and only required to support Android apps (which don't allow background services anymore).
|
||||
#
|
||||
firebase-key-file: "/etc/ntfy/ntfy-sh-firebase-adminsdk-ahnce-9f4d6f14b5.json"
|
||||
```
|
||||
|
||||
## Rate limiting
|
||||
!!! info
|
||||
Be aware that if you are running ntfy behind a proxy, you must set the `behind-proxy` flag.
|
||||
Otherwise, all visitors are rate limited as if they are one.
|
||||
|
||||
By default, ntfy runs without authentication, so it is vitally important that we protect the server from abuse or overload.
|
||||
There are various limits and rate limits in place that you can use to configure the server. Let's do the easy ones first:
|
||||
|
||||
* `global-topic-limit` defines the total number of topics before the server rejects new topics. It defaults to 5000.
|
||||
* `visitor-subscription-limit` is the number of subscriptions (open connections) per visitor. This value defaults to 30.
|
||||
|
||||
A **visitor** is identified by its IP address (or the `X-Forwarded-For` header if `behind-proxy` is set). All config
|
||||
options that start with the word `visitor` apply only on a per-visitor basis.
|
||||
|
||||
In addition to the limits above, there is a requests/second limit per visitor for all sensitive GET/PUT/POST requests.
|
||||
This limit uses a [token bucket](https://en.wikipedia.org/wiki/Token_bucket) (using Go's [rate package](https://pkg.go.dev/golang.org/x/time/rate)):
|
||||
|
||||
Each visitor has a bucket of 60 requests they can fire against the server (defined by `visitor-request-limit-burst`).
|
||||
After the 60, new requests will encounter a `429 Too Many Requests` response. The visitor request bucket is refilled at a rate of one
|
||||
request every 10s (defined by `visitor-request-limit-replenish`)
|
||||
|
||||
* `visitor-request-limit-burst` is the initial bucket of requests each visitor has. This defaults to 60.
|
||||
* `visitor-request-limit-replenish` is the rate at which the bucket is refilled (one request per x). Defaults to 10s.
|
||||
|
||||
Similarly to the request limit, there is also an e-mail limit (only relevant if [e-mail notifications](#e-mail-notifications)
|
||||
are enabled):
|
||||
|
||||
* `visitor-email-limit-burst` is the initial bucket of emails each visitor has. This defaults to 16.
|
||||
* `visitor-email-limit-replenish` is the rate at which the bucket is refilled (one email per x). Defaults to 1h.
|
||||
|
||||
During normal usage, you shouldn't encounter these limits at all, and even if you burst a few requests or emails
|
||||
(e.g. when you reconnect after a connection drop), it shouldn't have any effect.
|
||||
|
||||
## Tuning for scale
|
||||
If you're running ntfy for your home server, you probably don't need to worry about scale at all. In its default config,
|
||||
if it's not behind a proxy, the ntfy server can keep about **as many connections as the open file limit allows**.
|
||||
This limit is typically called `nofile`. Other than that, RAM and CPU are obviously relevant. You may also want to check
|
||||
out [this discussion on Reddit](https://www.reddit.com/r/golang/comments/r9u4ee/how_many_actively_connected_http_clients_can_a_go/).
|
||||
|
||||
Depending on *how you run it*, here are a few limits that are relevant:
|
||||
|
||||
### For systemd services
|
||||
If you're running ntfy in a systemd service (e.g. for .deb/.rpm packages), the main limiting factor is the
|
||||
`LimitNOFILE` setting in the systemd unit. The default open files limit for `ntfy.service` is 10000. You can override it
|
||||
by creating a `/etc/systemd/system/ntfy.service.d/override.conf` file. As far as I can tell, `/etc/security/limits.conf`
|
||||
is not relevant.
|
||||
|
||||
=== "/etc/systemd/system/ntfy.service.d/override.conf"
|
||||
```
|
||||
# Allow 20,000 ntfy connections (and give room for other file handles)
|
||||
[Service]
|
||||
LimitNOFILE=20500
|
||||
```
|
||||
|
||||
### Outside of systemd
|
||||
If you're running outside systemd, you may want to adjust your `/etc/security/limits.conf` file to
|
||||
increase the `nofile` setting. Here's an example that increases the limit to 5000. You can find out the current setting
|
||||
by running `ulimit -n`, or manually override it temporarily by running `ulimit -n 50000`.
|
||||
|
||||
=== "/etc/security/limits.conf"
|
||||
```
|
||||
# Increase open files limit globally
|
||||
* hard nofile 20500
|
||||
```
|
||||
|
||||
### Proxy limits (nginx, Apache2)
|
||||
If you are running [behind a proxy](#behind-a-proxy-tls-etc) (e.g. nginx, Apache), the open files limit of the proxy is also
|
||||
relevant. So if your proxy runs inside of systemd, increase the limits in systemd for the proxy. Typically, the proxy
|
||||
open files limit has to be **double the number of how many connections you'd like to support**, because the proxy has
|
||||
to maintain the client connection and the connection to ntfy.
|
||||
|
||||
=== "/etc/nginx/nginx.conf"
|
||||
```
|
||||
events {
|
||||
# Allow 40,000 proxy connections (2x of the desired ntfy connection count;
|
||||
# and give room for other file handles)
|
||||
worker_connections 40500;
|
||||
}
|
||||
```
|
||||
=== "/etc/systemd/system/nginx.service.d/override.conf"
|
||||
```
|
||||
# Allow 40,000 proxy connections (2x of the desired ntfy connection count;
|
||||
# and give room for other file handles)
|
||||
[Service]
|
||||
LimitNOFILE=40500
|
||||
```
|
||||
|
||||
## Config options
|
||||
Each config option can be set in the config file `/etc/ntfy/server.yml` (e.g. `listen-http: :80`) or as a
|
||||
CLI option (e.g. `--listen-http :80`. Here's a list of all available options. Alternatively, you can set an environment
|
||||
variable before running the `ntfy` command (e.g. `export NTFY_LISTEN_HTTP=:80`).
|
||||
|
||||
| Config option | Env variable | Format | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `base-url` | `NTFY_BASE_URL` | *URL* | - | Public facing base URL of the service (e.g. `https://ntfy.sh`) |
|
||||
| `listen-http` | `NTFY_LISTEN_HTTP` | `[host]:port` | `:80` | Listen address for the HTTP web server |
|
||||
| `listen-https` | `NTFY_LISTEN_HTTPS` | `[host]:port` | - | Listen address for the HTTPS web server. If set, you also need to set `key-file` and `cert-file`. |
|
||||
| `key-file` | `NTFY_KEY_FILE` | *filename* | - | HTTPS/TLS private key file, only used if `listen-https` is set. |
|
||||
| `cert-file` | `NTFY_CERT_FILE` | *filename* | - | HTTPS/TLS certificate file, only used if `listen-https` is set. |
|
||||
| `firebase-key-file` | `NTFY_FIREBASE_KEY_FILE` | *filename* | - | If set, also publish messages to a Firebase Cloud Messaging (FCM) topic for your app. This is optional and only required to save battery when using the Android app. See [Firebase (FCM](#firebase-fcm). |
|
||||
| `cache-file` | `NTFY_CACHE_FILE` | *filename* | - | If set, messages are cached in a local SQLite database instead of only in-memory. This allows for service restarts without losing messages in support of the since= parameter. See [message cache](#message-cache). |
|
||||
| `cache-duration` | `NTFY_CACHE_DURATION` | *duration* | 12h | Duration for which messages will be buffered before they are deleted. This is required to support the `since=...` and `poll=1` parameter. Set this to `0` to disable the cache entirely. |
|
||||
| `behind-proxy` | `NTFY_BEHIND_PROXY` | *bool* | false | If set, the X-Forwarded-For header is used to determine the visitor IP address instead of the remote address of the connection. |
|
||||
| `smtp-addr` | `NTFY_SMTP_ADDR` | `host:port` | - | SMTP server address to allow email sending |
|
||||
| `smtp-user` | `NTFY_SMTP_USER` | *string* | - | SMTP user; only used if e-mail sending is enabled |
|
||||
| `smtp-pass` | `NTFY_SMTP_PASS` | *string* | - | SMTP password; only used if e-mail sending is enabled |
|
||||
| `smtp-from` | `NTFY_SMTP_FROM` | *e-mail address* | - | SMTP sender e-mail address; only used if e-mail sending is enabled |
|
||||
| `keepalive-interval` | `NTFY_KEEPALIVE_INTERVAL` | *duration* | 30s | Interval in which keepalive messages are sent to the client. This is to prevent intermediaries closing the connection for inactivity. Note that the Android app has a hardcoded timeout at 77s, so it should be less than that. |
|
||||
| `manager-interval` | `$NTFY_MANAGER_INTERVAL` | *duration* | 1m | Interval in which the manager prunes old messages, deletes topics and prints the stats. |
|
||||
| `global-topic-limit` | `NTFY_GLOBAL_TOPIC_LIMIT` | *number* | 5000 | Rate limiting: Total number of topics before the server rejects new topics. |
|
||||
| `visitor-subscription-limit` | `NTFY_VISITOR_SUBSCRIPTION_LIMIT` | *number* | 30 | Rate limiting: Number of subscriptions per visitor (IP address) |
|
||||
| `visitor-request-limit-burst` | `NTFY_VISITOR_REQUEST_LIMIT_BURST` | *number* | 60 | Allowed GET/PUT/POST requests per second, per visitor. This setting is the initial bucket of requests each visitor has |
|
||||
| `visitor-request-limit-replenish` | `NTFY_VISITOR_REQUEST_LIMIT_REPLENISH` | *duration* | 10s | Strongly related to `visitor-request-limit-burst`: The rate at which the bucket is refilled |
|
||||
| `visitor-email-limit-burst` | `NTFY_VISITOR_EMAIL_LIMIT_BURST` | *number* | 16 |Initial limit of e-mails per visitor |
|
||||
| `visitor-email-limit-replenish` | `NTFY_VISITOR_EMAIL_LIMIT_REPLENISH` | *duration* | 1h | Strongly related to `visitor-email-limit-burst`: The rate at which the bucket is refilled |
|
||||
|
||||
The format for a *duration* is: `<number>(smh)`, e.g. 30s, 20m or 1h.
|
||||
|
||||
## Command line options
|
||||
```
|
||||
$ ntfy serve --help
|
||||
NAME:
|
||||
ntfy serve - Run the ntfy server
|
||||
|
||||
USAGE:
|
||||
ntfy serve [OPTIONS..]
|
||||
|
||||
DESCRIPTION:
|
||||
Run the ntfy server and listen for incoming requests
|
||||
|
||||
The command will load the configuration from /etc/ntfy/server.yml. Config options can
|
||||
be overridden using the command line options.
|
||||
|
||||
Examples:
|
||||
ntfy serve # Starts server in the foreground (on port 80)
|
||||
ntfy serve --listen-http :8080 # Starts server with alternate port
|
||||
|
||||
OPTIONS:
|
||||
--config value, -c value config file (default: /etc/ntfy/server.yml) [$NTFY_CONFIG_FILE]
|
||||
--base-url value, -B value externally visible base URL for this host (e.g. https://ntfy.sh) [$NTFY_BASE_URL]
|
||||
--listen-http value, -l value ip:port used to as HTTP listen address (default: ":80") [$NTFY_LISTEN_HTTP]
|
||||
--listen-https value, -L value ip:port used to as HTTPS listen address [$NTFY_LISTEN_HTTPS]
|
||||
--key-file value, -K value private key file, if listen-https is set [$NTFY_KEY_FILE]
|
||||
--cert-file value, -E value certificate file, if listen-https is set [$NTFY_CERT_FILE]
|
||||
--firebase-key-file value, -F value Firebase credentials file; if set additionally publish to FCM topic [$NTFY_FIREBASE_KEY_FILE]
|
||||
--cache-file value, -C value cache file used for message caching [$NTFY_CACHE_FILE]
|
||||
--cache-duration since, -b since buffer messages for this time to allow since requests (default: 12h0m0s) [$NTFY_CACHE_DURATION]
|
||||
--keepalive-interval value, -k value interval of keepalive messages (default: 30s) [$NTFY_KEEPALIVE_INTERVAL]
|
||||
--manager-interval value, -m value interval of for message pruning and stats printing (default: 1m0s) [$NTFY_MANAGER_INTERVAL]
|
||||
--smtp-addr value SMTP server address (host:port) to allow email sending [$NTFY_SMTP_ADDR]
|
||||
--smtp-user value SMTP user (if e-mail sending is enabled) [$NTFY_SMTP_USER]
|
||||
--smtp-pass value SMTP password (if e-mail sending is enabled) [$NTFY_SMTP_PASS]
|
||||
--smtp-from value SMTP sender address (if e-mail sending is enabled) [$NTFY_SMTP_FROM]
|
||||
--global-topic-limit value, -T value total number of topics allowed (default: 5000) [$NTFY_GLOBAL_TOPIC_LIMIT]
|
||||
--visitor-subscription-limit value number of subscriptions per visitor (default: 30) [$NTFY_VISITOR_SUBSCRIPTION_LIMIT]
|
||||
--visitor-request-limit-burst value initial limit of requests per visitor (default: 60) [$NTFY_VISITOR_REQUEST_LIMIT_BURST]
|
||||
--visitor-request-limit-replenish value interval at which burst limit is replenished (one per x) (default: 10s) [$NTFY_VISITOR_REQUEST_LIMIT_REPLENISH]
|
||||
--visitor-email-limit-burst value initial limit of e-mails per visitor (default: 16) [$NTFY_VISITOR_EMAIL_LIMIT_BURST]
|
||||
--visitor-email-limit-replenish value interval at which burst limit is replenished (one per x) (default: 1h0m0s) [$NTFY_VISITOR_EMAIL_LIMIT_REPLENISH]
|
||||
--behind-proxy, -P if set, use X-Forwarded-For header to determine visitor IP address (for rate limiting) (default: false) [$NTFY_BEHIND_PROXY]
|
||||
--help, -h show help (default: false)
|
||||
```
|
||||
|
||||
25
docs/deprecations.md
Normal file
@@ -0,0 +1,25 @@
|
||||
# Deprecation notices
|
||||
This page is used to list deprecation notices for ntfy. Deprecated commands and options will be
|
||||
**removed after ~3 months** from the time they were deprecated.
|
||||
|
||||
## Active deprecations
|
||||
|
||||
### Running server via `ntfy` (instead of `ntfy serve`)
|
||||
> since 2021-12-17
|
||||
|
||||
As more commands are added to the `ntfy` CLI tool, using just `ntfy` to run the server is not practical
|
||||
anymore. Please use `ntfy serve` instead. This also applies to Docker images, as they can also execute more than
|
||||
just the server.
|
||||
|
||||
=== "Before"
|
||||
```
|
||||
$ ntfy
|
||||
2021/12/17 08:16:01 Listening on :80/http
|
||||
```
|
||||
|
||||
=== "After"
|
||||
```
|
||||
$ ntfy serve
|
||||
2021/12/17 08:16:01 Listening on :80/http
|
||||
```
|
||||
|
||||
71
docs/develop.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Building
|
||||
|
||||
## ntfy server
|
||||
The ntfy server source code is available [on GitHub](https://github.com/binwiederhier/ntfy).
|
||||
To quickly build on amd64, you can use `make build-simple`:
|
||||
|
||||
```
|
||||
git clone git@github.com:binwiederhier/ntfy.git
|
||||
cd ntfy
|
||||
make build-simple
|
||||
```
|
||||
|
||||
That'll generate a statically linked binary in `dist/ntfy_linux_amd64/ntfy`.
|
||||
|
||||
For all other platforms (including Docker), and for production or other snapshot builds, you should use the amazingly
|
||||
awesome [GoReleaser](https://goreleaser.com/) make targets:
|
||||
|
||||
```
|
||||
Build:
|
||||
make build - Build
|
||||
make build-snapshot - Build snapshot
|
||||
make build-simple - Build (using go build, without goreleaser)
|
||||
make clean - Clean build folder
|
||||
|
||||
Releasing (requires goreleaser):
|
||||
make release - Create a release
|
||||
make release-snapshot - Create a test release
|
||||
```
|
||||
|
||||
There are currently no platform-specific make targets, so they will build for all platforms (which may take a while).
|
||||
|
||||
## Android app
|
||||
The ntfy Android app source code is available [on GitHub](https://github.com/binwiederhier/ntfy-android).
|
||||
The Android app has two flavors:
|
||||
|
||||
* **Google Play:** The `play` flavor includes Firebase (FCM) and requires a Firebase account
|
||||
* **F-Droid:** The `fdroid` flavor does not include Firebase or Google dependencies
|
||||
|
||||
First check out the repository:
|
||||
|
||||
```
|
||||
git clone git@github.com:binwiederhier/ntfy-android.git
|
||||
cd ntfy-android
|
||||
```
|
||||
|
||||
Then either follow the steps for building with or without Firebase.
|
||||
|
||||
### Building without Firebase (F-Droid flavor)
|
||||
Without Firebase, you may want to still change the default `app_base_url` in [strings.xml](https://github.com/binwiederhier/ntfy-android/blob/main/app/src/main/res/values/strings.xml)
|
||||
if you're self-hosting the server. Then run:
|
||||
```
|
||||
# To build an unsigned .apk (app/build/outputs/apk/fdroid/*.apk)
|
||||
./gradlew assembleFdroidRelease
|
||||
|
||||
# To build a bundle .aab (app/fdroid/release/*.aab)
|
||||
./gradlew bundleFdroidRelease
|
||||
```
|
||||
|
||||
### Building with Firebase (FCM, Google Play flavor)
|
||||
To build your own version with Firebase, you must:
|
||||
* Create a Firebase/FCM account
|
||||
* Place your account file at `app/google-services.json`
|
||||
* And change `app_base_url` in [strings.xml](https://github.com/binwiederhier/ntfy-android/blob/main/app/src/main/res/values/strings.xml)
|
||||
* Then run:
|
||||
```
|
||||
# To build an unsigned .apk (app/build/outputs/apk/play/*.apk)
|
||||
./gradlew assemblePlayRelease
|
||||
|
||||
# To build a bundle .aab (app/play/release/*.aab)
|
||||
./gradlew bundlePlayRelease
|
||||
```
|
||||
1831
docs/emojis.md
Normal file
77
docs/examples.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Examples
|
||||
|
||||
There are a million ways to use ntfy, but here are some inspirations. I try to collect
|
||||
<a href="https://github.com/binwiederhier/ntfy/tree/main/examples">examples on GitHub</a>, so be sure to check
|
||||
those out, too.
|
||||
|
||||
## A long process is done: backups, copying data, pipelines, ...
|
||||
I started adding notifications pretty much all of my scripts. Typically, I just chain the <tt>curl</tt> call
|
||||
directly to the command I'm running. The following example will either send <i>Laptop backup succeeded</i>
|
||||
or ⚠️ <i>Laptop backup failed</i> directly to my phone:
|
||||
|
||||
```
|
||||
rsync -a root@laptop /backups/laptop \
|
||||
&& zfs snapshot ... \
|
||||
&& curl -H prio:low -d "Laptop backup succeeded" ntfy.sh/backups \
|
||||
|| curl -H tags:warning -H prio:high -d "Laptop backup failed" ntfy.sh/backups
|
||||
```
|
||||
|
||||
## Server-sent messages in your web app
|
||||
Just as you can [subscribe to topics in the Web UI](subscribe/web.md), you can use ntfy in your own
|
||||
web application. Check out the <a href="/example.html">live example</a> or just look the source of this page.
|
||||
|
||||
## Notify on SSH login
|
||||
Years ago my home server was broken into. That shook me hard, so every time someone logs into any machine that I
|
||||
own, I now message myself. Here's an example of how to use <a href="https://en.wikipedia.org/wiki/Linux_PAM">PAM</a>
|
||||
to notify yourself on SSH login.
|
||||
|
||||
=== "/etc/pam.d/sshd"
|
||||
```
|
||||
# at the end of the file
|
||||
session optional pam_exec.so /usr/bin/ntfy-ssh-login.sh
|
||||
```
|
||||
|
||||
=== "/usr/bin/ntfy-ssh-login.sh"
|
||||
```bash
|
||||
#!/bin/bash
|
||||
if [ "${PAM_TYPE}" = "open_session" ]; then
|
||||
curl \
|
||||
-H prio:high \
|
||||
-H tags:warning \
|
||||
-d "SSH login: ${PAM_USER} from ${PAM_RHOST}" \
|
||||
ntfy.sh/alerts
|
||||
fi
|
||||
```
|
||||
|
||||
## Collect data from multiple machines
|
||||
The other day I was running tasks on 20 servers, and I wanted to collect the interim results
|
||||
as a CSV in one place. Each of the servers was publishing to a topic as the results completed (`publish-result.sh`),
|
||||
and I had one central collector to grab the results as they came in (`collect-results.sh`).
|
||||
|
||||
It looked something like this:
|
||||
|
||||
=== "collect-results.sh"
|
||||
```bash
|
||||
while read result; do
|
||||
[ -n "$result" ] && echo "$result" >> results.csv
|
||||
done < <(stdbuf -i0 -o0 curl -s ntfy.sh/results/raw)
|
||||
```
|
||||
=== "publish-result.sh"
|
||||
```bash
|
||||
// This script was run on each of the 20 servers. It was doing heavy processing ...
|
||||
|
||||
// Publish script results
|
||||
curl -d "$(hostname),$count,$time" ntfy.sh/results
|
||||
```
|
||||
|
||||
## Ansible, Salt and Puppet
|
||||
You can easily integrate ntfy into Ansible, Salt, or Puppet to notify you when runs are done or are highstated.
|
||||
One of my co-workers uses the following Ansible task to let him know when things are done:
|
||||
|
||||
```yml
|
||||
- name: Send ntfy.sh update
|
||||
uri:
|
||||
url: "https://ntfy.sh/{{ ntfy_channel }}"
|
||||
method: POST
|
||||
body: "{{ inventory_hostname }} reseeding complete"
|
||||
```
|
||||
48
docs/faq.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# Frequently asked questions (FAQ)
|
||||
|
||||
## Isn't this like ...?
|
||||
Who knows. I didn't do a lot of research before making this. It was fun making it.
|
||||
|
||||
## Can I use this in my app? Will it stay free?
|
||||
Yes. As long as you don't abuse it, it'll be available and free of charge. I do not plan on monetizing
|
||||
the service.
|
||||
|
||||
## What are the uptime guarantees?
|
||||
Best effort.
|
||||
|
||||
## What happens if there are multiple subscribers to the same topic?
|
||||
As per usual with pub-sub, all subscribers receive notifications if they are
|
||||
subscribed to a topic.
|
||||
|
||||
## Will you know what topics exist, can you spy on me?
|
||||
If you don't trust me or your messages are sensitive, run your own server. It's <a href="https://github.com/binwiederhier/ntfy">open source</a>.
|
||||
That said, the logs do not contain any topic names or other details about you.
|
||||
Messages are cached for the duration configured in `server.yml` (12h by default) to facilitate service restarts, message polling and to overcome
|
||||
client network disruptions.
|
||||
|
||||
## Can I self-host it?
|
||||
Yes. The server (including this Web UI) can be self-hosted, and the Android app supports adding topics from
|
||||
your own server as well. Check out the [install instructions](install.md).
|
||||
|
||||
## Why is Firebase used?
|
||||
In addition to caching messages locally and delivering them to long-polling subscribers, all messages are also
|
||||
published to Firebase Cloud Messaging (FCM) (if `FirebaseKeyFile` is set, which it is on ntfy.sh). This
|
||||
is to facilitate notifications on Android.
|
||||
|
||||
If you do not care for Firebase, I suggest you install the [F-Droid version](https://f-droid.org/en/packages/io.heckel.ntfy/)
|
||||
of the app and [self-host your own ntfy server](install.md).
|
||||
|
||||
## How much battery does the Android app use?
|
||||
If you use the ntfy.sh server and you don't use the [instant delivery](subscribe/phone.md#instant-delivery) feature,
|
||||
the Android app uses no additional battery, since Firebase Cloud Messaging (FCM) is used. If you use your own server,
|
||||
or you use *instant delivery*, the app has to maintain a constant connection to the server, which consumes about 4% of
|
||||
battery in 17h of use (on my phone). I use it, and it makes no difference to me.
|
||||
|
||||
## What is instant delivery?
|
||||
[Instant delivery](subscribe/phone.md#instant-delivery) is a feature in the Android app. If turned on, the app maintains a constant connection to the
|
||||
server and listens for incoming notifications. This consumes <a href="#battery-usage">additional battery</a>,
|
||||
but delivers notifications instantly.
|
||||
|
||||
## Why is there no iOS app (yet)?
|
||||
I don't have an iPhone or a Mac, so I didn't make an iOS app yet. It'd be awesome if
|
||||
<a href="https://github.com/binwiederhier/ntfy/issues/4">someone else could help out</a>.
|
||||
95
docs/index.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Getting started
|
||||
ntfy lets you **send push notifications to your phone or desktop via scripts from any computer**, using simple HTTP PUT
|
||||
or POST requests. I use it to notify myself when scripts fail, or long-running commands complete.
|
||||
|
||||
## Step 1: Get the app
|
||||
<a href="https://play.google.com/store/apps/details?id=io.heckel.ntfy"><img src="../../static/img/badge-googleplay.png"></a>
|
||||
<a href="https://f-droid.org/en/packages/io.heckel.ntfy/"><img src="../../static/img/badge-fdroid.png"></a>
|
||||
<a href="https://github.com/binwiederhier/ntfy/issues/4"><img src="../../static/img/badge-appstore.png"></a>
|
||||
|
||||
To [receive notifications on your phone](subscribe/phone.md), install the app, either via Google Play or F-Droid.
|
||||
Once installed, open it and subscribe to a topic of your choosing. Topics don't have to explicitly be created, so just
|
||||
pick a name and use it later when you [publish a message](publish.md). Note that **topic names are public, so it's wise
|
||||
to choose something that cannot be guessed easily.**
|
||||
|
||||
For this guide, we'll just use `mytopic` as our topic name:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Creating/adding your first topic</figcaption>
|
||||
</figure>
|
||||
|
||||
That's it. After you tap "Subscribe", the app is listening for new messages on that topic.
|
||||
|
||||
## Step 2: Send a message
|
||||
Now let's [send a message](publish.md) to our topic. It's easy in every language, since we're just using HTTP PUT/POST,
|
||||
or with the [ntfy CLI](install.md). The message is in the request body. Here's an example showing how to publish a
|
||||
simple message using a POST request:
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -d "Backup successful 😀" ntfy.sh/mytopic
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish mytopic "Backup successful 😀"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /mytopic HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
|
||||
Backup successful 😀
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mytopic', {
|
||||
method: 'POST', // PUT works too
|
||||
body: 'Backup successful 😀'
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
http.Post("https://ntfy.sh/mytopic", "text/plain",
|
||||
strings.NewReader("Backup successful 😀"))
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/mytopic",
|
||||
data="Backup successful 😀".encode(encoding='utf-8'))
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mytopic', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST', // PUT also works
|
||||
'header' => 'Content-Type: text/plain',
|
||||
'content' => 'Backup successful 😀'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
This will create a notification that looks like this:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Android notification</figcaption>
|
||||
</figure>
|
||||
|
||||
That's it. You're all set. Go play and read the rest of the docs. I highly recommend reading at least the page on
|
||||
[publishing messages](publish.md), as well as the detailed page on the [Android app](subscribe/phone.md).
|
||||
|
||||
Here's another video showing the entire process:
|
||||
|
||||
<figure>
|
||||
<video controls muted autoplay loop width="650" src="static/img/android-video-overview.mp4"></video>
|
||||
<figcaption>Sending push notifications to your Android phone</figcaption>
|
||||
</figure>
|
||||
|
||||
|
||||
192
docs/install.md
Normal file
@@ -0,0 +1,192 @@
|
||||
# Installing ntfy
|
||||
The `ntfy` CLI allows you to [publish messages](publish.md), [subscribe to topics](subscribe/cli.md) as well as to
|
||||
self-host your own ntfy server. It's all pretty straight forward. Just install the binary, package or Docker image,
|
||||
configure it and run it. Just like any other software. No fuzz.
|
||||
|
||||
!!! info
|
||||
The following steps are only required if you want to **self-host your own ntfy server or you want to use the ntfy CLI**.
|
||||
If you just want to [send messages using ntfy.sh](publish.md), you don't need to install anything. You can just use
|
||||
`curl`.
|
||||
|
||||
## General steps
|
||||
The ntfy server comes as a statically linked binary and is shipped as tarball, deb/rpm packages and as a Docker image.
|
||||
We support amd64, armv7 and arm64.
|
||||
|
||||
1. Install ntfy using one of the methods described below
|
||||
2. Then (optionally) edit `/etc/ntfy/server.yml` for the server (see [configuration](config.md) or [sample server.yml](https://github.com/binwiederhier/ntfy/blob/main/server/server.yml))
|
||||
3. Or (optionally) create/edit `~/.config/ntfy/client.yml` (or `/etc/ntfy/client.yml`, see [sample client.yml](https://github.com/binwiederhier/ntfy/blob/main/client/client.yml))
|
||||
|
||||
To run the ntfy server, then just run `ntfy serve` (or `systemctl start ntfy` when using the deb/rpm).
|
||||
To send messages, use `ntfy publish`. To subscribe to topics, use `ntfy subscribe` (see [subscribing via CLI][subscribe/cli.md]
|
||||
for details).
|
||||
|
||||
## Binaries and packages
|
||||
Please check out the [releases page](https://github.com/binwiederhier/ntfy/releases) for binaries and
|
||||
deb/rpm packages.
|
||||
|
||||
=== "x86_64/amd64"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_x86_64.tar.gz
|
||||
sudo tar -C /usr/bin -zxf ntfy_*.tar.gz ntfy
|
||||
sudo ./ntfy serve
|
||||
```
|
||||
|
||||
=== "armv7/armhf"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_armv7.tar.gz
|
||||
sudo tar -C /usr/bin -zxf ntfy_*.tar.gz ntfy
|
||||
sudo ./ntfy serve
|
||||
```
|
||||
|
||||
=== "arm64"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_arm64.tar.gz
|
||||
sudo tar -C /usr/bin -zxf ntfy_*.tar.gz ntfy
|
||||
sudo ./ntfy serve
|
||||
```
|
||||
|
||||
## Debian/Ubuntu repository
|
||||
Installation via Debian repository:
|
||||
|
||||
=== "x86_64/amd64"
|
||||
```bash
|
||||
curl -sSL https://archive.heckel.io/apt/pubkey.txt | sudo apt-key add -
|
||||
sudo apt install apt-transport-https
|
||||
sudo sh -c "echo 'deb [arch=amd64] https://archive.heckel.io/apt debian main' \
|
||||
> /etc/apt/sources.list.d/archive.heckel.io.list"
|
||||
sudo apt update
|
||||
sudo apt install ntfy
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "armv7/armhf"
|
||||
```bash
|
||||
curl -sSL https://archive.heckel.io/apt/pubkey.txt | sudo apt-key add -
|
||||
sudo apt install apt-transport-https
|
||||
sudo sh -c "echo 'deb [arch=armhf] https://archive.heckel.io/apt debian main' \
|
||||
> /etc/apt/sources.list.d/archive.heckel.io.list"
|
||||
sudo apt update
|
||||
sudo apt install ntfy
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "arm64"
|
||||
```bash
|
||||
curl -sSL https://archive.heckel.io/apt/pubkey.txt | sudo apt-key add -
|
||||
sudo apt install apt-transport-https
|
||||
sudo sh -c "echo 'deb [arch=arm64] https://archive.heckel.io/apt debian main' \
|
||||
> /etc/apt/sources.list.d/archive.heckel.io.list"
|
||||
sudo apt update
|
||||
sudo apt install ntfy
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
Manually installing the .deb file:
|
||||
|
||||
=== "x86_64/amd64"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_amd64.deb
|
||||
sudo dpkg -i ntfy_*.deb
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "armv7/armhf"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_armv7.deb
|
||||
sudo dpkg -i ntfy_*.deb
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "arm64"
|
||||
```bash
|
||||
wget https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_arm64.deb
|
||||
sudo dpkg -i ntfy_*.deb
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
## Fedora/RHEL/CentOS
|
||||
|
||||
=== "x86_64/amd64"
|
||||
```bash
|
||||
sudo rpm -ivh https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_amd64.rpm
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "armv7/armhf"
|
||||
```bash
|
||||
sudo rpm -ivh https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_armv7.rpm
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
=== "arm64"
|
||||
```bash
|
||||
sudo rpm -ivh https://github.com/binwiederhier/ntfy/releases/download/v1.10.0/ntfy_1.10.0_linux_arm64.rpm
|
||||
sudo systemctl enable ntfy
|
||||
sudo systemctl start ntfy
|
||||
```
|
||||
|
||||
## Arch Linux
|
||||
ntfy can be installed using an [AUR package](https://aur.archlinux.org/packages/ntfysh-bin/). You can use an [AUR helper](https://wiki.archlinux.org/title/AUR_helpers) like `paru`, `yay` or others to download, build and install ntfy and keep it up to date.
|
||||
```
|
||||
paru -S ntfysh-bin
|
||||
```
|
||||
|
||||
Alternatively, run the following commands to install ntfy manually:
|
||||
```
|
||||
curl https://aur.archlinux.org/cgit/aur.git/snapshot/ntfysh-bin.tar.gz | tar xzv
|
||||
cd ntfysh-bin
|
||||
makepkg -si
|
||||
```
|
||||
|
||||
|
||||
## Docker
|
||||
The [ntfy image](https://hub.docker.com/r/binwiederhier/ntfy) is available for amd64, armv7 and arm64. It should be pretty
|
||||
straight forward to use.
|
||||
|
||||
The server exposes its web UI and the API on port 80, so you need to expose that in Docker. To use the persistent
|
||||
[message cache](config.md#message-cache), you also need to map a volume to `/var/cache/ntfy`. To change other settings,
|
||||
you should map `/etc/ntfy`, so you can edit `/etc/ntfy/server.yml`.
|
||||
|
||||
Basic usage (no cache or additional config):
|
||||
```
|
||||
docker run -p 80:80 -it binwiederhier/ntfy serve
|
||||
```
|
||||
|
||||
With persistent cache (configured as command line arguments):
|
||||
```bash
|
||||
docker run \
|
||||
-v /var/cache/ntfy:/var/cache/ntfy \
|
||||
-p 80:80 \
|
||||
-it \
|
||||
binwiederhier/ntfy \
|
||||
--cache-file /var/cache/ntfy/cache.db \
|
||||
serve
|
||||
```
|
||||
|
||||
With other config options (configured via `/etc/ntfy/server.yml`, see [configuration](config.md) for details):
|
||||
```bash
|
||||
docker run \
|
||||
-v /etc/ntfy:/etc/ntfy \
|
||||
-p 80:80 \
|
||||
-it \
|
||||
binwiederhier/ntfy \
|
||||
serve
|
||||
```
|
||||
|
||||
## Go
|
||||
To install via Go, simply run:
|
||||
```bash
|
||||
go install heckel.io/ntfy@latest
|
||||
```
|
||||
|
||||
!!! info
|
||||
Please [let me know](https://github.com/binwiederhier/ntfy/issues) if there are any issues with this installation
|
||||
method. The SQLite bindings require CGO and it works for me, but I have the feeling it may not work for everyone.
|
||||
12
docs/privacy.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# Privacy policy
|
||||
|
||||
I love free software, and I'm doing this because it's fun. I have no bad intentions, and **I will
|
||||
never monetize or sell your information, and this service and software will always stay free and open.**
|
||||
|
||||
Neither the server nor the app record any personal information, or share any of the messages and topics with
|
||||
any outside service. All data is exclusively used to make the service function properly. The only external service
|
||||
I use is Firebase Cloud Messaging (FCM) service, which is required to provide instant Android notifications (see
|
||||
[FAQ](faq.md) for details). To avoid FCM altogether, download the F-Droid version.
|
||||
|
||||
The web server does not log or otherwise store request paths, remote IP addresses or even topics or messages,
|
||||
aside from a short on-disk cache to support service restarts.
|
||||
888
docs/publish.md
Normal file
@@ -0,0 +1,888 @@
|
||||
# Publishing
|
||||
Publishing messages can be done via HTTP PUT/POST or via the [ntfy CLI](install.md). Topics are created on the fly by
|
||||
subscribing or publishing to them. Because there is no sign-up, **the topic is essentially a password**, so pick
|
||||
something that's not easily guessable.
|
||||
|
||||
Here's an example showing how to publish a simple message using a POST request:
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -d "Backup successful 😀" ntfy.sh/mytopic
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish mytopic "Backup successful 😀"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /mytopic HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
|
||||
Backup successful 😀
|
||||
```
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mytopic', {
|
||||
method: 'POST', // PUT works too
|
||||
body: 'Backup successful 😀'
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
http.Post("https://ntfy.sh/mytopic", "text/plain",
|
||||
strings.NewReader("Backup successful 😀"))
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/mytopic",
|
||||
data="Backup successful 😀".encode(encoding='utf-8'))
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mytopic', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST', // PUT also works
|
||||
'header' => 'Content-Type: text/plain',
|
||||
'content' => 'Backup successful 😀'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
If you have the [Android app](subscribe/phone.md) installed on your phone, this will create a notification that looks like this:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Android notification</figcaption>
|
||||
</figure>
|
||||
|
||||
There are more features related to publishing messages: You can set a [notification priority](#message-priority),
|
||||
a [title](#message-title), and [tag messages](#tags-emojis) 🥳 🎉. Here's an example that uses some of them at together:
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl \
|
||||
-H "Title: Unauthorized access detected" \
|
||||
-H "Priority: urgent" \
|
||||
-H "Tags: warning,skull" \
|
||||
-d "Remote access to phils-laptop detected. Act right away." \
|
||||
ntfy.sh/phil_alerts
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--title "Unauthorized access detected" \
|
||||
--tags warning,skull \
|
||||
--priority urgent \
|
||||
mytopic \
|
||||
"Remote access to phils-laptop detected. Act right away."
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /phil_alerts HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Title: Unauthorized access detected
|
||||
Priority: urgent
|
||||
Tags: warning,skull
|
||||
|
||||
Remote access to phils-laptop detected. Act right away.
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/phil_alerts', {
|
||||
method: 'POST', // PUT works too
|
||||
body: 'Remote access to phils-laptop detected. Act right away.',
|
||||
headers: {
|
||||
'Title': 'Unauthorized access detected',
|
||||
'Priority': 'urgent',
|
||||
'Tags': 'warning,skull'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/phil_alerts",
|
||||
strings.NewReader("Remote access to phils-laptop detected. Act right away."))
|
||||
req.Header.Set("Title", "Unauthorized access detected")
|
||||
req.Header.Set("Priority", "urgent")
|
||||
req.Header.Set("Tags", "warning,skull")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/phil_alerts",
|
||||
data="Remote access to phils-laptop detected. Act right away.",
|
||||
headers={
|
||||
"Title": "Unauthorized access detected",
|
||||
"Priority": "urgent",
|
||||
"Tags": "warning,skull"
|
||||
})
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/phil_alerts', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST', // PUT also works
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Title: Unauthorized access detected\r\n" .
|
||||
"Priority: urgent\r\n" .
|
||||
"Tags: warning,skull",
|
||||
'content' => 'Remote access to phils-laptop detected. Act right away.'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Urgent notification with tags and title</figcaption>
|
||||
</figure>
|
||||
|
||||
## Message title
|
||||
The notification title is typically set to the topic short URL (e.g. `ntfy.sh/mytopic`). To override the title,
|
||||
you can set the `X-Title` header (or any of its aliases: `Title`, `ti`, or `t`).
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "X-Title: Dogs are better than cats" -d "Oh my ..." ntfy.sh/controversial
|
||||
curl -H "Title: Dogs are better than cats" -d "Oh my ..." ntfy.sh/controversial
|
||||
curl -H "t: Dogs are better than cats" -d "Oh my ..." ntfy.sh/controversial
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
-t "Dogs are better than cats" \
|
||||
controversial "Oh my ..."
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /controversial HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Title: Dogs are better than cats
|
||||
|
||||
Oh my ...
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/controversial', {
|
||||
method: 'POST',
|
||||
body: 'Oh my ...',
|
||||
headers: { 'Title': 'Dogs are better than cats' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/controversial", strings.NewReader("Oh my ..."))
|
||||
req.Header.Set("Title", "Dogs are better than cats")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/controversial",
|
||||
data="Oh my ...",
|
||||
headers={ "Title": "Dogs are better than cats" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/controversial', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Title: Dogs are better than cats",
|
||||
'content' => 'Oh my ...'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Detail view of notification with title</figcaption>
|
||||
</figure>
|
||||
|
||||
## Message priority
|
||||
All messages have a priority, which defines how urgently your phone notifies you. You can set custom
|
||||
notification sounds and vibration patterns on your phone to map to these priorities (see [Android config](subscribe/phone.md)).
|
||||
|
||||
The following priorities exist:
|
||||
|
||||
| Priority | Icon | ID | Name | Description |
|
||||
|---|---|---|---|---|
|
||||
| Max priority |  | `5` | `max`/`urgent` | Really long vibration bursts, default notification sound with a pop-over notification. |
|
||||
| High priority |  | `4` | `high` | Long vibration burst, default notification sound with a pop-over notification. |
|
||||
| **Default priority** | *(none)* | `3` | `default` | Short default vibration and sound. Default notification behavior. |
|
||||
| Low priority |  |`2` | `low` | No vibration or sound. Notification will not visibly show up until notification drawer is pulled down. |
|
||||
| Min priority |  | `1` | `min` | No vibration or sound. The notification will be under the fold in "Other notifications". |
|
||||
|
||||
You can set the priority with the header `X-Priority` (or any of its aliases: `Priority`, `prio`, or `p`).
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "X-Priority: 5" -d "An urgent message" ntfy.sh/phil_alerts
|
||||
curl -H "Priority: low" -d "Low priority message" ntfy.sh/phil_alerts
|
||||
curl -H p:4 -d "A high priority message" ntfy.sh/phil_alerts
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
-p 5 \
|
||||
phil_alerts An urgent message
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /phil_alerts HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Priority: 5
|
||||
|
||||
An urgent message
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/phil_alerts', {
|
||||
method: 'POST',
|
||||
body: 'An urgent message',
|
||||
headers: { 'Priority': '5' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/phil_alerts", strings.NewReader("An urgent message"))
|
||||
req.Header.Set("Priority", "5")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/phil_alerts",
|
||||
data="An urgent message",
|
||||
headers={ "Priority": "5" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/phil_alerts', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Priority: 5",
|
||||
'content' => 'An urgent message'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Detail view of priority notifications</figcaption>
|
||||
</figure>
|
||||
|
||||
## Tags & emojis 🥳 🎉
|
||||
You can tag messages with emojis and other relevant strings:
|
||||
|
||||
* **Emojis**: If a tag matches an [emoji short code](emojis.md), it'll be converted to an emoji and prepended
|
||||
to title or message.
|
||||
* **Other tags:** If a tag doesn't match, it will be listed below the notification.
|
||||
|
||||
This feature is useful for things like warnings (⚠️, ️🚨, or 🚩), but also to simply tag messages otherwise (e.g. script
|
||||
names, hostnames, etc.). Use [the emoji short code list](emojis.md) to figure out what tags can be converted to emojis.
|
||||
Here's an **excerpt of emojis** I've found very useful in alert messages:
|
||||
|
||||
<table class="remove-md-box"><tr>
|
||||
<td>
|
||||
<table><thead><tr><th>Tag</th><th>Emoji</th></tr></thead><tbody>
|
||||
<tr><td><code>+1</code></td><td>👍️</td></tr>
|
||||
<tr><td><code>partying_face</code></td><td>🥳</td></tr>
|
||||
<tr><td><code>tada</code></td><td>🎉</td></tr>
|
||||
<tr><td><code>heavy_check_mark</code></td><td>✔️</td></tr>
|
||||
<tr><td><code>loudspeaker</code></td><td>📢</td></tr>
|
||||
<tr><td>...</td><td>...</td></tr>
|
||||
</tbody></table>
|
||||
</td>
|
||||
<td>
|
||||
<table><thead><tr><th>Tag</th><th>Emoji</th></tr></thead><tbody>
|
||||
<tr><td><code>-1</code></td><td>👎️</td></tr>
|
||||
<tr><td><code>warning</code></td><td>⚠️</td></tr>
|
||||
<tr><td><code>rotating_light</code></td><td>️🚨</td></tr>
|
||||
<tr><td><code>triangular_flag_on_post</code></td><td>🚩</td></tr>
|
||||
<tr><td><code>skull</code></td><td>💀</td></tr>
|
||||
<tr><td>...</td><td>...</td></tr>
|
||||
</tbody></table>
|
||||
</td>
|
||||
<td>
|
||||
<table><thead><tr><th>Tag</th><th>Emoji</th></tr></thead><tbody>
|
||||
<tr><td><code>facepalm</code></td><td>🤦</td></tr>
|
||||
<tr><td><code>no_entry</code></td><td>⛔</td></tr>
|
||||
<tr><td><code>no_entry_sign</code></td><td>🚫</td></tr>
|
||||
<tr><td><code>cd</code></td><td>💿</td></tr>
|
||||
<tr><td><code>computer</code></td><td>💻</td></tr>
|
||||
<tr><td>...</td><td>...</td></tr>
|
||||
</tbody></table>
|
||||
</td>
|
||||
</tr></table>
|
||||
|
||||
You can set tags with the `X-Tags` header (or any of its aliases: `Tags`, `tag`, or `ta`). Specify multiple tags by separating
|
||||
them with a comma, e.g. `tag1,tag2,tag3`.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "X-Tags: warning,mailsrv13,daily-backup" -d "Backup of mailsrv13 failed" ntfy.sh/backups
|
||||
curl -H "Tags: horse,unicorn" -d "Unicorns are just horses with unique horns" ntfy.sh/backups
|
||||
curl -H ta:dog -d "Dogs are awesome" ntfy.sh/backups
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--tags=warning,mailsrv13,daily-backup \
|
||||
backups "Backup of mailsrv13 failed"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /backups HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Tags: warning,mailsrv13,daily-backup
|
||||
|
||||
Backup of mailsrv13 failed
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/backups', {
|
||||
method: 'POST',
|
||||
body: 'Backup of mailsrv13 failed',
|
||||
headers: { 'Tags': 'warning,mailsrv13,daily-backup' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/backups", strings.NewReader("Backup of mailsrv13 failed"))
|
||||
req.Header.Set("Tags", "warning,mailsrv13,daily-backup")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/backups",
|
||||
data="Backup of mailsrv13 failed",
|
||||
headers={ "Tags": "warning,mailsrv13,daily-backup" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/backups', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Tags: warning,mailsrv13,daily-backup",
|
||||
'content' => 'Backup of mailsrv13 failed'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Detail view of notifications with tags</figcaption>
|
||||
</figure>
|
||||
|
||||
## Scheduled delivery
|
||||
You can delay the delivery of messages and let ntfy send them at a later date. This can be used to send yourself
|
||||
reminders or even to execute commands at a later date (if your subscriber acts on messages).
|
||||
|
||||
Usage is pretty straight forward. You can set the delivery time using the `X-Delay` header (or any of its aliases: `Delay`,
|
||||
`X-At`, `At`, `X-In` or `In`), either by specifying a Unix timestamp (e.g. `1639194738`), a duration (e.g. `30m`,
|
||||
`3h`, `2 days`), or a natural language time string (e.g. `10am`, `8:30pm`, `tomorrow, 3pm`, `Tuesday, 7am`,
|
||||
[and more](https://github.com/olebedev/when)).
|
||||
|
||||
As of today, the minimum delay you can set is **10 seconds** and the maximum delay is **3 days**. This can currently
|
||||
not be configured otherwise ([let me know](https://github.com/binwiederhier/ntfy/issues) if you'd like to change
|
||||
these limits).
|
||||
|
||||
For the purposes of [message caching](config.md#message-cache), scheduled messages are kept in the cache until 12 hours
|
||||
after they were delivered (or whatever the server-side cache duration is set to). For instance, if a message is scheduled
|
||||
to be delivered in 3 days, it'll remain in the cache for 3 days and 12 hours. Also note that naturally,
|
||||
[turning off server-side caching](#message-caching) is not possible in combination with this feature.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "At: tomorrow, 10am" -d "Good morning" ntfy.sh/hello
|
||||
curl -H "In: 30min" -d "It's 30 minutes later now" ntfy.sh/reminder
|
||||
curl -H "Delay: 1639194738" -d "Unix timestamps are awesome" ntfy.sh/itsaunixsystem
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--at="tomorrow, 10am" \
|
||||
hello "Good morning"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /hello HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
At: tomorrow, 10am
|
||||
|
||||
Good morning
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/hello', {
|
||||
method: 'POST',
|
||||
body: 'Good morning',
|
||||
headers: { 'At': 'tomorrow, 10am' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/hello", strings.NewReader("Good morning"))
|
||||
req.Header.Set("At", "tomorrow, 10am")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/hello",
|
||||
data="Good morning",
|
||||
headers={ "At": "tomorrow, 10am" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/backups', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"At: tomorrow, 10am",
|
||||
'content' => 'Good morning'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
Here are a few examples (assuming today's date is **12/10/2021, 9am, Eastern Time Zone**):
|
||||
|
||||
<table class="remove-md-box"><tr>
|
||||
<td>
|
||||
<table><thead><tr><th><code>Delay/At/In</code> header</th><th>Message will be delivered at</th><th>Explanation</th></tr></thead><tbody>
|
||||
<tr><td><code>30m</code></td><td>12/10/2021, 9:<b>30</b>am</td><td>30 minutes from now</td></tr>
|
||||
<tr><td><code>2 hours</code></td><td>12/10/2021, <b>11:30</b>am</td><td>2 hours from now</td></tr>
|
||||
<tr><td><code>1 day</code></td><td>12/<b>11</b>/2021, 9am</td><td>24 hours from now</td></tr>
|
||||
<tr><td><code>10am</code></td><td>12/10/2021, <b>10am</b></td><td>Today at 10am (same day, because it's only 9am)</td></tr>
|
||||
<tr><td><code>8am</code></td><td>12/<b>11</b>/2021, <b>8am</b></td><td>Tomorrow at 8am (because it's 9am already)</td></tr>
|
||||
<tr><td><code>1639152000</code></td><td>12/10/2021, 11am (EST)</td><td> Today at 11am (EST)</td></tr>
|
||||
</tbody></table>
|
||||
</td>
|
||||
</tr></table>
|
||||
|
||||
## Webhooks (Send via GET)
|
||||
In addition to using PUT/POST, you can also send to topics via simple HTTP GET requests. This makes it easy to use
|
||||
a ntfy topic as a [webhook](https://en.wikipedia.org/wiki/Webhook), or if your client has limited HTTP support (e.g.
|
||||
like the [MacroDroid](https://play.google.com/store/apps/details?id=com.arlosoft.macrodroid) Android app).
|
||||
|
||||
To send messages via HTTP GET, simply call the `/publish` endpoint (or its aliases `/send` and `/trigger`). Without
|
||||
any arguments, this will send the message `triggered` to the topic. However, you can provide all arguments that are
|
||||
also supported as HTTP headers as URL-encoded arguments. Be sure to check the list of all
|
||||
[supported parameters and headers](#list-of-all-parameters) for details.
|
||||
|
||||
For instance, assuming your topic is `mywebhook`, you can simply call `/mywebhook/trigger` to send a message
|
||||
(aka trigger the webhook):
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl ntfy.sh/mywebhook/trigger
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy trigger mywebhook
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
GET /mywebhook/trigger HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mywebhook/trigger')
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
http.Get("https://ntfy.sh/mywebhook/trigger")
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.get("https://ntfy.sh/mywebhook/trigger")
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mywebhook/trigger');
|
||||
```
|
||||
|
||||
To add a custom message, simply append the `message=` URL parameter. And of course you can set the
|
||||
[message priority](#message-priority), the [message title](#message-title), and [tags](#tags-emojis) as well.
|
||||
For a full list of possible parameters, check the list of [supported parameters and headers](#list-of-all-parameters).
|
||||
|
||||
Here's an example with a custom message, tags and a priority:
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl "ntfy.sh/mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull"
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
-p 5 --tags=warning,skull \
|
||||
mywebhook "Webhook triggered"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
GET /mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull')
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
http.Get("https://ntfy.sh/mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull")
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.get("https://ntfy.sh/mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull")
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mywebhook/publish?message=Webhook+triggered&priority=high&tags=warning,skull');
|
||||
```
|
||||
|
||||
## E-mail notifications
|
||||
You can forward messages to e-mail by specifying an address in the header. This can be useful for messages that
|
||||
you'd like to persist longer, or to blast-notify yourself on all possible channels.
|
||||
|
||||
Usage is easy: Simply pass the `X-Email` header (or any of its aliases: `X-E-mail`, `Email`, `E-mail`, `Mail`, or `e`).
|
||||
Only one e-mail address is supported.
|
||||
|
||||
Since ntfy does not provide auth (yet), the rate limiting is pretty strict (see [limitations](#limitations)). In the
|
||||
default configuration, you get **16 e-mails per visitor** (IP address) and then after that one per hour. On top of
|
||||
that, your IP address appears in the e-mail body. This is to prevent abuse.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl \
|
||||
-H "Email: phil@example.com" \
|
||||
-H "Tags: warning,skull,backup-host,ssh-login" \
|
||||
-H "Priority: high" \
|
||||
-d "Unknown login from 5.31.23.83 to backups.example.com" \
|
||||
ntfy.sh/alerts
|
||||
curl -H "Email: phil@example.com" -d "You've Got Mail"
|
||||
curl -d "You've Got Mail" "ntfy.sh/alerts?email=phil@example.com"
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--email=phil@example.com \
|
||||
--tags=warning,skull,backup-host,ssh-login \
|
||||
--priority=high \
|
||||
alerts "Unknown login from 5.31.23.83 to backups.example.com"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /alerts HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Email: phil@example.com
|
||||
Tags: warning,skull,backup-host,ssh-login
|
||||
Priority: high
|
||||
|
||||
Unknown login from 5.31.23.83 to backups.example.com
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/alerts', {
|
||||
method: 'POST',
|
||||
body: "Unknown login from 5.31.23.83 to backups.example.com",
|
||||
headers: {
|
||||
'Email': 'phil@example.com',
|
||||
'Tags': 'warning,skull,backup-host,ssh-login',
|
||||
'Priority': 'high'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/alerts",
|
||||
strings.NewReader("Unknown login from 5.31.23.83 to backups.example.com"))
|
||||
req.Header.Set("Email", "phil@example.com")
|
||||
req.Header.Set("Tags", "warning,skull,backup-host,ssh-login")
|
||||
req.Header.Set("Priority", "high")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/alerts",
|
||||
data="Unknown login from 5.31.23.83 to backups.example.com",
|
||||
headers={
|
||||
"Email": "phil@example.com",
|
||||
"Tags": "warning,skull,backup-host,ssh-login",
|
||||
"Priority": "high"
|
||||
})
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/alerts', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Email: phil@example.com\r\n" .
|
||||
"Tags: warning,skull,backup-host,ssh-login\r\n" .
|
||||
"Priority: high",
|
||||
'content' => 'Unknown login from 5.31.23.83 to backups.example.com'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
Here's what that looks like in Google Mail:
|
||||
|
||||
<figure markdown>
|
||||
{ width=600 }
|
||||
<figcaption>E-mail notification</figcaption>
|
||||
</figure>
|
||||
|
||||
## E-mail publishing
|
||||
You can publish messages to a topic via e-mail, i.e. by sending an email to a specific address. For instance, you can
|
||||
publish a message to the topic `sometopic` by sending an e-mail to `ntfy-sometopic@ntfy.sh`. This is useful for e-mail
|
||||
based integrations such as for statuspage.io (though these days most services also support webhooks and HTTP calls).
|
||||
|
||||
Depending on the [server configuration](config.md#e-mail-publishing), the e-mail address format can have a prefix to
|
||||
prevent spam on topics. For ntfy.sh, the prefix is configured to `ntfy-`, meaning that the general e-mail address
|
||||
format is:
|
||||
|
||||
```
|
||||
ntfy-$topic@ntfy.sh
|
||||
```
|
||||
|
||||
As of today, e-mail publishing only supports adding a [message title](#message-title) (the e-mail subject). Tags, priority,
|
||||
delay and other features are not supported (yet). Here's an example that will publish a message with the
|
||||
title `You've Got Mail` to topic `sometopic` (see [ntfy.sh/sometopic](https://ntfy.sh/sometopic)):
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Publishing a message via e-mail</figcaption>
|
||||
</figure>
|
||||
|
||||
## Advanced features
|
||||
|
||||
### Message caching
|
||||
!!! info
|
||||
If `Cache: no` is used, messages will only be delivered to connected subscribers, and won't be re-delivered if a
|
||||
client re-connects. If a subscriber has (temporary) network issues or is reconnecting momentarily,
|
||||
**messages might be missed**.
|
||||
|
||||
By default, the ntfy server caches messages on disk for 12 hours (see [message caching](config.md#message-cache)), so
|
||||
all messages you publish are stored server-side for a little while. The reason for this is to overcome temporary
|
||||
client-side network disruptions, but arguably this feature also may raise privacy concerns.
|
||||
|
||||
To avoid messages being cached server-side entirely, you can set `X-Cache` header (or its alias: `Cache`) to `no`.
|
||||
This will make sure that your message is not cached on the server, even if server-side caching is enabled. Messages
|
||||
are still delivered to connected subscribers, but [`since=`](subscribe/api.md#fetch-cached-messages) and
|
||||
[`poll=1`](subscribe/api.md#poll-for-messages) won't return the message anymore.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "X-Cache: no" -d "This message won't be stored server-side" ntfy.sh/mytopic
|
||||
curl -H "Cache: no" -d "This message won't be stored server-side" ntfy.sh/mytopic
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--no-cache \
|
||||
mytopic "This message won't be stored server-side"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /mytopic HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Cache: no
|
||||
|
||||
This message won't be stored server-side
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mytopic', {
|
||||
method: 'POST',
|
||||
body: 'This message won't be stored server-side',
|
||||
headers: { 'Cache': 'no' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/mytopic", strings.NewReader("This message won't be stored server-side"))
|
||||
req.Header.Set("Cache", "no")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/mytopic",
|
||||
data="This message won't be stored server-side",
|
||||
headers={ "Cache": "no" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mytopic', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Cache: no",
|
||||
'content' => 'This message won't be stored server-side'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
### Disable Firebase
|
||||
!!! info
|
||||
If `Firebase: no` is used and [instant delivery](subscribe/phone.md#instant-delivery) isn't enabled in the Android
|
||||
app (Google Play variant only), **message delivery will be significantly delayed (up to 15 minutes)**. To overcome
|
||||
this delay, simply enable instant delivery.
|
||||
|
||||
The ntfy server can be configured to use [Firebase Cloud Messaging (FCM)](https://firebase.google.com/docs/cloud-messaging)
|
||||
(see [Firebase config](config.md#firebase-fcm)) for message delivery on Android (to minimize the app's battery footprint).
|
||||
The ntfy.sh server is configured this way, meaning that all messages published to ntfy.sh are also published to corresponding
|
||||
FCM topics.
|
||||
|
||||
If you'd like to avoid forwarding messages to Firebase, you can set the `X-Firebase` header (or its alias: `Firebase`)
|
||||
to `no`. This will instruct the server not to forward messages to Firebase.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
curl -H "X-Firebase: no" -d "This message won't be forwarded to FCM" ntfy.sh/mytopic
|
||||
curl -H "Firebase: no" -d "This message won't be forwarded to FCM" ntfy.sh/mytopic
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
ntfy publish \
|
||||
--no-firebase \
|
||||
mytopic "This message won't be forwarded to FCM"
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
POST /mytopic HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
Firebase: no
|
||||
|
||||
This message won't be forwarded to FCM
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
fetch('https://ntfy.sh/mytopic', {
|
||||
method: 'POST',
|
||||
body: 'This message won't be forwarded to FCM',
|
||||
headers: { 'Firebase': 'no' }
|
||||
})
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
req, _ := http.NewRequest("POST", "https://ntfy.sh/mytopic", strings.NewReader("This message won't be forwarded to FCM"))
|
||||
req.Header.Set("Firebase", "no")
|
||||
http.DefaultClient.Do(req)
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
requests.post("https://ntfy.sh/mytopic",
|
||||
data="This message won't be forwarded to FCM",
|
||||
headers={ "Firebase": "no" })
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
file_get_contents('https://ntfy.sh/mytopic', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST',
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Firebase: no",
|
||||
'content' => 'This message won't be stored server-side'
|
||||
]
|
||||
]));
|
||||
```
|
||||
|
||||
## Limitations
|
||||
There are a few limitations to the API to prevent abuse and to keep the server healthy. Most of them you won't run into,
|
||||
but just in case, let's list them all:
|
||||
|
||||
| Limit | Description |
|
||||
|---|---|
|
||||
| **Message length** | Each message can be up to 512 bytes long. Longer messages are truncated. |
|
||||
| **Requests** | By default, the server is configured to allow 60 requests at once, and then refills the your allowed requests bucket at a rate of one request per 10 seconds. You can read more about this in the [rate limiting](config.md#rate-limiting) section. |
|
||||
| **E-mails** | By default, the server is configured to allow sending 16 e-mails at once, and then refills the your allowed e-mail bucket at a rate of one per hour. You can read more about this in the [rate limiting](config.md#rate-limiting) section. |
|
||||
| **Subscription limits** | By default, the server allows each visitor to keep 30 connections to the server open. |
|
||||
| **Total number of topics** | By default, the server is configured to allow 5,000 topics. The ntfy.sh server has higher limits though. |
|
||||
|
||||
## List of all parameters
|
||||
The following is a list of all parameters that can be passed when publishing a message. Parameter names are **case-insensitive**,
|
||||
and can be passed as **HTTP headers** or **query parameters in the URL**. They are listed in the table in their canonical form.
|
||||
|
||||
| Parameter | Aliases (case-insensitive) | Description |
|
||||
|---|---|---|
|
||||
| `X-Message` | `Message`, `m` | Main body of the message as shown in the notification |
|
||||
| `X-Title` | `Title`, `t` | [Message title](#message-title) |
|
||||
| `X-Priority` | `Priority`, `prio`, `p` | [Message priority](#message-priority) |
|
||||
| `X-Tags` | `Tags`, `Tag`, `ta` | [Tags and emojis](#tags-emojis) |
|
||||
| `X-Delay` | `Delay`, `X-At`, `At`, `X-In`, `In` | Timestamp or duration for [delayed delivery](#scheduled-delivery) |
|
||||
| `X-Email` | `X-E-Mail`, `Email`, `E-Mail`, `mail`, `e` | E-mail address for [e-mail notifications](#e-mail-notifications) |
|
||||
| `X-Cache` | `Cache` | Allows disabling [message caching](#message-caching) |
|
||||
| `X-Firebase` | `Firebase` | Allows disabling [sending to Firebase](#disable-firebase) |
|
||||
119
docs/static/css/extra.css
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
:root {
|
||||
--md-primary-fg-color: #3a9784;
|
||||
--md-primary-fg-color--light: #3a9784;
|
||||
--md-primary-fg-color--dark: #3a9784;
|
||||
}
|
||||
|
||||
.md-header__button.md-logo :is(img, svg) {
|
||||
width: unset !important;
|
||||
}
|
||||
|
||||
.admonition {
|
||||
font-size: .74rem !important;
|
||||
}
|
||||
|
||||
article {
|
||||
padding-bottom: 50px;
|
||||
}
|
||||
|
||||
figure img, figure video {
|
||||
border-radius: 7px;
|
||||
}
|
||||
|
||||
body[data-md-color-scheme="default"] figure img, body[data-md-color-scheme="default"] figure video {
|
||||
filter: drop-shadow(3px 3px 3px #ccc);
|
||||
}
|
||||
|
||||
body[data-md-color-scheme="slate"] figure img, body[data-md-color-scheme="slate"] figure video {
|
||||
filter: drop-shadow(3px 3px 3px #1a1313);
|
||||
}
|
||||
|
||||
figure video {
|
||||
width: 100%;
|
||||
max-height: 450px;
|
||||
}
|
||||
|
||||
.remove-md-box {
|
||||
background: none;
|
||||
border: none;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.remove-md-box td {
|
||||
padding: 0 10px
|
||||
}
|
||||
|
||||
/* Lightbox; thanks to https://yossiabramov.com/blog/vanilla-js-lightbox */
|
||||
|
||||
.screenshots {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.screenshots img {
|
||||
height: 230px;
|
||||
margin: 3px;
|
||||
border-radius: 5px;
|
||||
filter: drop-shadow(2px 2px 2px #ddd);
|
||||
}
|
||||
|
||||
.screenshots .nowrap {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lightbox {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
position: fixed;
|
||||
left:0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: -1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.15s ease-in;
|
||||
}
|
||||
|
||||
.lightbox.show {
|
||||
background-color: rgba(0,0,0, 0.75);
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.lightbox img {
|
||||
max-width: 90%;
|
||||
max-height: 90%;
|
||||
filter: drop-shadow(5px 5px 10px #222);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.lightbox .close-lightbox {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
top: 30px;
|
||||
right: 30px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.lightbox .close-lightbox::after,
|
||||
.lightbox .close-lightbox::before {
|
||||
content: '';
|
||||
width: 3px;
|
||||
height: 20px;
|
||||
background-color: #ddd;
|
||||
position: absolute;
|
||||
border-radius: 5px;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
.lightbox .close-lightbox::before {
|
||||
transform: rotate(-45deg);
|
||||
}
|
||||
|
||||
.lightbox .close-lightbox:hover::after,
|
||||
.lightbox .close-lightbox:hover::before {
|
||||
background-color: #fff;
|
||||
}
|
||||
BIN
docs/static/img/android-notification-settings.png
vendored
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
docs/static/img/android-screenshot-add-instant.png
vendored
Normal file
|
After Width: | Height: | Size: 93 KiB |
BIN
docs/static/img/android-screenshot-add-other.png
vendored
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
docs/static/img/android-screenshot-add.png
vendored
Normal file
|
After Width: | Height: | Size: 77 KiB |
BIN
docs/static/img/android-screenshot-basic-notification.png
vendored
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/static/img/android-screenshot-detail.png
vendored
Normal file
|
After Width: | Height: | Size: 74 KiB |
BIN
docs/static/img/android-screenshot-macrodroid-action.png
vendored
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
docs/static/img/android-screenshot-macrodroid-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 90 KiB |
BIN
docs/static/img/android-screenshot-macrodroid-send-action.png
vendored
Normal file
|
After Width: | Height: | Size: 83 KiB |
BIN
docs/static/img/android-screenshot-macrodroid-send-macro.png
vendored
Normal file
|
After Width: | Height: | Size: 77 KiB |
BIN
docs/static/img/android-screenshot-macrodroid-trigger.png
vendored
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
docs/static/img/android-screenshot-main.png
vendored
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/static/img/android-screenshot-muted.png
vendored
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
docs/static/img/android-screenshot-pause.png
vendored
Normal file
|
After Width: | Height: | Size: 74 KiB |
BIN
docs/static/img/android-screenshot-tasker-action-edit.png
vendored
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
docs/static/img/android-screenshot-tasker-action-http-post.png
vendored
Normal file
|
After Width: | Height: | Size: 110 KiB |
BIN
docs/static/img/android-screenshot-tasker-event-edit.png
vendored
Normal file
|
After Width: | Height: | Size: 74 KiB |
BIN
docs/static/img/android-screenshot-tasker-profile-send.png
vendored
Normal file
|
After Width: | Height: | Size: 51 KiB |
BIN
docs/static/img/android-screenshot-tasker-profiles.png
vendored
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
docs/static/img/android-screenshot-tasker-task-edit-post.png
vendored
Normal file
|
After Width: | Height: | Size: 48 KiB |
BIN
docs/static/img/android-screenshot-tasker-task-edit.png
vendored
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
docs/static/img/android-video-overview.mp4
vendored
Normal file
BIN
docs/static/img/badge-appstore.png
vendored
Normal file
|
After Width: | Height: | Size: 5.8 KiB |
BIN
docs/static/img/badge-fdroid.png
vendored
Normal file
|
After Width: | Height: | Size: 4.4 KiB |
BIN
docs/static/img/badge-googleplay.png
vendored
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
docs/static/img/cli-subscribe-video-1.mp4
vendored
Normal file
BIN
docs/static/img/cli-subscribe-video-2.webm
vendored
Normal file
BIN
docs/static/img/cli-subscribe-video-3.webm
vendored
Normal file
BIN
docs/static/img/favicon.png
vendored
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
BIN
docs/static/img/foreground-service.png
vendored
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
docs/static/img/getting-started-add.png
vendored
Normal file
|
After Width: | Height: | Size: 90 KiB |
BIN
docs/static/img/notification-settings.png
vendored
Normal file
|
After Width: | Height: | Size: 67 KiB |
BIN
docs/static/img/notification-with-tags.png
vendored
Normal file
|
After Width: | Height: | Size: 155 KiB |
BIN
docs/static/img/notification-with-title.png
vendored
Normal file
|
After Width: | Height: | Size: 161 KiB |
BIN
docs/static/img/ntfy.png
vendored
Normal file
|
After Width: | Height: | Size: 3.5 KiB |
47
docs/static/img/priority-1.svg
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="24px"
|
||||
viewBox="0 0 24 24"
|
||||
width="24px"
|
||||
fill="#000000"
|
||||
version="1.1"
|
||||
id="svg1428"
|
||||
sodipodi:docname="priority_1_24dp.svg"
|
||||
inkscape:version="1.1.1 (3bf5ae0, 2021-09-20)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1432" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1430"
|
||||
pagecolor="#505050"
|
||||
bordercolor="#eeeeee"
|
||||
borderopacity="1"
|
||||
inkscape:pageshadow="0"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
showgrid="false"
|
||||
inkscape:zoom="20.517358"
|
||||
inkscape:cx="22.834324"
|
||||
inkscape:cy="15.742768"
|
||||
inkscape:window-width="1863"
|
||||
inkscape:window-height="1025"
|
||||
inkscape:window-x="57"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1428" />
|
||||
<path
|
||||
style="color:#000000;fill:#999999;fill-opacity:1;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.195014,20.828316 a 1.2747098,1.2747098 0 0 0 0.661605,-0.185206 l 6.646593,-4.037178 a 1.2745823,1.2745823 0 0 0 0.427537,-1.751107 1.2745823,1.2745823 0 0 0 -1.750928,-0.427718 l -5.984807,3.635327 -5.9848086,-3.635327 a 1.2745823,1.2745823 0 0 0 -1.750927,0.427718 1.2745823,1.2745823 0 0 0 0.427536,1.751107 l 6.6464146,4.037178 a 1.2747098,1.2747098 0 0 0 0.661785,0.185206 z"
|
||||
id="rect3554" />
|
||||
<path
|
||||
style="color:#000000;fill:#b3b3b3;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.195014,15.694014 a 1.2747098,1.2747098 0 0 0 0.661605,-0.185206 l 6.646593,-4.037176 A 1.2745823,1.2745823 0 0 0 19.930749,9.7205243 1.2745823,1.2745823 0 0 0 18.179821,9.2928073 L 12.195014,12.928134 6.2102054,9.2928073 a 1.2745823,1.2745823 0 0 0 -1.750927,0.427717 1.2745823,1.2745823 0 0 0 0.427536,1.7511077 l 6.6464146,4.037176 a 1.2747098,1.2747098 0 0 0 0.661785,0.185206 z"
|
||||
id="path9314" />
|
||||
<path
|
||||
style="color:#000000;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.116784,10.426777 a 1.2747098,1.2747098 0 0 0 0.661606,-0.185205 l 6.646593,-4.0371767 a 1.2745823,1.2745823 0 0 0 0.427537,-1.751108 1.2745823,1.2745823 0 0 0 -1.750928,-0.427718 l -5.984808,3.635327 -5.9848066,-3.635327 a 1.2745823,1.2745823 0 0 0 -1.750928,0.427718 1.2745823,1.2745823 0 0 0 0.427537,1.751108 L 11.455,10.241572 a 1.2747098,1.2747098 0 0 0 0.661784,0.185205 z"
|
||||
id="path9316" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
43
docs/static/img/priority-2.svg
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="24px"
|
||||
viewBox="0 0 24 24"
|
||||
width="24px"
|
||||
fill="#000000"
|
||||
version="1.1"
|
||||
id="svg1428"
|
||||
sodipodi:docname="priority_2_24dp.svg"
|
||||
inkscape:version="1.1.1 (3bf5ae0, 2021-09-20)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1432" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1430"
|
||||
pagecolor="#505050"
|
||||
bordercolor="#eeeeee"
|
||||
borderopacity="1"
|
||||
inkscape:pageshadow="0"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
showgrid="false"
|
||||
inkscape:zoom="20.517358"
|
||||
inkscape:cx="22.834324"
|
||||
inkscape:cy="15.742768"
|
||||
inkscape:window-width="1863"
|
||||
inkscape:window-height="1025"
|
||||
inkscape:window-x="57"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1428" />
|
||||
<path
|
||||
style="color:#000000;fill:#999999;fill-opacity:1;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.172712,17.774352 a 1.2747098,1.2747098 0 0 0 0.661605,-0.185206 l 6.646593,-4.037178 a 1.2745823,1.2745823 0 0 0 0.427537,-1.751107 1.2745823,1.2745823 0 0 0 -1.750928,-0.427718 L 12.172712,15.00847 6.1879033,11.373143 a 1.2745823,1.2745823 0 0 0 -1.750927,0.427718 1.2745823,1.2745823 0 0 0 0.427536,1.751107 l 6.6464147,4.037178 a 1.2747098,1.2747098 0 0 0 0.661785,0.185206 z"
|
||||
id="rect3554" />
|
||||
<path
|
||||
style="color:#000000;fill:#b3b3b3;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.172712,12.64005 a 1.2747098,1.2747098 0 0 0 0.661605,-0.185206 L 19.48091,8.4176679 A 1.2745823,1.2745823 0 0 0 19.908447,6.6665602 1.2745823,1.2745823 0 0 0 18.157519,6.2388432 L 12.172712,9.8741699 6.1879033,6.2388432 a 1.2745823,1.2745823 0 0 0 -1.750927,0.427717 1.2745823,1.2745823 0 0 0 0.427536,1.7511077 l 6.6464147,4.0371761 a 1.2747098,1.2747098 0 0 0 0.661785,0.185206 z"
|
||||
id="path9314" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
43
docs/static/img/priority-4.svg
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="24px"
|
||||
viewBox="0 0 24 24"
|
||||
width="24px"
|
||||
fill="#000000"
|
||||
version="1.1"
|
||||
id="svg1428"
|
||||
sodipodi:docname="priority_4_24dp.svg"
|
||||
inkscape:version="1.1.1 (3bf5ae0, 2021-09-20)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1432" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1430"
|
||||
pagecolor="#505050"
|
||||
bordercolor="#eeeeee"
|
||||
borderopacity="1"
|
||||
inkscape:pageshadow="0"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
showgrid="false"
|
||||
inkscape:zoom="20.517358"
|
||||
inkscape:cx="22.834324"
|
||||
inkscape:cy="15.742768"
|
||||
inkscape:window-width="1863"
|
||||
inkscape:window-height="1025"
|
||||
inkscape:window-x="57"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1428" />
|
||||
<path
|
||||
style="color:#000000;fill:#c60000;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="M 12.116784,6.5394415 A 1.2747098,1.2747098 0 0 0 11.455179,6.724648 l -6.6465926,4.037176 a 1.2745823,1.2745823 0 0 0 -0.427537,1.751108 1.2745823,1.2745823 0 0 0 1.7509281,0.427717 l 5.9848065,-3.635327 5.984809,3.635327 A 1.2745823,1.2745823 0 0 0 19.85252,12.512932 1.2745823,1.2745823 0 0 0 19.424984,10.761824 L 12.778569,6.724648 A 1.2747098,1.2747098 0 0 0 12.116784,6.5394415 Z"
|
||||
id="path9314" />
|
||||
<path
|
||||
style="color:#000000;fill:#de0000;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.195014,11.806679 a 1.2747098,1.2747098 0 0 0 -0.661606,0.185205 l -6.6465924,4.037177 a 1.2745823,1.2745823 0 0 0 -0.427537,1.751108 1.2745823,1.2745823 0 0 0 1.750928,0.427718 l 5.9848074,-3.635327 5.984807,3.635327 a 1.2745823,1.2745823 0 0 0 1.750928,-0.427718 1.2745823,1.2745823 0 0 0 -0.427537,-1.751108 l -6.646414,-4.037177 a 1.2747098,1.2747098 0 0 0 -0.661784,-0.185205 z"
|
||||
id="path9316" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
47
docs/static/img/priority-5.svg
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="24px"
|
||||
viewBox="0 0 24 24"
|
||||
width="24px"
|
||||
fill="#000000"
|
||||
version="1.1"
|
||||
id="svg1428"
|
||||
sodipodi:docname="priority_5_24dp.svg"
|
||||
inkscape:version="1.1.1 (3bf5ae0, 2021-09-20)"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs1432" />
|
||||
<sodipodi:namedview
|
||||
id="namedview1430"
|
||||
pagecolor="#505050"
|
||||
bordercolor="#eeeeee"
|
||||
borderopacity="1"
|
||||
inkscape:pageshadow="0"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
showgrid="false"
|
||||
inkscape:zoom="20.517358"
|
||||
inkscape:cx="22.834323"
|
||||
inkscape:cy="15.742767"
|
||||
inkscape:window-width="1863"
|
||||
inkscape:window-height="1025"
|
||||
inkscape:window-x="57"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1"
|
||||
inkscape:current-layer="svg1428" />
|
||||
<path
|
||||
style="color:#000000;fill:#aa0000;fill-opacity:1;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="M 12.116784,3.40514 A 1.2747098,1.2747098 0 0 0 11.455179,3.5903463 L 4.8085864,7.6275238 A 1.2745823,1.2745823 0 0 0 4.3810494,9.3786313 1.2745823,1.2745823 0 0 0 6.1319775,9.8063489 L 12.116784,6.1710217 18.101593,9.8063489 A 1.2745823,1.2745823 0 0 0 19.85252,9.3786313 1.2745823,1.2745823 0 0 0 19.424984,7.6275238 L 12.778569,3.5903463 A 1.2747098,1.2747098 0 0 0 12.116784,3.40514 Z"
|
||||
id="rect3554" />
|
||||
<path
|
||||
style="color:#000000;fill:#c60000;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="M 12.116784,8.5394415 A 1.2747098,1.2747098 0 0 0 11.455179,8.724648 l -6.6465926,4.037176 a 1.2745823,1.2745823 0 0 0 -0.427537,1.751108 1.2745823,1.2745823 0 0 0 1.7509281,0.427717 l 5.9848065,-3.635327 5.984809,3.635327 A 1.2745823,1.2745823 0 0 0 19.85252,14.512932 1.2745823,1.2745823 0 0 0 19.424984,12.761824 L 12.778569,8.724648 A 1.2747098,1.2747098 0 0 0 12.116784,8.5394415 Z"
|
||||
id="path9314" />
|
||||
<path
|
||||
style="color:#000000;fill:#de0000;fill-opacity:1;stroke:none;stroke-width:0.0919748;stroke-linecap:round;stroke-linejoin:round;-inkscape-stroke:none"
|
||||
d="m 12.195014,13.806679 a 1.2747098,1.2747098 0 0 0 -0.661606,0.185205 l -6.6465924,4.037177 a 1.2745823,1.2745823 0 0 0 -0.427537,1.751108 1.2745823,1.2745823 0 0 0 1.750928,0.427718 l 5.9848074,-3.635327 5.984807,3.635327 a 1.2745823,1.2745823 0 0 0 1.750928,-0.427718 1.2745823,1.2745823 0 0 0 -0.427537,-1.751108 l -6.646414,-4.037177 a 1.2747098,1.2747098 0 0 0 -0.661784,-0.185205 z"
|
||||
id="path9316" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
BIN
docs/static/img/priority-detail-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 193 KiB |
BIN
docs/static/img/priority-notification.png
vendored
Normal file
|
After Width: | Height: | Size: 270 KiB |
BIN
docs/static/img/screenshot-curl.png
vendored
Normal file
|
After Width: | Height: | Size: 253 KiB |
BIN
docs/static/img/screenshot-email-publishing-dns.png
vendored
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
docs/static/img/screenshot-email-publishing-gmail.png
vendored
Normal file
|
After Width: | Height: | Size: 29 KiB |
BIN
docs/static/img/screenshot-email.png
vendored
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
docs/static/img/screenshot-phone-add.jpg
vendored
Normal file
|
After Width: | Height: | Size: 227 KiB |
BIN
docs/static/img/screenshot-phone-detail.jpg
vendored
Normal file
|
After Width: | Height: | Size: 225 KiB |
BIN
docs/static/img/screenshot-phone-main.jpg
vendored
Normal file
|
After Width: | Height: | Size: 128 KiB |
BIN
docs/static/img/screenshot-phone-notification.jpg
vendored
Normal file
|
After Width: | Height: | Size: 224 KiB |
BIN
docs/static/img/web-detail.png
vendored
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
docs/static/img/web-notification.png
vendored
Normal file
|
After Width: | Height: | Size: 297 KiB |
BIN
docs/static/img/web-pin.png
vendored
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/static/img/web-subscribe.png
vendored
Normal file
|
After Width: | Height: | Size: 31 KiB |
99
docs/static/js/extra.js
vendored
Normal file
@@ -0,0 +1,99 @@
|
||||
// Link tabs, as per https://facelessuser.github.io/pymdown-extensions/extensions/tabbed/#linked-tabs
|
||||
|
||||
const savedTab = localStorage.getItem('savedTab')
|
||||
const tabs = document.querySelectorAll(".tabbed-set > input")
|
||||
for (const tab of tabs) {
|
||||
tab.addEventListener("click", () => {
|
||||
const current = document.querySelector(`label[for=${tab.id}]`)
|
||||
const pos = current.getBoundingClientRect().top
|
||||
const labelContent = current.innerHTML
|
||||
const labels = document.querySelectorAll('.tabbed-set > label, .tabbed-alternate > .tabbed-labels > label')
|
||||
for (const label of labels) {
|
||||
if (label.innerHTML === labelContent) {
|
||||
document.querySelector(`input[id=${label.getAttribute('for')}]`).checked = true
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve scroll position
|
||||
const delta = (current.getBoundingClientRect().top) - pos
|
||||
window.scrollBy(0, delta)
|
||||
|
||||
// Save
|
||||
localStorage.setItem('savedTab', labelContent)
|
||||
})
|
||||
|
||||
// Select saved tab
|
||||
const current = document.querySelector(`label[for=${tab.id}]`)
|
||||
const labelContent = current.innerHTML
|
||||
if (savedTab === labelContent) {
|
||||
tab.checked = true
|
||||
}
|
||||
}
|
||||
|
||||
// Lightbox for screenshot
|
||||
|
||||
const lightbox = document.createElement('div');
|
||||
lightbox.classList.add('lightbox');
|
||||
document.body.appendChild(lightbox);
|
||||
|
||||
const showScreenshotOverlay = (e, el, group, index) => {
|
||||
lightbox.classList.add('show');
|
||||
document.addEventListener('keydown', nextScreenshotKeyboardListener);
|
||||
return showScreenshot(e, group, index);
|
||||
};
|
||||
|
||||
const showScreenshot = (e, group, index) => {
|
||||
const actualIndex = resolveScreenshotIndex(group, index);
|
||||
lightbox.innerHTML = '<div class="close-lightbox"></div>' + screenshots[group][actualIndex].innerHTML;
|
||||
lightbox.querySelector('img').onclick = (e) => { return showScreenshot(e, group, actualIndex+1); };
|
||||
currentScreenshotGroup = group;
|
||||
currentScreenshotIndex = actualIndex;
|
||||
e.stopPropagation();
|
||||
return false;
|
||||
};
|
||||
|
||||
const nextScreenshot = (e) => {
|
||||
return showScreenshot(e, currentScreenshotGroup, currentScreenshotIndex+1);
|
||||
};
|
||||
|
||||
const previousScreenshot = (e) => {
|
||||
return showScreenshot(e, currentScreenshotGroup, currentScreenshotIndex-1);
|
||||
};
|
||||
|
||||
const resolveScreenshotIndex = (group, index) => {
|
||||
if (index < 0) {
|
||||
return screenshots[group].length - 1;
|
||||
} else if (index > screenshots[group].length - 1) {
|
||||
return 0;
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
const hideScreenshotOverlay = (e) => {
|
||||
lightbox.classList.remove('show');
|
||||
document.removeEventListener('keydown', nextScreenshotKeyboardListener);
|
||||
};
|
||||
|
||||
const nextScreenshotKeyboardListener = (e) => {
|
||||
switch (e.keyCode) {
|
||||
case 37:
|
||||
previousScreenshot(e);
|
||||
break;
|
||||
case 39:
|
||||
nextScreenshot(e);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let currentScreenshotGroup = '';
|
||||
let currentScreenshotIndex = 0;
|
||||
let screenshots = {};
|
||||
Array.from(document.getElementsByClassName('screenshots')).forEach((sg) => {
|
||||
const group = sg.id;
|
||||
screenshots[group] = [...sg.querySelectorAll('a')];
|
||||
screenshots[group].forEach((el, index) => {
|
||||
el.onclick = (e) => { return showScreenshotOverlay(e, el, group, index); };
|
||||
});
|
||||
});
|
||||
|
||||
lightbox.onclick = hideScreenshotOverlay;
|
||||
327
docs/subscribe/api.md
Normal file
@@ -0,0 +1,327 @@
|
||||
# Subscribe via API
|
||||
You can create and subscribe to a topic in the [web UI](web.md), via the [phone app](phone.md), via the [ntfy CLI](cli.md),
|
||||
or in your own app or script by subscribing the API. This page describes how to subscribe via API. You may also want to
|
||||
check out the page that describes how to [publish messages](../publish.md).
|
||||
|
||||
The subscription API relies on a simple HTTP GET request with a streaming HTTP response, i.e **you open a GET request and
|
||||
the connection stays open forever**, sending messages back as they come in. There are three different API endpoints, which
|
||||
only differ in the response format:
|
||||
|
||||
* [JSON stream](#subscribe-as-json-stream): `<topic>/json` returns a JSON stream, with one JSON message object per line
|
||||
* [SSE stream](#subscribe-as-sse-stream): `<topic>/sse` returns messages as [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events), which
|
||||
can be used with [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
|
||||
* [Raw stream](#subscribe-as-raw-stream): `<topic>/raw` returns messages as raw text, with one line per message
|
||||
|
||||
## Subscribe as JSON stream
|
||||
Here are a few examples of how to consume the JSON endpoint (`<topic>/json`). For almost all languages, **this is the
|
||||
recommended way to subscribe to a topic**. The notable exception is JavaScript, for which the
|
||||
[SSE/EventSource stream](#subscribe-as-sse-stream) is much easier to work with.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
$ curl -s ntfy.sh/disk-alerts/json
|
||||
{"id":"SLiKI64DOt","time":1635528757,"event":"open","topic":"mytopic"}
|
||||
{"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
|
||||
{"id":"DGUDShMCsc","time":1635528787,"event":"keepalive","topic":"mytopic"}
|
||||
...
|
||||
```
|
||||
|
||||
=== "ntfy CLI"
|
||||
```
|
||||
$ ntfy subcribe disk-alerts
|
||||
{"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
|
||||
...
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
GET /disk-alerts/json HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/x-ndjson; charset=utf-8
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
{"id":"SLiKI64DOt","time":1635528757,"event":"open","topic":"mytopic"}
|
||||
{"id":"hwQ2YpKdmg","time":1635528741,"event":"message","topic":"mytopic","message":"Disk full"}
|
||||
{"id":"DGUDShMCsc","time":1635528787,"event":"keepalive","topic":"mytopic"}
|
||||
...
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
resp, err := http.Get("https://ntfy.sh/disk-alerts/json")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
println(scanner.Text())
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
resp = requests.get("https://ntfy.sh/disk-alerts/json", stream=True)
|
||||
for line in resp.iter_lines():
|
||||
if line:
|
||||
print(line)
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
$fp = fopen('https://ntfy.sh/disk-alerts/json', 'r');
|
||||
if (!$fp) die('cannot open stream');
|
||||
while (!feof($fp)) {
|
||||
echo fgets($fp, 2048);
|
||||
flush();
|
||||
}
|
||||
fclose($fp);
|
||||
```
|
||||
|
||||
## Subscribe as SSE stream
|
||||
Using [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) in JavaScript, you can consume
|
||||
notifications via a [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events) stream. It's incredibly
|
||||
easy to use. Here's what it looks like. You may also want to check out the [live example](/example.html).
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
$ curl -s ntfy.sh/mytopic/sse
|
||||
event: open
|
||||
data: {"id":"weSj9RtNkj","time":1635528898,"event":"open","topic":"mytopic"}
|
||||
|
||||
data: {"id":"p0M5y6gcCY","time":1635528909,"event":"message","topic":"mytopic","message":"Hi!"}
|
||||
|
||||
event: keepalive
|
||||
data: {"id":"VNxNIg5fpt","time":1635528928,"event":"keepalive","topic":"test"}
|
||||
...
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
GET /mytopic/sse HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/event-stream; charset=utf-8
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
event: open
|
||||
data: {"id":"weSj9RtNkj","time":1635528898,"event":"open","topic":"mytopic"}
|
||||
|
||||
data: {"id":"p0M5y6gcCY","time":1635528909,"event":"message","topic":"mytopic","message":"Hi!"}
|
||||
|
||||
event: keepalive
|
||||
data: {"id":"VNxNIg5fpt","time":1635528928,"event":"keepalive","topic":"test"}
|
||||
...
|
||||
```
|
||||
|
||||
=== "JavaScript"
|
||||
``` javascript
|
||||
const eventSource = new EventSource('https://ntfy.sh/mytopic/sse');
|
||||
eventSource.onmessage = (e) => {
|
||||
console.log(e.data);
|
||||
};
|
||||
```
|
||||
|
||||
## Subscribe as raw stream
|
||||
The `/raw` endpoint will output one line per message, and **will only include the message body**. It's useful for extremely
|
||||
simple scripts, and doesn't include all the data. Additional fields such as [priority](../publish.md#message-priority),
|
||||
[tags](../publish.md#tags--emojis--) or [message title](../publish.md#message-title) are not included in this output
|
||||
format. Keepalive messages are sent as empty lines.
|
||||
|
||||
=== "Command line (curl)"
|
||||
```
|
||||
$ curl -s ntfy.sh/disk-alerts/raw
|
||||
|
||||
Disk full
|
||||
...
|
||||
```
|
||||
|
||||
=== "HTTP"
|
||||
``` http
|
||||
GET /disk-alerts/raw HTTP/1.1
|
||||
Host: ntfy.sh
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
Disk full
|
||||
...
|
||||
```
|
||||
|
||||
=== "Go"
|
||||
``` go
|
||||
resp, err := http.Get("https://ntfy.sh/disk-alerts/raw")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
println(scanner.Text())
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
``` python
|
||||
resp = requests.get("https://ntfy.sh/disk-alerts/raw", stream=True)
|
||||
for line in resp.iter_lines():
|
||||
if line:
|
||||
print(line)
|
||||
```
|
||||
|
||||
=== "PHP"
|
||||
``` php-inline
|
||||
$fp = fopen('https://ntfy.sh/disk-alerts/raw', 'r');
|
||||
if (!$fp) die('cannot open stream');
|
||||
while (!feof($fp)) {
|
||||
echo fgets($fp, 2048);
|
||||
flush();
|
||||
}
|
||||
fclose($fp);
|
||||
```
|
||||
|
||||
## Advanced features
|
||||
|
||||
### Poll for messages
|
||||
You can also just poll for messages if you don't like the long-standing connection using the `poll=1`
|
||||
query parameter. The connection will end after all available messages have been read. This parameter can be
|
||||
combined with `since=` (defaults to `since=all`).
|
||||
|
||||
```
|
||||
curl -s "ntfy.sh/mytopic/json?poll=1"
|
||||
```
|
||||
|
||||
### Fetch cached messages
|
||||
Messages may be cached for a couple of hours (see [message caching](../config.md#message-cache)) to account for network
|
||||
interruptions of subscribers. If the server has configured message caching, you can read back what you missed by using
|
||||
the `since=` query parameter. It takes either a duration (e.g. `10m` or `30s`), a Unix timestamp (e.g. `1635528757`)
|
||||
or `all` (all cached messages).
|
||||
|
||||
```
|
||||
curl -s "ntfy.sh/mytopic/json?since=10m"
|
||||
```
|
||||
|
||||
### Fetch scheduled messages
|
||||
Messages that are [scheduled to be delivered](../publish.md#scheduled-delivery) at a later date are not typically
|
||||
returned when subscribing via the API, which makes sense, because after all, the messages have technically not been
|
||||
delivered yet. To also return scheduled messages from the API, you can use the `scheduled=1` (alias: `sched=1`)
|
||||
parameter (makes most sense with the `poll=1` parameter):
|
||||
|
||||
```
|
||||
curl -s "ntfy.sh/mytopic/json?poll=1&sched=1"
|
||||
```
|
||||
|
||||
### Filter messages
|
||||
You can filter which messages are returned based on the well-known message fields `message`, `title`, `priority` and
|
||||
`tags`. Here's an example that only returns messages of high or urgent priority that contains the both tags
|
||||
"zfs-error" and "error". Note that the `priority` filter is a logical OR and the `tags` filter is a logical AND.
|
||||
|
||||
```
|
||||
$ curl "ntfy.sh/alerts/json?priority=high&tags=zfs-error"
|
||||
{"id":"0TIkJpBcxR","time":1640122627,"event":"open","topic":"alerts"}
|
||||
{"id":"X3Uzz9O1sM","time":1640122674,"event":"message","topic":"alerts","priority":4,
|
||||
"tags":["error", "zfs-error"], "message":"ZFS pool corruption detected"}
|
||||
```
|
||||
|
||||
Available filters (all case-insensitive):
|
||||
|
||||
| Filter variable | Alias | Example | Description |
|
||||
|---|---|---|---|
|
||||
| `message` | `X-Message`, `m` | `ntfy.sh/mytopic?message=lalala` | Only return messages that match this exact message string |
|
||||
| `title` | `X-Title`, `t` | `ntfy.sh/mytopic?title=some+title` | Only return messages that match this exact title string |
|
||||
| `priority` | `X-Priority`, `prio`, `p` | `ntfy.sh/mytopic?p=high,urgent` | Only return messages that match *any priority listed* (comma-separated) |
|
||||
| `tags` | `X-Tags`, `tag`, `ta` | `ntfy.sh/mytopic?tags=error,alert` | Only return messages that match *all listed tags* (comma-separated) |
|
||||
|
||||
### Subscribe to multiple topics
|
||||
It's possible to subscribe to multiple topics in one HTTP call by providing a comma-separated list of topics
|
||||
in the URL. This allows you to reduce the number of connections you have to maintain:
|
||||
|
||||
```
|
||||
$ curl -s ntfy.sh/mytopic1,mytopic2/json
|
||||
{"id":"0OkXIryH3H","time":1637182619,"event":"open","topic":"mytopic1,mytopic2,mytopic3"}
|
||||
{"id":"dzJJm7BCWs","time":1637182634,"event":"message","topic":"mytopic1","message":"for topic 1"}
|
||||
{"id":"Cm02DsxUHb","time":1637182643,"event":"message","topic":"mytopic2","message":"for topic 2"}
|
||||
```
|
||||
|
||||
## JSON message format
|
||||
Both the [`/json` endpoint](#subscribe-as-json-stream) and the [`/sse` endpoint](#subscribe-as-sse-stream) return a JSON
|
||||
format of the message. It's very straight forward:
|
||||
|
||||
| Field | Required | Type | Example | Description |
|
||||
|---|---|---|---|---|
|
||||
| `id` | ✔️ | *string* | `hwQ2YpKdmg` | Randomly chosen message identifier |
|
||||
| `time` | ✔️ | *int* | `1635528741` | Message date time, as Unix time stamp |
|
||||
| `event` | ✔️ | `open`, `keepalive` or `message` | `message` | Message type, typically you'd be only interested in `message` |
|
||||
| `topic` | ✔️ | *string* | `topic1,topic2` | Comma-separated list of topics the message is associated with; only one for all `message` events, but may be a list in `open` events |
|
||||
| `message` | - | *string* | `Some message` | Message body; always present in `message` events |
|
||||
| `title` | - | *string* | `Some title` | Message [title](../publish.md#message-title); if not set defaults to `ntfy.sh/<topic>` |
|
||||
| `tags` | - | *string array* | `["tag1","tag2"]` | List of [tags](../publish.md#tags-emojis) that may or not map to emojis |
|
||||
| `priority` | - | *1, 2, 3, 4, or 5* | `4` | Message [priority](../publish.md#message-priority) with 1=min, 3=default and 5=max |
|
||||
|
||||
Here's an example for each message type:
|
||||
|
||||
=== "Notification message"
|
||||
``` json
|
||||
{
|
||||
"id": "wze9zgqK41",
|
||||
"time": 1638542110,
|
||||
"event": "message",
|
||||
"topic": "phil_alerts",
|
||||
"priority": 5,
|
||||
"tags": [
|
||||
"warning",
|
||||
"skull"
|
||||
],
|
||||
"title": "Unauthorized access detected",
|
||||
"message": "Remote access to phils-laptop detected. Act right away."
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
=== "Notification message (minimal)"
|
||||
``` json
|
||||
{
|
||||
"id": "wze9zgqK41",
|
||||
"time": 1638542110,
|
||||
"event": "message",
|
||||
"topic": "phil_alerts",
|
||||
"message": "Remote access to phils-laptop detected. Act right away."
|
||||
}
|
||||
```
|
||||
|
||||
=== "Open message"
|
||||
``` json
|
||||
{
|
||||
"id": "2pgIAaGrQ8",
|
||||
"time": 1638542215,
|
||||
"event": "open",
|
||||
"topic": "phil_alerts"
|
||||
}
|
||||
```
|
||||
|
||||
=== "Keepalive message"
|
||||
``` json
|
||||
{
|
||||
"id": "371sevb0pD",
|
||||
"time": 1638542275,
|
||||
"event": "keepalive",
|
||||
"topic": "phil_alerts"
|
||||
}
|
||||
```
|
||||
|
||||
## List of all parameters
|
||||
The following is a list of all parameters that can be passed when subscribing to a message. Parameter names are **case-insensitive**,
|
||||
and can be passed as **HTTP headers** or **query parameters in the URL**. They are listed in the table in their canonical form.
|
||||
|
||||
| Parameter | Aliases (case-insensitive) | Description |
|
||||
|---|---|---|
|
||||
| `poll` | `X-Poll`, `po` | Return cached messages and close connection |
|
||||
| `scheduled` | `X-Scheduled`, `sched` | Include scheduled/delayed messages in message list |
|
||||
| `message` | `X-Message`, `m` | Filter: Only return messages that match this exact message string |
|
||||
| `title` | `X-Title`, `t` | Filter: Only return messages that match this exact title string |
|
||||
| `priority` | `X-Priority`, `prio`, `p` | Filter: Only return messages that match *any priority listed* (comma-separated) |
|
||||
| `tags` | `X-Tags`, `tag`, `ta` | Filter: Only return messages that match *all listed tags* (comma-separated) |
|
||||
198
docs/subscribe/cli.md
Normal file
@@ -0,0 +1,198 @@
|
||||
# Subscribe via ntfy CLI
|
||||
In addition to subscribing via the [web UI](web.md), the [phone app](phone.md), or the [API](api.md), you can subscribe
|
||||
to topics via the ntfy CLI. The CLI is included in the same `ntfy` binary that can be used to [self-host a server](../install.md).
|
||||
|
||||
!!! info
|
||||
The **ntfy CLI is not required to send or receive messages**. You can instead [send messages with curl](../publish.md),
|
||||
and even use it to [subscribe to topics](api.md). It may be a little more convenient to use the ntfy CLI than writing
|
||||
your own script. It all depends on the use case. 😀
|
||||
|
||||
## Install + configure
|
||||
To install the ntfy CLI, simply **follow the steps outlined on the [install page](../install.md)**. The ntfy server and
|
||||
client are the same binary, so it's all very convenient. After installing, you can (optionally) configure the client
|
||||
by creating `~/.config/ntfy/client.yml` (for the non-root user), or `/etc/ntfy/client.yml` (for the root user). You
|
||||
can find a [skeleton config](https://github.com/binwiederhier/ntfy/blob/main/client/client.yml) on GitHub.
|
||||
|
||||
If you just want to use [ntfy.sh](https://ntfy.sh), you don't have to change anything. If you **self-host your own server**,
|
||||
you may want to edit the `default-host` option:
|
||||
|
||||
``` yaml
|
||||
# Base URL used to expand short topic names in the "ntfy publish" and "ntfy subscribe" commands.
|
||||
# If you self-host a ntfy server, you'll likely want to change this.
|
||||
#
|
||||
default-host: https://ntfy.myhost.com
|
||||
```
|
||||
|
||||
## Publish messages
|
||||
You can send messages with the ntfy CLI using the `ntfy publish` command (or any of its aliases `pub`, `send` or
|
||||
`trigger`). There are a lot of examples on the page about [publishing messages](../publish.md), but here are a few
|
||||
quick ones:
|
||||
|
||||
=== "Simple send"
|
||||
```
|
||||
ntfy publish mytopic This is a message
|
||||
ntfy publish mytopic "This is a message"
|
||||
ntfy pub mytopic "This is a message"
|
||||
```
|
||||
|
||||
=== "Send with title, priority, and tags"
|
||||
```
|
||||
ntfy publish \
|
||||
--title="Thing sold on eBay" \
|
||||
--priority=high \
|
||||
--tags=partying_face \
|
||||
mytopic \
|
||||
"Somebody just bought the thing that you sell"
|
||||
```
|
||||
|
||||
=== "Send at 8:30am"
|
||||
```
|
||||
ntfy pub --at=8:30am delayed_topic Laterzz
|
||||
```
|
||||
|
||||
=== "Triggering a webhook"
|
||||
```
|
||||
ntfy trigger mywebhook
|
||||
ntfy pub mywebhook
|
||||
```
|
||||
|
||||
## Subscribe to topics
|
||||
You can subscribe to topics using `ntfy subscribe`. Depending on how it is called, this command
|
||||
will either print or execute a command for every arriving message. There are a few different ways
|
||||
in which the command can be run:
|
||||
|
||||
### Stream messages as JSON
|
||||
```
|
||||
ntfy subscribe TOPIC
|
||||
```
|
||||
If you run the command like this, it prints the JSON representation of every incoming message. This is useful
|
||||
when you have a command that wants to stream-read incoming JSON messages. Unless `--poll` is passed, this command
|
||||
stays open forever.
|
||||
|
||||
```
|
||||
$ ntfy sub mytopic
|
||||
{"id":"nZ8PjH5oox","time":1639971913,"event":"message","topic":"mytopic","message":"hi there"}
|
||||
{"id":"sekSLWTujn","time":1639972063,"event":"message","topic":"mytopic",priority:5,"message":"Oh no!"}
|
||||
...
|
||||
```
|
||||
|
||||
<figure>
|
||||
<video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-1.mp4"></video>
|
||||
<figcaption>Subscribe in JSON mode</figcaption>
|
||||
</figure>
|
||||
|
||||
### Run command for every message
|
||||
```
|
||||
ntfy subscribe TOPIC COMMAND
|
||||
```
|
||||
If you run it like this, a COMMAND is executed for every incoming messages. Scroll down to see a list of available
|
||||
environment variables. Here are a few examples:
|
||||
|
||||
```
|
||||
ntfy sub mytopic 'notify-send "$m"'
|
||||
ntfy sub topic1 /my/script.sh
|
||||
ntfy sub topic1 'echo "Message $m was received. Its title was $t and it had priority $p'
|
||||
```
|
||||
|
||||
<figure>
|
||||
<video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-2.webm"></video>
|
||||
<figcaption>Execute command on incoming messages</figcaption>
|
||||
</figure>
|
||||
|
||||
The message fields are passed to the command as environment variables and can be used in scripts. Note that since
|
||||
these are environment variables, you typically don't have to worry about quoting too much, as long as you enclose them
|
||||
in double-quotes, you should be fine:
|
||||
|
||||
| Variable | Aliases | Description |
|
||||
|---|---|---
|
||||
| `$NTFY_ID` | `$id` | Unique message ID |
|
||||
| `$NTFY_TIME` | `$time` | Unix timestamp of the message delivery |
|
||||
| `$NTFY_TOPIC` | `$topic` | Topic name |
|
||||
| `$NTFY_MESSAGE` | `$message`, `$m` | Message body |
|
||||
| `$NTFY_TITLE` | `$title`, `$t` | Message title |
|
||||
| `$NTFY_PRIORITY` | `$priority`, `$prio`, `$p` | Message priority (1=min, 5=max) |
|
||||
| `$NTFY_TAGS` | `$tags`, `$tag`, `$ta` | Message tags (comma separated list) |
|
||||
| `$NTFY_RAW` | `$raw` | Raw JSON message |
|
||||
|
||||
### Subscribe to multiple topics
|
||||
```
|
||||
ntfy subscribe --from-config
|
||||
```
|
||||
To subscribe to multiple topics at once, and run different commands for each one, you can use `ntfy subscribe --from-config`,
|
||||
which will read the `subscribe` config from the config file. Please also check out the [ntfy-client systemd service](#using-the-systemd-service).
|
||||
|
||||
Here's an example config file that subscribes to three different topics, executing a different command for each of them:
|
||||
|
||||
=== "~/.config/ntfy/client.yml"
|
||||
```yaml
|
||||
subscribe:
|
||||
- topic: echo-this
|
||||
command: 'echo "Message received: $message"'
|
||||
- topic: alerts
|
||||
command: notify-send -i /usr/share/ntfy/logo.png "Important" "$m"
|
||||
if:
|
||||
priority: high,urgent
|
||||
- topic: calc
|
||||
command: 'gnome-calculator 2>/dev/null &'
|
||||
- topic: print-temp
|
||||
command: |
|
||||
echo "You can easily run inline scripts, too."
|
||||
temp="$(sensors | awk '/Pack/ { print substr($4,2,2) }')"
|
||||
if [ $temp -gt 80 ]; then
|
||||
echo "Warning: CPU temperature is $temp. Too high."
|
||||
else
|
||||
echo "CPU temperature is $temp. That's alright."
|
||||
fi
|
||||
```
|
||||
|
||||
In this example, when `ntfy subscribe --from-config` is executed:
|
||||
|
||||
* Messages to `echo-this` simply echos to standard out
|
||||
* Messages to `alerts` display as desktop notification for high priority messages using [notify-send](https://manpages.ubuntu.com/manpages/focal/man1/notify-send.1.html)
|
||||
* Messages to `calc` open the gnome calculator 😀 (*because, why not*)
|
||||
* Messages to `print-temp` execute an inline script and print the CPU temperature
|
||||
|
||||
I hope this shows how powerful this command is. Here's a short video that demonstrates the above example:
|
||||
|
||||
<figure>
|
||||
<video controls muted autoplay loop width="650" src="../../static/img/cli-subscribe-video-3.webm"></video>
|
||||
<figcaption>Execute all the things</figcaption>
|
||||
</figure>
|
||||
|
||||
### Using the systemd service
|
||||
You can use the `ntfy-client` systemd service (see [ntfy-client.service](https://github.com/binwiederhier/ntfy/blob/main/client/ntfy-client.service))
|
||||
to subscribe to multiple topics just like in the example above. The service is automatically installed (but not started)
|
||||
if you install the deb/rpm package. To configure it, simply edit `/etc/ntfy/client.yml` and run `sudo systemctl restart ntfy-client`.
|
||||
|
||||
!!! info
|
||||
The `ntfy-client.service` runs as user `ntfy`, meaning that typical Linux permission restrictions apply. See below
|
||||
for how to fix this.
|
||||
|
||||
If the service runs on your personal desktop machine, you may want to override the service user/group (`User=` and `Group=`), and
|
||||
adjust the `DISPLAY` and `DBUS_SESSION_BUS_ADDRESS` environment variables. This will allow you to run commands in your X session
|
||||
as the primary machine user.
|
||||
|
||||
You can either manually override these systemd service entries with `sudo systemctl edit ntfy-client`, and add this
|
||||
(assuming your user is `phil`). Don't forget to run `sudo systemctl daemon-reload` and `sudo systemctl restart ntfy-client`
|
||||
after editing the service file:
|
||||
|
||||
=== "/etc/systemd/system/ntfy-client.service.d/override.conf"
|
||||
```
|
||||
[Service]
|
||||
User=phil
|
||||
Group=phil
|
||||
Environment="DISPLAY=:0" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus"
|
||||
```
|
||||
Or you can run the following script that creates this override config for you:
|
||||
|
||||
```
|
||||
sudo sh -c 'cat > /etc/systemd/system/ntfy-client.service.d/override.conf' <<EOF
|
||||
[Service]
|
||||
User=$USER
|
||||
Group=$USER
|
||||
Environment="DISPLAY=:0" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus"
|
||||
EOF
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl restart ntfy-client
|
||||
```
|
||||
163
docs/subscribe/phone.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# Subscribe from your phone
|
||||
You can use the [ntfy Android App](https://play.google.com/store/apps/details?id=io.heckel.ntfy) to receive
|
||||
notifications directly on your phone. Just like the server, this app is also [open source](https://github.com/binwiederhier/ntfy-android).
|
||||
Since I don't have an iPhone or a Mac, I didn't make an iOS app yet. I'd be awesome if [someone else could help out](https://github.com/binwiederhier/ntfy/issues/4).
|
||||
|
||||
<a href="https://play.google.com/store/apps/details?id=io.heckel.ntfy"><img src="../../static/img/badge-googleplay.png"></a>
|
||||
<a href="https://f-droid.org/en/packages/io.heckel.ntfy/"><img src="../../static/img/badge-fdroid.png"></a>
|
||||
|
||||
You can get the Android app from both [Google Play](https://play.google.com/store/apps/details?id=io.heckel.ntfy) and
|
||||
from [F-Droid](https://f-droid.org/en/packages/io.heckel.ntfy/). Both are largely identical, with the one exception that
|
||||
the F-Droid flavor does not use Firebase.
|
||||
|
||||
## Overview
|
||||
A picture is worth a thousand words. Here are a few screenshots showing what the app looks like. It's all pretty
|
||||
straight forward. You can add topics and as soon as you add them, you can [publish messages](../publish.md) to them.
|
||||
|
||||
<div id="android-screenshots" class="screenshots">
|
||||
<a href="../../static/img/android-screenshot-main.png"><img src="../../static/img/android-screenshot-main.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-detail.png"><img src="../../static/img/android-screenshot-detail.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-pause.png"><img src="../../static/img/android-screenshot-pause.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-add.png"><img src="../../static/img/android-screenshot-add.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-add-instant.png"><img src="../../static/img/android-screenshot-add-instant.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-add-other.png"><img src="../../static/img/android-screenshot-add-other.png"/></a>
|
||||
</div>
|
||||
|
||||
If those screenshots are still not enough, here's a video:
|
||||
|
||||
<figure>
|
||||
<video controls muted autoplay loop width="650" src="../../static/img/android-video-overview.mp4"></video>
|
||||
<figcaption>Sending push notifications to your Android phone</figcaption>
|
||||
</figure>
|
||||
|
||||
## Message priority
|
||||
When you [publish messages](../publish.md#message-priority) to a topic, you can define a priority. This priority defines
|
||||
how urgently Android will notify you about the notification, and whether they make a sound and/or vibrate.
|
||||
|
||||
By default, messages with default priority or higher (>= 3) will vibrate and make a sound. Messages with high or urgent
|
||||
priority (>= 4) will also show as pop-over, like so:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>High and urgent notifications show as pop-over</figcaption>
|
||||
</figure>
|
||||
|
||||
You can change these settings in Android by long-pressing on the app, and tapping "Notifications". You can then configure
|
||||
the settings (and custom sounds or vibration) for each of the priorities:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Per-priority sound/vibration settings</figcaption>
|
||||
</figure>
|
||||
|
||||
## Instant delivery
|
||||
Instant delivery allows you to receive messages on your phone instantly, **even when your phone is in doze mode**, i.e.
|
||||
when the screen turns off, and you leave it on the desk for a while. This is achieved with a foreground service, which
|
||||
you'll see as a permanent notification that looks like this:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Instant delivery foreground notification</figcaption>
|
||||
</figure>
|
||||
|
||||
Android does not allow you to dismiss this notification, unless you turn off the notification channel in the settings.
|
||||
To do so, long-press on the foreground notification (screenshot above) and navigate to the settings. Then toggle the
|
||||
"Subscription Service" off:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Turning off the persistent instant delivery notification</figcaption>
|
||||
</figure>
|
||||
|
||||
**Limitations without instant delivery**: Without instant delivery, **messages may arrive with a significant delay**
|
||||
(sometimes many minutes, or even hours later). If you've ever picked up your phone and
|
||||
suddenly had 10 messages that were sent long before you know what I'm talking about.
|
||||
|
||||
The reason for this is [Firebase Cloud Messaging (FCM)](https://firebase.google.com/docs/cloud-messaging). FCM is the
|
||||
*only* Google approved way to send push messages to Android devices, and it's what pretty much all apps use to deliver push
|
||||
notifications. Firebase is overall pretty bad at delivering messages in time, but on Android, most apps are stuck with it.
|
||||
|
||||
The ntfy Android app uses Firebase only for the main host `ntfy.sh`, and only in the Google Play flavor of the app.
|
||||
It won't use Firebase for any self-hosted servers, and not at all in the the F-Droid flavor.
|
||||
|
||||
## Integrations
|
||||
The ntfy Android app integrates nicely with automation apps such as [MacroDroid](https://play.google.com/store/apps/details?id=com.arlosoft.macrodroid)
|
||||
or [Tasker](https://play.google.com/store/apps/details?id=net.dinglisch.android.taskerm). Using Android intents, you can
|
||||
**react to incoming messages**, as well as **send messages**.
|
||||
|
||||
### React to incoming messages
|
||||
To react on incoming notifications, you have to register to intents with the `io.heckel.ntfy.MESSAGE_RECEIVED` action (see
|
||||
[code for details](https://github.com/binwiederhier/ntfy-android/blob/main/app/src/main/java/io/heckel/ntfy/msg/BroadcastService.kt)).
|
||||
Here's an example using [MacroDroid](https://play.google.com/store/apps/details?id=com.arlosoft.macrodroid)
|
||||
and [Tasker](https://play.google.com/store/apps/details?id=net.dinglisch.android.taskerm), but any app that can catch
|
||||
broadcasts is supported:
|
||||
|
||||
<div id="integration-screenshots-receive" class="screenshots">
|
||||
<a href="../../static/img/android-screenshot-macrodroid-overview.png"><img src="../../static/img/android-screenshot-macrodroid-overview.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-macrodroid-trigger.png"><img src="../../static/img/android-screenshot-macrodroid-trigger.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-macrodroid-action.png"><img src="../../static/img/android-screenshot-macrodroid-action.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-profiles.png"><img src="../../static/img/android-screenshot-tasker-profiles.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-event-edit.png"><img src="../../static/img/android-screenshot-tasker-event-edit.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-task-edit.png"><img src="../../static/img/android-screenshot-tasker-task-edit.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-action-edit.png"><img src="../../static/img/android-screenshot-tasker-action-edit.png"/></a>
|
||||
</div>
|
||||
|
||||
For MacroDroid, be sure to type in the package name `io.heckel.ntfy`, otherwise intents may be silently swallowed.
|
||||
If you're using topics to drive automation, you'll likely want to mute the topic in the ntfy app. This will prevent
|
||||
notification popups:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Muting notifications to prevent popups</figcaption>
|
||||
</figure>
|
||||
|
||||
Here's a list of extras you can access. Most likely, you'll want to filter for `topic` and react on `message`:
|
||||
|
||||
| Extra name | Type | Example | Description |
|
||||
|---|---|---|---|
|
||||
| `id` | *string* | `bP8dMjO8ig` | Randomly chosen message identifier (likely not very useful for task automation) |
|
||||
| `base_url` | *string* | `https://ntfy.sh` | Root URL of the ntfy server this message came from |
|
||||
| `topic` ❤️ | *string* | `mytopic` | Topic name; **you'll likely want to filter for a specific topic** |
|
||||
| `muted` | *bool* | `true` | Indicates whether the subscription was muted in the app |
|
||||
| `muted_str` | *string (`true` or `false`)* | `true` | Same as `muted`, but as string `true` or `false` |
|
||||
| `time` | *int* | `1635528741` | Message date time, as Unix time stamp |
|
||||
| `title` | *string* | `Some title` | Message [title](../publish.md#message-title); may be empty if not set |
|
||||
| `message` ❤️ | *string* | `Some message` | Message body; **this is likely what you're interested in** |
|
||||
| `tags` | *string* | `tag1,tag2,..` | Comma-separated list of [tags](../publish.md#tags-emojis) |
|
||||
| `tags_map` | *string* | `0=tag1,1=tag2,..` | Map of tags to make it easier to map first, second, ... tag |
|
||||
| `priority` | *int (between 1-5)* | `4` | Message [priority](../publish.md#message-priority) with 1=min, 3=default and 5=max |
|
||||
|
||||
### Send messages using intents
|
||||
To send messages from other apps (such as [MacroDroid](https://play.google.com/store/apps/details?id=com.arlosoft.macrodroid)
|
||||
and [Tasker](https://play.google.com/store/apps/details?id=net.dinglisch.android.taskerm)), you can
|
||||
broadcast an intent with the `io.heckel.ntfy.SEND_MESSAGE` action. The ntfy Android app will forward the intent as a HTTP
|
||||
POST request to [publish a message](../publish.md). This is primarily useful for apps that do not support HTTP POST/PUT
|
||||
(like MacroDroid). In Tasker, you can simply use the "HTTP Request" action, which is a little easier and also works if
|
||||
ntfy is not installed.
|
||||
|
||||
Here's what that looks like:
|
||||
|
||||
<div id="integration-screenshots-send" class="screenshots">
|
||||
<a href="../../static/img/android-screenshot-macrodroid-send-macro.png"><img src="../../static/img/android-screenshot-macrodroid-send-macro.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-macrodroid-send-action.png"><img src="../../static/img/android-screenshot-macrodroid-send-action.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-profile-send.png"><img src="../../static/img/android-screenshot-tasker-profile-send.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-task-edit-post.png"><img src="../../static/img/android-screenshot-tasker-task-edit-post.png"/></a>
|
||||
<a href="../../static/img/android-screenshot-tasker-action-http-post.png"><img src="../../static/img/android-screenshot-tasker-action-http-post.png"/></a>
|
||||
</div>
|
||||
|
||||
The following intent extras are supported when for the intent with the `io.heckel.ntfy.SEND_MESSAGE` action:
|
||||
|
||||
| Extra name | Required | Type | Example | Description |
|
||||
|---|---|---|---|---|
|
||||
| `base_url` | - | *string* | `https://ntfy.sh` | Root URL of the ntfy server this message came from, defaults to `https://ntfy.sh` |
|
||||
| `topic` ❤️ | ✔ | *string* | `mytopic` | Topic name; **you must set this** |
|
||||
| `title` | - | *string* | `Some title` | Message [title](../publish.md#message-title); may be empty if not set |
|
||||
| `message` ❤️ | ✔ | *string* | `Some message` | Message body; **you must set this** |
|
||||
| `tags` | - | *string* | `tag1,tag2,..` | Comma-separated list of [tags](../publish.md#tags-emojis) |
|
||||
| `priority` | - | *string or int (between 1-5)* | `4` | Message [priority](../publish.md#message-priority) with 1=min, 3=default and 5=max |
|
||||
|
||||
## iPhone/iOS
|
||||
I almost feel devious for putting the *Download on the App Store* button on this page. Currently, there is no iOS app
|
||||
for ntfy, but it's in the works. You can track the status on GitHub.
|
||||
|
||||
<a href="https://github.com/binwiederhier/ntfy/issues/4"><img src="../../static/img/badge-appstore.png"></a>
|
||||
20
docs/subscribe/web.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Subscribe from the Web UI
|
||||
You can use the Web UI to subscribe to topics as well. If you do, and you keep the website open, **notifications will
|
||||
pop up as desktop notifications**. Simply type in the topic name and click the *Subscribe* button. The browser will
|
||||
keep a connection open and listen for incoming notifications.
|
||||
|
||||
To learn how to send messages, check out the [publishing page](../publish.md).
|
||||
|
||||
<div id="web-screenshots" class="screenshots">
|
||||
<a href="../../static/img/web-subscribe.png"><img src="../../static/img/web-subscribe.png"/></a>
|
||||
<a href="../../static/img/web-notification.png"><img src="../../static/img/web-notification.png"/></a>
|
||||
<a href="../../static/img/web-detail.png"><img src="../../static/img/web-detail.png"/></a>
|
||||
</div>
|
||||
|
||||
To keep receiving desktop notifications from ntfy, you need to keep the website open. What I do, and what I highly recommend,
|
||||
is to pin the tab so that it's always open, but sort of out of the way:
|
||||
|
||||
<figure markdown>
|
||||
{ width=500 }
|
||||
<figcaption>Pin web app to move it out of the way</figcaption>
|
||||
</figure>
|
||||
@@ -2,6 +2,8 @@
|
||||
# This is an example shell script showing how to consume a ntfy.sh topic using
|
||||
# a simple script. The notify-send command sends any arriving message as a desktop notification.
|
||||
|
||||
TOPIC_URL=ntfy.sh/mytopic
|
||||
|
||||
while read msg; do
|
||||
[ -n "$msg" ] && notify-send "$msg"
|
||||
done < <(stdbuf -i0 -o0 curl -s ntfy.sh/mytopic/raw)
|
||||
done < <(stdbuf -i0 -o0 curl -s $TOPIC_URL/raw)
|
||||
27
examples/publish-go/main.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Without additional headers (priority, tags, title), it's a one liner.
|
||||
// Check out https://ntfy.sh/mytopic in your browser after running this.
|
||||
http.Post("https://ntfy.sh/mytopic", "text/plain", strings.NewReader("Backup successful 😀"))
|
||||
|
||||
// If you'd like to add title, priority, or tags, it's a little harder.
|
||||
// Check out https://ntfy.sh/phil_alerts in your browser.
|
||||
req, err := http.NewRequest("POST", "https://ntfy.sh/phil_alerts",
|
||||
strings.NewReader("Remote access to phils-laptop detected. Act right away."))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Title", "Unauthorized access detected")
|
||||
req.Header.Set("Priority", "urgent")
|
||||
req.Header.Set("Tags", "warning,skull")
|
||||
if _, err := http.DefaultClient.Do(req); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
14
examples/publish-php/publish.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
// Check out https://ntfy.sh/phil_alerts in your browser after running this.
|
||||
file_get_contents('https://ntfy.sh/phil_alerts', false, stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'POST', // PUT also works
|
||||
'header' =>
|
||||
"Content-Type: text/plain\r\n" .
|
||||
"Title: Unauthorized access detected\r\n" .
|
||||
"Priority: urgent\r\n" .
|
||||
"Tags: warning,skull",
|
||||
'content' => 'Remote access to phils-laptop detected. Act right away.'
|
||||
]
|
||||
]));
|
||||
12
examples/publish-python/publish.py
Executable file
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import requests
|
||||
|
||||
resp = requests.get("https://ntfy.sh/mytopic/trigger",
|
||||
data="Backup successful 😀".encode(encoding='utf-8'),
|
||||
headers={
|
||||
"Priority": "high",
|
||||
"Tags": "warning,skull",
|
||||
"Title": "Hello there"
|
||||
})
|
||||
resp.raise_for_status()
|
||||
9
examples/ssh-login-alert/ntfy-ssh-login.sh
Normal file
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
# This is a PAM script hook that shows how to notify you when
|
||||
# somebody logs into your server. Place at /usr/local/bin/ntfy-ssh-login.sh (with chmod +x!).
|
||||
|
||||
TOPIC_URL=ntfy.sh/alerts
|
||||
|
||||
if [ "${PAM_TYPE}" = "open_session" ]; then
|
||||
curl -H tags:warning -H prio:high -d "SSH login to $(hostname): ${PAM_USER} from ${PAM_RHOST}" "${TOPIC_URL}"
|
||||
fi
|
||||
8
examples/ssh-login-alert/pam_sshd
Normal file
@@ -0,0 +1,8 @@
|
||||
# PAM config file snippet
|
||||
#
|
||||
# Put this snippet AT THE END of the file /etc/pam.d/sshd
|
||||
# See https://geekthis.net/post/run-scripts-after-ssh-authentication/ for details.
|
||||
|
||||
# (lots of stuff here ...)
|
||||
|
||||
session optional pam_exec.so /usr/local/bin/ntfy-ssh-login.sh
|
||||
19
examples/subscribe-go/main.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
resp, err := http.Get("https://ntfy.sh/phil_alerts/json")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
println(scanner.Text())
|
||||
}
|
||||
}
|
||||
12
examples/subscribe-php/subscribe.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
$fp = fopen('https://ntfy.sh/phil_alerts/json', 'r');
|
||||
if (!$fp) {
|
||||
die('cannot open stream');
|
||||
}
|
||||
while (!feof($fp)) {
|
||||
$buffer = fgets($fp, 2048);
|
||||
echo $buffer;
|
||||
flush();
|
||||
}
|
||||
fclose($fp);
|
||||
8
examples/subscribe-python/subscribe.py
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import requests
|
||||
|
||||
resp = requests.get("https://ntfy.sh/mytopic/json", stream=True)
|
||||
for line in resp.iter_lines():
|
||||
if line:
|
||||
print(line)
|
||||