desktop-notifier 5.0.0.dev0__tar.gz → 5.0.0.dev2__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.
Files changed (24) hide show
  1. {desktop_notifier-5.0.0.dev0/src/desktop_notifier.egg-info → desktop_notifier-5.0.0.dev2}/PKG-INFO +2 -2
  2. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/pyproject.toml +2 -2
  3. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/__init__.py +3 -2
  4. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/base.py +4 -1
  5. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/dbus.py +48 -10
  6. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/dummy.py +7 -2
  7. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/macos.py +33 -52
  8. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/main.py +34 -107
  9. desktop_notifier-5.0.0.dev2/src/desktop_notifier/sync.py +137 -0
  10. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2/src/desktop_notifier.egg-info}/PKG-INFO +2 -2
  11. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier.egg-info/SOURCES.txt +3 -1
  12. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier.egg-info/requires.txt +1 -1
  13. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/tests/test_api.py +0 -26
  14. desktop_notifier-5.0.0.dev2/tests/test_sync_api.py +66 -0
  15. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/LICENSE +0 -0
  16. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/README.md +0 -0
  17. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/setup.cfg +0 -0
  18. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/macos_support.py +0 -0
  19. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/py.typed +0 -0
  20. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/resources/__init__.py +0 -0
  21. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/resources/python.png +0 -0
  22. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier/winrt.py +0 -0
  23. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier.egg-info/dependency_links.txt +0 -0
  24. {desktop_notifier-5.0.0.dev0 → desktop_notifier-5.0.0.dev2}/src/desktop_notifier.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: desktop-notifier
3
- Version: 5.0.0.dev0
3
+ Version: 5.0.0.dev2
4
4
  Summary: Python library for cross-platform desktop notifications
5
5
  Author-email: Sam Schott <sam.schott@outlook.com>
6
6
  License: MIT
@@ -41,7 +41,7 @@ Requires-Dist: pytest-cov; extra == "dev"
41
41
  Provides-Extra: docs
42
42
  Requires-Dist: furo==2024.5.6; extra == "docs"
43
43
  Requires-Dist: sphinx==7.3.7; extra == "docs"
44
- Requires-Dist: sphinx-autoapi==3.1.1; extra == "docs"
44
+ Requires-Dist: sphinx-autoapi==3.1.2; extra == "docs"
45
45
  Requires-Dist: sphinx-mdinclude==0.6.1; extra == "docs"
46
46
 
