Merge branch 'master' into master

pull/4219/head
Frank Elsinga 1 month ago committed by GitHub
commit d2ff2ea385
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -6,7 +6,7 @@ body:
- type: checkboxes - type: checkboxes
id: no-duplicate-issues id: no-duplicate-issues
attributes: attributes:
label: "⚠️ Please verify that this bug has NOT been raised before." label: "⚠️ Please verify that this question has NOT been raised before."
description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)" description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)"
options: options:
- label: "I checked and didn't find similar issue" - label: "I checked and didn't find similar issue"
@ -24,7 +24,7 @@ body:
required: true required: true
attributes: attributes:
label: "📝 Describe your problem" label: "📝 Describe your problem"
description: "Please walk us through it step by step." description: "Please walk us through it step by step. Include all important details and add screenshots where appropriate"
placeholder: "Describe what are you asking for..." placeholder: "Describe what are you asking for..."
- type: textarea - type: textarea
id: error-msg id: error-msg
@ -56,19 +56,20 @@ body:
placeholder: "Ex. Google Chrome 95.0.4638.69" placeholder: "Ex. Google Chrome 95.0.4638.69"
validations: validations:
required: true required: true
- type: input - type: textarea
id: docker-version id: deployment-info
attributes:
label: "🐋 Docker Version"
description: "If running with Docker, which version are you running?"
placeholder: "Ex. Docker 20.10.9 / K8S / Podman"
validations:
required: false
- type: input
id: nodejs-version
attributes: attributes:
label: "🟩 NodeJS Version" label: "🖥️ Deployment Environment"
description: "If running with Node.js? which version are you running?" description: |
placeholder: "Ex. 14.18.0" examples:
- **Runtime**: Docker 20.10.9 / nodejs 14.18.0 / K8S via ... v1.3.3 / ..
- **Database**: sqlite/embedded mariadb/external mariadb
- **Filesystem used to store the database on**: Windows/ZFS/btrfs/NFSv3 on a SSD/HDD/eMMC
- **number of monitors**: 42
value: |
- Runtime:
- Database:
- Filesystem used to store the database on:
- number of monitors:
validations: validations:
required: false required: true

@ -3,14 +3,14 @@ description: "Submit a bug report to help us improve"
#title: "[Bug] " #title: "[Bug] "
labels: [bug] labels: [bug]
body: body:
- type: checkboxes - type: textarea
id: no-duplicate-issues id: related-issues
validations:
required: true
attributes: attributes:
label: "⚠️ Please verify that this bug has NOT been raised before." label: "📑 I have found these related issues/pull requests"
description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)" description: "Search related issues by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=) and explain what the difference between them or explain that you are unable to find any related issues"
options: placeholder: "Related to #1 by also touching the ... system. They should not be merged because ..."
- label: "I checked and didn't find similar issue"
required: true
- type: checkboxes - type: checkboxes
attributes: attributes:
label: "🛡️ Security Policy" label: "🛡️ Security Policy"
@ -31,7 +31,7 @@ body:
required: true required: true
attributes: attributes:
label: "👟 Reproduction steps" label: "👟 Reproduction steps"
description: "How do you trigger this bug? Please walk us through it step by step." description: "How do you trigger this bug? Please walk us through it step by step. Include all important details and add screenshots where appropriate"
placeholder: "..." placeholder: "..."
- type: textarea - type: textarea
id: expected-behavior id: expected-behavior
@ -73,22 +73,23 @@ body:
placeholder: "Ex. Google Chrome 95.0.4638.69" placeholder: "Ex. Google Chrome 95.0.4638.69"
validations: validations:
required: true required: true
- type: input - type: textarea
id: docker-version id: deployment-info
attributes:
label: "🐋 Docker Version"
description: "If running with Docker, which version are you running?"
placeholder: "Ex. Docker 20.10.9 / K8S / Podman"
validations:
required: false
- type: input
id: nodejs-version
attributes: attributes:
label: "🟩 NodeJS Version" label: "🖥️ Deployment Environment"
description: "If running with Node.js? which version are you running?" description: |
placeholder: "Ex. 14.18.0" examples:
- **Runtime**: Docker 20.10.9 / nodejs 18.17.1 / K8S via ... v1.3.3 / ..
- **Database**: sqlite/embedded mariadb/external mariadb
- **Filesystem used to store the database on**: Windows/ZFS/btrfs/NFSv3 on a SSD/HDD/eMMC
- **number of monitors**: 42
value: |
- Runtime:
- Database:
- Filesystem used to store the database on:
- number of monitors:
validations: validations:
required: false required: true
- type: textarea - type: textarea
id: logs id: logs
attributes: attributes:

@ -3,14 +3,14 @@ description: "Submit a proposal for a new feature"
#title: "[Feature] " #title: "[Feature] "
labels: [feature-request] labels: [feature-request]
body: body:
- type: checkboxes - type: textarea
id: no-duplicate-issues id: related-issues
validations:
required: true
attributes: attributes:
label: "⚠️ Please verify that this feature request has NOT been suggested before." label: "📑 I have found these related issues/pull requests"
description: "Search in the issues sections by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=)" description: "Search related issues by clicking [HERE](https://github.com/louislam/uptime-kuma/issues?q=) and explain what the difference between them or explain that you are unable to find any related issues"
options: placeholder: "Related to #1 by also touching the ... system. They should not be merged because ..."
- label: "I checked and didn't find similar feature request"
required: true
- type: dropdown - type: dropdown
id: feature-area id: feature-area
attributes: attributes:
@ -18,10 +18,17 @@ body:
description: "What kind of feature request is this?" description: "What kind of feature request is this?"
multiple: true multiple: true
options: options:
- API - API / automation options
- New Notification - New notification-provider
- New Monitor - Change to existing notification-provider
- UI Feature - New monitor
- Change to existing monitor
- Dashboard
- Status-page
- Maintenance
- Deployment
- Certificate expiry
- Settings
- Other - Other
validations: validations:
required: true required: true

@ -22,7 +22,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [macos-latest, ubuntu-latest, windows-latest, ARM64] os: [macos-latest, ubuntu-latest, windows-latest, ARM64]
node: [ 14, 20.5 ] node: [ 18, 20.5 ]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
@ -33,7 +33,6 @@ jobs:
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node }} node-version: ${{ matrix.node }}
- run: npm install npm@9 -g
- run: npm install - run: npm install
- run: npm run build - run: npm run build
- run: npm run test-backend - run: npm run test-backend
@ -50,7 +49,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ ARMv7 ] os: [ ARMv7 ]
node: [ 14, 20 ] node: [ 18, 20 ]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
@ -61,7 +60,6 @@ jobs:
uses: actions/setup-node@v4 uses: actions/setup-node@v4
with: with:
node-version: ${{ matrix.node }} node-version: ${{ matrix.node }}
- run: npm install npm@9 -g
- run: npm ci --production - run: npm ci --production
check-linters: check-linters:

@ -11,7 +11,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest]
node-version: [16] node-version: [18]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

@ -11,12 +11,32 @@ jobs:
steps: steps:
- uses: actions/stale@v8 - uses: actions/stale@v8
with: with:
stale-issue-message: 'We are clearing up our old issues and your ticket has been open for 3 months with no activity. Remove stale label or comment or this will be closed in 2 days.' stale-issue-message: |-
close-issue-message: 'This issue was closed because it has been stalled for 2 days with no activity.' We are clearing up our old `help`-issues and your issue has been open for 60 days with no activity.
days-before-stale: 90 If no comment is made and the stale label is not removed, this issue will be closed in 7 days.
days-before-close: 2 days-before-stale: 60
days-before-close: 7
days-before-pr-stale: -1 days-before-pr-stale: -1
days-before-pr-close: -1 days-before-pr-close: -1
exempt-issue-labels: 'News,Medium,High,discussion,bug,doc,feature-request' exempt-issue-labels: 'News,Medium,High,discussion,bug,doc,feature-request'
exempt-issue-assignees: 'louislam' exempt-issue-assignees: 'louislam'
operations-per-run: 200 operations-per-run: 200
- uses: actions/stale@v8
with:
stale-issue-message: |-
This issue was marked as `cannot-reproduce` by a maintainer.
If an issue is non-reproducible, we cannot fix it, as we do not know what the underlying issue is.
If you have any ideas how we can reproduce this issue, we would love to hear them.
We don't have a good way to deal with truely unreproducible issues and are going to close this issue in a month.
If think there might be other differences in our environment or in how we tried to reproduce this, we would appreciate any ideas.
close-issue-message: |-
This issue will be closed as no way to reproduce it has been found.
If you/somebody finds a way how to (semi-reliably) reproduce this, we can reopen this issue. ^^
days-before-stale: 180
days-before-close: 30
days-before-pr-stale: -1
days-before-pr-close: -1
any-of-issue-labels: 'cannot-reproduce'
operations-per-run: 200

