notify-frame 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 elves / tango_util / python
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: notify-frame
3
+ Version: 0.1.2
4
+ Summary: Lightweight REST notification client/server for calculation scripts
5
+ Requires-Python: >=3.8
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: requests>=2.20
9
+ Provides-Extra: server
10
+ Requires-Dist: fastapi>=0.100; extra == "server"
11
+ Requires-Dist: pydantic>=2.0; extra == "server"
12
+ Requires-Dist: uvicorn>=0.20; extra == "server"
13
+ Provides-Extra: windows-outlook
14
+ Requires-Dist: pywin32>=300; platform_system == "Windows" and extra == "windows-outlook"
15
+ Dynamic: license-file
@@ -0,0 +1,206 @@
1
+ # notify
2
+
3
+ 計算機から自分の PC 上の通知サーバーへ REST API で通知要求を送り、PC
4
+ 側からメールを送信する Python パッケージです。
5
+
6
+ 計算機側にはメールアカウント、SMTP
7
+ パスワード、アプリパスワードを置きません。メール送信は PC
8
+ 側だけで行います。
9
+
10
+ ## v0.1.0
11
+
12
+ v0.1.0 では、計算スクリプトから通知を簡単に呼び出せるように
13
+ `configure()` を追加しました。また、サーバー設定を環境変数だけでなく
14
+ `NotifyConfig` へ直接指定できるようにしました。
15
+
16
+ ### 計算機側
17
+
18
+ 最初に一度だけ通知サーバーを設定します。
19
+
20
+ ``` python
21
+ from notify import configure, notify
22
+
23
+ configure(
24
+ server_url="http://your-pc-hostname-or-ip:8000/notify",
25
+ token="shared-token",
26
+ )
27
+
28
+ notify("Calculation started")
29
+
30
+ # calculation()
31
+
32
+ notify(
33
+ "Calculation finished",
34
+ "Calculation completed successfully.",
35
+ )
36
+ ```
37
+
38
+ `configure()` で設定した値は、その後の `notify()`
39
+ で既定値として使用されます。
40
+
41
+ `notify()` は成功時に `True`、失敗時に `False`
42
+ を返します。デフォルトでは、サーバー停止、通信不能、timeout、HTTP
43
+ エラー、設定不足などが発生しても例外を計算側へ伝播しません。
44
+
45
+ 通知失敗を例外として扱う場合だけ `strict=True` を指定します。
46
+
47
+ ``` python
48
+ notify("Calculation finished", strict=True)
49
+ ```
50
+
51
+ `configure()` を使用せず、従来どおり `NOTIFY_SERVER_URL` と
52
+ `NOTIFY_TOKEN` の環境変数を使用することもできます。
53
+
54
+ ### PC 側サーバー
55
+
56
+ サーバー設定は `NotifyConfig` へ直接渡せます。
57
+
58
+ ``` python
59
+ from notify.server import NotifyConfig, main
60
+
61
+ config = NotifyConfig(
62
+ token="shared-token",
63
+ backend="mail_client",
64
+ mail_client="mail",
65
+ mail_to="your_account@example.com",
66
+ )
67
+
68
+ main(
69
+ config=config,
70
+ host="0.0.0.0",
71
+ port=8000,
72
+ )
73
+ ```
74
+
75
+ `NotifyConfig`
76
+ に値を指定しなかった項目については、従来どおり環境変数が使用されます。
77
+
78
+ `main()` の `host` / `port` を省略した場合も、`NOTIFY_HOST` /
79
+ `NOTIFY_PORT` を参照し、未設定なら `127.0.0.1:8000` を使用します。
80
+
81
+ ## 通知方式
82
+
83
+ ### macOS Mail.app
84
+
85
+ ``` python
86
+ config = NotifyConfig(
87
+ token="shared-token",
88
+ backend="mail_client",
89
+ mail_client="mail",
90
+ mail_to="your_account@example.com",
91
+ )
92
+ ```
93
+
94
+ AppleScript で macOS Mail.app を操作してメールを送信します。
95
+
96
+ ### Microsoft Outlook
97
+
98
+ ``` python
99
+ config = NotifyConfig(
100
+ token="shared-token",
101
+ backend="mail_client",
102
+ mail_client="outlook",
103
+ mail_to="your_account@example.com",
104
+ )
105
+ ```
106
+
107
+ macOS では AppleScript、Windows では COM (`pywin32`) を使用して
108
+ Microsoft Outlook を操作します。
109
+
110
+ ### SMTP
111
+
112
+ ``` python
113
+ config = NotifyConfig(
114
+ token="shared-token",
115
+ backend="smtp",
116
+ mail_to="your_account@example.com",
117
+ smtp_host="smtp.example.com",
118
+ smtp_port=587,
119
+ smtp_user="your_account@example.com",
120
+ smtp_password="password-or-app-password",
121
+ )
122
+ ```
123
+
124
+ SMTP は STARTTLS と SMTP 認証を使用します。
125
+
126
+ ## Shell スクリプト
127
+
128
+ Shell から使用する場合は、従来どおり `NOTIFY_SERVER_URL` と
129
+ `NOTIFY_TOKEN` を環境変数で与えれば `python -c` から呼び出せます。
130
+
131
+ ``` bash
132
+ if ./run_calc.sh; then
133
+ python -c 'from notify import notify; notify("OK", "Calculation finished successfully.")'
134
+ else
135
+ status=$?
136
+ python -c 'from notify import notify; notify("FAILED", "Calculation failed.")'
137
+ exit "$status"
138
+ fi
139
+ ```
140
+
141
+ デフォルトでは通知失敗が計算コマンドの終了状態へ影響しません。
142
+
143
+ ## REST API
144
+
145
+ REST API は従来と同じです。
146
+
147
+ ``` text
148
+ POST /notify
149
+ ```
150
+
151
+ JSON:
152
+
153
+ ``` json
154
+ {
155
+ "title": "OK",
156
+ "body": "Calculation finished successfully."
157
+ }
158
+ ```
159
+
160
+ HTTP header:
161
+
162
+ ``` text
163
+ X-Notify-Token: shared-token
164
+ ```
165
+
166
+ ## サーバー設定項目
167
+
168
+ `NotifyConfig` で直接指定できる項目は次のとおりです。
169
+
170
+ ``` text
171
+ token
172
+ backend
173
+ mail_client
174
+ mail_to
175
+ smtp_host
176
+ smtp_port
177
+ smtp_user
178
+ smtp_password
179
+ ```
180
+
181
+ 対応する従来の環境変数も使用できます。
182
+
183
+ ``` text
184
+ NOTIFY_TOKEN
185
+ NOTIFY_BACKEND
186
+ NOTIFY_MAIL_CLIENT
187
+ MAIL_TO
188
+ SMTP_HOST
189
+ SMTP_PORT
190
+ SMTP_USER
191
+ SMTP_PASSWORD
192
+ NOTIFY_HOST
193
+ NOTIFY_PORT
194
+ ```
195
+
196
+ 直接指定した値は環境変数より優先されます。
197
+
198
+ ## セキュリティ
199
+
200
+ 計算機側に必要なのは通知サーバー URL
201
+ と共有トークンだけです。メールアカウントや SMTP 認証情報は PC
202
+ 側に置きます。
203
+
204
+ REST
205
+ サーバーをインターネットへ直接公開することは前提としていません。外部ネットワークから利用する場合は、VPN、SSH
206
+ トンネル、ファイアウォール、HTTPS 等を別途使用してください。
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "notify-frame"
7
+ version = "0.1.2"
8
+
9
+ description = "Lightweight REST notification client/server for calculation scripts"
10
+ readme = "README.ja.md"
11
+ requires-python = ">=3.8"
12
+ dependencies = [
13
+ "requests>=2.20",
14
+ ]
15
+
16
+ [project.optional-dependencies]
17
+ server = [
18
+ "fastapi>=0.100",
19
+ "pydantic>=2.0",
20
+ "uvicorn>=0.20",
21
+ ]
22
+ windows-outlook = [
23
+ "pywin32>=300; platform_system == 'Windows'",
24
+ ]
25
+
26
+ [project.scripts]
27
+ notify-server = "notify.server:main"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+ include = ["notify*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .client import NotifyClient, configure, notify
4
+
5
+ __all__ = ["NotifyClient", "configure", "notify"]
@@ -0,0 +1,95 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Client-side notification API for compute hosts."""
3
+
4
+ import os
5
+ from typing import Optional
6
+
7
+ import requests
8
+
9
+ DEFAULT_TIMEOUT = 10.0
10
+
11
+ _default_server_url = ""
12
+ _default_token = ""
13
+ _default_timeout = DEFAULT_TIMEOUT
14
+
15
+
16
+ def configure(
17
+ server_url: str,
18
+ token: str,
19
+ timeout: float = DEFAULT_TIMEOUT,
20
+ ) -> None:
21
+ """Set default client settings used by notify()."""
22
+ global _default_server_url
23
+ global _default_token
24
+ global _default_timeout
25
+
26
+ _default_server_url = server_url
27
+ _default_token = token
28
+ _default_timeout = timeout
29
+
30
+
31
+ class NotifyClient(object):
32
+ """Small HTTP client used from calculation scripts."""
33
+
34
+ def __init__(
35
+ self,
36
+ server_url: Optional[str] = None,
37
+ token: Optional[str] = None,
38
+ timeout: Optional[float] = None,
39
+ ) -> None:
40
+ if server_url is None:
41
+ server_url = _default_server_url
42
+ if server_url == "":
43
+ server_url = os.environ.get("NOTIFY_SERVER_URL", "")
44
+
45
+ if token is None:
46
+ token = _default_token
47
+ if token == "":
48
+ token = os.environ.get("NOTIFY_TOKEN", "")
49
+
50
+ if timeout is None:
51
+ timeout = _default_timeout
52
+
53
+ self.server_url = server_url
54
+ self.token = token
55
+ self.timeout = timeout
56
+
57
+ def validate(self) -> None:
58
+ if self.server_url == "":
59
+ raise RuntimeError("NOTIFY_SERVER_URL is not set")
60
+ if self.token == "":
61
+ raise RuntimeError("NOTIFY_TOKEN is not set")
62
+
63
+ def send(self, title: str, body: str = "", strict: bool = False) -> bool:
64
+ """Send a notification. Failure is isolated unless strict=True."""
65
+ try:
66
+ self.validate()
67
+ response = requests.post(
68
+ self.server_url,
69
+ json={"title": title, "body": body},
70
+ headers={"X-Notify-Token": self.token},
71
+ timeout=self.timeout,
72
+ )
73
+ response.raise_for_status()
74
+ return True
75
+ except Exception:
76
+ if strict:
77
+ raise
78
+ return False
79
+
80
+
81
+ def notify(
82
+ title: str,
83
+ body: str = "",
84
+ strict: bool = False,
85
+ server_url: Optional[str] = None,
86
+ token: Optional[str] = None,
87
+ timeout: Optional[float] = None,
88
+ ) -> bool:
89
+ """Send a notification with a one-call API."""
90
+ client = NotifyClient(
91
+ server_url=server_url,
92
+ token=token,
93
+ timeout=timeout,
94
+ )
95
+ return client.send(title=title, body=body, strict=strict)
@@ -0,0 +1,229 @@
1
+ # -*- coding: utf-8 -*-
2
+ """REST notification server intended to run on the user's PC."""
3
+
4
+ import os
5
+ import platform
6
+ import smtplib
7
+ import subprocess
8
+ from email.mime.text import MIMEText
9
+ from typing import Any, Dict, Optional
10
+
11
+ import uvicorn
12
+ from fastapi import FastAPI, Header, HTTPException
13
+ from pydantic import BaseModel
14
+
15
+ DEFAULT_HOST = "127.0.0.1"
16
+ DEFAULT_PORT = 8000
17
+
18
+ app = FastAPI(title="Notify Server")
19
+ _server_config = None
20
+
21
+
22
+ class NotifyMessage(BaseModel):
23
+ title: str
24
+ body: str = ""
25
+
26
+
27
+ class NotifyConfig(object):
28
+ """Server settings. Direct values take priority over environment variables."""
29
+
30
+ def __init__(
31
+ self,
32
+ token: Optional[str] = None,
33
+ backend: Optional[str] = None,
34
+ mail_client: Optional[str] = None,
35
+ mail_to: Optional[str] = None,
36
+ smtp_host: Optional[str] = None,
37
+ smtp_port: Optional[int] = None,
38
+ smtp_user: Optional[str] = None,
39
+ smtp_password: Optional[str] = None,
40
+ ) -> None:
41
+ if token is None:
42
+ token = os.environ.get("NOTIFY_TOKEN", "")
43
+ if backend is None:
44
+ backend = os.environ.get("NOTIFY_BACKEND", "mail_client")
45
+ if mail_client is None:
46
+ mail_client = os.environ.get("NOTIFY_MAIL_CLIENT", "mail")
47
+ if mail_to is None:
48
+ mail_to = os.environ.get("MAIL_TO", "")
49
+ if smtp_host is None:
50
+ smtp_host = os.environ.get("SMTP_HOST", "")
51
+ if smtp_port is None:
52
+ smtp_port = int(os.environ.get("SMTP_PORT", "587"))
53
+ if smtp_user is None:
54
+ smtp_user = os.environ.get("SMTP_USER", "")
55
+ if smtp_password is None:
56
+ smtp_password = os.environ.get("SMTP_PASSWORD", "")
57
+
58
+ self.token = token
59
+ self.backend = backend
60
+ self.mail_client = mail_client
61
+ self.mail_to = mail_to
62
+ self.smtp_host = smtp_host
63
+ self.smtp_port = smtp_port
64
+ self.smtp_user = smtp_user
65
+ self.smtp_password = smtp_password
66
+
67
+ def validate_common(self) -> None:
68
+ if self.token == "":
69
+ raise RuntimeError("NOTIFY_TOKEN is not set")
70
+ if self.mail_to == "":
71
+ raise RuntimeError("MAIL_TO is not set")
72
+
73
+ def validate_mail_client(self) -> None:
74
+ if self.mail_client not in ("mail", "outlook"):
75
+ raise RuntimeError("Unknown NOTIFY_MAIL_CLIENT: %s" % self.mail_client)
76
+ system = platform.system()
77
+ if self.mail_client == "mail" and system != "Darwin":
78
+ raise RuntimeError("Mail.app backend is available only on macOS")
79
+ if self.mail_client == "outlook" and system not in ("Darwin", "Windows"):
80
+ raise RuntimeError("Outlook backend is available on macOS or Windows")
81
+
82
+ def validate_smtp(self) -> None:
83
+ if self.smtp_host == "":
84
+ raise RuntimeError("SMTP_HOST is not set")
85
+ if self.smtp_user == "":
86
+ raise RuntimeError("SMTP_USER is not set")
87
+ if self.smtp_password == "":
88
+ raise RuntimeError("SMTP_PASSWORD is not set")
89
+
90
+
91
+ def get_config() -> NotifyConfig:
92
+ if _server_config is not None:
93
+ return _server_config
94
+ return NotifyConfig()
95
+
96
+
97
+ def escape_applescript_text(text: str) -> str:
98
+ escaped = text.replace("\\", "\\\\")
99
+ escaped = escaped.replace('"', '\\"')
100
+ return escaped
101
+
102
+
103
+ def send_by_mail_app(config: NotifyConfig, title: str, body: str) -> None:
104
+ subject = escape_applescript_text(title)
105
+ content = escape_applescript_text(body)
106
+ recipient = escape_applescript_text(config.mail_to)
107
+ script = '''
108
+ tell application "Mail"
109
+ set newMessage to make new outgoing message with properties {subject:"%s", content:"%s", visible:false}
110
+ tell newMessage
111
+ make new to recipient at end of to recipients with properties {address:"%s"}
112
+ send
113
+ end tell
114
+ end tell
115
+ ''' % (subject, content, recipient)
116
+ subprocess.check_call(["osascript", "-e", script])
117
+
118
+
119
+ def send_by_outlook_mac(config: NotifyConfig, title: str, body: str) -> None:
120
+ subject = escape_applescript_text(title)
121
+ content = escape_applescript_text(body)
122
+ recipient = escape_applescript_text(config.mail_to)
123
+ script = '''
124
+ tell application "Microsoft Outlook"
125
+ set newMessage to make new outgoing message with properties {subject:"%s", content:"%s"}
126
+ make new recipient at newMessage with properties {email address:{address:"%s"}}
127
+ send newMessage
128
+ end tell
129
+ ''' % (subject, content, recipient)
130
+ subprocess.check_call(["osascript", "-e", script])
131
+
132
+
133
+ def send_by_outlook_windows(config: NotifyConfig, title: str, body: str) -> None:
134
+ try:
135
+ import win32com.client # type: ignore
136
+ except ImportError:
137
+ raise RuntimeError("Windows Outlook backend requires pywin32")
138
+
139
+ outlook = win32com.client.Dispatch("Outlook.Application")
140
+ message = outlook.CreateItem(0)
141
+ message.To = config.mail_to
142
+ message.Subject = title
143
+ message.Body = body
144
+ message.Send()
145
+
146
+
147
+ def send_by_outlook_app(config: NotifyConfig, title: str, body: str) -> None:
148
+ system = platform.system()
149
+ if system == "Darwin":
150
+ send_by_outlook_mac(config, title, body)
151
+ return
152
+ if system == "Windows":
153
+ send_by_outlook_windows(config, title, body)
154
+ return
155
+ raise RuntimeError("Outlook backend is available on macOS or Windows")
156
+
157
+
158
+ def send_by_mail_client(config: NotifyConfig, title: str, body: str) -> None:
159
+ config.validate_mail_client()
160
+ if config.mail_client == "mail":
161
+ send_by_mail_app(config, title, body)
162
+ return
163
+ if config.mail_client == "outlook":
164
+ send_by_outlook_app(config, title, body)
165
+ return
166
+ raise RuntimeError("Unknown NOTIFY_MAIL_CLIENT: %s" % config.mail_client)
167
+
168
+
169
+ def send_by_smtp(config: NotifyConfig, title: str, body: str) -> None:
170
+ config.validate_smtp()
171
+ message = MIMEText(body, "plain", "utf-8")
172
+ message["Subject"] = title
173
+ message["From"] = config.smtp_user
174
+ message["To"] = config.mail_to
175
+ with smtplib.SMTP(config.smtp_host, config.smtp_port) as smtp:
176
+ smtp.starttls()
177
+ smtp.login(config.smtp_user, config.smtp_password)
178
+ smtp.send_message(message)
179
+
180
+
181
+ def send_notification(config: NotifyConfig, title: str, body: str) -> None:
182
+ config.validate_common()
183
+ if config.backend == "mail_client":
184
+ send_by_mail_client(config, title, body)
185
+ return
186
+ if config.backend == "smtp":
187
+ send_by_smtp(config, title, body)
188
+ return
189
+ raise RuntimeError("Unknown NOTIFY_BACKEND: %s" % config.backend)
190
+
191
+
192
+ @app.post("/notify")
193
+ def receive_notify(
194
+ message: NotifyMessage,
195
+ x_notify_token: str = Header(default=""),
196
+ ) -> Dict[str, Any]:
197
+ config = get_config()
198
+ if x_notify_token != config.token:
199
+ raise HTTPException(status_code=403, detail="Forbidden")
200
+ try:
201
+ send_notification(config, message.title, message.body)
202
+ except Exception as exc:
203
+ raise HTTPException(status_code=500, detail=str(exc))
204
+ return {
205
+ "ok": True,
206
+ "backend": config.backend,
207
+ "mail_client": config.mail_client,
208
+ }
209
+
210
+
211
+ def main(
212
+ config: Optional[NotifyConfig] = None,
213
+ host: Optional[str] = None,
214
+ port: Optional[int] = None,
215
+ ) -> None:
216
+ global _server_config
217
+
218
+ _server_config = config
219
+
220
+ if host is None:
221
+ host = os.environ.get("NOTIFY_HOST", DEFAULT_HOST)
222
+ if port is None:
223
+ port = int(os.environ.get("NOTIFY_PORT", str(DEFAULT_PORT)))
224
+
225
+ uvicorn.run(app, host=host, port=port)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: notify-frame
3
+ Version: 0.1.2
4
+ Summary: Lightweight REST notification client/server for calculation scripts
5
+ Requires-Python: >=3.8
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: requests>=2.20
9
+ Provides-Extra: server
10
+ Requires-Dist: fastapi>=0.100; extra == "server"
11
+ Requires-Dist: pydantic>=2.0; extra == "server"
12
+ Requires-Dist: uvicorn>=0.20; extra == "server"
13
+ Provides-Extra: windows-outlook
14
+ Requires-Dist: pywin32>=300; platform_system == "Windows" and extra == "windows-outlook"
15
+ Dynamic: license-file
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/notify/__init__.py
5
+ src/notify/client.py
6
+ src/notify/server.py
7
+ src/notify_frame.egg-info/PKG-INFO
8
+ src/notify_frame.egg-info/SOURCES.txt
9
+ src/notify_frame.egg-info/dependency_links.txt
10
+ src/notify_frame.egg-info/entry_points.txt
11
+ src/notify_frame.egg-info/requires.txt
12
+ src/notify_frame.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ notify-server = notify.server:main
@@ -0,0 +1,11 @@
1
+ requests>=2.20
2
+
3
+ [server]
4
+ fastapi>=0.100
5
+ pydantic>=2.0
6
+ uvicorn>=0.20
7
+
8
+ [windows-outlook]
9
+
10
+ [windows-outlook:platform_system == "Windows"]
11
+ pywin32>=300