47
47
  [![PyPi Release](https://img.shields.io/pypi/v/desktop-notifier.svg)](https://pypi.org/project/desktop-notifier/)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "desktop-notifier"
7
- version = "5.0.0.dev0"
7
+ version = "5.0.0.dev2"
8
8
  authors = [{name = "Sam Schott", email = "sam.schott@outlook.com"}]
9
9
  license = {text = "MIT"}
10
10
  description = "Python library for cross-platform desktop notifications"
@@ -56,7 +56,7 @@ dev = [
56
56
  docs = [
57
57
  "furo==2024.5.6",
58
58
  "sphinx==7.3.7",
59
- "sphinx-autoapi==3.1.1",
59
+ "sphinx-autoapi==3.1.2",
60
60
  "sphinx-mdinclude==0.6.1",
61
61
  ]
62
62
 
@@ -15,9 +15,9 @@ from .main import (
15
15
  DEFAULT_SOUND,
16
16
  DEFAULT_ICON,
17
17
  )
18
+ from .sync import DesktopNotifierSync
18
19
 
19
-
20
- __version__ = "5.0.0.dev0"
20
+ __version__ = "5.0.0.dev2"
21
21
  __author__ = "Sam Schott"
22
22
  __url__ = "https://github.com/samschott/desktop-notifier"
23
23
 
@@ -33,6 +33,7 @@ __all__ = [
33
33
  "Sound",
34
34
  "Attachment",
35
35
  "DesktopNotifier",
36
+ "DesktopNotifierSync",
36
37
  "Capability",
37
38
  "DEFAULT_SOUND",
38
39
  "DEFAULT_ICON",
@@ -322,7 +322,10 @@ class Notification:
322
322
  self._identifier = nid
323
323
 
324
324
  def __repr__(self) -> str:
325
- return f"<{self.__class__.__name__}(title='{self.title}', message='{self.message}')>"
325
+ return (
326
+ f"<{self.__class__.__name__}(identifier='{self.identifier}', "
327
+ f"title='{self.title}', message='{self.message}')>"
328
+ )
326
329
 
327
330
 
328
331
  class Capability(Enum):
@@ -57,12 +57,14 @@ class DBusDesktopNotifier(DesktopNotifierBase):
57
57
  notification center.
58
58
  """
59
59
 
60
- _to_native_urgency = {
60
+ to_native_urgency = {
61
61
  Urgency.Low: Variant("y", 0),
62
62
  Urgency.Normal: Variant("y", 1),
63
63
  Urgency.Critical: Variant("y", 2),
64
64
  }
65
65
 
66
+ supported_hint_signatures = {"a{sv}", "a{ss}"}
67
+
66
68
  def __init__(
67
69
  self,
68
70
  app_name: str = "Python",
@@ -102,13 +104,9 @@ class DBusDesktopNotifier(DesktopNotifierBase):
102
104
  # Some older interfaces may not support notification actions.
103
105
  if hasattr(self.interface, "on_notification_closed"):
104
106
  self.interface.on_notification_closed(self._on_closed)
105
- else:
106
- logger.warning("on_closed callbacks not supported")
107
107
 
108
108
  if hasattr(self.interface, "on_action_invoked"):
109
109
  self.interface.on_action_invoked(self._on_action)
110
- else:
111
- logger.warning("on_action_invoked callbacks not supported")
112
110
 
113
111
  return self.interface
114
112
 
@@ -131,7 +129,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
131
129
  else:
132
130
  replaces_nid = 0
133
131
 
134
- actions = []
132
+ actions: list[str] = []
135
133
 
136
134
  if notification.on_clicked:
137
135
  # The "default" action is typically invoked when clicking on the
@@ -145,16 +143,37 @@ class DBusDesktopNotifier(DesktopNotifierBase):
145
143
  for n, button in enumerate(notification.buttons):
146
144
  actions += [str(n), button.title]
147
145
 
148
- hints = {"urgency": self._to_native_urgency[notification.urgency]}
146
+ hints_v: dict[str, Variant] = dict()
147
+ hints_v["urgency"] = self.to_native_urgency[notification.urgency]
149
148
 
150
149
  if notification.sound:
151
150
  if notification.sound.is_named():
152
- hints["sound-name"] = Variant("s", "message-new-instant")
151
+ hints_v["sound-name"] = Variant("s", "message-new-instant")
153
152
  else:
154
- hints["sound-file"] = Variant("s", notification.sound.as_uri())
153
+ hints_v["sound-file"] = Variant("s", notification.sound.as_uri())
155
154
 
156
155
  if notification.attachment:
157
- hints["image-path"] = Variant("s", notification.attachment.as_uri())
156
+ hints_v["image-path"] = Variant("s", notification.attachment.as_uri())
157
+
158
+ # The current notification spec defines hints as a Dbus dictionary type 'a{sv}',
159
+ # represented in Python as dict[str, Variant]. However, some older notification
160
+ # servers expect 'a{ss}' (Python dict[str, str]). We therefore check the
161
+ # expected argument type at runtime and cast arguments accordingly.
162
+ # See https://github.com/samschott/desktop-notifier/issues/143.
163
+ hints_signature = get_hints_signature(self.interface)
164
+
165
+ if hints_signature == "":
166
+ logger.warning("Notification server not supported")
167
+ return
168
+
169
+ hints: dict[str, str] | dict[str, Variant]
170
+
171
+ if hints_signature == "a{sv}":
172
+ hints = hints_v
173
+ elif hints_signature == "a{ss}":
174
+ hints = {k: str(v.value) for k, v in hints_v.items()}
175
+ else:
176
+ hints = {}
158
177
 
159
178
  timeout = notification.timeout * 1000 if notification.timeout != -1 else -1
160
179
  if notification.icon:
@@ -267,6 +286,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
267
286
  Capability.ICON,
268
287
  Capability.TITLE,
269
288
  Capability.TIMEOUT,
289
+ Capability.URGENCY,
270
290
  }
271
291
 
272
292
  # Capabilities supported by some notification servers.
@@ -284,4 +304,22 @@ class DBusDesktopNotifier(DesktopNotifierBase):
284
304
  capabilities.add(Capability.SOUND)
285
305
  capabilities.add(Capability.SOUND_NAME)
286
306
 
307
+ hints_signature = get_hints_signature(self.interface)
308
+ if hints_signature not in self.supported_hint_signatures:
309
+ # Any hint-based capabilities are not supported because we got an unexpected
310
+ # DBus interface.
311
+ capabilities.discard(Capability.SOUND)
312
+ capabilities.discard(Capability.SOUND_NAME)
313
+ capabilities.discard(Capability.URGENCY)
314
+
287
315
  return frozenset(capabilities)
316
+
317
+
318
+ def get_hints_signature(interface: ProxyInterface) -> str:
319
+ """Returns the dbus type signature for the hints argument"""
320
+ methods = interface.introspection.methods
321
+ notify_method = next(m for m in methods if m.name == "Notify")
322
+ try:
323
+ return str(notify_method.in_args[6].signature)
324
+ except IndexError:
325
+ return ""
@@ -5,7 +5,9 @@ Dummy backend for unsupported platforms
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
- # local imports
8
+ import uuid
9
+
10
+ from . import Capability
9
11
  from .base import Notification, DesktopNotifierBase
10
12
 
11
13
 
@@ -38,10 +40,13 @@ class DummyNotificationCenter(DesktopNotifierBase):
38
40
  notification: Notification,
39
41
  notification_to_replace: Notification | None,
40
42
  ) -> None:
41
- pass
43
+ notification.identifier = str(uuid.uuid4())
42
44
 
43
45
  async def _clear(self, notification: Notification) -> None:
44
46
  pass
45
47
 
46
48
  async def _clear_all(self) -> None:
47
49
  pass
50
+
51
+ async def get_capabilities(self) -> frozenset[Capability]:
52
+ return frozenset()
@@ -28,7 +28,6 @@ from rubicon.objc.runtime import load_library, objc_id, objc_block
28
28
  from .base import (
29
29
  Notification,
30
30
  DesktopNotifierBase,
31
- AuthorisationError,
32
31
  Urgency,
33
32
  Capability,
34
33
  DEFAULT_SOUND,
@@ -82,20 +81,6 @@ UNAuthorizationStatusAuthorized = 2
82
81
  UNAuthorizationStatusProvisional = 3
83
82
  UNAuthorizationStatusEphemeral = 4
84
83
 
85
- UNErrorDomain = "UNErrorDomain"
86
-
87
-
88
- class UNErrorCode(enum.Enum):
89
- NotificationsNotAllowed = 1
90
- AttachmentInvalidURL = 100
91
- AttachmentUnrecognizedType = 101
92
- AttachmentInvalidFileSize = 102
93
- AttachmentNotInDataStore = 103
94
- AttachmentMoveIntoDataStoreFailed = 104
95
- AttachmentCorrupt = 105
96
- NotificationInvalidNoDate = 1400
97
- NotificationInvalidNoContent = 1401
98
-
99
84
 
100
85
  class UNNotificationInterruptionLevel(enum.Enum):
101
86
  Passive = 0
@@ -104,7 +89,7 @@ class UNNotificationInterruptionLevel(enum.Enum):
104
89
  Critical = 3
105
90
 
106
91
 
107
- class NotificationCenterDelegate(NSObject): # type: ignore
92
+ class NotificationCenterDelegate(NSObject): # type:ignore
108
93
  """Delegate to handle user interactions with notifications"""
109
94
 
110
95
  @objc_method # type:ignore
@@ -187,8 +172,9 @@ class CocoaNotificationCenter(DesktopNotifierBase):
187
172
 
188
173
  def on_auth_completed(granted: bool, error: objc_id) -> None:
189
174
  ns_error = py_from_ns(error)
190
- error_str = str(ns_error.localizedDescription) if ns_error else ""
191
- future.set_result((granted, error_str))
175
+ if ns_error:
176
+ ns_error.retain()
177
+ future.set_result((granted, ns_error))
192
178
 
193
179
  self.nc.requestAuthorizationWithOptions(
194
180
  UNAuthorizationOptionAlert
@@ -197,16 +183,17 @@ class CocoaNotificationCenter(DesktopNotifierBase):
197
183
  completionHandler=on_auth_completed,
198
184
  )
199
185
 
200
- granted, error_str = await asyncio.wrap_future(future)
186
+ has_authorization, error = await asyncio.wrap_future(future)
201
187
 
202
- if error_str:
203
- logger.warning("Authorisation denied: %s", error_str)
188
+ if error:
189
+ log_nserror(error, "Authorisation denied")
190
+ error.autorelease() # type:ignore[attr-defined]
204
191
 
205
- return granted
192
+ return has_authorization
206
193
 
207
194
  async def has_authorisation(self) -> bool:
208
195
  """Whether we have authorisation to send notifications."""
209
- future: Future[UNNotificationSettings] = Future() # type:ignore
196
+ future: Future[UNNotificationSettings] = Future() # type:ignore[valid-type]
210
197
 
211
198
  def handler(settings: objc_id) -> None:
212
199
  settings = py_from_ns(settings)
@@ -216,12 +203,12 @@ class CocoaNotificationCenter(DesktopNotifierBase):
216
203
  self.nc.getNotificationSettingsWithCompletionHandler(handler)
217
204
 
218
205
  settings = await asyncio.wrap_future(future)
219
- authorized = settings.authorizationStatus in ( # type:ignore
206
+ authorized = settings.authorizationStatus in ( # type:ignore[attr-defined]
220
207
  UNAuthorizationStatusAuthorized,
221
208
  UNAuthorizationStatusProvisional,
222
209
  UNAuthorizationStatusEphemeral,
223
210
  )
224
- settings.release() # type:ignore
211
+ settings.autorelease() # type:ignore[attr-defined]
225
212
 
226
213
  return authorized
227
214
 
@@ -283,7 +270,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
283
270
  platform_nid, content=content, trigger=None
284
271
  )
285
272
 
286
- future: Future[NSError] = Future() # type:ignore
273
+ future: Future[NSError] = Future() # type:ignore[valid-type]
287
274
 
288
275
  def handler(error: objc_id) -> None:
289
276
  ns_error = py_from_ns(error)
@@ -300,27 +287,8 @@ class CocoaNotificationCenter(DesktopNotifierBase):
300
287
  error = await asyncio.wrap_future(future)
301
288
 
302
289
  if error:
303
- error.autorelease() # type:ignore
304
-
305
- if error.domain == UNErrorDomain: # type:ignore
306
- if error.code == UNErrorCode.NotificationsNotAllowed: # type:ignore
307
- raise AuthorisationError("Not authorised")
308
- elif error.code == UNErrorCode.NotificationInvalidNoDate: # type:ignore
309
- raise RuntimeError("Missing notification date")
310
- elif (
311
- error.code # type:ignore
312
- == UNErrorCode.NotificationInvalidNoContent
313
- ):
314
- raise RuntimeError("Missing notification content")
315
- else:
316
- # In case of attachment errors, the notification will still be
317
- # delivered, just without an attachment. We therefore do not raise
318
- # the error.
319
- logger.warning(
320
- f"{error.localizedDescription}: {notification.attachment}" # type:ignore
321
- )
322
- else:
323
- raise RuntimeError(error.localizedDescription) # type:ignore
290
+ log_nserror(error, "Error when scheduling notification")
291
+ error.autorelease() # type:ignore[attr-defined]
324
292
 
325
293
  notification.identifier = platform_nid
326
294
 
@@ -344,7 +312,10 @@ class CocoaNotificationCenter(DesktopNotifierBase):
344
312
  # Retrieve existing categories. We do not cache this value because it may be
345
313
  # modified by other Python processes using desktop-notifier.
346
314
  categories = await self._get_notification_categories()
347
- category_ids = set(py_from_ns(c.identifier) for c in categories.allObjects()) # type: ignore
315
+ category_ids = set(
316
+ py_from_ns(c.identifier)
317
+ for c in categories.allObjects() # type:ignore[attr-defined]
318
+ )
348
319
 
349
320
  # Register new category if necessary.
350
321
  if category_id not in category_ids:
@@ -368,7 +339,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
368
339
  actions.append(action)
369
340
 
370
341
  # Add category for new set of buttons.
371
- new_categories = categories.setByAddingObject( # type: ignore
342
+ new_categories = categories.setByAddingObject( # type:ignore[attr-defined]
372
343
  UNNotificationCategory.categoryWithIdentifier(
373
344
  category_id,
374
345
  actions=actions,
@@ -380,9 +351,9 @@ class CocoaNotificationCenter(DesktopNotifierBase):
380
351
 
381
352
  return category_id
382
353
 
383
- async def _get_notification_categories(self) -> NSSet: # type:ignore
354
+ async def _get_notification_categories(self) -> NSSet: # type:ignore[valid-type]
384
355
  """Returns the registered notification categories for this app / Python."""
385
- future: Future[NSSet] = Future() # type:ignore
356
+ future: Future[NSSet] = Future() # type:ignore[valid-type]
386
357
 
387
358
  def handler(categories: objc_id) -> None:
388
359
  categories = py_from_ns(categories)
@@ -392,7 +363,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
392
363
  self.nc.getNotificationCategoriesWithCompletionHandler(handler)
393
364
 
394
365
  categories = await asyncio.wrap_future(future)
395
- categories.autorelease() # type:ignore
366
+ categories.autorelease() # type:ignore[attr-defined]
396
367
 
397
368
  return categories
398
369
 
@@ -433,3 +404,13 @@ class CocoaNotificationCenter(DesktopNotifierBase):
433
404
  capabilities.add(Capability.URGENCY)
434
405
 
435
406
  return frozenset(capabilities)
407
+
408
+
409
+ def log_nserror(error: NSError, prefix: str) -> None: # type:ignore[valid-type]
410
+ domain = str(error.domain) # type:ignore[attr-defined]
411
+ code = int(error.code) # type:ignore[attr-defined]
412
+ description = str(error.localizedDescription) # type:ignore[attr-defined]
413
+
414
+ logger.warning(
415
+ "%s: domain=%s, code=%s, description=%s", prefix, domain, code, description
416
+ )
@@ -1,6 +1,6 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """
3
- Desktop notifications for Windows, Linux, macOS, iOS and iPadOS.
3
+ Asynchronous desktop notification API
4
4
  """
5
5
 
6
6
  from __future__ import annotations
@@ -15,7 +15,6 @@ from pathlib import Path
15
15
  from typing import (
16
16
  Type,
17
17
  Callable,
18
- Coroutine,
19
18
  List,
20
19
  Any,
21
20
  TypeVar,
@@ -126,11 +125,10 @@ class DesktopNotifier:
126
125
  Linux, this should correspond to the application name in a desktop entry. On
127
126
  macOS, this argument is ignored and the app is identified by the bundle ID of
128
127
  the sending program (e.g., Python).
129
- :param app_icon: Default icon to use for notifications. This should be either a URI
130
- string, a :class:`pathlib.Path` path, or a name in a freedesktop.org-compliant
131
- icon theme. If None, the icon of the calling application will be used if it
132
- can be determined. On macOS, this argument is ignored and the app icon is
133
- identified by the bundle ID of the sending program (e.g., Python).
128
+ :param app_icon: Default icon to use for notifications. This should be a
129
+ :class:`desktop_notifier.base.Icon` instance referencing either a file or a
130
+ named system icon. :class:`str` or :class:`pathlib.Path` are also accepted but
131
+ deprecated.
134
132
  :param notification_limit: Maximum number of notifications to keep in the system's
135
133
  notification center. This may be ignored by some implementations.
136
134
  """
@@ -140,11 +138,9 @@ class DesktopNotifier:
140
138
  def __init__(
141
139
  self,
142
140
  app_name: str = "Python",
143
- app_icon: Path | str | Icon | None = DEFAULT_ICON,
141
+ app_icon: Icon | Path | str | None = DEFAULT_ICON,
144
142
  notification_limit: int | None = None,
145
143
  ) -> None:
146
- impl_cls = get_implementation_class()
147
-
148
144
  if isinstance(app_icon, str):
149
145
  warnings.warn(
150
146
  message="Pass an Icon instance instead of a string. "
@@ -166,29 +162,12 @@ class DesktopNotifier:
166
162
 
167
163
  self.app_icon = app_icon
168
164
 
169
- self._lock = asyncio.Lock()
165
+ impl_cls = get_implementation_class()
170
166
  self._impl = impl_cls(app_name, notification_limit)
171
167
  self._did_request_authorisation = False
172
168
 
173
- # Use our own event loop for the sync API so that we don't interfere with any
174
- # other ansycio event loops / threads, etc.
175
- self._loop = default_event_loop_policy.new_event_loop()
176
-
177
169
  self._capabilities: frozenset[Capability] | None = None
178
170
 
179
- def _run_coro_sync(self, coro: Coroutine[None, None, T]) -> T:
180
- """
181
- Runs the given coroutine and returns the result synchronously. This is used as a
182
- wrapper to conveniently convert the async API calls to synchronous ones.
183
- """
184
- if self._loop.is_running():
185
- future = asyncio.run_coroutine_threadsafe(coro, self._loop)
186
- res = future.result()
187
- else:
188
- res = self._loop.run_until_complete(coro)
189
-
190
- return res
191
-
192
171
  @property
193
172
  def app_name(self) -> str:
194
173
  """The application name"""
@@ -211,9 +190,8 @@ class DesktopNotifier:
211
190
 
212
191
  :returns: Whether authorisation has been granted.
213
192
  """
214
- async with self._lock:
215
- self._did_request_authorisation = True
216
- return await self._impl.request_authorisation()
193
+ self._did_request_authorisation = True
194
+ return await self._impl.request_authorisation()
217
195
 
218
196
  async def has_authorisation(self) -> bool:
219
197
  """Returns whether we have authorisation to send notifications."""
@@ -223,26 +201,31 @@ class DesktopNotifier:
223
201
  """
224
202
  Sends a desktop notification.
225
203
 
226
- This method takes a fully constructed :class:`Notification` instance as input.
227
- Use :meth:`send` to provide separate notification properties such as ``title``,
228
- ``message``, etc., instead.
204
+ This method does not raise an exception when scheduling the notification fails
205
+ but logs warnings instead. If the notification was scheduled successfully, its
206
+ ``identifier`` will be set to the platform's native notification identifier.
207
+ Otherwise, the ``identifier`` will be ``None``.
208
+
209
+ Note that even a successfully scheduled notification may not be displayed to the
210
+ user, depending on their notification center settings (for instance if "do not
211
+ disturb" is enabled on macOS).
229
212
 
230
213
  :param notification: The notification to send.
214
+ :returns: The passed notification instance with a unique identifier populated.
231
215
  """
232
216
  if not notification.icon:
233
217
  notification.icon = self.app_icon
234
218
 
235
- async with self._lock:
236
- # Ask for authorisation if not already done. On some platforms, this will
237
- # trigger a system dialog to ask the user for permission.
238
- if not self._did_request_authorisation:
239
- await self.request_authorisation()
219
+ # Ask for authorisation if not already done. On some platforms, this will
220
+ # trigger a system dialog to ask the user for permission.
221
+ if not self._did_request_authorisation:
222
+ await self.request_authorisation()
240
223
 
241
- # We attempt to send the notification regardless of authorization.
242
- # The user may have changed settings in the meantime.
243
- await self._impl.send(notification)
224
+ # We attempt to send the notification regardless of authorization.
225
+ # The user may have changed settings in the meantime.
226
+ await self._impl.send(notification)
244
227
 
245
- return notification
228
+ return notification
246
229
 
247
230
  async def send(
248
231
  self,
@@ -262,16 +245,9 @@ class DesktopNotifier:
262
245
  """
263
246
  Sends a desktop notification
264
247
 
265
- Arguments are the same as and will be passed on to :class:`Notification`.
266
-
267
- This method will always return a :class:`Notification` instance and will not
268
- raise an exception when scheduling the notification fails. If the notification
269
- was scheduled successfully, its ``identifier`` will be set to the platform's
270
- native notification identifier. Otherwise, the ``identifier`` will be ``None``.
271
-
272
- Note that even a successfully scheduled notification may not be displayed to the
273
- user, depending on their notification center settings (for instance if "do not
274
- disturb" is enabled on macOS).
248
+ This is a convenience function which creates a
249
+ :class:`desktop_notifier.base.Notification` with the provided arguments and then
250
+ calls :meth:`send_notification`.
275
251
 
276
252
  :returns: The scheduled notification instance.
277
253
  """
@@ -291,52 +267,6 @@ class DesktopNotifier:
291
267
  )
292
268
  return await self.send_notification(notification)
293
269
 
294
- def send_sync(
295
- self,
296
- title: str,
297
- message: str,
298
- urgency: Urgency = Urgency.Normal,
299
- icon: str | Icon | None = None,
300
- buttons: Sequence[Button] = (),
301
- reply_field: ReplyField | None = None,
302
- on_clicked: Callable[[], Any] | None = None,
303
- on_dismissed: Callable[[], Any] | None = None,
304
- attachment: str | Attachment | None = None,
305
- sound: bool | Sound | None = None,
306
- thread: str | None = None,
307
- timeout: int = -1,
308
- ) -> Notification:
309
- """
310
- Synchronous call of :meth:`send`, for use without an asyncio event loop.
311
-
312
- .. deprecated:: 5.0.0
313
- Use the async :func:`send` instead and schedule and block on its completion
314
- if required.
315
-
316
- :returns: The scheduled notification instance.
317
- """
318
- warnings.warn(
319
- message="'send_sync' is deprecated and will be removed in a future "
320
- "version. Use the async 'send' API instead",
321
- category=DeprecationWarning,
322
- )
323
-
324
- coro = self.send(
325
- title,
326
- message,
327
- urgency=urgency,
328
- icon=icon,
329
- buttons=buttons,
330
- reply_field=reply_field,
331
- on_clicked=on_clicked,
332
- on_dismissed=on_dismissed,
333
- attachment=attachment,
334
- sound=sound,
335
- thread=thread,
336
- timeout=timeout,
337
- )
338
- return self._run_coro_sync(coro)
339
-
340
270
  @property
341
271
  def current_notifications(self) -> List[Notification]:
342
272
  """A list of all currently displayed notifications for this app"""
@@ -348,22 +278,19 @@ class DesktopNotifier:
348
278
 
349
279
  :param notification: Notification to clear.
350
280
  """
351
- async with self._lock:
352
- await self._impl.clear(notification)
281
+ await self._impl.clear(notification)
353
282
 
354
283
  async def clear_all(self) -> None:
355
284
  """
356
285
  Removes all currently displayed notifications for this app from the notification
357
286
  center.
358
287
  """
359
- async with self._lock:
360
- await self._impl.clear_all()
288
+ await self._impl.clear_all()
361
289
 
362
- @property
363
- def capabilities(self) -> frozenset[Capability]:
290
+ async def get_capabilities(self) -> frozenset[Capability]:
364
291
  """
365
- Returns which functionality us supported by the implementation.
292
+ Returns which functionality is supported by the implementation.
366
293
  """
367
294
  if not self._capabilities:
368
- self._capabilities = self._run_coro_sync(self._impl.get_capabilities())
295
+ self._capabilities = await self._impl.get_capabilities()
369
296
  return self._capabilities
@@ -0,0 +1,137 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Synchronous desktop notification API
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ # system imports
9
+ import asyncio
10
+ from typing import Callable, Coroutine, Any, Sequence, TypeVar, List
11
+
12
+ # local imports
13
+ from .main import DesktopNotifier
14
+ from .base import (
15
+ Capability,
16
+ Urgency,
17
+ Button,
18
+ ReplyField,
19
+ Icon,
20
+ Sound,
21
+ Attachment,
22
+ Notification,
23
+ DEFAULT_ICON,
24
+ )
25
+
26
+ __all__ = ["DesktopNotifierSync"]
27
+
28
+
29
+ T = TypeVar("T")
30
+
31
+
32
+ class DesktopNotifierSync:
33
+ """
34
+ A synchronous counterpart to :class:`desktop_notifier.main.DesktopNotifier`
35
+
36
+ .. warning::
37
+ Callbacks on interaction with the notification will not work on macOS or Linux
38
+ without a running event loop.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ app_name: str = "Python",
44
+ app_icon: Icon | None = DEFAULT_ICON,
45
+ notification_limit: int | None = None,
46
+ ) -> None:
47
+ self._async_api = DesktopNotifier(app_name, app_icon, notification_limit)
48
+ self._loop = asyncio.new_event_loop()
49
+
50
+ def _run_coro_sync(self, coro: Coroutine[None, None, T]) -> T:
51
+ # Make sure to always use the same loop because async queues, future, etc. are
52
+ # always bound to a loop.
53
+ if self._loop.is_running():
54
+ future = asyncio.run_coroutine_threadsafe(coro, self._loop)
55
+ res = future.result()
56
+ else:
57
+ res = self._loop.run_until_complete(coro)
58
+
59
+ return res
60
+
61
+ @property
62
+ def app_name(self) -> str:
63
+ """The application name"""
64
+ return self._async_api.app_name
65
+
66
+ @app_name.setter
67
+ def app_name(self, value: str) -> None:
68
+ """Setter: app_name"""
69
+ self._async_api.app_name = value
70
+
71
+ def request_authorisation(self) -> bool:
72
+ """See :meth:`desktop_notifier.main.DesktopNotifier.request_authorisation`"""
73
+ coro = self._async_api.request_authorisation()
74
+ return self._run_coro_sync(coro)
75
+
76
+ def has_authorisation(self) -> bool:
77
+ """See :meth:`desktop_notifier.main.DesktopNotifier.has_authorisation`"""
78
+ coro = self._async_api.has_authorisation()
79
+ return self._run_coro_sync(coro)
80
+
81
+ def send_notification(self, notification: Notification) -> Notification:
82
+ """See :meth:`desktop_notifier.main.DesktopNotifier.send_notification`"""
83
+ coro = self._async_api.send_notification(notification)
84
+ return self._run_coro_sync(coro)
85
+
86
+ def send(
87
+ self,
88
+ title: str,
89
+ message: str,
90
+ urgency: Urgency = Urgency.Normal,
91
+ icon: Icon | None = None,
92
+ buttons: Sequence[Button] = (),
93
+ reply_field: ReplyField | None = None,
94
+ on_clicked: Callable[[], Any] | None = None,
95
+ on_dismissed: Callable[[], Any] | None = None,
96
+ attachment: Attachment | None = None,
97
+ sound: Sound | None = None,
98
+ thread: str | None = None,
99
+ timeout: int = -1,
100
+ ) -> Notification:
101
+ """See :meth:`desktop_notifier.main.DesktopNotifier.send`"""
102
+ notification = Notification(
103
+ title,
104
+ message,
105
+ urgency=urgency,
106
+ icon=icon,
107
+ buttons=buttons,
108
+ reply_field=reply_field,
109
+ on_clicked=on_clicked,
110
+ on_dismissed=on_dismissed,
111
+ attachment=attachment,
112
+ sound=sound,
113
+ thread=thread,
114
+ timeout=timeout,
115
+ )
116
+ coro = self._async_api.send_notification(notification)
117
+ return self._run_coro_sync(coro)
118
+
119
+ @property
120
+ def current_notifications(self) -> List[Notification]:
121
+ """A list of all currently displayed notifications for this app"""
122
+ return self._async_api.current_notifications
123
+
124
+ def clear(self, notification: Notification) -> None:
125
+ """See :meth:`desktop_notifier.main.DesktopNotifier.notification`"""
126
+ coro = self._async_api.clear(notification)
127
+ return self._run_coro_sync(coro)
128
+
129
+ def clear_all(self) -> None:
130
+ """See :meth:`desktop_notifier.main.DesktopNotifier.clear_all`"""
131
+ coro = self._async_api.clear_all()
132
+ return self._run_coro_sync(coro)
133
+
134
+ def get_capabilities(self) -> frozenset[Capability]:
135
+ """See :meth:`desktop_notifier.main.DesktopNotifier.get_capabilities`"""
136
+ coro = self._async_api.get_capabilities()
137
+ return self._run_coro_sync(coro)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: desktop-notifier
3
- Version: 5.0.0.dev0
3
+ Version: 5.0.0.dev2
4
4
  Summary: Python library for cross-platform desktop notifications
5
5
  Author-email: Sam Schott <sam.schott@outlook.com>
6
6
  License: MIT
@@ -41,7 +41,7 @@ Requires-Dist: pytest-cov; extra == "dev"
41
41
  Provides-Extra: docs
42
42
  Requires-Dist: furo==2024.5.6; extra == "docs"
43
43
  Requires-Dist: sphinx==7.3.7; extra == "docs"
44
- Requires-Dist: sphinx-autoapi==3.1.1; extra == "docs"
44
+ Requires-Dist: sphinx-autoapi==3.1.2; extra == "docs"
45
45
  Requires-Dist: sphinx-mdinclude==0.6.1; extra == "docs"
46
46
 
47
47
  [![PyPi Release](https://img.shields.io/pypi/v/desktop-notifier.svg)](https://pypi.org/project/desktop-notifier/)
@@ -9,6 +9,7 @@ src/desktop_notifier/macos.py
9
9
  src/desktop_notifier/macos_support.py
10
10
  src/desktop_notifier/main.py
11
11
  src/desktop_notifier/py.typed
12
+ src/desktop_notifier/sync.py
12
13
  src/desktop_notifier/winrt.py
13
14
  src/desktop_notifier.egg-info/PKG-INFO
14
15
  src/desktop_notifier.egg-info/SOURCES.txt
@@ -17,4 +18,5 @@ src/desktop_notifier.egg-info/requires.txt
17
18
  src/desktop_notifier.egg-info/top_level.txt
18
19
  src/desktop_notifier/resources/__init__.py
19
20
  src/desktop_notifier/resources/python.png
20
- tests/test_api.py
21
+ tests/test_api.py
22
+ tests/test_sync_api.py
@@ -27,5 +27,5 @@ pytest-cov
27
27
  [docs]
28
28
  furo==2024.5.6
29
29
  sphinx==7.3.7
30
- sphinx-autoapi==3.1.1
30
+ sphinx-autoapi==3.1.2
31
31
  sphinx-mdinclude==0.6.1
@@ -110,32 +110,6 @@ async def test_attachment_uri(notifier):
110
110
  )
111
111
 
112
112
 
113
- def test_send_sync(notifier):
114
- notification = notifier.send_sync(
115
- title="Julius Caesar",
116
- message="Et tu, Brute?",
117
- urgency=Urgency.Critical,
118
- buttons=[
119
- Button(
120
- title="Mark as read",
121
- on_pressed=lambda: print("Marked as read"),
122
- )
123
- ],
124
- reply_field=ReplyField(
125
- title="Reply",
126
- button_title="Send",
127
- on_replied=lambda text: print("Brutus replied:", text),
128
- ),
129
- on_clicked=lambda: print("Notification clicked"),
130
- on_dismissed=lambda: print("Notification dismissed"),
131
- sound=DEFAULT_SOUND,
132
- thread="test_notifications",
133
- timeout=5,
134
- )
135
- assert notification in notifier.current_notifications
136
- assert notification.identifier != ""
137
-
138
-
139
113
  @pytest.mark.asyncio
140
114
  @pytest.mark.skipif(
141
115
  sys.platform.startswith("win"),
@@ -0,0 +1,66 @@
1
+ import sys
2
+ import pytest
3
+
4
+ from desktop_notifier import Urgency, Button, ReplyField, DEFAULT_SOUND
5
+
6
+
7
+ def test_send(notifier_sync):
8
+ notification = notifier_sync.send(
9
+ title="Julius Caesar",
10
+ message="Et tu, Brute?",
11
+ urgency=Urgency.Critical,
12
+ buttons=[
13
+ Button(
14
+ title="Mark as read",
15
+ on_pressed=lambda: print("Marked as read"),
16
+ )
17
+ ],
18
+ reply_field=ReplyField(
19
+ title="Reply",
20
+ button_title="Send",
21
+ on_replied=lambda text: print("Brutus replied:", text),
22
+ ),
23
+ on_clicked=lambda: print("Notification clicked"),
24
+ on_dismissed=lambda: print("Notification dismissed"),
25
+ sound=DEFAULT_SOUND,
26
+ thread="test_notifications",
27
+ timeout=5,
28
+ )
29
+ assert notification in notifier_sync.current_notifications
30
+ assert notification.identifier != ""
31
+
32
+
33
+ @pytest.mark.skipif(
34
+ sys.platform.startswith("win"),
35
+ reason="Clearing individual notifications is broken on Windows",
36
+ )
37
+ def test_clear(notifier_sync):
38
+ n0 = notifier_sync.send(
39
+ title="Julius Caesar",
40
+ message="Et tu, Brute?",
41
+ )
42
+ n1 = notifier_sync.send(
43
+ title="Julius Caesar",
44
+ message="Et tu, Brute?",
45
+ )
46
+ assert n0 in notifier_sync.current_notifications
47
+ assert n1 in notifier_sync.current_notifications
48
+
49
+ notifier_sync.clear(n0)
50
+ assert n0 not in notifier_sync.current_notifications
51
+
52
+
53
+ def test_clear_all(notifier_sync):
54
+ n0 = notifier_sync.send(
55
+ title="Julius Caesar",
56
+ message="Et tu, Brute?",
57
+ )
58
+ n1 = notifier_sync.send(
59
+ title="Julius Caesar",
60
+ message="Et tu, Brute?",
61
+ )
62
+ assert n0 in notifier_sync.current_notifications
63
+ assert n1 in notifier_sync.current_notifications
64
+
65
+ notifier_sync.clear_all()
66
+ assert len(notifier_sync.current_notifications) == 0