@ -1,76 +1,193 @@
# Project Info # Project Info
First of all, I want to thank everyone who have made pull requests for Uptime Kuma. I never thought the GitHub community would be so nice! Because of this, I also never thought that other people would actually read and edit my code. It is not very well structured or commented, sorry about that. First of all, I want to thank everyone who have wrote issues or shared pull requests for Uptime Kuma.
I never thought the GitHub community would be so nice!
Because of this, I also never thought that other people would actually read and edit my code.
Parts of the code are not very well-structured or commented, sorry about that.
The project was created with vite.js (vue3). Then I created a subdirectory called "server" for the server part. Both frontend and backend share the same `package.json`. The project was created with `vite.js` and is written in `vue3`.
Our backend lives in the `server`-directory and mostly communicates via websockets.
Both frontend and backend share the same `package.json`.
The frontend code builds into "dist" directory. The server (express.js) exposes the "dist" directory as the root of the endpoint. This is how production is working. For production, the frontend is build into `dist`-directory and the server (`express.js`) exposes the `dist` directory as the root of the endpoint.
For development, we run vite in development mode on another port.
## Key Technical Skills
- Node.js (You should know about promises, async/await, arrow functions, etc.)
- Socket.io
- SCSS
- Vue.js
- Bootstrap
- SQLite
## Directories ## Directories
- config (dev config files) - `config` (dev config files)
- data (App data) - `data` (App data)
- db (Base database and migration scripts) - `db` (Base database and migration scripts)
- dist (Frontend build) - `dist` (Frontend build)
- docker (Dockerfiles) - `docker` (Dockerfiles)
- extra (Extra useful scripts) - `extra` (Extra useful scripts)
- public (Frontend resources for dev only) - `public` (Frontend resources for dev only)
- server (Server source code) - `server` (Server source code)
- src (Frontend source code) - `src` (Frontend source code)
- test (unit test) - `test` (unit test)
## Can I create a pull request for Uptime Kuma? ## Can I create a pull request for Uptime Kuma?
Yes or no, it depends on what you will try to do. Since I don't want to waste your time, be sure to **create an empty draft pull request or open an issue, so we can have a discussion first**. Especially for a large pull request or you don't know if it will be merged or not. Yes or no, it depends on what you will try to do.
Both your and our maintainers time is precious, and we don't want to waste both time.
Here are some references:
If you have any questions about any process/.. is not clear, you are likely not alone => please ask them ^^
### ✅ Usually accepted
Different guidelines exist for different types of pull requests (PRs):
- Bug fix - <details><summary><b>security fixes</b></summary>
- Security fix <p>
- Adding notification providers
- Adding new language files (see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md)) Submitting security fixes is something that may put the community at risk.
- Adding new language keys: `$t("...")` Please read through our [security policy](SECURITY.md) and submit vulnerabilities via an [advisory](https://github.com/louislam/uptime-kuma/security/advisories/new) + [issue](https://github.com/louislam/uptime-kuma/issues/new?assignees=&labels=help&template=security.md) instead.
We encourage you to submit how to fix a vulnerability if you know how to, this is not required.
### ⚠️ Discussion required Following the security policy allows us to properly test, fix bugs.
This review allows us to notice, if there are any changes necessary to unrelated parts like the documentation.
- Large pull requests [**PLEASE SEE OUR SECURITY POLICY.**](SECURITY.md)
- New features
</p>
### ❌ Won't be merged </details>
- <details><summary><b>small, non-breaking bug fixes</b></summary>
<p>
If you come across a bug and think you can solve, we appreciate your work.
Please make sure that you follow by these rules:
- keep the PR as small as possible, fix only one thing at a time => keeping it reviewable
- test that your code does what you came it does.
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>translations / internationalisation (i18n)</b></summary>
<p>
We use weblate to localise this project into many languages.
If you are unhappy with a translation this is the best start.
On how to translate using weblate, please see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md).
There are two cases in which a change cannot be done in weblate and requires a PR:
- A text may not be currently localisable. In this case, **adding a new language key** via `$t("languageKey")` might be nessesary
- language keys need to be **added to `en.json`** to be visible in weblate. If this has not happened, a PR is appreciated.
- **Adding a new language** requires a new file see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md)
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>new notification providers</b></summary>
<p>
To set up a new notification provider these files need to be modified/created:
- `server/notification-providers/PROVIDER_NAME.js` is where the heart of the notification provider lives.
- Both `monitorJSON` and `heartbeatJSON` can be `null` for some events.
If both are `null`, this is a general testing message, but if just `heartbeatJSON` is `null` this is a certificate expiry.
- Please wrap the axios call into a
```js
try {
let result = await axios.post(...);
if (result.status === ...) ...
} catch (error) {
this.throwGeneralAxiosError(error);
}
```
- `server/notification.js` is where the backend of the notification provider needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
- `src/components/NotificationDialog.vue` you need to decide if the provider is a regional or a global one and add it with a name to the respective list
- `src/components/notifications/PROVIDER_NAME.vue` is where the frontend of each provider lives.
Please make sure that you have:
- used `HiddenInput` for secret credentials
- included all the necessary helptexts/placeholder/.. to make sure the notification provider is simple to setup for new users.
- include all translations (`{{ $t("Translation key") }}`, [`i18n-t keypath="Translation key">`](https://vue-i18n.intlify.dev/guide/advanced/component.html)) in `src/lang/en.json` to enable our translators to translate this
- `src/components/notifications/index.js` is where the frontend of the provider needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
Offering notifications is close to the core of what we are as an uptime monitor.
Therefore, making sure that they work is also really important.
Because testing notification providers is quite time intensive, we mostly offload this onto the person contributing a notification provider.
To make shure you have tested the notification provider, please include screenshots of the following events in the pull-request description:
- `UP`/`DOWN`
- Certificate Expiry via https://expired.badssl.com/
- Testing (the test button on the notification provider setup page)
Using the following way to format this is encouraged:
```md
| Event | Before | After |
------------------
| `UP` | paste-image-here | paste-image-here |
| `DOWN` | paste-image-here | paste-image-here |
| Certificate-expiry | paste-image-here | paste-image-here |
| Testing | paste-image-here | paste-image-here |
```
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>new monitoring types</b></summary>
<p>
To set up a new notification provider these files need to be modified/created:
- `server/monitor-types/MONITORING_TYPE.js` is the core of each monitor.
the `async check(...)`-function should:
- throw an error for each fault that is detected with an actionable error message
- in the happy-path, you should set `heartbeat.msg` to a successfull message and set `heartbeat.status = UP`
- `server/uptime-kuma-server.js` is where the monitoring backend needs to be registered.
*If you have an idea how we can skip this step, we would love to hear about it ^^*
- `src/pages/EditMonitor.vue` is the shared frontend users interact with.
Please make sure that you have:
- used `HiddenInput` for secret credentials
- included all the necessary helptexts/placeholder/.. to make sure the notification provider is simple to setup for new users.
- include all translations (`{{ $t("Translation key") }}`, [`i18n-t keypath="Translation key">`](https://vue-i18n.intlify.dev/guide/advanced/component.html)) in `src/lang/en.json` to enable our translators to translate this
-
<sub>Because maintainer time is precious junior maintainers may merge uncontroversial PRs in this area.</sub>
</p>
</details>
- <details><summary><b>new features/ major changes / breaking bugfixes</b></summary>
<p>
be sure to **create an empty draft pull request or open an issue, so we can have a discussion first**.
This is especially important for a large pull request or you don't know if it will be merged or not.
<sub>Because of the large impact of this work, only senior maintainers may merge PRs in this area.</sub>
</p>
</details>
The following rules are essential for making your PR mergable:
- Merging multiple issues by a huge PR is more difficult to review and causes conflicts with other PRs. Please
- (if possible) **create one PR for one issue** or
- (if not possible) **explain which issues a PR addresses and why this PR should not be broken apart**
- Make sure your **PR passes our continuous integration**.
PRs will not be merged unless all CI-Checks are green.
- **Breaking changes** (unless for a good reason and discussed beforehand) will not get merged / not get merged quickly.
Such changes require a major version release.
- **Test your code** before submitting a PR.
Buggy PRs will not be merged.
- Make sure the **UI/UX is close to Uptime Kuma**.
- **Think about the maintainability**:
Don't add functionality that is completely **out of scope**.
Keep in mind that we need to be able to maintain the functionality.
- Don't modify or delete existing logic without a valid reason.
- Don't convert existing code into other programming languages for no reason.
I ([@louislam](https://github.com/louislam)) have the final say.
If your pull request does not meet my expectations, I will reject it, no matter how much time you spent on it.
Therefore, it is essential to have a discussion beforehand.
- A dedicated PR for translating existing languages (see [these instructions](https://github.com/louislam/uptime-kuma/blob/master/src/lang/README.md)) I will assign your pull request to a [milestone](https://github.com/louislam/uptime-kuma/milestones), if I plan to review and merge it.
- Do not pass the auto-test
- Any breaking changes
- Duplicated pull requests
- Buggy
- UI/UX is not close to Uptime Kuma
- Modifications or deletions of existing logic without a valid reason.
- Adding functions that is completely out of scope
- Converting existing code into other programming languages
- Unnecessarily large code changes that are hard to review and cause conflicts with other PRs.
The above cases may not cover all possible situations. Please don't rush or ask for an ETA.
We have to understand the pull request, make sure it has no breaking changes and stick to the vision of this project, especially for large pull requests.
I ([@louislam](https://github.com/louislam)) have the final say. If your pull request does not meet my expectations, I will reject it, no matter how much time you spent on it. Therefore, it is essential to have a discussion beforehand.
I will assign your pull request to a [milestone](https://github.com/louislam/uptime-kuma/milestones), if I plan to review and merge it. ## I'd like to work on an issue. How do I do that?
Also, please don't rush or ask for an ETA, because I have to understand the pull request, make sure it is no breaking changes and stick to my vision of this project, especially for large pull requests. We have found that assigning people to issues is management-overhead that we don't need.
A short comment that you want to try your hand at this issue is appreciated to save other devs time.
If you come across any problem during development, feel free to leave a comment with what you are stuck on.
### Recommended Pull Request Guideline ### Recommended Pull Request Guideline
Before deep into coding, discussion first is preferred. Creating an empty pull request for discussion would be recommended. Before diving deep into coding, having a discussion first by creating an empty pull request for discussion is preferred.
The rationale behind this is that we can align the direction and scope of the feature to eliminate any conflicts with existing and planned work, and can help by pointing out any potential pitfalls.
1. Fork the project 1. Fork the project
2. Clone your fork repo to local 2. Clone your fork repo to local
@ -84,10 +201,16 @@ Before deep into coding, discussion first is preferred. Creating an empty pull r
## Project Styles ## Project Styles
I personally do not like something that requires so many configurations before you can finally start the app. I hope Uptime Kuma installation will be as easy as like installing a mobile app. I personally do not like something that requires so many configurations before you can finally start the app.
The goal is to make the Uptime Kuma installation as easy as installing a mobile app.
- Easy to install for non-Docker users, no native build dependency is needed (for x86_64/armv7/arm64), no extra config, and no extra effort required to get it running - Easy to install for non-Docker users
- Single container for Docker users, no very complex docker-compose file. Just map the volume and expose the port, then good to go - no native build dependency is needed (for `x86_64`/`armv7`/`arm64`)
- no extra configuration and
- no extra effort required to get it running
- Single container for Docker users
- no complex docker-compose file
- mapping the volume and exposing the port should be the only requirements
- Settings should be configurable in the frontend. Environment variables are discouraged, unless it is related to startup such as `DATA_DIR` - Settings should be configurable in the frontend. Environment variables are discouraged, unless it is related to startup such as `DATA_DIR`
- Easy to use - Easy to use
- The web UI styling should be consistent and nice - The web UI styling should be consistent and nice
@ -107,8 +230,8 @@ I personally do not like something that requires so many configurations before y
## Tools ## Tools
- [`Node.js`](https://nodejs.org/) >= 14 - [`Node.js`](https://nodejs.org/) >= 18
- [`npm`](https://www.npmjs.com/) >= 8.5 - [`npm`](https://www.npmjs.com/) >= 9.3
- [`git`](https://git-scm.com/) - [`git`](https://git-scm.com/)
- IDE that supports [`ESLint`](https://eslint.org/) and EditorConfig (I am using [`IntelliJ IDEA`](https://www.jetbrains.com/idea/)) - IDE that supports [`ESLint`](https://eslint.org/) and EditorConfig (I am using [`IntelliJ IDEA`](https://www.jetbrains.com/idea/))
- A SQLite GUI tool (f.ex. [`SQLite Expert Personal`](https://www.sqliteexpert.com/download.html) or [`DBeaver Community`](https://dbeaver.io/download/)) - A SQLite GUI tool (f.ex. [`SQLite Expert Personal`](https://www.sqliteexpert.com/download.html) or [`DBeaver Community`](https://dbeaver.io/download/))
@ -154,25 +277,25 @@ npm run start-server-dev
It binds to `0.0.0.0:3001` by default. It binds to `0.0.0.0:3001` by default.
It is mainly a socket.io app + express.js. The backend is an `express.js` server with `socket.io` integrated.
It uses `socket.io` to communicate with clients, and most server logic is encapsulated in the `socket.io` handlers.
`express.js` is also used to serve:
express.js is used for: - as an entry point for redirecting to a status page or the dashboard
- the frontend built files (`index.html`, `*.js`, `*.css`, etc.)
- internal APIs of the status page
- entry point such as redirecting to a status page or the dashboard ### Structure in `/server/`
- serving the frontend built files (index.html, .js and .css etc.)
- serving internal APIs of the status page
### Structure in /server/ - `jobs/` (Jobs that are running in another process)
- `model/` (Object model, auto-mapping to the database table name)
- jobs/ (Jobs that are running in another process) - `modules/` (Modified 3rd-party modules)
- model/ (Object model, auto-mapping to the database table name) - `monitor_types/` (Monitor Types)
- modules/ (Modified 3rd-party modules) - `notification-providers/` (individual notification logic)
- monitor_types (Monitor Types) - `routers/` (Express Routers)
- notification-providers/ (individual notification logic) - `socket-handler/` (Socket.io Handlers)
- routers/ (Express Routers) - `server.js` (Server entry point)
- socket-handler (Socket.io Handlers) - `uptime-kuma-server.js` (UptimeKumaServer class, main logic should be here, but some still in `server.js`)
- server.js (Server entry point)
- uptime-kuma-server.js (UptimeKumaServer class, main logic should be here, but some still in `server.js`)
## Frontend Dev Server ## Frontend Dev Server
@ -211,14 +334,15 @@ npm test
## Dependencies ## Dependencies
Both frontend and backend share the same package.json. However, the frontend dependencies are eventually not used in the production environment, because it is usually also baked into dist files. So: Both frontend and backend share the same `package.json`.
However, the frontend dependencies are eventually not used in the production environment, because it is usually also baked into `dist` files. So:
- Frontend dependencies = "devDependencies" - Frontend dependencies = "devDependencies"
- Examples: vue, chart.js - Examples: `vue`, `chart.js`
- Backend dependencies = "dependencies" - Backend dependencies = "dependencies"
- Examples: socket.io, sqlite3 - Examples: `socket.io`, `sqlite3`
- Development dependencies = "devDependencies" - Development dependencies = "devDependencies"
- Examples: eslint, sass - Examples: `eslint`, `sass`
### Update Dependencies ### Update Dependencies
@ -289,54 +413,105 @@ https://github.com/louislam/uptime-kuma-wiki
Check the latest issues and pull requests: Check the latest issues and pull requests:
https://github.com/louislam/uptime-kuma/issues?q=sort%3Aupdated-desc https://github.com/louislam/uptime-kuma/issues?q=sort%3Aupdated-desc
### Release Procedures ### What is a maintainer and what are their roles?
1. Draft a release note This project has multiple maintainers which specialise in different areas.
2. Make sure the repo is cleared Currently, there are 3 maintainers:
3. If the healthcheck is updated, remember to re-compile it: `npm run build-docker-builder-go`
4. `npm run release-final` with env vars: `VERSION` and `GITHUB_TOKEN` | Person | Role | Main Area |
5. Wait until the `Press any key to continue` |-------------------|-------------------|------------------|
6. `git push` | `@louislam` | senior maintainer | major features |
7. Publish the release note as 1.X.X | `@chakflying` | junior maintainer | fixing bugs |
8. Press any key to continue | `@commanderstorm` | junior maintainer | issue-management |
9. Deploy to the demo server: `npm run deploy-demo-server`
### Procedures
Checking:
We have a few procedures we follow. These are documented here:
- Check all tags is fine on https://hub.docker.com/r/louislam/uptime-kuma/tags
- Try the Docker image with tag 1.X.X (Clean install / amd64 / arm64 / armv7) - <details><summary>Release</summary>
- Try clean installation with Node.js <p>
### Release Beta Procedures 1. Draft a release note
2. Make sure the repo is cleared
1. Draft a release note, check "This is a pre-release" 3. If the healthcheck is updated, remember to re-compile it: `npm run build-docker-builder-go`
2. Make sure the repo is cleared 4. `npm run release-final` with env vars: `VERSION` and `GITHUB_TOKEN`
3. `npm run release-beta` with env vars: `VERSION` and `GITHUB_TOKEN` 5. Wait until the `Press any key to continue`
4. Wait until the `Press any key to continue` 6. `git push`
5. Publish the release note as 1.X.X-beta.X 7. Publish the release note as `1.X.X`
6. Press any key to continue 8. Press any key to continue
9. Deploy to the demo server: `npm run deploy-demo-server`
### Release Wiki
These Items need to be checked:
#### Setup Repo
- [ ] Check all tags is fine on https://hub.docker.com/r/louislam/uptime-kuma/tags
```bash - [ ] Try the Docker image with tag 1.X.X (Clean install / amd64 / arm64 / armv7)
git clone https://github.com/louislam/uptime-kuma-wiki.git - [ ] Try clean installation with Node.js
cd uptime-kuma-wiki
git remote add production https://github.com/louislam/uptime-kuma.wiki.git </p>
``` </details>
- <details><summary>Release Beta</summary>
#### Push to Production Wiki <p>
```bash 1. Draft a release note, check `This is a pre-release`
git pull 2. Make sure the repo is cleared
git push production master 3. `npm run release-beta` with env vars: `VERSION` and `GITHUB_TOKEN`
``` 4. Wait until the `Press any key to continue`
5. Publish the release note as `1.X.X-beta.X`
## Useful Commands 6. Press any key to continue
Change the base of a pull request such as `master` to `1.23.X` </p>
</details>
```bash - <details><summary>Release Wiki</summary>
git rebase --onto <new parent> <old parent> <p>
```
**Setup Repo**
```bash
git clone https://github.com/louislam/uptime-kuma-wiki.git
cd uptime-kuma-wiki
git remote add production https://github.com/louislam/uptime-kuma.wiki.git
```
**Push to Production Wiki**
```bash
git pull
git push production master
```
</p>
</details>
- <details><summary>Change the base of a pull request such as <code>master</code> to <code>1.23.X</code></summary>
<p>
```bash
git rebase --onto <new parent> <old parent>
```
</p>
</details>
### Set up a Docker Builder
- amd64, armv7 using local.
- arm64 using remote arm64 cpu, as the emulator is too slow and can no longer pass the `npm ci` command.
1. Add the public key to the remote server.
2. Add the remote context. The remote machine must be arm64 and installed Docker CE.
```
docker context create oracle-arm64-jp --docker "host=ssh://root@100.107.174.88"
```
3. Create a new builder.
```
docker buildx create --name kuma-builder --platform linux/amd64,linux/arm/v7
docker buildx use kuma-builder
docker buildx inspect --bootstrap
```
4. Append the remote context to the builder.
```
docker buildx create --append --name kuma-builder --platform linux/arm64 oracle-arm64-jp
```
5. Verify the builder and check if the builder is using `kuma-builder`.
```
docker buildx inspect kuma-builder
docker buildx ls
```

@ -6,7 +6,7 @@
Uptime Kuma is an easy-to-use self-hosted monitoring tool. Uptime Kuma is an easy-to-use self-hosted monitoring tool.
<a target="_blank" href="https://github.com/louislam/uptime-kuma"><img src="https://img.shields.io/github/stars/louislam/uptime-kuma" /></a> <a target="_blank" href="https://hub.docker.com/r/louislam/uptime-kuma"><img src="https://img.shields.io/docker/pulls/louislam/uptime-kuma" /></a> <a target="_blank" href="https://hub.docker.com/r/louislam/uptime-kuma"><img src="https://img.shields.io/docker/v/louislam/uptime-kuma/latest?label=docker%20image%20ver." /></a> <a target="_blank" href="https://github.com/louislam/uptime-kuma"><img src="https://img.shields.io/github/last-commit/louislam/uptime-kuma" /></a> <a target="_blank" href="https://opencollective.com/uptime-kuma"><img src="https://opencollective.com/uptime-kuma/total/badge.svg?label=Open%20Collective%20Backers&color=brightgreen" /></a> <a target="_blank" href="https://github.com/louislam/uptime-kuma"><img src="https://img.shields.io/github/stars/louislam/uptime-kuma?style=flat" /></a> <a target="_blank" href="https://hub.docker.com/r/louislam/uptime-kuma"><img src="https://img.shields.io/docker/pulls/louislam/uptime-kuma" /></a> <a target="_blank" href="https://hub.docker.com/r/louislam/uptime-kuma"><img src="https://img.shields.io/docker/v/louislam/uptime-kuma/latest?label=docker%20image%20ver." /></a> <a target="_blank" href="https://github.com/louislam/uptime-kuma"><img src="https://img.shields.io/github/last-commit/louislam/uptime-kuma" /></a> <a target="_blank" href="https://opencollective.com/uptime-kuma"><img src="https://opencollective.com/uptime-kuma/total/badge.svg?label=Open%20Collective%20Backers&color=brightgreen" /></a>
[![GitHub Sponsors](https://img.shields.io/github/sponsors/louislam?label=GitHub%20Sponsors)](https://github.com/sponsors/louislam) <a href="https://weblate.kuma.pet/projects/uptime-kuma/uptime-kuma/"> [![GitHub Sponsors](https://img.shields.io/github/sponsors/louislam?label=GitHub%20Sponsors)](https://github.com/sponsors/louislam) <a href="https://weblate.kuma.pet/projects/uptime-kuma/uptime-kuma/">
<img src="https://weblate.kuma.pet/widgets/uptime-kuma/-/svg-badge.svg" alt="Translation status" /> <img src="https://weblate.kuma.pet/widgets/uptime-kuma/-/svg-badge.svg" alt="Translation status" />
</a> </a>
@ -17,9 +17,9 @@ Uptime Kuma is an easy-to-use self-hosted monitoring tool.
Try it! Try it!
- Tokyo Demo Server: https://demo.uptime.kuma.pet (Sponsored by [Uptime Kuma Sponsors](https://github.com/louislam/uptime-kuma#%EF%B8%8F-sponsors)) Demo Server (Location: Frankfurt - Germany): https://demo.kuma.pet/start-demo
It is a temporary live demo, all data will be deleted after 10 minutes. Use the one that is closer to you, but I suggest that you should install and try it out for the best demo experience. It is a temporary live demo, all data will be deleted after 10 minutes. Sponsored by [Uptime Kuma Sponsors](https://github.com/louislam/uptime-kuma#%EF%B8%8F-sponsors).
## ⭐ Features ## ⭐ Features
@ -56,15 +56,12 @@ Requirements:
- ✅ Major Linux distros such as Debian, Ubuntu, CentOS, Fedora and ArchLinux etc. - ✅ Major Linux distros such as Debian, Ubuntu, CentOS, Fedora and ArchLinux etc.
- ✅ Windows 10 (x64), Windows Server 2012 R2 (x64) or higher - ✅ Windows 10 (x64), Windows Server 2012 R2 (x64) or higher
- ❌ Replit / Heroku - ❌ Replit / Heroku
- [Node.js](https://nodejs.org/en/download/) 14 / 16 / 18 / 20.4 - [Node.js](https://nodejs.org/en/download/) 18 / 20.4
- [npm](https://docs.npmjs.com/cli/) 9 - [npm](https://docs.npmjs.com/cli/) 9
- [Git](https://git-scm.com/downloads) - [Git](https://git-scm.com/downloads)
- [pm2](https://pm2.keymetrics.io/) - For running Uptime Kuma in the background - [pm2](https://pm2.keymetrics.io/) - For running Uptime Kuma in the background
```bash ```bash
# Update your npm
npm install npm@9 -g
git clone https://github.com/louislam/uptime-kuma.git git clone https://github.com/louislam/uptime-kuma.git
cd uptime-kuma cd uptime-kuma
npm run setup npm run setup

@ -0,0 +1,9 @@
services:
uptime-kuma:
image: louislam/uptime-kuma:1
volumes:
- ./data:/app/data
ports:
# <Host Port>:<Container Port>
- 3001:3001
restart: unless-stopped

@ -2,6 +2,7 @@ import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
import visualizer from "rollup-plugin-visualizer"; import visualizer from "rollup-plugin-visualizer";
import viteCompression from "vite-plugin-compression"; import viteCompression from "vite-plugin-compression";
import VueDevTools from "vite-plugin-vue-devtools";
const postCssScss = require("postcss-scss"); const postCssScss = require("postcss-scss");
const postcssRTLCSS = require("postcss-rtlcss"); const postcssRTLCSS = require("postcss-rtlcss");
@ -32,6 +33,7 @@ export default defineConfig({
algorithm: "brotliCompress", algorithm: "brotliCompress",
filter: viteCompressionFilter, filter: viteCompressionFilter,
}), }),
VueDevTools(),
], ],
css: { css: {
postcss: { postcss: {

@ -318,7 +318,10 @@ async function createTables() {
// monitor_tls_info // monitor_tls_info
await knex.schema.createTable("monitor_tls_info", (table) => { await knex.schema.createTable("monitor_tls_info", (table) => {
table.increments("id"); table.increments("id");
table.integer("monitor_id").unsigned().notNullable(); //TODO: no fk ? table.integer("monitor_id").unsigned().notNullable()
.references("id").inTable("monitor")
.onDelete("CASCADE")
.onUpdate("CASCADE");
table.text("info_json"); table.text("info_json");
}); });

@ -0,0 +1,24 @@
exports.up = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds");
table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds");
})
.alterTable("stat_minutely", function (table) {
table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds");
table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds");
});
};
exports.down = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.dropColumn("ping_min");
table.dropColumn("ping_max");
})
.alterTable("stat_minutely", function (table) {
table.dropColumn("ping_min");
table.dropColumn("ping_max");
});
};

@ -0,0 +1,26 @@
exports.up = function (knex) {
return knex.schema
.createTable("stat_hourly", function (table) {
table.increments("id");
table.comment("This table contains the hourly aggregate statistics for each monitor");
table.integer("monitor_id").unsigned().notNullable()
.references("id").inTable("monitor")
.onDelete("CASCADE")
.onUpdate("CASCADE");
table.integer("timestamp")
.notNullable()
.comment("Unix timestamp rounded down to the nearest hour");
table.float("ping").notNullable().comment("Average ping in milliseconds");
table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds");
table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds");
table.smallint("up").notNullable();
table.smallint("down").notNullable();
table.unique([ "monitor_id", "timestamp" ]);
});
};
exports.down = function (knex) {
return knex.schema
.dropTable("stat_hourly");
};

@ -0,0 +1,26 @@
exports.up = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
})
.alterTable("stat_minutely", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
})
.alterTable("stat_hourly", function (table) {
table.text("extras").defaultTo(null).comment("Extra statistics during this time period");
});
};
exports.down = function (knex) {
return knex.schema
.alterTable("stat_daily", function (table) {
table.dropColumn("extras");
})
.alterTable("stat_minutely", function (table) {
table.dropColumn("extras");
})
.alterTable("stat_hourly", function (table) {
table.dropColumn("extras");
});
};

@ -0,0 +1,18 @@
BEGIN TRANSACTION;
PRAGMA writable_schema = TRUE;
UPDATE
SQLITE_MASTER
SET
sql = replace(sql,
'monitor_id INTEGER NOT NULL',
'monitor_id INTEGER NOT NULL REFERENCES [monitor] ([id]) ON DELETE CASCADE ON UPDATE CASCADE'
)
WHERE
name = 'monitor_tls_info'
AND type = 'table';
PRAGMA writable_schema = RESET;
COMMIT;

@ -1,15 +0,0 @@
version: '3.8'
services:
uptime-kuma:
image: louislam/uptime-kuma:1
container_name: uptime-kuma
volumes:
- uptime-kuma:/app/data
ports:
- "3001:3001" # <Host Port>:<Container Port>
restart: always
volumes:
uptime-kuma:

@ -37,7 +37,7 @@ const github = require("@actions/github");
owner: issue.owner, owner: issue.owner,
repo: issue.repo, repo: issue.repo,
issue_number: issue.number, issue_number: issue.number,
body: `@${username}: Hello! :wave:\n\nThis issue is being automatically closed because it does not follow the issue template. Please DO NOT open a blank issue.` body: `@${username}: Hello! :wave:\n\nThis issue is being automatically closed because it does not follow the issue template. Please **DO NOT open blank issues and use our [issue-templates](https://github.com/louislam/uptime-kuma/issues/new/choose) instead**.\nBlank Issues do not contain the context nessesary for a good discussions.`
}); });
// Close the issue // Close the issue

@ -8,6 +8,7 @@ const User = require("../server/model/user");
const { io } = require("socket.io-client"); const { io } = require("socket.io-client");
const { localWebSocketURL } = require("../server/config"); const { localWebSocketURL } = require("../server/config");
const args = require("args-parser")(process.argv); const args = require("args-parser")(process.argv);
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout output: process.stdout
@ -19,10 +20,10 @@ const main = async () => {
} }
console.log("Connecting the database"); console.log("Connecting the database");
Database.initDataDir(args);
await Database.connect(false, false, true);
try { try {
Database.initDataDir(args);
await Database.connect(false, false, true);
// No need to actually reset the password for testing, just make sure no connection problem. It is ok for now. // No need to actually reset the password for testing, just make sure no connection problem. It is ok for now.
if (!process.env.TEST_BACKEND) { if (!process.env.TEST_BACKEND) {
const user = await R.findOne("user"); const user = await R.findOne("user");

6714
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -7,7 +7,7 @@
"url": "https://github.com/louislam/uptime-kuma.git" "url": "https://github.com/louislam/uptime-kuma.git"
}, },
"engines": { "engines": {
"node": "14 || 16 || 18 || >= 20.4.0" "node": "18 || >= 20.4.0"
}, },
"scripts": { "scripts": {
"lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .", "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
@ -49,7 +49,7 @@
"build-docker-nightly-local": "npm run build && docker build -f docker/dockerfile -t louislam/uptime-kuma:nightly2 --target nightly .", "build-docker-nightly-local": "npm run build && docker build -f docker/dockerfile -t louislam/uptime-kuma:nightly2 --target nightly .",
"build-docker-pr-test": "docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64 -t louislam/uptime-kuma:pr-test2 --target pr-test2 . --push", "build-docker-pr-test": "docker buildx build -f docker/dockerfile --platform linux/amd64,linux/arm64 -t louislam/uptime-kuma:pr-test2 --target pr-test2 . --push",
"upload-artifacts": "docker buildx build -f docker/dockerfile --platform linux/amd64 -t louislam/uptime-kuma:upload-artifact --build-arg VERSION --build-arg GITHUB_TOKEN --target upload-artifact . --progress plain", "upload-artifacts": "docker buildx build -f docker/dockerfile --platform linux/amd64 -t louislam/uptime-kuma:upload-artifact --build-arg VERSION --build-arg GITHUB_TOKEN --target upload-artifact . --progress plain",
"setup": "git checkout 1.23.10 && npm ci --production && npm run download-dist", "setup": "git checkout 1.23.11 && npm ci --production && npm run download-dist",
"download-dist": "node extra/download-dist.js", "download-dist": "node extra/download-dist.js",
"mark-as-nightly": "node extra/mark-as-nightly.js", "mark-as-nightly": "node extra/mark-as-nightly.js",
"reset-password": "node extra/reset-password.js", "reset-password": "node extra/reset-password.js",
@ -77,8 +77,9 @@
"@grpc/grpc-js": "~1.7.3", "@grpc/grpc-js": "~1.7.3",
"@louislam/ping": "~0.4.4-mod.1", "@louislam/ping": "~0.4.4-mod.1",
"@louislam/sqlite3": "15.1.6", "@louislam/sqlite3": "15.1.6",
"@vvo/tzdb": "^6.125.0",
"args-parser": "~1.3.0", "args-parser": "~1.3.0",
"axios": "~0.27.0", "axios": "~0.28.0",
"axios-ntlm": "1.3.0", "axios-ntlm": "1.3.0",
"badge-maker": "~3.3.1", "badge-maker": "~3.3.1",
"bcryptjs": "~2.4.3", "bcryptjs": "~2.4.3",
@ -92,7 +93,7 @@
"croner": "~6.0.5", "croner": "~6.0.5",
"dayjs": "~1.11.5", "dayjs": "~1.11.5",
"dotenv": "~16.0.3", "dotenv": "~16.0.3",
"express": "~4.17.3", "express": "~4.19.2",
"express-basic-auth": "~1.2.1", "express-basic-auth": "~1.2.1",
"express-static-gzip": "~2.1.7", "express-static-gzip": "~2.1.7",
"form-data": "~4.0.0", "form-data": "~4.0.0",
@ -120,7 +121,7 @@
"nanoid": "~3.3.4", "nanoid": "~3.3.4",
"node-cloudflared-tunnel": "~1.0.9", "node-cloudflared-tunnel": "~1.0.9",
"node-radius-client": "~1.0.0", "node-radius-client": "~1.0.0",
"nodemailer": "~6.6.5", "nodemailer": "~6.9.13",
"nostr-tools": "^1.13.1", "nostr-tools": "^1.13.1",
"notp": "~2.0.3", "notp": "~2.0.3",
"openid-client": "^5.4.2", "openid-client": "^5.4.2",
@ -157,8 +158,8 @@
"@types/node": "^20.8.6", "@types/node": "^20.8.6",
"@typescript-eslint/eslint-plugin": "^6.7.5", "@typescript-eslint/eslint-plugin": "^6.7.5",
"@typescript-eslint/parser": "^6.7.5", "@typescript-eslint/parser": "^6.7.5",
"@vitejs/plugin-vue": "~4.2.3", "@vitejs/plugin-vue": "~5.0.1",
"@vue/compiler-sfc": "~3.3.4", "@vue/compiler-sfc": "~3.4.2",
"@vuepic/vue-datepicker": "~3.4.8", "@vuepic/vue-datepicker": "~3.4.8",
"aedes": "^0.46.3", "aedes": "^0.46.3",
"bootstrap": "5.1.3", "bootstrap": "5.1.3",
@ -189,12 +190,12 @@
"stylelint-config-standard": "~25.0.0", "stylelint-config-standard": "~25.0.0",
"terser": "~5.15.0", "terser": "~5.15.0",
"test": "~3.3.0", "test": "~3.3.0",
"timezones-list": "~3.0.1",
"typescript": "~4.4.4", "typescript": "~4.4.4",
"v-pagination-3": "~0.1.7", "v-pagination-3": "~0.1.7",
"vite": "~4.4.1", "vite": "~5.0.10",
"vite-plugin-compression": "^0.5.1", "vite-plugin-compression": "^0.5.1",
"vue": "~3.3.4", "vite-plugin-vue-devtools": "^7.0.15",
"vue": "~3.4.2",
"vue-chartjs": "~5.2.0", "vue-chartjs": "~5.2.0",
"vue-confirm-dialog": "~1.0.2", "vue-confirm-dialog": "~1.0.2",
"vue-contenteditable": "~3.0.4", "vue-contenteditable": "~3.0.4",
@ -203,7 +204,7 @@
"vue-multiselect": "~3.0.0-alpha.2", "vue-multiselect": "~3.0.0-alpha.2",
"vue-prism-editor": "~2.0.0-alpha.2", "vue-prism-editor": "~2.0.0-alpha.2",
"vue-qrcode": "~1.0.0", "vue-qrcode": "~1.0.0",
"vue-router": "~4.0.14", "vue-router": "~4.2.5",
"vue-toastification": "~2.0.0-rc.5", "vue-toastification": "~2.0.0-rc.5",
"vuedraggable": "~4.1.0", "vuedraggable": "~4.1.0",
"wait-on": "^7.2.0", "wait-on": "^7.2.0",

@ -130,7 +130,7 @@ function userAuthorizer(username, password, callback) {
* @param {express.Request} req Express request object * @param {express.Request} req Express request object
* @param {express.Response} res Express response object * @param {express.Response} res Express response object
* @param {express.NextFunction} next Next handler in chain * @param {express.NextFunction} next Next handler in chain
* @returns {void} * @returns {Promise<void>}
*/ */
exports.basicAuth = async function (req, res, next) { exports.basicAuth = async function (req, res, next) {
const middleware = basicAuth({ const middleware = basicAuth({
@ -153,7 +153,7 @@ exports.basicAuth = async function (req, res, next) {
* @param {express.Request} req Express request object * @param {express.Request} req Express request object
* @param {express.Response} res Express response object * @param {express.Response} res Express response object
* @param {express.NextFunction} next Next handler in chain * @param {express.NextFunction} next Next handler in chain
* @returns {void} * @returns {Promise<void>}
*/ */
exports.apiAuth = async function (req, res, next) { exports.apiAuth = async function (req, res, next) {
if (!await Settings.get("disableAuth")) { if (!await Settings.get("disableAuth")) {

@ -8,6 +8,7 @@ const server = UptimeKumaServer.getInstance();
const io = server.io; const io = server.io;
const { setting } = require("./util-server"); const { setting } = require("./util-server");
const checkVersion = require("./check-version"); const checkVersion = require("./check-version");
const Database = require("./database");
/** /**
* Send list of notification providers to client * Send list of notification providers to client
@ -144,17 +145,20 @@ async function sendInfo(socket, hideVersion = false) {
let version; let version;
let latestVersion; let latestVersion;
let isContainer; let isContainer;
let dbType;
if (!hideVersion) { if (!hideVersion) {
version = checkVersion.version; version = checkVersion.version;
latestVersion = checkVersion.latestVersion; latestVersion = checkVersion.latestVersion;
isContainer = (process.env.UPTIME_KUMA_IS_CONTAINER === "1"); isContainer = (process.env.UPTIME_KUMA_IS_CONTAINER === "1");
dbType = Database.dbConfig.type;
} }
socket.emit("info", { socket.emit("info", {
version, version,
latestVersion, latestVersion,
isContainer, isContainer,
dbType,
primaryBaseURL: await setting("primaryBaseURL"), primaryBaseURL: await setting("primaryBaseURL"),
serverTimezone: await server.getTimezone(), serverTimezone: await server.getTimezone(),
serverTimezoneOffset: server.getTimezoneOffset(), serverTimezoneOffset: server.getTimezoneOffset(),

@ -105,7 +105,8 @@ class Database {
"patch-add-gamedig-given-port.sql": true, "patch-add-gamedig-given-port.sql": true,
"patch-notification-config.sql": true, "patch-notification-config.sql": true,
"patch-fix-kafka-producer-booleans.sql": true, "patch-fix-kafka-producer-booleans.sql": true,
"patch-timeout.sql": true, // The last file so far converted to a knex migration file "patch-timeout.sql": true,
"patch-monitor-tls-info-add-fk.sql": true, // The last file so far converted to a knex migration file
}; };
/** /**
@ -378,7 +379,7 @@ class Database {
/** /**
* Patch the database * Patch the database
* @returns {void} * @returns {Promise<void>}
*/ */
static async patch() { static async patch() {
// Still need to keep this for old versions of Uptime Kuma // Still need to keep this for old versions of Uptime Kuma

@ -65,7 +65,7 @@ class DockerHost {
/** /**
* Fetches the amount of containers on the Docker host * Fetches the amount of containers on the Docker host
* @param {object} dockerHost Docker host to check for * @param {object} dockerHost Docker host to check for
* @returns {number} Total amount of containers on the host * @returns {Promise<number>} Total amount of containers on the host
*/ */
static async testDockerHost(dockerHost) { static async testDockerHost(dockerHost) {
const options = { const options = {

@ -9,7 +9,7 @@ class Group extends BeanModel {
* @param {boolean} showTags Should the JSON include monitor tags * @param {boolean} showTags Should the JSON include monitor tags
* @param {boolean} certExpiry Should JSON include info about * @param {boolean} certExpiry Should JSON include info about
* certificate expiry? * certificate expiry?
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON(showTags = false, certExpiry = false) { async toPublicJSON(showTags = false, certExpiry = false) {
let monitorBeanList = await this.getMonitorList(); let monitorBeanList = await this.getMonitorList();
@ -29,7 +29,7 @@ class Group extends BeanModel {
/** /**
* Get all monitors * Get all monitors
* @returns {Bean[]} List of monitors * @returns {Promise<Bean[]>} List of monitors
*/ */
async getMonitorList() { async getMonitorList() {
return R.convertToBeans("monitor", await R.getAll(` return R.convertToBeans("monitor", await R.getAll(`

@ -11,7 +11,7 @@ class Maintenance extends BeanModel {
/** /**
* Return an object that ready to parse to JSON for public * Return an object that ready to parse to JSON for public
* Only show necessary data to public * Only show necessary data to public
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON() { async toPublicJSON() {
@ -98,7 +98,7 @@ class Maintenance extends BeanModel {
/** /**
* Return an object that ready to parse to JSON * Return an object that ready to parse to JSON
* @param {string} timezone If not specified, the timeRange will be in UTC * @param {string} timezone If not specified, the timeRange will be in UTC
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toJSON(timezone = null) { async toJSON(timezone = null) {
return this.toPublicJSON(timezone); return this.toPublicJSON(timezone);
@ -143,7 +143,7 @@ class Maintenance extends BeanModel {
* Convert data from socket to bean * Convert data from socket to bean
* @param {Bean} bean Bean to fill in * @param {Bean} bean Bean to fill in
* @param {object} obj Data to fill bean with * @param {object} obj Data to fill bean with
* @returns {Bean} Filled bean * @returns {Promise<Bean>} Filled bean
*/ */
static async jsonToBean(bean, obj) { static async jsonToBean(bean, obj) {
if (obj.id) { if (obj.id) {
@ -189,9 +189,9 @@ class Maintenance extends BeanModel {
/** /**
* Throw error if cron is invalid * Throw error if cron is invalid
* @param {string|Date} cron Pattern or date * @param {string|Date} cron Pattern or date
* @returns {Promise<void>} * @returns {void}
*/ */
static async validateCron(cron) { static validateCron(cron) {
let job = new Cron(cron, () => {}); let job = new Cron(cron, () => {});
job.stop(); job.stop();
} }
@ -324,7 +324,7 @@ class Maintenance extends BeanModel {
/** /**
* Is this maintenance currently active * Is this maintenance currently active
* @returns {boolean} The maintenance is active? * @returns {Promise<boolean>} The maintenance is active?
*/ */
async isUnderMaintenance() { async isUnderMaintenance() {
return (await this.getStatus()) === "under-maintenance"; return (await this.getStatus()) === "under-maintenance";
@ -332,7 +332,7 @@ class Maintenance extends BeanModel {
/** /**
* Get the timezone of the maintenance * Get the timezone of the maintenance
* @returns {string} timezone * @returns {Promise<string>} timezone
*/ */
async getTimezone() { async getTimezone() {
if (!this.timezone || this.timezone === "SAME_AS_SERVER") { if (!this.timezone || this.timezone === "SAME_AS_SERVER") {
@ -343,7 +343,7 @@ class Maintenance extends BeanModel {
/** /**
* Get offset for timezone * Get offset for timezone
* @returns {string} offset * @returns {Promise<string>} offset
*/ */
async getTimezoneOffset() { async getTimezoneOffset() {
return dayjs.tz(dayjs(), await this.getTimezone()).format("Z"); return dayjs.tz(dayjs(), await this.getTimezone()).format("Z");
@ -351,7 +351,7 @@ class Maintenance extends BeanModel {
/** /**
* Get the current status of the maintenance * Get the current status of the maintenance
* @returns {string} Current status * @returns {Promise<string>} Current status
*/ */
async getStatus() { async getStatus() {
if (!this.active) { if (!this.active) {

@ -43,7 +43,7 @@ class Monitor extends BeanModel {
* @param {boolean} showTags Include tags in JSON * @param {boolean} showTags Include tags in JSON
* @param {boolean} certExpiry Include certificate expiry info in * @param {boolean} certExpiry Include certificate expiry info in
* JSON * JSON
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toPublicJSON(showTags = false, certExpiry = false) { async toPublicJSON(showTags = false, certExpiry = false) {
let obj = { let obj = {
@ -74,7 +74,7 @@ class Monitor extends BeanModel {
* Return an object that ready to parse to JSON * Return an object that ready to parse to JSON
* @param {boolean} includeSensitiveData Include sensitive data in * @param {boolean} includeSensitiveData Include sensitive data in
* JSON * JSON
* @returns {object} Object ready to parse * @returns {Promise<object>} Object ready to parse
*/ */
async toJSON(includeSensitiveData = true) { async toJSON(includeSensitiveData = true) {
@ -96,11 +96,15 @@ class Monitor extends BeanModel {
screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png"; screenshot = "/screenshots/" + jwt.sign(this.id, UptimeKumaServer.getInstance().jwtSecret) + ".png";
} }
const path = await this.getPath();
const pathName = path.join(" / ");
let data = { let data = {
id: this.id, id: this.id,
name: this.name, name: this.name,
description: this.description, description: this.description,
pathName: await this.getPathName(), path,
pathName,
parent: this.parent, parent: this.parent,
childrenIDs: await Monitor.getAllChildrenIDs(this.id), childrenIDs: await Monitor.getAllChildrenIDs(this.id),
url: this.url, url: this.url,
@ -324,9 +328,9 @@ class Monitor extends BeanModel {
/** /**
* Start monitor * Start monitor
* @param {Server} io Socket server instance * @param {Server} io Socket server instance
* @returns {void} * @returns {Promise<void>}
*/ */
start(io) { async start(io) {
let previousBeat = null; let previousBeat = null;
let retries = 0; let retries = 0;
@ -943,7 +947,7 @@ class Monitor extends BeanModel {
log.debug("monitor", `[${this.name}] apicache clear`); log.debug("monitor", `[${this.name}] apicache clear`);
apicache.clear(); apicache.clear();
UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id); await UptimeKumaServer.getInstance().sendMaintenanceListByUserID(this.user_id);
} else { } else {
bean.important = false; bean.important = false;
@ -1098,9 +1102,9 @@ class Monitor extends BeanModel {
/** /**
* Stop monitor * Stop monitor
* @returns {void} * @returns {Promise<void>}
*/ */
stop() { async stop() {
clearTimeout(this.heartbeatInterval); clearTimeout(this.heartbeatInterval);
this.isStop = true; this.isStop = true;
@ -1373,7 +1377,7 @@ class Monitor extends BeanModel {
let notifyDays = await setting("tlsExpiryNotifyDays"); let notifyDays = await setting("tlsExpiryNotifyDays");
if (notifyDays == null || !Array.isArray(notifyDays)) { if (notifyDays == null || !Array.isArray(notifyDays)) {
// Reset Default // Reset Default
setSetting("tlsExpiryNotifyDays", [ 7, 14, 21 ], "general"); await setSetting("tlsExpiryNotifyDays", [ 7, 14, 21 ], "general");
notifyDays = [ 7, 14, 21 ]; notifyDays = [ 7, 14, 21 ];
} }
@ -1527,11 +1531,11 @@ class Monitor extends BeanModel {
} }
/** /**
* Gets Full Path-Name (Groups and Name) * Gets the full path
* @returns {Promise<string>} Full path name of this monitor * @returns {Promise<string[]>} Full path (includes groups and the name) of the monitor
*/ */
async getPathName() { async getPath() {
let path = this.name; const path = [ this.name ];
if (this.parent === null) { if (this.parent === null) {
return path; return path;
@ -1539,7 +1543,7 @@ class Monitor extends BeanModel {
let parent = await Monitor.getParent(this.id); let parent = await Monitor.getParent(this.id);
while (parent !== null) { while (parent !== null) {
path = `${parent.name} / ${path}`; path.unshift(parent.name);
parent = await Monitor.getParent(parent.id); parent = await Monitor.getParent(parent.id);
} }
@ -1569,7 +1573,7 @@ class Monitor extends BeanModel {
} }
/** /**
* Unlinks all children of the the group monitor * Unlinks all children of the group monitor
* @param {number} groupID ID of group to remove children of * @param {number} groupID ID of group to remove children of
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */

@ -18,7 +18,7 @@ class StatusPage extends BeanModel {
* @param {Response} response Response object * @param {Response} response Response object
* @param {string} indexHTML HTML to render * @param {string} indexHTML HTML to render
* @param {string} slug Status page slug * @param {string} slug Status page slug
* @returns {void} * @returns {Promise<void>}
*/ */
static async handleStatusPageResponse(response, indexHTML, slug) { static async handleStatusPageResponse(response, indexHTML, slug) {
// Handle url with trailing slash (http://localhost:3001/status/) // Handle url with trailing slash (http://localhost:3001/status/)
@ -42,7 +42,7 @@ class StatusPage extends BeanModel {
* SSR for status pages * SSR for status pages
* @param {string} indexHTML HTML page to render * @param {string} indexHTML HTML page to render
* @param {StatusPage} statusPage Status page populate HTML with * @param {StatusPage} statusPage Status page populate HTML with
* @returns {void} * @returns {Promise<string>} the rendered html
*/ */
static async renderHTML(indexHTML, statusPage) { static async renderHTML(indexHTML, statusPage) {
const $ = cheerio.load(indexHTML); const $ = cheerio.load(indexHTML);

@ -1,5 +1,4 @@
class MonitorType { class MonitorType {
name = undefined; name = undefined;
/** /**

@ -81,7 +81,8 @@ class MqttMonitorType extends MonitorType {
let client = mqtt.connect(mqttUrl, { let client = mqtt.connect(mqttUrl, {
username, username,
password password,
clientId: "uptime-kuma_" + Math.random().toString(16).substr(2, 8)
}); });
client.on("connect", () => { client.on("connect", () => {

@ -96,7 +96,7 @@ async function getBrowser() {
async function getRemoteBrowser(remoteBrowserID, userId) { async function getRemoteBrowser(remoteBrowserID, userId) {
let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId); let remoteBrowser = await RemoteBrowser.get(remoteBrowserID, userId);
log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`); log.debug("MONITOR", `Using remote browser: ${remoteBrowser.name} (${remoteBrowser.id})`);
browser = chromium.connect(remoteBrowser.url); browser = await chromium.connect(remoteBrowser.url);
return browser; return browser;
} }

@ -16,7 +16,7 @@ class TailscalePing extends MonitorType {
* @param {object} monitor The monitor object associated with the check. * @param {object} monitor The monitor object associated with the check.
* @param {object} heartbeat The heartbeat object to update. * @param {object} heartbeat The heartbeat object to update.
* @returns {Promise<void>} * @returns {Promise<void>}
* @throws Will throw an error if checking Tailscale ping encounters any error * @throws Error if checking Tailscale ping encounters any error
*/ */
async check(monitor, heartbeat) { async check(monitor, heartbeat) {
try { try {
@ -38,7 +38,8 @@ class TailscalePing extends MonitorType {
async runTailscalePing(hostname, interval) { async runTailscalePing(hostname, interval) {
let timeout = interval * 1000 * 0.8; let timeout = interval * 1000 * 0.8;
let res = await childProcessAsync.spawn("tailscale", [ "ping", "--c", "1", hostname ], { let res = await childProcessAsync.spawn("tailscale", [ "ping", "--c", "1", hostname ], {
timeout: timeout timeout: timeout,
encoding: "utf8",
}); });
if (res.stderr && res.stderr.toString()) { if (res.stderr && res.stderr.toString()) {
throw new Error(`Error in output: ${res.stderr.toString()}`); throw new Error(`Error in output: ${res.stderr.toString()}`);

@ -3,17 +3,15 @@ const { DOWN, UP } = require("../../src/util");
const axios = require("axios"); const axios = require("axios");
class Alerta extends NotificationProvider { class Alerta extends NotificationProvider {
name = "alerta"; name = "alerta";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let alertaUrl = `${notification.alertaApiEndpoint}`;
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json;charset=UTF-8", "Content-Type": "application/json;charset=UTF-8",
@ -40,7 +38,7 @@ class Alerta extends NotificationProvider {
resource: "Message", resource: "Message",
}, data); }, data);
await axios.post(alertaUrl, postData, config); await axios.post(notification.alertaApiEndpoint, postData, config);
} else { } else {
let datadup = Object.assign( { let datadup = Object.assign( {
correlate: [ "service_up", "service_down" ], correlate: [ "service_up", "service_down" ],
@ -52,11 +50,11 @@ class Alerta extends NotificationProvider {
if (heartbeatJSON["status"] === DOWN) { if (heartbeatJSON["status"] === DOWN) {
datadup.severity = notification.alertaAlertState; // critical datadup.severity = notification.alertaAlertState; // critical
datadup.text = "Service " + monitorJSON["type"] + " is down."; datadup.text = "Service " + monitorJSON["type"] + " is down.";
await axios.post(alertaUrl, datadup, config); await axios.post(notification.alertaApiEndpoint, datadup, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
datadup.severity = notification.alertaRecoverState; // cleaned datadup.severity = notification.alertaRecoverState; // cleaned
datadup.text = "Service " + monitorJSON["type"] + " is up."; datadup.text = "Service " + monitorJSON["type"] + " is up.";
await axios.post(alertaUrl, datadup, config); await axios.post(notification.alertaApiEndpoint, datadup, config);
} }
} }
return okMsg; return okMsg;

@ -4,14 +4,14 @@ const { setting } = require("../util-server");
const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util"); const { getMonitorRelativeURL, UP, DOWN } = require("../../src/util");
class AlertNow extends NotificationProvider { class AlertNow extends NotificationProvider {
name = "AlertNow"; name = "AlertNow";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let textMsg = ""; let textMsg = "";
let status = "open"; let status = "open";

@ -11,7 +11,7 @@ class AliyunSMS extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON != null) { if (heartbeatJSON != null) {
@ -44,7 +44,7 @@ class AliyunSMS extends NotificationProvider {
* Send the SMS notification * Send the SMS notification
* @param {BeanModel} notification Notification details * @param {BeanModel} notification Notification details
* @param {string} msgbody Message template * @param {string} msgbody Message template
* @returns {boolean} True if successful else false * @returns {Promise<boolean>} True if successful else false
*/ */
async sendSms(notification, msgbody) { async sendSms(notification, msgbody) {
let params = { let params = {

@ -2,26 +2,29 @@ const NotificationProvider = require("./notification-provider");
const childProcessAsync = require("promisify-child-process"); const childProcessAsync = require("promisify-child-process");
class Apprise extends NotificationProvider { class Apprise extends NotificationProvider {
name = "apprise"; name = "apprise";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const args = [ "-vv", "-b", msg, notification.appriseURL ]; const args = [ "-vv", "-b", msg, notification.appriseURL ];
if (notification.title) { if (notification.title) {
args.push("-t"); args.push("-t");
args.push(notification.title); args.push(notification.title);
} }
const s = await childProcessAsync.spawn("apprise", args); const s = await childProcessAsync.spawn("apprise", args, {
encoding: "utf8",
});
const output = (s.stdout) ? s.stdout.toString() : "ERROR: maybe apprise not found"; const output = (s.stdout) ? s.stdout.toString() : "ERROR: maybe apprise not found";
if (output) { if (output) {
if (! output.includes("ERROR")) { if (! output.includes("ERROR")) {
return "Sent Successfully"; return okMsg;
} }
throw new Error(output); throw new Error(output);

@ -46,29 +46,29 @@ class Bark extends NotificationProvider {
} }
/** /**
* Add additional parameter for Bark v1 endpoints * Add additional parameter for Bark v1 endpoints.
* Leads to better on device styles (iOS 15 optimized)
* @param {BeanModel} notification Notification to send * @param {BeanModel} notification Notification to send
* @param {string} postUrl URL to append parameters to
* @returns {string} Additional URL parameters * @returns {string} Additional URL parameters
*/ */
appendAdditionalParameters(notification, postUrl) { additionalParameters(notification) {
// set icon to uptime kuma icon, 11kb should be fine // set icon to uptime kuma icon, 11kb should be fine
postUrl += "?icon=" + barkNotificationAvatar; let params = "?icon=" + barkNotificationAvatar;
// grouping all our notifications // grouping all our notifications
if (notification.barkGroup != null) { if (notification.barkGroup != null) {
postUrl += "&group=" + notification.barkGroup; params += "&group=" + notification.barkGroup;
} else { } else {
// default name // default name
postUrl += "&group=" + "UptimeKuma"; params += "&group=" + "UptimeKuma";
} }
// picked a sound, this should follow system's mute status when arrival // picked a sound, this should follow system's mute status when arrival
if (notification.barkSound != null) { if (notification.barkSound != null) {
postUrl += "&sound=" + notification.barkSound; params += "&sound=" + notification.barkSound;
} else { } else {
// default sound // default sound
postUrl += "&sound=" + "telegraph"; params += "&sound=" + "telegraph";
} }
return postUrl; return params;
} }
/** /**
@ -92,7 +92,7 @@ class Bark extends NotificationProvider {
* @param {string} title Message title * @param {string} title Message title
* @param {string} subtitle Message * @param {string} subtitle Message
* @param {string} endpoint Endpoint to send request to * @param {string} endpoint Endpoint to send request to
* @returns {string} Success message * @returns {Promise<string>} Success message
*/ */
async postNotification(notification, title, subtitle, endpoint) { async postNotification(notification, title, subtitle, endpoint) {
let result; let result;
@ -100,9 +100,8 @@ class Bark extends NotificationProvider {
// url encode title and subtitle // url encode title and subtitle
title = encodeURIComponent(title); title = encodeURIComponent(title);
subtitle = encodeURIComponent(subtitle); subtitle = encodeURIComponent(subtitle);
let postUrl = endpoint + "/" + title + "/" + subtitle; const params = this.additionalParameters(notification);
postUrl = this.appendAdditionalParameters(notification, postUrl); result = await axios.get(`${endpoint}/${title}/${subtitle}${params}`);
result = await axios.get(postUrl);
} else { } else {
result = await axios.post(`${endpoint}/push`, { result = await axios.post(`${endpoint}/push`, {
title, title,

@ -0,0 +1,23 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class CallMeBot extends NotificationProvider {
name = "CallMeBot";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
const url = new URL(notification.callMeBotEndpoint);
url.searchParams.set("text", msg);
await axios.get(url.toString());
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = CallMeBot;

@ -0,0 +1,39 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class Cellsynt extends NotificationProvider {
name = "Cellsynt";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const data = {
// docs at https://www.cellsynt.com/en/sms/api-integration
params: {
"username": notification.cellsyntLogin,
"password": notification.cellsyntPassword,
"destination": notification.cellsyntDestination,
"text": msg.replace(/[^\x00-\x7F]/g, ""),
"originatortype": notification.cellsyntOriginatortype,
"originator": notification.cellsyntOriginator,
"allowconcat": notification.cellsyntAllowLongSMS ? 6 : 1
}
};
try {
const resp = await axios.post("https://se-1.cellsynt.net/sms.php", null, data);
if (resp.data == null ) {
throw new Error("Could not connect to Cellsynt, please try again.");
} else if (resp.data.includes("Error:")) {
resp.data = resp.data.replaceAll("Error:", "");
throw new Error(resp.data);
}
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Cellsynt;

@ -2,14 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class ClickSendSMS extends NotificationProvider { class ClickSendSMS extends NotificationProvider {
name = "clicksendsms"; name = "clicksendsms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://rest.clicksend.com/v3/sms/send";
try { try {
let config = { let config = {
headers: { headers: {
@ -28,7 +29,7 @@ class ClickSendSMS extends NotificationProvider {
} }
] ]
}; };
let resp = await axios.post("https://rest.clicksend.com/v3/sms/send", data, config); let resp = await axios.post(url, data, config);
if (resp.data.data.messages[0].status !== "SUCCESS") { if (resp.data.data.messages[0].status !== "SUCCESS") {
let error = "Something gone wrong. Api returned " + resp.data.data.messages[0].status + "."; let error = "Something gone wrong. Api returned " + resp.data.data.messages[0].status + ".";
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

@ -10,7 +10,7 @@ class DingDing extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON != null) { if (heartbeatJSON != null) {
@ -21,7 +21,7 @@ class DingDing extends NotificationProvider {
text: `## [${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, text: `## [${this.statusToString(heartbeatJSON["status"])}] ${monitorJSON["name"]} \n> ${heartbeatJSON["msg"]}\n> Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
} }
}; };
if (this.sendToDingDing(notification, params)) { if (await this.sendToDingDing(notification, params)) {
return okMsg; return okMsg;
} }
} else { } else {
@ -31,7 +31,7 @@ class DingDing extends NotificationProvider {
content: msg content: msg
} }
}; };
if (this.sendToDingDing(notification, params)) { if (await this.sendToDingDing(notification, params)) {
return okMsg; return okMsg;
} }
} }
@ -44,7 +44,7 @@ class DingDing extends NotificationProvider {
* Send message to DingDing * Send message to DingDing
* @param {BeanModel} notification Notification to send * @param {BeanModel} notification Notification to send
* @param {object} params Parameters of message * @param {object} params Parameters of message
* @returns {boolean} True if successful else false * @returns {Promise<boolean>} True if successful else false
*/ */
async sendToDingDing(notification, params) { async sendToDingDing(notification, params) {
let timestamp = Date.now(); let timestamp = Date.now();

@ -3,14 +3,13 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Discord extends NotificationProvider { class Discord extends NotificationProvider {
name = "discord"; name = "discord";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
const discordDisplayName = notification.discordUsername || "Uptime Kuma"; const discordDisplayName = notification.discordUsername || "Uptime Kuma";

@ -9,8 +9,7 @@ class Feishu extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let feishuWebHookUrl = notification.feishuWebHookUrl;
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
@ -20,7 +19,7 @@ class Feishu extends NotificationProvider {
text: msg, text: msg,
}, },
}; };
await axios.post(feishuWebHookUrl, testdata); await axios.post(notification.feishuWebHookUrl, testdata);
return okMsg; return okMsg;
} }
@ -46,7 +45,7 @@ class Feishu extends NotificationProvider {
}, },
}, },
}; };
await axios.post(feishuWebHookUrl, downdata); await axios.post(notification.feishuWebHookUrl, downdata);
return okMsg; return okMsg;
} }
@ -72,7 +71,7 @@ class Feishu extends NotificationProvider {
}, },
}, },
}; };
await axios.post(feishuWebHookUrl, updata); await axios.post(notification.feishuWebHookUrl, updata);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class FreeMobile extends NotificationProvider { class FreeMobile extends NotificationProvider {
name = "FreeMobile"; name = "FreeMobile";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://smsapi.free-mobile.fr/sendmsg?msg=${encodeURIComponent(msg.replace("🔴", "⛔️"))}`, { await axios.post(`https://smsapi.free-mobile.fr/sendmsg?msg=${encodeURIComponent(msg.replace("🔴", "⛔️"))}`, {
"user": notification.freemobileUser, "user": notification.freemobileUser,

@ -3,21 +3,20 @@ const axios = require("axios");
const { UP } = require("../../src/util"); const { UP } = require("../../src/util");
class GoAlert extends NotificationProvider { class GoAlert extends NotificationProvider {
name = "GoAlert"; name = "GoAlert";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let closeAction = "close";
let data = { let data = {
summary: msg, summary: msg,
}; };
if (heartbeatJSON != null && heartbeatJSON["status"] === UP) { if (heartbeatJSON != null && heartbeatJSON["status"] === UP) {
data["action"] = closeAction; data["action"] = "close";
} }
let headers = { let headers = {
"Content-Type": "multipart/form-data", "Content-Type": "multipart/form-data",
@ -27,7 +26,6 @@ class GoAlert extends NotificationProvider {
}; };
await axios.post(`${notification.goAlertBaseURL}/api/v2/generic/incoming?token=${notification.goAlertToken}`, data, config); await axios.post(`${notification.goAlertBaseURL}/api/v2/generic/incoming?token=${notification.goAlertToken}`, data, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
let msg = (error.response.data) ? error.response.data : "Error without response"; let msg = (error.response.data) ? error.response.data : "Error without response";
throw new Error(msg); throw new Error(msg);

@ -1,41 +1,85 @@
const NotificationProvider = require("./notification-provider"); const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
const { setting } = require("../util-server"); const { setting } = require("../util-server");
const { getMonitorRelativeURL } = require("../../src/util"); const { getMonitorRelativeURL, UP } = require("../../src/util");
const { DOWN, UP } = require("../../src/util");
class GoogleChat extends NotificationProvider { class GoogleChat extends NotificationProvider {
name = "GoogleChat"; name = "GoogleChat";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
// Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic // Google Chat message formatting: https://developers.google.com/chat/api/guides/message-formats/basic
let textMsg = ""; let chatHeader = {
if (heartbeatJSON && heartbeatJSON.status === UP) { title: "Uptime Kuma Alert",
textMsg = "✅ Application is back online\n"; };
} else if (heartbeatJSON && heartbeatJSON.status === DOWN) {
textMsg = "🔴 Application went down\n";
}
if (monitorJSON && monitorJSON.name) { if (monitorJSON && heartbeatJSON) {
textMsg += `*${monitorJSON.name}*\n`; chatHeader["title"] =
heartbeatJSON["status"] === UP
? `${monitorJSON["name"]} is back online`
: `🔴 ${monitorJSON["name"]} went down`;
} }
textMsg += `${msg}`; // always show msg
let sectionWidgets = [
{
textParagraph: {
text: `<b>Message:</b>\n${msg}`,
},
},
];
// add time if available
if (heartbeatJSON) {
sectionWidgets.push({
textParagraph: {
text: `<b>Time (${heartbeatJSON["timezone"]}):</b>\n${heartbeatJSON["localDateTime"]}`,
},
});
}
// add button for monitor link if available
const baseURL = await setting("primaryBaseURL"); const baseURL = await setting("primaryBaseURL");
if (baseURL && monitorJSON) { if (baseURL) {
textMsg += `\n${baseURL + getMonitorRelativeURL(monitorJSON.id)}`; const urlPath = monitorJSON ? getMonitorRelativeURL(monitorJSON.id) : "/";
sectionWidgets.push({
buttonList: {
buttons: [
{
text: "Visit Uptime Kuma",
onClick: {
openLink: {
url: baseURL + urlPath,
},
},
},
],
},
});
} }
const data = { let chatSections = [
"text": textMsg, {
widgets: sectionWidgets,
},
];
// construct json data
let data = {
cardsV2: [
{
card: {
header: chatHeader,
sections: chatSections,
},
},
],
}; };
await axios.post(notification.googleChatWebhookURL, data); await axios.post(notification.googleChatWebhookURL, data);

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Gorush extends NotificationProvider { class Gorush extends NotificationProvider {
name = "gorush"; name = "gorush";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let platformMapping = { let platformMapping = {
"ios": 1, "ios": 1,

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Gotify extends NotificationProvider { class Gotify extends NotificationProvider {
name = "gotify"; name = "gotify";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (notification.gotifyserverurl && notification.gotifyserverurl.endsWith("/")) { if (notification.gotifyserverurl && notification.gotifyserverurl.endsWith("/")) {
notification.gotifyserverurl = notification.gotifyserverurl.slice(0, -1); notification.gotifyserverurl = notification.gotifyserverurl.slice(0, -1);

@ -3,19 +3,18 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class GrafanaOncall extends NotificationProvider { class GrafanaOncall extends NotificationProvider {
name = "GrafanaOncall"; name = "GrafanaOncall";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
if (!notification.GrafanaOncallURL) { if (!notification.GrafanaOncallURL) {
throw new Error("GrafanaOncallURL cannot be empty"); throw new Error("GrafanaOncallURL cannot be empty");
} }
let okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON === null) { if (heartbeatJSON === null) {
let grafanaupdata = { let grafanaupdata = {
@ -23,10 +22,7 @@ class GrafanaOncall extends NotificationProvider {
message: msg, message: msg,
state: "alerting", state: "alerting",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanaupdata);
notification.GrafanaOncallURL,
grafanaupdata
);
return okMsg; return okMsg;
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let grafanadowndata = { let grafanadowndata = {
@ -34,10 +30,7 @@ class GrafanaOncall extends NotificationProvider {
message: heartbeatJSON["msg"], message: heartbeatJSON["msg"],
state: "alerting", state: "alerting",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanadowndata);
notification.GrafanaOncallURL,
grafanadowndata
);
return okMsg; return okMsg;
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let grafanaupdata = { let grafanaupdata = {
@ -45,10 +38,7 @@ class GrafanaOncall extends NotificationProvider {
message: heartbeatJSON["msg"], message: heartbeatJSON["msg"],
state: "ok", state: "ok",
}; };
await axios.post( await axios.post(notification.GrafanaOncallURL, grafanaupdata);
notification.GrafanaOncallURL,
grafanaupdata
);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

@ -0,0 +1,33 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class GtxMessaging extends NotificationProvider {
name = "gtxmessaging";
/**
* @inheritDoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
// The UP/DOWN symbols will be replaced with `???` by gtx-messaging
const text = msg.replaceAll("🔴 ", "").replaceAll("✅ ", "");
try {
const data = new URLSearchParams();
data.append("from", notification.gtxMessagingFrom.trim());
data.append("to", notification.gtxMessagingTo.trim());
data.append("text", text);
const url = `https://rest.gtx-messaging.net/smsc/sendsms/${notification.gtxMessagingApiKey}/json`;
await axios.post(url, data);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = GtxMessaging;

@ -0,0 +1,52 @@
const { UP, DOWN, getMonitorRelativeURL } = require("../../src/util");
const { setting } = require("../util-server");
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class HeiiOnCall extends NotificationProvider {
name = "HeiiOnCall";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const payload = heartbeatJSON || {};
const baseURL = await setting("primaryBaseURL");
if (baseURL && monitorJSON) {
payload["url"] = baseURL + getMonitorRelativeURL(monitorJSON.id);
}
const config = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + notification.heiiOnCallApiKey,
},
};
const heiiUrl = `https://heiioncall.com/triggers/${notification.heiiOnCallTriggerId}/`;
// docs https://heiioncall.com/docs#manual-triggers
try {
if (!heartbeatJSON) {
// Testing or general notification like certificate expiry
payload["msg"] = msg;
await axios.post(heiiUrl + "alert", payload, config);
return okMsg;
}
if (heartbeatJSON.status === DOWN) {
await axios.post(heiiUrl + "alert", payload, config);
return okMsg;
}
if (heartbeatJSON.status === UP) {
await axios.post(heiiUrl + "resolve", payload, config);
return okMsg;
}
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = HeiiOnCall;

@ -9,7 +9,9 @@ class HomeAssistant extends NotificationProvider {
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, message, monitor = null, heartbeat = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const notificationService = notification?.notificationService || defaultNotificationService; const notificationService = notification?.notificationService || defaultNotificationService;
try { try {
@ -17,10 +19,12 @@ class HomeAssistant extends NotificationProvider {
`${notification.homeAssistantUrl.trim().replace(/\/*$/, "")}/api/services/notify/${notificationService}`, `${notification.homeAssistantUrl.trim().replace(/\/*$/, "")}/api/services/notify/${notificationService}`,
{ {
title: "Uptime Kuma", title: "Uptime Kuma",
message, message: msg,
...(notificationService !== "persistent_notification" && { data: { ...(notificationService !== "persistent_notification" && { data: {
name: monitor?.name, name: monitorJSON?.name,
status: heartbeat?.status, status: heartbeatJSON?.status,
channel: "Uptime Kuma",
icon_url: "https://github.com/louislam/uptime-kuma/blob/master/public/icon.png?raw=true",
} }), } }),
}, },
{ {
@ -31,7 +35,7 @@ class HomeAssistant extends NotificationProvider {
} }
); );
return "Sent Successfully."; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);
} }

@ -2,15 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Kook extends NotificationProvider { class Kook extends NotificationProvider {
name = "Kook"; name = "Kook";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let url = "https://www.kookapp.cn/api/v3/message/create"; const url = "https://www.kookapp.cn/api/v3/message/create";
let data = { let data = {
target_id: notification.kookGuildID, target_id: notification.kookGuildID,
content: msg, content: msg,

@ -3,16 +3,16 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Line extends NotificationProvider { class Line extends NotificationProvider {
name = "line"; name = "line";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api.line.me/v2/bot/message/push";
try { try {
let lineAPIUrl = "https://api.line.me/v2/bot/message/push";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -29,7 +29,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, testMessage, config); await axios.post(url, testMessage, config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downMessage = { let downMessage = {
"to": notification.lineUserID, "to": notification.lineUserID,
@ -43,7 +43,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, downMessage, config); await axios.post(url, downMessage, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upMessage = { let upMessage = {
"to": notification.lineUserID, "to": notification.lineUserID,
@ -57,7 +57,7 @@ class Line extends NotificationProvider {
} }
] ]
}; };
await axios.post(lineAPIUrl, upMessage, config); await axios.post(url, upMessage, config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

@ -4,16 +4,16 @@ const qs = require("qs");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class LineNotify extends NotificationProvider { class LineNotify extends NotificationProvider {
name = "LineNotify"; name = "LineNotify";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://notify-api.line.me/api/notify";
try { try {
let lineAPIUrl = "https://notify-api.line.me/api/notify";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
@ -24,7 +24,7 @@ class LineNotify extends NotificationProvider {
let testMessage = { let testMessage = {
"message": msg, "message": msg,
}; };
await axios.post(lineAPIUrl, qs.stringify(testMessage), config); await axios.post(url, qs.stringify(testMessage), config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downMessage = { let downMessage = {
"message": "\n[🔴 Down]\n" + "message": "\n[🔴 Down]\n" +
@ -32,7 +32,7 @@ class LineNotify extends NotificationProvider {
heartbeatJSON["msg"] + "\n" + heartbeatJSON["msg"] + "\n" +
`Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lineAPIUrl, qs.stringify(downMessage), config); await axios.post(url, qs.stringify(downMessage), config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upMessage = { let upMessage = {
"message": "\n[✅ Up]\n" + "message": "\n[✅ Up]\n" +
@ -40,7 +40,7 @@ class LineNotify extends NotificationProvider {
heartbeatJSON["msg"] + "\n" + heartbeatJSON["msg"] + "\n" +
`Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `Time (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lineAPIUrl, qs.stringify(upMessage), config); await axios.post(url, qs.stringify(upMessage), config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

@ -3,28 +3,23 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class LunaSea extends NotificationProvider { class LunaSea extends NotificationProvider {
name = "lunasea"; name = "lunasea";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let lunaseaurl = ""; const url = "https://notify.lunasea.app/v1";
if (notification.lunaseaTarget === "user") {
lunaseaurl = "https://notify.lunasea.app/v1/custom/user/" + notification.lunaseaUserID;
} else {
lunaseaurl = "https://notify.lunasea.app/v1/custom/device/" + notification.lunaseaDevice;
}
try { try {
const target = this.getTarget(notification);
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
let testdata = { let testdata = {
"title": "Uptime Kuma Alert", "title": "Uptime Kuma Alert",
"body": msg, "body": msg,
}; };
await axios.post(lunaseaurl, testdata); await axios.post(`${url}/custom/${target}`, testdata);
return okMsg; return okMsg;
} }
@ -35,7 +30,7 @@ class LunaSea extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lunaseaurl, downdata); await axios.post(`${url}/custom/${target}`, downdata);
return okMsg; return okMsg;
} }
@ -46,13 +41,25 @@ class LunaSea extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}` `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`
}; };
await axios.post(lunaseaurl, updata); await axios.post(`${url}/custom/${target}`, updata);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);
} }
}
/**
* Generates the lunasea target to send the notification to
* @param {BeanModel} notification Notification details
* @returns {string} The target to send the notification to
*/
getTarget(notification) {
if (notification.lunaseaTarget === "user") {
return "user/" + notification.lunaseaUserID;
}
return "device/" + notification.lunaseaDevice;
} }
} }

@ -10,7 +10,7 @@ class Matrix extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const size = 20; const size = 20;
const randomString = encodeURIComponent( const randomString = encodeURIComponent(

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Mattermost extends NotificationProvider { class Mattermost extends NotificationProvider {
name = "mattermost"; name = "mattermost";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
const mattermostUserName = notification.mattermostusername || "Uptime Kuma"; const mattermostUserName = notification.mattermostusername || "Uptime Kuma";
// If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing. // If heartbeatJSON is null, assume non monitoring notification (Certificate warning) or testing.
@ -98,10 +98,7 @@ class Mattermost extends NotificationProvider {
}, },
], ],
}; };
await axios.post( await axios.post(notification.mattermostWebhookUrl, mattermostdata);
notification.mattermostWebhookUrl,
mattermostdata
);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

@ -107,7 +107,7 @@ class Nostr extends NotificationProvider {
/** /**
* Get public keys for recipients * Get public keys for recipients
* @param {string} recipients Newline delimited list of recipients * @param {string} recipients Newline delimited list of recipients
* @returns {nip19.DecodeResult[]} Public keys * @returns {Promise<nip19.DecodeResult[]>} Public keys
*/ */
async getPublicKeys(recipients) { async getPublicKeys(recipients) {
const recipientsList = recipients.split("\n"); const recipientsList = recipients.split("\n");

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Ntfy extends NotificationProvider { class Ntfy extends NotificationProvider {
name = "ntfy"; name = "ntfy";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let headers = {}; let headers = {};
if (notification.ntfyAuthenticationMethod === "usernamePassword") { if (notification.ntfyAuthenticationMethod === "usernamePassword") {
@ -31,7 +31,7 @@ class Ntfy extends NotificationProvider {
"priority": notification.ntfyPriority, "priority": notification.ntfyPriority,
"tags": [ "test_tube" ], "tags": [ "test_tube" ],
}; };
await axios.post(`${notification.ntfyserverurl}`, ntfyTestData, { headers: headers }); await axios.post(notification.ntfyserverurl, ntfyTestData, { headers: headers });
return okMsg; return okMsg;
} }
let tags = []; let tags = [];
@ -54,20 +54,23 @@ class Ntfy extends NotificationProvider {
"priority": priority, "priority": priority,
"title": monitorJSON.name + " " + status + " [Uptime-Kuma]", "title": monitorJSON.name + " " + status + " [Uptime-Kuma]",
"tags": tags, "tags": tags,
"actions": [ };
if (monitorJSON.url && monitorJSON.url !== "https://") {
data.actions = [
{ {
"action": "view", "action": "view",
"label": "Open " + monitorJSON.name, "label": "Open " + monitorJSON.name,
"url": monitorJSON.url, "url": monitorJSON.url,
} },
] ];
}; }
if (notification.ntfyIcon) { if (notification.ntfyIcon) {
data.icon = notification.ntfyIcon; data.icon = notification.ntfyIcon;
} }
await axios.post(`${notification.ntfyserverurl}`, data, { headers: headers }); await axios.post(notification.ntfyserverurl, data, { headers: headers });
return okMsg; return okMsg;

@ -2,14 +2,15 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Octopush extends NotificationProvider { class Octopush extends NotificationProvider {
name = "octopush"; name = "octopush";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const urlV2 = "https://api.octopush.com/v1/public/sms-campaign/send";
const urlV1 = "https://www.octopush-dm.com/api/sms/json";
try { try {
// Default - V2 // Default - V2
@ -33,7 +34,7 @@ class Octopush extends NotificationProvider {
"purpose": "alert", "purpose": "alert",
"sender": notification.octopushSenderName "sender": notification.octopushSenderName
}; };
await axios.post("https://api.octopush.com/v1/public/sms-campaign/send", data, config); await axios.post(urlV2, data, config);
} else if (notification.octopushVersion === "1") { } else if (notification.octopushVersion === "1") {
let data = { let data = {
"user_login": notification.octopushDMLogin, "user_login": notification.octopushDMLogin,
@ -55,7 +56,7 @@ class Octopush extends NotificationProvider {
// V1 API returns 200 even on error so we must check // V1 API returns 200 even on error so we must check
// response data // response data
let response = await axios.post("https://www.octopush-dm.com/api/sms/json", {}, config); let response = await axios.post(urlV1, {}, config);
if ("error_code" in response.data) { if ("error_code" in response.data) {
if (response.data.error_code !== "000") { if (response.data.error_code !== "000") {
this.throwGeneralAxiosError(`Octopush error ${JSON.stringify(response.data)}`); this.throwGeneralAxiosError(`Octopush error ${JSON.stringify(response.data)}`);

@ -2,23 +2,23 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class OneBot extends NotificationProvider { class OneBot extends NotificationProvider {
name = "OneBot"; name = "OneBot";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let httpAddr = notification.httpAddr; let url = notification.httpAddr;
if (!httpAddr.startsWith("http")) { if (!url.startsWith("http")) {
httpAddr = "http://" + httpAddr; url = "http://" + url;
} }
if (!httpAddr.endsWith("/")) { if (!url.endsWith("/")) {
httpAddr += "/"; url += "/";
} }
let onebotAPIUrl = httpAddr + "send_msg"; url += "send_msg";
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -37,7 +37,7 @@ class OneBot extends NotificationProvider {
data["message_type"] = "private"; data["message_type"] = "private";
data["user_id"] = notification.recieverId; data["user_id"] = notification.recieverId;
} }
await axios.post(onebotAPIUrl, data, config); await axios.post(url, data, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

@ -4,10 +4,9 @@ const { UP, DOWN } = require("../../src/util");
const opsgenieAlertsUrlEU = "https://api.eu.opsgenie.com/v2/alerts"; const opsgenieAlertsUrlEU = "https://api.eu.opsgenie.com/v2/alerts";
const opsgenieAlertsUrlUS = "https://api.opsgenie.com/v2/alerts"; const opsgenieAlertsUrlUS = "https://api.opsgenie.com/v2/alerts";
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
class Opsgenie extends NotificationProvider { class Opsgenie extends NotificationProvider {
name = "Opsgenie"; name = "Opsgenie";
/** /**

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class PromoSMS extends NotificationProvider { class PromoSMS extends NotificationProvider {
name = "promosms"; name = "promosms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://promosms.com/api/rest/v3_2/sms";
if (notification.promosmsAllowLongSMS === undefined) { if (notification.promosmsAllowLongSMS === undefined) {
notification.promosmsAllowLongSMS = false; notification.promosmsAllowLongSMS = false;
@ -36,7 +36,7 @@ class PromoSMS extends NotificationProvider {
"sender": notification.promosmsSenderName "sender": notification.promosmsSenderName
}; };
let resp = await axios.post("https://promosms.com/api/rest/v3_2/sms", data, config); let resp = await axios.post(url, data, config);
if (resp.data.response.status !== 0) { if (resp.data.response.status !== 0) {
let error = "Something gone wrong. Api returned " + resp.data.response.status + "."; let error = "Something gone wrong. Api returned " + resp.data.response.status + ".";

@ -4,17 +4,16 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class Pushbullet extends NotificationProvider { class Pushbullet extends NotificationProvider {
name = "pushbullet"; name = "pushbullet";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api.pushbullet.com/v2/pushes";
try { try {
let pushbulletUrl = "https://api.pushbullet.com/v2/pushes";
let config = { let config = {
headers: { headers: {
"Access-Token": notification.pushbulletAccessToken, "Access-Token": notification.pushbulletAccessToken,
@ -27,7 +26,7 @@ class Pushbullet extends NotificationProvider {
"title": "Uptime Kuma Alert", "title": "Uptime Kuma Alert",
"body": msg, "body": msg,
}; };
await axios.post(pushbulletUrl, data, config); await axios.post(url, data, config);
} else if (heartbeatJSON["status"] === DOWN) { } else if (heartbeatJSON["status"] === DOWN) {
let downData = { let downData = {
"type": "note", "type": "note",
@ -36,7 +35,7 @@ class Pushbullet extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
}; };
await axios.post(pushbulletUrl, downData, config); await axios.post(url, downData, config);
} else if (heartbeatJSON["status"] === UP) { } else if (heartbeatJSON["status"] === UP) {
let upData = { let upData = {
"type": "note", "type": "note",
@ -45,7 +44,7 @@ class Pushbullet extends NotificationProvider {
heartbeatJSON["msg"] + heartbeatJSON["msg"] +
`\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`, `\nTime (${heartbeatJSON["timezone"]}): ${heartbeatJSON["localDateTime"]}`,
}; };
await axios.post(pushbulletUrl, upData, config); await axios.post(url, upData, config);
} }
return okMsg; return okMsg;
} catch (error) { } catch (error) {

@ -3,17 +3,15 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class PushDeer extends NotificationProvider { class PushDeer extends NotificationProvider {
name = "PushDeer"; name = "PushDeer";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let endpoint = "/message/push"; const serverUrl = notification.pushdeerServer || "https://api2.pushdeer.com";
let serverUrl = notification.pushdeerServer || "https://api2.pushdeer.com"; const url = `${serverUrl.trim().replace(/\/*$/, "")}/message/push`;
let pushdeerlink = `${serverUrl.trim().replace(/\/*$/, "")}${endpoint}`;
let valid = msg != null && monitorJSON != null && heartbeatJSON != null; let valid = msg != null && monitorJSON != null && heartbeatJSON != null;
@ -34,7 +32,7 @@ class PushDeer extends NotificationProvider {
}; };
try { try {
let res = await axios.post(pushdeerlink, data); let res = await axios.post(url, data);
if ("error" in res.data) { if ("error" in res.data) {
let error = res.data.error; let error = res.data.error;

@ -2,15 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Pushover extends NotificationProvider { class Pushover extends NotificationProvider {
name = "pushover"; name = "pushover";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
let pushoverlink = "https://api.pushover.net/1/messages.json"; const url = "https://api.pushover.net/1/messages.json";
let data = { let data = {
"message": msg, "message": msg,
@ -33,11 +32,11 @@ class Pushover extends NotificationProvider {
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
await axios.post(pushoverlink, data); await axios.post(url, data);
return okMsg; return okMsg;
} else { } else {
data.message += `\n<b>Time (${heartbeatJSON["timezone"]})</b>:${heartbeatJSON["localDateTime"]}`; data.message += `\n<b>Time (${heartbeatJSON["timezone"]})</b>:${heartbeatJSON["localDateTime"]}`;
await axios.post(pushoverlink, data); await axios.post(url, data);
return okMsg; return okMsg;
} }
} catch (error) { } catch (error) {

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Pushy extends NotificationProvider { class Pushy extends NotificationProvider {
name = "pushy"; name = "pushy";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://api.pushy.me/push?api_key=${notification.pushyAPIKey}`, { await axios.post(`https://api.pushy.me/push?api_key=${notification.pushyAPIKey}`, {

@ -5,14 +5,14 @@ const { setting } = require("../util-server");
const { getMonitorRelativeURL, DOWN } = require("../../src/util"); const { getMonitorRelativeURL, DOWN } = require("../../src/util");
class RocketChat extends NotificationProvider { class RocketChat extends NotificationProvider {
name = "rocket.chat"; name = "rocket.chat";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
let data = { let data = {

@ -3,14 +3,14 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class ServerChan extends NotificationProvider { class ServerChan extends NotificationProvider {
name = "ServerChan"; name = "ServerChan";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://sctapi.ftqq.com/${notification.serverChanSendKey}.send`, { await axios.post(`https://sctapi.ftqq.com/${notification.serverChanSendKey}.send`, {
"title": this.checkStatus(heartbeatJSON, monitorJSON), "title": this.checkStatus(heartbeatJSON, monitorJSON),

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class SerwerSMS extends NotificationProvider { class SerwerSMS extends NotificationProvider {
name = "serwersms"; name = "serwersms";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api2.serwersms.pl/messages/send_sms";
try { try {
let config = { let config = {
@ -25,7 +25,7 @@ class SerwerSMS extends NotificationProvider {
"sender": notification.serwersmsSenderName, "sender": notification.serwersmsSenderName,
}; };
let resp = await axios.post("https://api2.serwersms.pl/messages/send_sms", data, config); let resp = await axios.post(url, data, config);
if (!resp.data.success) { if (!resp.data.success) {
if (resp.data.error) { if (resp.data.error) {

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Signal extends NotificationProvider { class Signal extends NotificationProvider {
name = "signal"; name = "signal";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let data = { let data = {

@ -4,7 +4,6 @@ const { setSettings, setting } = require("../util-server");
const { getMonitorRelativeURL, UP } = require("../../src/util"); const { getMonitorRelativeURL, UP } = require("../../src/util");
class Slack extends NotificationProvider { class Slack extends NotificationProvider {
name = "slack"; name = "slack";
/** /**
@ -27,11 +26,98 @@ class Slack extends NotificationProvider {
} }
} }
/**
* Builds the actions available in the slack message
* @param {string} baseURL Uptime Kuma base URL
* @param {object} monitorJSON The monitor config
* @returns {Array} The relevant action objects
*/
static buildActions(baseURL, monitorJSON) {
const actions = [];
if (baseURL) {
actions.push({
"type": "button",
"text": {
"type": "plain_text",
"text": "Visit Uptime Kuma",
},
"value": "Uptime-Kuma",
"url": baseURL + getMonitorRelativeURL(monitorJSON.id),
});
}
if (monitorJSON.url) {
actions.push({
"type": "button",
"text": {
"type": "plain_text",
"text": "Visit site",
},
"value": "Site",
"url": monitorJSON.url,
});
}
return actions;
}
/**
* Builds the different blocks the Slack message consists of.
* @param {string} baseURL Uptime Kuma base URL
* @param {object} monitorJSON The monitor object
* @param {object} heartbeatJSON The heartbeat object
* @param {string} title The message title
* @param {string} msg The message body
* @returns {Array<object>} The rich content blocks for the Slack message
*/
static buildBlocks(baseURL, monitorJSON, heartbeatJSON, title, msg) {
//create an array to dynamically add blocks
const blocks = [];
// the header block
blocks.push({
"type": "header",
"text": {
"type": "plain_text",
"text": title,
},
});
// the body block, containing the details
blocks.push({
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Message*\n" + msg,
},
{
"type": "mrkdwn",
"text": `*Time (${heartbeatJSON["timezone"]})*\n${heartbeatJSON["localDateTime"]}`,
}
],
});
const actions = this.buildActions(baseURL, monitorJSON);
if (actions.length > 0) {
//the actions block, containing buttons
blocks.push({
"type": "actions",
"elements": actions,
});
}
return blocks;
}
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
if (notification.slackchannelnotify) { if (notification.slackchannelnotify) {
msg += " <!channel>"; msg += " <!channel>";
@ -49,35 +135,18 @@ class Slack extends NotificationProvider {
return okMsg; return okMsg;
} }
const textMsg = "Uptime Kuma Alert"; const baseURL = await setting("primaryBaseURL");
const title = "Uptime Kuma Alert";
let data = { let data = {
"text": `${textMsg}\n${msg}`, "text": `${title}\n${msg}`,
"channel": notification.slackchannel, "channel": notification.slackchannel,
"username": notification.slackusername, "username": notification.slackusername,
"icon_emoji": notification.slackiconemo, "icon_emoji": notification.slackiconemo,
"attachments": [ "attachments": [
{ {
"color": (heartbeatJSON["status"] === UP) ? "#2eb886" : "#e01e5a", "color": (heartbeatJSON["status"] === UP) ? "#2eb886" : "#e01e5a",
"blocks": [ "blocks": Slack.buildBlocks(baseURL, monitorJSON, heartbeatJSON, title, msg),
{
"type": "header",
"text": {
"type": "plain_text",
"text": textMsg,
},
},
{
"type": "section",
"fields": [{
"type": "mrkdwn",
"text": "*Message*\n" + msg,
},
{
"type": "mrkdwn",
"text": `*Time (${heartbeatJSON["timezone"]})*\n${heartbeatJSON["localDateTime"]}`,
}],
}
],
} }
] ]
}; };
@ -86,26 +155,6 @@ class Slack extends NotificationProvider {
await Slack.deprecateURL(notification.slackbutton); await Slack.deprecateURL(notification.slackbutton);
} }
const baseURL = await setting("primaryBaseURL");
// Button
if (baseURL) {
data.attachments.forEach(element => {
element.blocks.push({
"type": "actions",
"elements": [{
"type": "button",
"text": {
"type": "plain_text",
"text": "Visit Uptime Kuma",
},
"value": "Uptime-Kuma",
"url": baseURL + getMonitorRelativeURL(monitorJSON.id),
}],
});
});
}
await axios.post(notification.slackwebhookURL, data); await axios.post(notification.slackwebhookURL, data);
return okMsg; return okMsg;
} catch (error) { } catch (error) {

@ -8,7 +8,9 @@ class SMSC extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://smsc.kz/sys/send.php?";
try { try {
let config = { let config = {
headers: { headers: {
@ -29,7 +31,7 @@ class SMSC extends NotificationProvider {
getArray.push("sender=" + notification.smscSenderName); getArray.push("sender=" + notification.smscSenderName);
} }
let resp = await axios.get("https://smsc.kz/sys/send.php?" + getArray.join("&"), config); let resp = await axios.get(url + getArray.join("&"), config);
if (resp.data.id === undefined) { if (resp.data.id === undefined) {
let error = `Something gone wrong. Api returned code ${resp.data.error_code}: ${resp.data.error}`; let error = `Something gone wrong. Api returned code ${resp.data.error_code}: ${resp.data.error}`;
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class SMSEagle extends NotificationProvider { class SMSEagle extends NotificationProvider {
name = "SMSEagle"; name = "SMSEagle";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let config = { let config = {

@ -2,23 +2,24 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class SMSManager extends NotificationProvider { class SMSManager extends NotificationProvider {
name = "SMSManager"; name = "SMSManager";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const url = "https://http-api.smsmanager.cz/Send";
try { try {
let data = { let data = {
apikey: notification.smsmanagerApiKey, apikey: notification.smsmanagerApiKey,
endpoint: "https://http-api.smsmanager.cz/Send",
message: msg.replace(/[^\x00-\x7F]/g, ""), message: msg.replace(/[^\x00-\x7F]/g, ""),
to: notification.numbers, number: notification.numbers,
messageType: notification.messageType, gateway: notification.messageType,
}; };
await axios.get(`${data.endpoint}?apikey=${data.apikey}&message=${data.message}&number=${data.to}&gateway=${data.messageType}`); await axios.get(`${url}?apikey=${data.apikey}&message=${data.message}&number=${data.number}&gateway=${data.messageType}`);
return "SMS sent sucessfully."; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);
} }

@ -4,13 +4,13 @@ const { DOWN } = require("../../src/util");
const { Liquid } = require("liquidjs"); const { Liquid } = require("liquidjs");
class SMTP extends NotificationProvider { class SMTP extends NotificationProvider {
name = "smtp"; name = "smtp";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
const config = { const config = {
host: notification.smtpHost, host: notification.smtpHost,
@ -76,7 +76,7 @@ class SMTP extends NotificationProvider {
text: body, text: body,
}); });
return "Sent Successfully."; return okMsg;
} }
/** /**

@ -3,14 +3,13 @@ const axios = require("axios");
const { DOWN } = require("../../src/util"); const { DOWN } = require("../../src/util");
class Squadcast extends NotificationProvider { class Squadcast extends NotificationProvider {
name = "squadcast"; name = "squadcast";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {

@ -4,14 +4,14 @@ const { setting } = require("../util-server");
const { getMonitorRelativeURL } = require("../../src/util"); const { getMonitorRelativeURL } = require("../../src/util");
class Stackfield extends NotificationProvider { class Stackfield extends NotificationProvider {
name = "stackfield"; name = "stackfield";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
// Stackfield message formatting: https://www.stackfield.com/help/formatting-messages-2001 // Stackfield message formatting: https://www.stackfield.com/help/formatting-messages-2001

@ -1,6 +1,7 @@
const NotificationProvider = require("./notification-provider"); const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { setting } = require("../util-server");
const { DOWN, UP, getMonitorRelativeURL } = require("../../src/util");
class Teams extends NotificationProvider { class Teams extends NotificationProvider {
name = "teams"; name = "teams";
@ -9,89 +10,172 @@ class Teams extends NotificationProvider {
* Generate the message to send * Generate the message to send
* @param {const} status The status constant * @param {const} status The status constant
* @param {string} monitorName Name of monitor * @param {string} monitorName Name of monitor
* @param {boolean} withStatusSymbol If the status should be prepended as symbol
* @returns {string} Status message * @returns {string} Status message
*/ */
_statusMessageFactory = (status, monitorName) => { _statusMessageFactory = (status, monitorName, withStatusSymbol) => {
if (status === DOWN) { if (status === DOWN) {
return `🔴 Application [${monitorName}] went down`; return (withStatusSymbol ? "🔴 " : "") + `[${monitorName}] went down`;
} else if (status === UP) { } else if (status === UP) {
return `✅ Application [${monitorName}] is back online`; return (withStatusSymbol ? "✅ " : "") + `[${monitorName}] is back online`;
} }
return "Notification"; return "Notification";
}; };
/** /**
* Select theme color to use based on status * Select the style to use based on status
* @param {const} status The status constant * @param {const} status The status constant
* @returns {string} Selected color in hex RGB format * @returns {string} Selected style for adaptive cards
*/ */
_getThemeColor = (status) => { _getStyle = (status) => {
if (status === DOWN) { if (status === DOWN) {
return "ff0000"; return "attention";
} }
if (status === UP) { if (status === UP) {
return "00e804"; return "good";
} }
return "008cff"; return "emphasis";
}; };
/** /**
* Generate payload for notification * Generate payload for notification
* @param {object} args Method arguments * @param {object} args Method arguments
* @param {const} args.status The status of the monitor * @param {object} args.heartbeatJSON Heartbeat details
* @param {string} args.monitorMessage Message to send * @param {string} args.monitorName Name of the monitor affected
* @param {string} args.monitorName Name of monitor affected * @param {string} args.monitorUrl URL of the monitor affected
* @param {string} args.monitorUrl URL of monitor affected * @param {string} args.dashboardUrl URL of the dashboard affected
* @returns {object} Notification payload * @returns {object} Notification payload
*/ */
_notificationPayloadFactory = ({ _notificationPayloadFactory = ({
status, heartbeatJSON,
monitorMessage,
monitorName, monitorName,
monitorUrl, monitorUrl,
dashboardUrl,
}) => { }) => {
const notificationMessage = this._statusMessageFactory( const status = heartbeatJSON?.status;
status,
monitorName
);
const facts = []; const facts = [];
const actions = [];
if (dashboardUrl) {
actions.push({
"type": "Action.OpenUrl",
"title": "Visit Uptime Kuma",
"url": dashboardUrl
});
}
if (heartbeatJSON?.msg) {
facts.push({
title: "Description",
value: heartbeatJSON.msg,
});
}
if (monitorName) { if (monitorName) {
facts.push({ facts.push({
name: "Monitor", title: "Monitor",
value: monitorName, value: monitorName,
}); });
} }
if (monitorUrl && monitorUrl !== "https://") { if (monitorUrl && monitorUrl !== "https://") {
facts.push({ facts.push({
name: "URL", title: "URL",
value: monitorUrl, // format URL as markdown syntax, to be clickable
value: `[${monitorUrl}](${monitorUrl})`,
});
actions.push({
"type": "Action.OpenUrl",
"title": "Visit Monitor URL",
"url": monitorUrl
}); });
} }
return { if (heartbeatJSON?.localDateTime) {
"@context": "https://schema.org/extensions", facts.push({
"@type": "MessageCard", title: "Time",
themeColor: this._getThemeColor(status), value: heartbeatJSON.localDateTime + (heartbeatJSON.timezone ? ` (${heartbeatJSON.timezone})` : ""),
summary: notificationMessage, });
sections: [ }
{
activityImage: const payload = {
"https://raw.githubusercontent.com/louislam/uptime-kuma/master/public/icon.png", "type": "message",
activityTitle: "**Uptime Kuma**", // message with status prefix as notification text
}, "summary": this._statusMessageFactory(status, monitorName, true),
{ "attachments": [
activityTitle: notificationMessage,
},
{ {
activityTitle: "**Description**", "contentType": "application/vnd.microsoft.card.adaptive",
text: monitorMessage, "contentUrl": "",
facts, "content": {
}, "type": "AdaptiveCard",
], "body": [
{
"type": "Container",
"verticalContentAlignment": "Center",
"items": [
{
"type": "ColumnSet",
"style": this._getStyle(status),
"columns": [
{
"type": "Column",
"width": "auto",
"verticalContentAlignment": "Center",
"items": [
{
"type": "Image",
"width": "32px",
"style": "Person",
"url": "https://raw.githubusercontent.com/louislam/uptime-kuma/master/public/icon.png",
"altText": "Uptime Kuma Logo"
}
]
},
{
"type": "Column",
"width": "stretch",
"items": [
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": `**${this._statusMessageFactory(status, monitorName, false)}**`,
},
{
"type": "TextBlock",
"size": "Small",
"weight": "Default",
"text": "Uptime Kuma Alert",
"isSubtle": true,
"spacing": "None"
}
]
}
]
}
]
},
{
"type": "FactSet",
"separator": false,
"facts": facts
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.5"
}
}
]
}; };
if (actions) {
payload.attachments[0].content.body.push({
"type": "ActionSet",
"actions": actions,
});
}
return payload;
}; };
/** /**
@ -112,7 +196,9 @@ class Teams extends NotificationProvider {
*/ */
_handleGeneralNotification = (webhookUrl, msg) => { _handleGeneralNotification = (webhookUrl, msg) => {
const payload = this._notificationPayloadFactory({ const payload = this._notificationPayloadFactory({
monitorMessage: msg heartbeatJSON: {
msg: msg
}
}); });
return this._sendNotification(webhookUrl, payload); return this._sendNotification(webhookUrl, payload);
@ -122,7 +208,7 @@ class Teams extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {
@ -130,26 +216,32 @@ class Teams extends NotificationProvider {
return okMsg; return okMsg;
} }
let url; let monitorUrl;
switch (monitorJSON["type"]) { switch (monitorJSON["type"]) {
case "http": case "http":
case "keywork": case "keywork":
url = monitorJSON["url"]; monitorUrl = monitorJSON["url"];
break; break;
case "docker": case "docker":
url = monitorJSON["docker_host"]; monitorUrl = monitorJSON["docker_host"];
break; break;
default: default:
url = monitorJSON["hostname"]; monitorUrl = monitorJSON["hostname"];
break; break;
} }
const baseURL = await setting("primaryBaseURL");
let dashboardUrl;
if (baseURL) {
dashboardUrl = baseURL + getMonitorRelativeURL(monitorJSON.id);
}
const payload = this._notificationPayloadFactory({ const payload = this._notificationPayloadFactory({
monitorMessage: heartbeatJSON.msg, heartbeatJSON: heartbeatJSON,
monitorName: monitorJSON.name, monitorName: monitorJSON.name,
monitorUrl: url, monitorUrl: monitorUrl,
status: heartbeatJSON.status, dashboardUrl: dashboardUrl,
}); });
await this._sendNotification(notification.webhookUrl, payload); await this._sendNotification(notification.webhookUrl, payload);

@ -2,14 +2,13 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class TechulusPush extends NotificationProvider { class TechulusPush extends NotificationProvider {
name = "PushByTechulus"; name = "PushByTechulus";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
await axios.post(`https://push.techulus.com/api/v1/notify/${notification.pushAPIKey}`, { await axios.post(`https://push.techulus.com/api/v1/notify/${notification.pushAPIKey}`, {

@ -2,14 +2,14 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Telegram extends NotificationProvider { class Telegram extends NotificationProvider {
name = "telegram"; name = "telegram";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
const url = "https://api.telegram.org";
try { try {
let params = { let params = {
@ -22,7 +22,7 @@ class Telegram extends NotificationProvider {
params.message_thread_id = notification.telegramMessageThreadID; params.message_thread_id = notification.telegramMessageThreadID;
} }
await axios.get(`https://api.telegram.org/bot${notification.telegramBotToken}/sendMessage`, { await axios.get(`${url}/bot${notification.telegramBotToken}/sendMessage`, {
params: params, params: params,
}); });
return okMsg; return okMsg;

@ -2,26 +2,21 @@ const NotificationProvider = require("./notification-provider");
const axios = require("axios"); const axios = require("axios");
class Twilio extends NotificationProvider { class Twilio extends NotificationProvider {
name = "twilio"; name = "twilio";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
let okMsg = "Sent Successfully."; let apiKey = notification.twilioApiKey ? notification.twilioApiKey : notification.twilioAccountSID;
let accountSID = notification.twilioAccountSID;
let apiKey = notification.twilioApiKey ? notification.twilioApiKey : accountSID;
let authToken = notification.twilioAuthToken;
try { try {
let config = { let config = {
headers: { headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8", "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
"Authorization": "Basic " + Buffer.from(apiKey + ":" + authToken).toString("base64"), "Authorization": "Basic " + Buffer.from(apiKey + ":" + notification.twilioAuthToken).toString("base64"),
} }
}; };
@ -30,9 +25,7 @@ class Twilio extends NotificationProvider {
data.append("From", notification.twilioFromNumber); data.append("From", notification.twilioFromNumber);
data.append("Body", msg); data.append("Body", msg);
let url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSID + "/Messages.json"; await axios.post(`https://api.twilio.com/2010-04-01/Accounts/${(notification.twilioAccountSID)}/Messages.json`, data, config);
await axios.post(url, data, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {

@ -4,14 +4,13 @@ const FormData = require("form-data");
const { Liquid } = require("liquidjs"); const { Liquid } = require("liquidjs");
class Webhook extends NotificationProvider { class Webhook extends NotificationProvider {
name = "webhook"; name = "webhook";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let data = { let data = {

@ -3,24 +3,22 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class WeCom extends NotificationProvider { class WeCom extends NotificationProvider {
name = "WeCom"; name = "WeCom";
/** /**
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
let WeComUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + notification.weComBotKey;
let config = { let config = {
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
}; };
let body = this.composeMessage(heartbeatJSON, msg); let body = this.composeMessage(heartbeatJSON, msg);
await axios.post(WeComUrl, body, config); await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${notification.weComBotKey}`, body, config);
return okMsg; return okMsg;
} catch (error) { } catch (error) {
this.throwGeneralAxiosError(error); this.throwGeneralAxiosError(error);

@ -0,0 +1,39 @@
const NotificationProvider = require("./notification-provider");
const axios = require("axios");
class Whapi extends NotificationProvider {
name = "whapi";
/**
* @inheritdoc
*/
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
const okMsg = "Sent Successfully.";
try {
const config = {
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer " + notification.whapiAuthToken,
}
};
let data = {
"to": notification.whapiRecipient,
"body": msg,
};
let url = (notification.whapiApiUrl || "https://gate.whapi.cloud/").replace(/\/+$/, "") + "/messages/text";
await axios.post(url, data, config);
return okMsg;
} catch (error) {
this.throwGeneralAxiosError(error);
}
}
}
module.exports = Whapi;

@ -3,7 +3,6 @@ const axios = require("axios");
const { DOWN, UP } = require("../../src/util"); const { DOWN, UP } = require("../../src/util");
class ZohoCliq extends NotificationProvider { class ZohoCliq extends NotificationProvider {
name = "ZohoCliq"; name = "ZohoCliq";
/** /**
@ -80,7 +79,7 @@ class ZohoCliq extends NotificationProvider {
* @inheritdoc * @inheritdoc
*/ */
async send(notification, msg, monitorJSON = null, heartbeatJSON = null) { async send(notification, msg, monitorJSON = null, heartbeatJSON = null) {
let okMsg = "Sent Successfully."; const okMsg = "Sent Successfully.";
try { try {
if (heartbeatJSON == null) { if (heartbeatJSON == null) {

@ -6,6 +6,7 @@ const AliyunSms = require("./notification-providers/aliyun-sms");
const Apprise = require("./notification-providers/apprise"); const Apprise = require("./notification-providers/apprise");
const Bark = require("./notification-providers/bark"); const Bark = require("./notification-providers/bark");
const ClickSendSMS = require("./notification-providers/clicksendsms"); const ClickSendSMS = require("./notification-providers/clicksendsms");
const CallMeBot = require("./notification-providers/call-me-bot");
const SMSC = require("./notification-providers/smsc"); const SMSC = require("./notification-providers/smsc");
const DingDing = require("./notification-providers/dingding"); const DingDing = require("./notification-providers/dingding");
const Discord = require("./notification-providers/discord"); const Discord = require("./notification-providers/discord");
@ -16,6 +17,7 @@ const Gorush = require("./notification-providers/gorush");
const Gotify = require("./notification-providers/gotify"); const Gotify = require("./notification-providers/gotify");
const GrafanaOncall = require("./notification-providers/grafana-oncall"); const GrafanaOncall = require("./notification-providers/grafana-oncall");
const HomeAssistant = require("./notification-providers/home-assistant"); const HomeAssistant = require("./notification-providers/home-assistant");
const HeiiOnCall = require("./notification-providers/heii-oncall");
const Kook = require("./notification-providers/kook"); const Kook = require("./notification-providers/kook");
const Line = require("./notification-providers/line"); const Line = require("./notification-providers/line");
const LineNotify = require("./notification-providers/linenotify"); const LineNotify = require("./notification-providers/linenotify");
@ -55,6 +57,9 @@ const SMSManager = require("./notification-providers/smsmanager");
const ServerChan = require("./notification-providers/serverchan"); const ServerChan = require("./notification-providers/serverchan");
const ZohoCliq = require("./notification-providers/zoho-cliq"); const ZohoCliq = require("./notification-providers/zoho-cliq");
const SevenIO = require("./notification-providers/sevenio"); const SevenIO = require("./notification-providers/sevenio");
const Whapi = require("./notification-providers/whapi");
const GtxMessaging = require("./notification-providers/gtx-messaging");
const Cellsynt = require("./notification-providers/cellsynt");
class Notification { class Notification {
@ -78,6 +83,7 @@ class Notification {
new Apprise(), new Apprise(),
new Bark(), new Bark(),
new ClickSendSMS(), new ClickSendSMS(),
new CallMeBot(),
new SMSC(), new SMSC(),
new DingDing(), new DingDing(),
new Discord(), new Discord(),
@ -88,6 +94,7 @@ class Notification {
new Gotify(), new Gotify(),
new GrafanaOncall(), new GrafanaOncall(),
new HomeAssistant(), new HomeAssistant(),
new HeiiOnCall(),
new Kook(), new Kook(),
new Line(), new Line(),
new LineNotify(), new LineNotify(),
@ -127,6 +134,9 @@ class Notification {
new GoAlert(), new GoAlert(),
new ZohoCliq(), new ZohoCliq(),
new SevenIO(), new SevenIO(),
new Whapi(),
new GtxMessaging(),
new Cellsynt(),
]; ];
for (let item of list) { for (let item of list) {
if (! item.name) { if (! item.name) {

@ -40,16 +40,12 @@ router.get("/api/status-page/:slug", cache("5 minutes"), async (request, respons
]); ]);
if (!statusPage) { if (!statusPage) {
sendHttpError(response, "Status Page Not Found");
return null; return null;
} }
let statusPageData = await StatusPage.getStatusPageData(statusPage); let statusPageData = await StatusPage.getStatusPageData(statusPage);
if (!statusPageData) {
sendHttpError(response, "Not Found");
return;
}
// Response // Response
response.json(statusPageData); response.json(statusPageData);

@ -294,7 +294,7 @@ let needSetup = false;
log.debug("server", "Adding socket handler"); log.debug("server", "Adding socket handler");
io.on("connection", async (socket) => { io.on("connection", async (socket) => {
sendInfo(socket, true); await sendInfo(socket, true);
if (needSetup) { if (needSetup) {
log.info("server", "Redirect to setup page"); log.info("server", "Redirect to setup page");
@ -326,7 +326,7 @@ let needSetup = false;
} }
log.debug("auth", "afterLogin"); log.debug("auth", "afterLogin");
afterLogin(socket, user); await afterLogin(socket, user);
log.debug("auth", "afterLogin ok"); log.debug("auth", "afterLogin ok");
log.info("auth", `Successfully logged in user ${decoded.username}. IP=${clientIP}`); log.info("auth", `Successfully logged in user ${decoded.username}. IP=${clientIP}`);
@ -382,7 +382,7 @@ let needSetup = false;
if (user) { if (user) {
if (user.twofa_status === 0) { if (user.twofa_status === 0) {
afterLogin(socket, user); await afterLogin(socket, user);
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`); log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
@ -405,7 +405,7 @@ let needSetup = false;
let verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions); let verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions);
if (user.twofa_last_token !== data.token && verify) { if (user.twofa_last_token !== data.token && verify) {
afterLogin(socket, user); await afterLogin(socket, user);
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [ await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
data.token, data.token,
@ -986,7 +986,7 @@ let needSetup = false;
log.info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`); log.info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`);
if (monitorID in server.monitorList) { if (monitorID in server.monitorList) {
server.monitorList[monitorID].stop(); await server.monitorList[monitorID].stop();
delete server.monitorList[monitorID]; delete server.monitorList[monitorID];
} }
@ -1351,8 +1351,8 @@ let needSetup = false;
msgi18n: true, msgi18n: true,
}); });
sendInfo(socket); await sendInfo(socket);
server.sendMaintenanceList(socket); await server.sendMaintenanceList(socket);
} catch (e) { } catch (e) {
callback({ callback({
@ -1491,6 +1491,14 @@ let needSetup = false;
log.info("manage", `Clear Statistics User ID: ${socket.userID}`); log.info("manage", `Clear Statistics User ID: ${socket.userID}`);
await R.exec("DELETE FROM heartbeat"); await R.exec("DELETE FROM heartbeat");
await R.exec("DELETE FROM stat_daily");
await R.exec("DELETE FROM stat_hourly");
await R.exec("DELETE FROM stat_minutely");
// Restart all monitors to reset the stats
for (let monitorID in server.monitorList) {
await restartMonitor(socket.userID, monitorID);
}
callback({ callback({
ok: true, ok: true,
@ -1524,7 +1532,7 @@ let needSetup = false;
log.debug("auth", "check auto login"); log.debug("auth", "check auto login");
if (await setting("disableAuth")) { if (await setting("disableAuth")) {
log.info("auth", "Disabled Auth: auto login to admin"); log.info("auth", "Disabled Auth: auto login to admin");
afterLogin(socket, await R.findOne("user")); await afterLogin(socket, await R.findOne("user"));
socket.emit("autoLogin"); socket.emit("autoLogin");
} else { } else {
log.debug("auth", "need auth"); log.debug("auth", "need auth");
@ -1540,7 +1548,7 @@ let needSetup = false;
process.exit(1); process.exit(1);
}); });
server.start(); await server.start();
server.httpServer.listen(port, hostname, () => { server.httpServer.listen(port, hostname, () => {
if (hostname) { if (hostname) {
@ -1611,15 +1619,15 @@ async function afterLogin(socket, user) {
socket.join(user.id); socket.join(user.id);
let monitorList = await server.sendMonitorList(socket); let monitorList = await server.sendMonitorList(socket);
sendInfo(socket); await Promise.allSettled([
server.sendMaintenanceList(socket); sendInfo(socket),
sendNotificationList(socket); server.sendMaintenanceList(socket),
sendProxyList(socket); sendNotificationList(socket),
sendDockerHostList(socket); sendProxyList(socket),
sendAPIKeyList(socket); sendDockerHostList(socket),
sendRemoteBrowserList(socket); sendAPIKeyList(socket),
sendRemoteBrowserList(socket),
await sleep(500); ]);
await StatusPage.sendStatusPageList(io, socket); await StatusPage.sendStatusPageList(io, socket);
@ -1695,11 +1703,11 @@ async function startMonitor(userID, monitorID) {
]); ]);
if (monitor.id in server.monitorList) { if (monitor.id in server.monitorList) {
server.monitorList[monitor.id].stop(); await server.monitorList[monitor.id].stop();
} }
server.monitorList[monitor.id] = monitor; server.monitorList[monitor.id] = monitor;
monitor.start(io); await monitor.start(io);
} }
/** /**
@ -1729,7 +1737,7 @@ async function pauseMonitor(userID, monitorID) {
]); ]);
if (monitorID in server.monitorList) { if (monitorID in server.monitorList) {
server.monitorList[monitorID].stop(); await server.monitorList[monitorID].stop();
server.monitorList[monitorID].active = 0; server.monitorList[monitorID].active = 0;
} }
} }
@ -1746,7 +1754,7 @@ async function startMonitors() {
} }
for (let monitor of list) { for (let monitor of list) {
monitor.start(io); await monitor.start(io);
// Give some delays, so all monitors won't make request at the same moment when just start the server. // Give some delays, so all monitors won't make request at the same moment when just start the server.
await sleep(getRandomInt(300, 1000)); await sleep(getRandomInt(300, 1000));
} }
@ -1767,7 +1775,7 @@ async function shutdownFunction(signal) {
log.info("server", "Stopping all monitors"); log.info("server", "Stopping all monitors");
for (let id in server.monitorList) { for (let id in server.monitorList) {
let monitor = server.monitorList[id]; let monitor = server.monitorList[id];
monitor.stop(); await monitor.stop();
} }
await sleep(2000); await sleep(2000);
await Database.close(); await Database.close();

@ -27,7 +27,7 @@ module.exports = (socket) => {
socket.on("shrinkDatabase", async (callback) => { socket.on("shrinkDatabase", async (callback) => {
try { try {
checkLogin(socket); checkLogin(socket);
Database.shrink(); await Database.shrink();
callback({ callback({
ok: true, ok: true,
}); });

@ -34,16 +34,25 @@ class UptimeCalculator {
*/ */
minutelyUptimeDataList = new LimitQueue(24 * 60); minutelyUptimeDataList = new LimitQueue(24 * 60);
/**
* Recent 30-day uptime, each item is a 1-hour interval
* Key: {number} DivisionKey
* @type {LimitQueue<number,string>}
*/
hourlyUptimeDataList = new LimitQueue(30 * 24);
/** /**
* Daily uptime data, * Daily uptime data,
* Key: {number} DailyKey * Key: {number} DailyKey
*/ */
dailyUptimeDataList = new LimitQueue(365); dailyUptimeDataList = new LimitQueue(365);
lastDailyUptimeData = null;
lastUptimeData = null; lastUptimeData = null;
lastHourlyUptimeData = null;
lastDailyUptimeData = null;
lastDailyStatBean = null; lastDailyStatBean = null;
lastHourlyStatBean = null;
lastMinutelyStatBean = null; lastMinutelyStatBean = null;
/** /**
@ -53,6 +62,10 @@ class UptimeCalculator {
* @returns {Promise<UptimeCalculator>} UptimeCalculator * @returns {Promise<UptimeCalculator>} UptimeCalculator
*/ */
static async getUptimeCalculator(monitorID) { static async getUptimeCalculator(monitorID) {
if (!monitorID) {
throw new Error("Monitor ID is required");
}
if (!UptimeCalculator.list[monitorID]) { if (!UptimeCalculator.list[monitorID]) {
UptimeCalculator.list[monitorID] = new UptimeCalculator(); UptimeCalculator.list[monitorID] = new UptimeCalculator();
await UptimeCalculator.list[monitorID].init(monitorID); await UptimeCalculator.list[monitorID].init(monitorID);
@ -103,27 +116,73 @@ class UptimeCalculator {
]); ]);
for (let bean of minutelyStatBeans) { for (let bean of minutelyStatBeans) {
let data = {
up: bean.up,
down: bean.down,
avgPing: bean.ping,
minPing: bean.pingMin,
maxPing: bean.pingMax,
};
if (bean.extras != null) {
data = {
...data,
...JSON.parse(bean.extras),
};
}
let key = bean.timestamp; let key = bean.timestamp;
this.minutelyUptimeDataList.push(key, { this.minutelyUptimeDataList.push(key, data);
}
// Load hourly data from database (recent 30 days only)
let hourlyStatBeans = await R.find("stat_hourly", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [
monitorID,
this.getHourlyKey(now.subtract(30, "day")),
]);
for (let bean of hourlyStatBeans) {
let data = {
up: bean.up, up: bean.up,
down: bean.down, down: bean.down,
avgPing: bean.ping, avgPing: bean.ping,
}); minPing: bean.pingMin,
maxPing: bean.pingMax,
};
if (bean.extras != null) {
data = {
...data,
...JSON.parse(bean.extras),
};
}
this.hourlyUptimeDataList.push(bean.timestamp, data);
} }
// Load daily data from database (recent 365 days only) // Load daily data from database (recent 365 days only)
let dailyStatBeans = await R.find("stat_daily", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [ let dailyStatBeans = await R.find("stat_daily", " monitor_id = ? AND timestamp > ? ORDER BY timestamp", [
monitorID, monitorID,
this.getDailyKey(now.subtract(365, "day").unix()), this.getDailyKey(now.subtract(365, "day")),
]); ]);
for (let bean of dailyStatBeans) { for (let bean of dailyStatBeans) {
let key = bean.timestamp; let data = {
this.dailyUptimeDataList.push(key, {
up: bean.up, up: bean.up,
down: bean.down, down: bean.down,
avgPing: bean.ping, avgPing: bean.ping,
}); minPing: bean.pingMin,
maxPing: bean.pingMax,
};
if (bean.extras != null) {
data = {
...data,
...JSON.parse(bean.extras),
};
}
this.dailyUptimeDataList.push(bean.timestamp, data);
} }
} }
@ -136,11 +195,6 @@ class UptimeCalculator {
async update(status, ping = 0) { async update(status, ping = 0) {
let date = this.getCurrentDate(); let date = this.getCurrentDate();
// Don't count MAINTENANCE into uptime
if (status === MAINTENANCE) {
return date;
}
let flatStatus = this.flatStatus(status); let flatStatus = this.flatStatus(status);
if (flatStatus === DOWN && ping > 0) { if (flatStatus === DOWN && ping > 0) {
@ -148,13 +202,21 @@ class UptimeCalculator {
} }
let divisionKey = this.getMinutelyKey(date); let divisionKey = this.getMinutelyKey(date);
let dailyKey = this.getDailyKey(divisionKey); let hourlyKey = this.getHourlyKey(date);
let dailyKey = this.getDailyKey(date);
let minutelyData = this.minutelyUptimeDataList[divisionKey]; let minutelyData = this.minutelyUptimeDataList[divisionKey];
let hourlyData = this.hourlyUptimeDataList[hourlyKey];
let dailyData = this.dailyUptimeDataList[dailyKey]; let dailyData = this.dailyUptimeDataList[dailyKey];
if (flatStatus === UP) { if (status === MAINTENANCE) {
minutelyData.maintenance = minutelyData.maintenance ? minutelyData.maintenance + 1 : 1;
hourlyData.maintenance = hourlyData.maintenance ? hourlyData.maintenance + 1 : 1;
dailyData.maintenance = dailyData.maintenance ? dailyData.maintenance + 1 : 1;
} else if (flatStatus === UP) {
minutelyData.up += 1; minutelyData.up += 1;
hourlyData.up += 1;
dailyData.up += 1; dailyData.up += 1;
// Only UP status can update the ping // Only UP status can update the ping
@ -163,32 +225,57 @@ class UptimeCalculator {
// The first beat of the minute, the ping is the current ping // The first beat of the minute, the ping is the current ping
if (minutelyData.up === 1) { if (minutelyData.up === 1) {
minutelyData.avgPing = ping; minutelyData.avgPing = ping;
minutelyData.minPing = ping;
minutelyData.maxPing = ping;
} else { } else {
minutelyData.avgPing = (minutelyData.avgPing * (minutelyData.up - 1) + ping) / minutelyData.up; minutelyData.avgPing = (minutelyData.avgPing * (minutelyData.up - 1) + ping) / minutelyData.up;
minutelyData.minPing = Math.min(minutelyData.minPing, ping);
minutelyData.maxPing = Math.max(minutelyData.maxPing, ping);
}
// Add avg ping
// The first beat of the hour, the ping is the current ping
if (hourlyData.up === 1) {
hourlyData.avgPing = ping;
hourlyData.minPing = ping;
hourlyData.maxPing = ping;
} else {
hourlyData.avgPing = (hourlyData.avgPing * (hourlyData.up - 1) + ping) / hourlyData.up;
hourlyData.minPing = Math.min(hourlyData.minPing, ping);
hourlyData.maxPing = Math.max(hourlyData.maxPing, ping);
} }
// Add avg ping (daily) // Add avg ping (daily)
// The first beat of the day, the ping is the current ping // The first beat of the day, the ping is the current ping
if (minutelyData.up === 1) { if (dailyData.up === 1) {
dailyData.avgPing = ping; dailyData.avgPing = ping;
dailyData.minPing = ping;
dailyData.maxPing = ping;
} else { } else {
dailyData.avgPing = (dailyData.avgPing * (dailyData.up - 1) + ping) / dailyData.up; dailyData.avgPing = (dailyData.avgPing * (dailyData.up - 1) + ping) / dailyData.up;
dailyData.minPing = Math.min(dailyData.minPing, ping);
dailyData.maxPing = Math.max(dailyData.maxPing, ping);
} }
} }
} else { } else if (flatStatus === DOWN) {
minutelyData.down += 1; minutelyData.down += 1;
hourlyData.down += 1;
dailyData.down += 1; dailyData.down += 1;
} }
if (dailyData !== this.lastDailyUptimeData) {
this.lastDailyUptimeData = dailyData;
}
if (minutelyData !== this.lastUptimeData) { if (minutelyData !== this.lastUptimeData) {
this.lastUptimeData = minutelyData; this.lastUptimeData = minutelyData;
} }
if (hourlyData !== this.lastHourlyUptimeData) {
this.lastHourlyUptimeData = hourlyData;
}
if (dailyData !== this.lastDailyUptimeData) {
this.lastDailyUptimeData = dailyData;
}
// Don't store data in test mode // Don't store data in test mode
if (process.env.TEST_BACKEND) { if (process.env.TEST_BACKEND) {
log.debug("uptime-calc", "Skip storing data in test mode"); log.debug("uptime-calc", "Skip storing data in test mode");
@ -199,12 +286,45 @@ class UptimeCalculator {
dailyStatBean.up = dailyData.up; dailyStatBean.up = dailyData.up;
dailyStatBean.down = dailyData.down; dailyStatBean.down = dailyData.down;
dailyStatBean.ping = dailyData.avgPing; dailyStatBean.ping = dailyData.avgPing;
dailyStatBean.pingMin = dailyData.minPing;
dailyStatBean.pingMax = dailyData.maxPing;
{
// eslint-disable-next-line no-unused-vars
const { up, down, avgPing, minPing, maxPing, ...extras } = dailyData;
if (Object.keys(extras).length > 0) {
dailyStatBean.extras = JSON.stringify(extras);
}
}
await R.store(dailyStatBean); await R.store(dailyStatBean);
let hourlyStatBean = await this.getHourlyStatBean(hourlyKey);
hourlyStatBean.up = hourlyData.up;
hourlyStatBean.down = hourlyData.down;
hourlyStatBean.ping = hourlyData.avgPing;
hourlyStatBean.pingMin = hourlyData.minPing;
hourlyStatBean.pingMax = hourlyData.maxPing;
{
// eslint-disable-next-line no-unused-vars
const { up, down, avgPing, minPing, maxPing, ...extras } = hourlyData;
if (Object.keys(extras).length > 0) {
hourlyStatBean.extras = JSON.stringify(extras);
}
}
await R.store(hourlyStatBean);
let minutelyStatBean = await this.getMinutelyStatBean(divisionKey); let minutelyStatBean = await this.getMinutelyStatBean(divisionKey);
minutelyStatBean.up = minutelyData.up; minutelyStatBean.up = minutelyData.up;
minutelyStatBean.down = minutelyData.down; minutelyStatBean.down = minutelyData.down;
minutelyStatBean.ping = minutelyData.avgPing; minutelyStatBean.ping = minutelyData.avgPing;
minutelyStatBean.pingMin = minutelyData.minPing;
minutelyStatBean.pingMax = minutelyData.maxPing;
{
// eslint-disable-next-line no-unused-vars
const { up, down, avgPing, minPing, maxPing, ...extras } = minutelyData;
if (Object.keys(extras).length > 0) {
minutelyStatBean.extras = JSON.stringify(extras);
}
}
await R.store(minutelyStatBean); await R.store(minutelyStatBean);
// Remove the old data // Remove the old data
@ -214,6 +334,11 @@ class UptimeCalculator {
this.getMinutelyKey(date.subtract(24, "hour")), this.getMinutelyKey(date.subtract(24, "hour")),
]); ]);
await R.exec("DELETE FROM stat_hourly WHERE monitor_id = ? AND timestamp < ?", [
this.monitorID,
this.getHourlyKey(date.subtract(30, "day")),
]);
return date; return date;
} }
@ -242,6 +367,31 @@ class UptimeCalculator {
return this.lastDailyStatBean; return this.lastDailyStatBean;
} }
/**
* Get the hourly stat bean
* @param {number} timestamp milliseconds
* @returns {Promise<import("redbean-node").Bean>} stat_hourly bean
*/
async getHourlyStatBean(timestamp) {
if (this.lastHourlyStatBean && this.lastHourlyStatBean.timestamp === timestamp) {
return this.lastHourlyStatBean;
}
let bean = await R.findOne("stat_hourly", " monitor_id = ? AND timestamp = ?", [
this.monitorID,
timestamp,
]);
if (!bean) {
bean = R.dispense("stat_hourly");
bean.monitor_id = this.monitorID;
bean.timestamp = timestamp;
}
this.lastHourlyStatBean = bean;
return this.lastHourlyStatBean;
}
/** /**
* Get the minutely stat bean * Get the minutely stat bean
* @param {number} timestamp milliseconds * @param {number} timestamp milliseconds
@ -268,11 +418,12 @@ class UptimeCalculator {
} }
/** /**
* Convert timestamp to minutely key
* @param {dayjs.Dayjs} date The heartbeat date * @param {dayjs.Dayjs} date The heartbeat date
* @returns {number} Timestamp * @returns {number} Timestamp
*/ */
getMinutelyKey(date) { getMinutelyKey(date) {
// Convert the current date to the nearest minute (e.g. 2021-01-01 12:34:56 -> 2021-01-01 12:34:00) // Truncate value to minutes (e.g. 2021-01-01 12:34:56 -> 2021-01-01 12:34:00)
date = date.startOf("minute"); date = date.startOf("minute");
// Convert to timestamp in second // Convert to timestamp in second
@ -283,6 +434,8 @@ class UptimeCalculator {
up: 0, up: 0,
down: 0, down: 0,
avgPing: 0, avgPing: 0,
minPing: 0,
maxPing: 0,
}); });
} }
@ -290,14 +443,37 @@ class UptimeCalculator {
} }
/** /**
* Convert timestamp to daily key * Convert timestamp to hourly key
* @param {number} timestamp Timestamp * @param {dayjs.Dayjs} date The heartbeat date
* @returns {number} Timestamp * @returns {number} Timestamp
*/ */
getDailyKey(timestamp) { getHourlyKey(date) {
let date = dayjs.unix(timestamp); // Truncate value to hours (e.g. 2021-01-01 12:34:56 -> 2021-01-01 12:00:00)
date = date.startOf("hour");
// Convert the date to the nearest day (e.g. 2021-01-01 12:34:56 -> 2021-01-01 00:00:00) // Convert to timestamp in second
let divisionKey = date.unix();
if (! (divisionKey in this.hourlyUptimeDataList)) {
this.hourlyUptimeDataList.push(divisionKey, {
up: 0,
down: 0,
avgPing: 0,
minPing: 0,
maxPing: 0,
});
}
return divisionKey;
}
/**
* Convert timestamp to daily key
* @param {dayjs.Dayjs} date The heartbeat date
* @returns {number} Timestamp
*/
getDailyKey(date) {
// Truncate value to start of day (e.g. 2021-01-01 12:34:56 -> 2021-01-01 00:00:00)
// Considering if the user keep changing could affect the calculation, so use UTC time to avoid this problem. // Considering if the user keep changing could affect the calculation, so use UTC time to avoid this problem.
date = date.utc().startOf("day"); date = date.utc().startOf("day");
let dailyKey = date.unix(); let dailyKey = date.unix();
@ -307,22 +483,44 @@ class UptimeCalculator {
up: 0, up: 0,
down: 0, down: 0,
avgPing: 0, avgPing: 0,
minPing: 0,
maxPing: 0,
}); });
} }
return dailyKey; return dailyKey;
} }
/**
* Convert timestamp to key
* @param {dayjs.Dayjs} datetime Datetime
* @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned
* @returns {number} Timestamp
* @throws {Error} If the type is invalid
*/
getKey(datetime, type) {
switch (type) {
case "day":
return this.getDailyKey(datetime);
case "hour":
return this.getHourlyKey(datetime);
case "minute":
return this.getMinutelyKey(datetime);
default:
throw new Error("Invalid type");
}
}
/** /**
* Flat status to UP or DOWN * Flat status to UP or DOWN
* @param {number} status the status which schould be turned into a flat status * @param {number} status the status which should be turned into a flat status
* @returns {UP|DOWN|PENDING} The flat status * @returns {UP|DOWN|PENDING} The flat status
* @throws {Error} Invalid status * @throws {Error} Invalid status
*/ */
flatStatus(status) { flatStatus(status) {
switch (status) { switch (status) {
case UP: case UP:
// case MAINTENANCE: case MAINTENANCE:
return UP; return UP;
case DOWN: case DOWN:
case PENDING: case PENDING:
@ -333,21 +531,21 @@ class UptimeCalculator {
/** /**
* @param {number} num the number of data points which are expected to be returned * @param {number} num the number of data points which are expected to be returned
* @param {"day" | "minute"} type the type of data which is expected to be returned * @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned
* @returns {UptimeDataResult} UptimeDataResult * @returns {UptimeDataResult} UptimeDataResult
* @throws {Error} The maximum number of minutes greater than 1440 * @throws {Error} The maximum number of minutes greater than 1440
*/ */
getData(num, type = "day") { getData(num, type = "day") {
let key;
if (type === "day") { if (type === "hour" && num > 24 * 30) {
key = this.getDailyKey(this.getCurrentDate().unix()); throw new Error("The maximum number of hours is 720");
} else {
if (num > 24 * 60) {
throw new Error("The maximum number of minutes is 1440");
}
key = this.getMinutelyKey(this.getCurrentDate());
} }
if (type === "minute" && num > 24 * 60) {
throw new Error("The maximum number of minutes is 1440");
}
// Get the current time period key based on the type
let key = this.getKey(this.getCurrentDate(), type);
let total = { let total = {
up: 0, up: 0,
@ -357,20 +555,37 @@ class UptimeCalculator {
let totalPing = 0; let totalPing = 0;
let endTimestamp; let endTimestamp;
if (type === "day") { // Get the eariest timestamp of the required period based on the type
endTimestamp = key - 86400 * (num - 1); switch (type) {
} else { case "day":
endTimestamp = key - 60 * (num - 1); endTimestamp = key - 86400 * (num - 1);
break;
case "hour":
endTimestamp = key - 3600 * (num - 1);
break;
case "minute":
endTimestamp = key - 60 * (num - 1);
break;
default:
throw new Error("Invalid type");
} }
// Sum up all data in the specified time range // Sum up all data in the specified time range
while (key >= endTimestamp) { while (key >= endTimestamp) {
let data; let data;
if (type === "day") { switch (type) {
data = this.dailyUptimeDataList[key]; case "day":
} else { data = this.dailyUptimeDataList[key];
data = this.minutelyUptimeDataList[key]; break;
case "hour":
data = this.hourlyUptimeDataList[key];
break;
case "minute":
data = this.minutelyUptimeDataList[key];
break;
default:
throw new Error("Invalid type");
} }
if (data) { if (data) {
@ -379,27 +594,53 @@ class UptimeCalculator {
totalPing += data.avgPing * data.up; totalPing += data.avgPing * data.up;
} }
// Previous day // Set key to the previous time period
if (type === "day") { switch (type) {
key -= 86400; case "day":
} else { key -= 86400;
key -= 60; break;
case "hour":
key -= 3600;
break;
case "minute":
key -= 60;
break;
default:
throw new Error("Invalid type");
} }
} }
let uptimeData = new UptimeDataResult(); let uptimeData = new UptimeDataResult();
// If there is no data in the previous time ranges, use the last data?
if (total.up === 0 && total.down === 0) { if (total.up === 0 && total.down === 0) {
if (type === "day" && this.lastDailyUptimeData) { switch (type) {
total = this.lastDailyUptimeData; case "day":
totalPing = total.avgPing * total.up; if (this.lastDailyUptimeData) {
} else if (type === "minute" && this.lastUptimeData) { total = this.lastDailyUptimeData;
total = this.lastUptimeData; totalPing = total.avgPing * total.up;
totalPing = total.avgPing * total.up; } else {
} else { return uptimeData;
uptimeData.uptime = 0; }
uptimeData.avgPing = null; break;
return uptimeData; case "hour":
if (this.lastHourlyUptimeData) {
total = this.lastHourlyUptimeData;
totalPing = total.avgPing * total.up;
} else {
return uptimeData;
}
break;
case "minute":
if (this.lastUptimeData) {
total = this.lastUptimeData;
totalPing = total.avgPing * total.up;
} else {
return uptimeData;
}
break;
default:
throw new Error("Invalid type");
} }
} }
@ -411,11 +652,94 @@ class UptimeCalculator {
avgPing = totalPing / total.up; avgPing = totalPing / total.up;
} }
uptimeData.uptime = total.up / (total.up + total.down); if (total.up + total.down === 0) {
uptimeData.uptime = 0;
} else {
uptimeData.uptime = total.up / (total.up + total.down);
}
uptimeData.avgPing = avgPing; uptimeData.avgPing = avgPing;
return uptimeData; return uptimeData;
} }
/**
* Get data in form of an array
* @param {number} num the number of data points which are expected to be returned
* @param {"day" | "hour" | "minute"} type the type of data which is expected to be returned
* @returns {Array<object>} uptime data
* @throws {Error} The maximum number of minutes greater than 1440
*/
getDataArray(num, type = "day") {
if (type === "hour" && num > 24 * 30) {
throw new Error("The maximum number of hours is 720");
}
if (type === "minute" && num > 24 * 60) {
throw new Error("The maximum number of minutes is 1440");
}
// Get the current time period key based on the type
let key = this.getKey(this.getCurrentDate(), type);
let result = [];
let endTimestamp;
// Get the eariest timestamp of the required period based on the type
switch (type) {
case "day":
endTimestamp = key - 86400 * (num - 1);
break;
case "hour":
endTimestamp = key - 3600 * (num - 1);
break;
case "minute":
endTimestamp = key - 60 * (num - 1);
break;
default:
throw new Error("Invalid type");
}
// Get datapoints in the specified time range
while (key >= endTimestamp) {
let data;
switch (type) {
case "day":
data = this.dailyUptimeDataList[key];
break;
case "hour":
data = this.hourlyUptimeDataList[key];
break;
case "minute":
data = this.minutelyUptimeDataList[key];
break;
default:
throw new Error("Invalid type");
}
if (data) {
data.timestamp = key;
result.push(data);
}
// Set key to the previous time period
switch (type) {
case "day":
key -= 86400;
break;
case "hour":
key -= 3600;
break;
case "minute":
key -= 60;
break;
default:
throw new Error("Invalid type");
}
}
return result;
}
/** /**
* Get the uptime data by duration * Get the uptime data by duration
* @param {'24h'|'30d'|'1y'} duration Only accept 24h, 30d, 1y * @param {'24h'|'30d'|'1y'} duration Only accept 24h, 30d, 1y
@ -446,7 +770,7 @@ class UptimeCalculator {
* @returns {UptimeDataResult} UptimeDataResult * @returns {UptimeDataResult} UptimeDataResult
*/ */
get7Day() { get7Day() {
return this.getData(7); return this.getData(168, "hour");
} }
/** /**
@ -464,7 +788,7 @@ class UptimeCalculator {
} }
/** /**
* @returns {dayjs.Dayjs} Current date * @returns {dayjs.Dayjs} Current datetime in UTC
*/ */
getCurrentDate() { getCurrentDate() {
return dayjs.utc(); return dayjs.utc();
@ -476,12 +800,12 @@ class UptimeDataResult {
/** /**
* @type {number} Uptime * @type {number} Uptime
*/ */
uptime; uptime = 0;
/** /**
* @type {number} Average ping * @type {number} Average ping
*/ */
avgPing; avgPing = null;
} }
module.exports = { module.exports = {

@ -195,7 +195,7 @@ class UptimeKumaServer {
/** /**
* Send list of monitors to client * Send list of monitors to client
* @param {Socket} socket Socket to send list on * @param {Socket} socket Socket to send list on
* @returns {object} List of monitors * @returns {Promise<object>} List of monitors
*/ */
async sendMonitorList(socket) { async sendMonitorList(socket) {
let list = await this.getMonitorJSONList(socket.userID); let list = await this.getMonitorJSONList(socket.userID);
@ -227,7 +227,7 @@ class UptimeKumaServer {
/** /**
* Send maintenance list to client * Send maintenance list to client
* @param {Socket} socket Socket.io instance to send to * @param {Socket} socket Socket.io instance to send to
* @returns {object} Maintenance list * @returns {Promise<object>} Maintenance list
*/ */
async sendMaintenanceList(socket) { async sendMaintenanceList(socket) {
return await this.sendMaintenanceListByUserID(socket.userID); return await this.sendMaintenanceListByUserID(socket.userID);
@ -236,7 +236,7 @@ class UptimeKumaServer {
/** /**
* Send list of maintenances to user * Send list of maintenances to user
* @param {number} userID User to send list to * @param {number} userID User to send list to
* @returns {object} Maintenance list * @returns {Promise<object>} Maintenance list
*/ */
async sendMaintenanceListByUserID(userID) { async sendMaintenanceListByUserID(userID) {
let list = await this.getMaintenanceJSONList(userID); let list = await this.getMaintenanceJSONList(userID);

@ -128,7 +128,7 @@ exports.ping = async (hostname, size = 56) => {
return await exports.pingAsync(hostname, false, size); return await exports.pingAsync(hostname, false, size);
} catch (e) { } catch (e) {
// If the host cannot be resolved, try again with ipv6 // If the host cannot be resolved, try again with ipv6
console.debug("ping", "IPv6 error message: " + e.message); log.debug("ping", "IPv6 error message: " + e.message);
// As node-ping does not report a specific error for this, try again if it is an empty message with ipv6 no matter what. // As node-ping does not report a specific error for this, try again if it is an empty message with ipv6 no matter what.
if (!e.message) { if (!e.message) {

@ -4,6 +4,7 @@ $warning: #f8a306;
$maintenance: #1747f5; $maintenance: #1747f5;
$link-color: #111; $link-color: #111;
$border-radius: 50rem; $border-radius: 50rem;
$secondary-text: #aaa;
$highlight: #7ce8a4; $highlight: #7ce8a4;
$highlight-white: #e7faec; $highlight-white: #e7faec;

@ -309,7 +309,7 @@ export default {
} }
.word { .word {
color: #aaa; color: $secondary-text;
font-size: 12px; font-size: 12px;
} }

@ -115,11 +115,13 @@ export default {
"apprise": this.$t("apprise"), "apprise": this.$t("apprise"),
"Bark": "Bark", "Bark": "Bark",
"clicksendsms": "ClickSend SMS", "clicksendsms": "ClickSend SMS",
"CallMeBot": "CallMeBot (WhatsApp, Telegram Call, Facebook Messanger)",
"discord": "Discord", "discord": "Discord",
"GoogleChat": "Google Chat (Google Workspace)", "GoogleChat": "Google Chat (Google Workspace)",
"gorush": "Gorush", "gorush": "Gorush",
"gotify": "Gotify", "gotify": "Gotify",
"GrafanaOncall": "Grafana Oncall", "GrafanaOncall": "Grafana Oncall",
"HeiiOnCall": "Heii On-Call",
"HomeAssistant": "Home Assistant", "HomeAssistant": "Home Assistant",
"Kook": "Kook", "Kook": "Kook",
"line": "LINE Messenger", "line": "LINE Messenger",
@ -153,6 +155,9 @@ export default {
"GoAlert": "GoAlert", "GoAlert": "GoAlert",
"ZohoCliq": "ZohoCliq", "ZohoCliq": "ZohoCliq",
"SevenIO": "SevenIO", "SevenIO": "SevenIO",
"whapi": "WhatsApp (Whapi)",
"gtxmessaging": "GtxMessaging",
"Cellsynt": "Cellsynt",
}; };
// Put notifications here if it's not supported in most regions or its documentation is not in English // Put notifications here if it's not supported in most regions or its documentation is not in English

@ -288,7 +288,7 @@ export default {
/** /**
* Submit tag and monitorTag changes to server * Submit tag and monitorTag changes to server
* @returns {void} * @returns {Promise<void>}
*/ */
async submit() { async submit() {
this.processing = true; this.processing = true;
@ -348,7 +348,7 @@ export default {
/** /**
* Delete the editing tag from server * Delete the editing tag from server
* @returns {void} * @returns {Promise<void>}
*/ */
async deleteTag() { async deleteTag() {
this.processing = true; this.processing = true;

@ -384,7 +384,7 @@ export default {
/** /**
* Submit the form data * Submit the form data
* @param {number} monitorId ID of monitor this change affects * @param {number} monitorId ID of monitor this change affects
* @returns {void} * @returns {Promise<void>}
*/ */
async submit(monitorId) { async submit(monitorId) {
console.log(`Submitting tag changes for monitor ${monitorId}...`); console.log(`Submitting tag changes for monitor ${monitorId}...`);

@ -0,0 +1,13 @@
<template>
<div class="mb-3">
<label for="callmebot-endpoint" class="form-label">{{ $t("Endpoint") }}</label>
<input id="callmebot-endpoint" v-model="$parent.notification.callMeBotEndpoint" type="text" class="form-control" required>
<i18n-t tag="div" keypath="callMeBotGet" class="form-text">
<a href="https://www.callmebot.com/blog/free-api-facebook-messenger/" target="_blank">Facebook Messenger</a>
<a href="https://www.callmebot.com/blog/test-whatsapp-api/" target="_blank">WhatsApp</a>
<a href="https://www.callmebot.com/blog/telegram-phone-call-using-your-browser/" target="_blank">Telegram Call</a>
1 message / 10 sec; 1 call / 65 sec
<!--There is no public documentation available. This data is based on testing!-->
</i18n-t>
</div>
</template>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save