desktop-notifier 5.0.0__tar.gz → 5.0.0.dev0__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/src/desktop_notifier.egg-info → desktop_notifier-5.0.0.dev0}/PKG-INFO +2 -2
  2. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/pyproject.toml +2 -2
  3. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/__init__.py +2 -3
  4. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/base.py +1 -4
  5. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/dbus.py +10 -48
  6. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/dummy.py +2 -7
  7. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/macos.py +52 -33
  8. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/main.py +107 -34
  9. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0/src/desktop_notifier.egg-info}/PKG-INFO +2 -2
  10. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier.egg-info/SOURCES.txt +1 -3
  11. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier.egg-info/requires.txt +1 -1
  12. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/tests/test_api.py +26 -0
  13. desktop_notifier-5.0.0/src/desktop_notifier/sync.py +0 -137
  14. desktop_notifier-5.0.0/tests/test_sync_api.py +0 -66
  15. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/LICENSE +0 -0
  16. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/README.md +0 -0
  17. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/setup.cfg +0 -0
  18. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/macos_support.py +0 -0
  19. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/py.typed +0 -0
  20. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/resources/__init__.py +0 -0
  21. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/resources/python.png +0 -0
  22. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier/winrt.py +0 -0
  23. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/src/desktop_notifier.egg-info/dependency_links.txt +0 -0
  24. {desktop_notifier-5.0.0 → desktop_notifier-5.0.0.dev0}/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
3
+ Version: 5.0.0.dev0
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.2; extra == "docs"
44
+ Requires-Dist: sphinx-autoapi==3.1.1; 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"
7
+ version = "5.0.0.dev0"
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.2",
59
+ "sphinx-autoapi==3.1.1",
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
19
18
 
20
- __version__ = "5.0.0"
19
+
20
+ __version__ = "5.0.0.dev0"
21
21
  __author__ = "Sam Schott"
22
22
  __url__ = "https://github.com/samschott/desktop-notifier"
23
23
 
@@ -33,7 +33,6 @@ __all__ = [
33
33
  "Sound",
34
34
  "Attachment",
35
35
  "DesktopNotifier",
36
- "DesktopNotifierSync",
37
36
  "Capability",
38
37
  "DEFAULT_SOUND",
39
38
  "DEFAULT_ICON",
@@ -322,10 +322,7 @@ class Notification:
322
322
  self._identifier = nid
323
323
 
324
324
  def __repr__(self) -> str:
325
- return (
326
- f"<{self.__class__.__name__}(identifier='{self.identifier}', "
327
- f"title='{self.title}', message='{self.message}')>"
328
- )
325
+ return f"<{self.__class__.__name__}(title='{self.title}', message='{self.message}')>"
329
326
 
330
327
 
331
328
  class Capability(Enum):
@@ -57,14 +57,12 @@ 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
-
68
66
  def __init__(
69
67
  self,
70
68
  app_name: str = "Python",
@@ -104,9 +102,13 @@ class DBusDesktopNotifier(DesktopNotifierBase):
104
102
  # Some older interfaces may not support notification actions.
105
103
  if hasattr(self.interface, "on_notification_closed"):
106
104
  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")
110
112
 
111
113
  return self.interface
112
114
 
@@ -129,7 +131,7 @@ class DBusDesktopNotifier(DesktopNotifierBase):
129
131
  else:
130
132
  replaces_nid = 0
131
133
 
132
- actions: list[str] = []
134
+ actions = []
133
135
 
134
136
  if notification.on_clicked:
135
137
  # The "default" action is typically invoked when clicking on the
@@ -143,37 +145,16 @@ class DBusDesktopNotifier(DesktopNotifierBase):
143
145
  for n, button in enumerate(notification.buttons):
144
146
  actions += [str(n), button.title]
145
147
 
146
- hints_v: dict[str, Variant] = dict()
147
- hints_v["urgency"] = self.to_native_urgency[notification.urgency]
148
+ hints = {"urgency": self._to_native_urgency[notification.urgency]}
148
149
 
149
150
  if notification.sound:
150
151
  if notification.sound.is_named():
151
- hints_v["sound-name"] = Variant("s", "message-new-instant")
152
+ hints["sound-name"] = Variant("s", "message-new-instant")
152
153
  else:
153
- hints_v["sound-file"] = Variant("s", notification.sound.as_uri())
154
+ hints["sound-file"] = Variant("s", notification.sound.as_uri())
154
155
 
155
156
  if notification.attachment:
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 = {}
157
+ hints["image-path"] = Variant("s", notification.attachment.as_uri())
177
158
 
178
159
  timeout = notification.timeout * 1000 if notification.timeout != -1 else -1
179
160
  if notification.icon:
@@ -286,7 +267,6 @@ class DBusDesktopNotifier(DesktopNotifierBase):
286
267
  Capability.ICON,
287
268
  Capability.TITLE,
288
269
  Capability.TIMEOUT,
289
- Capability.URGENCY,
290
270
  }
291
271
 
292
272
  # Capabilities supported by some notification servers.
@@ -304,22 +284,4 @@ class DBusDesktopNotifier(DesktopNotifierBase):
304
284
  capabilities.add(Capability.SOUND)
305
285
  capabilities.add(Capability.SOUND_NAME)
306
286
 
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
-
315
287
  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,9 +5,7 @@ Dummy backend for unsupported platforms
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
- import uuid
9
-
10
- from . import Capability
8
+ # local imports
11
9
  from .base import Notification, DesktopNotifierBase
12
10
 
13
11
 
@@ -40,13 +38,10 @@ class DummyNotificationCenter(DesktopNotifierBase):
40
38
  notification: Notification,
41
39
  notification_to_replace: Notification | None,
42
40
  ) -> None:
43
- notification.identifier = str(uuid.uuid4())
41
+ pass
44
42
 
45
43
  async def _clear(self, notification: Notification) -> None:
46
44
  pass
47
45
 
48
46
  async def _clear_all(self) -> None:
49
47
  pass
50
-
51
- async def get_capabilities(self) -> frozenset[Capability]:
52
- return frozenset()
@@ -28,6 +28,7 @@ from rubicon.objc.runtime import load_library, objc_id, objc_block
28
28
  from .base import (
29
29
  Notification,
30
30
  DesktopNotifierBase,
31
+ AuthorisationError,
31
32
  Urgency,
32
33
  Capability,
33
34
  DEFAULT_SOUND,
@@ -81,6 +82,20 @@ UNAuthorizationStatusAuthorized = 2
81
82
  UNAuthorizationStatusProvisional = 3
82
83
  UNAuthorizationStatusEphemeral = 4
83
84
 
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
+
84
99
 
85
100
  class UNNotificationInterruptionLevel(enum.Enum):
86
101
  Passive = 0
@@ -89,7 +104,7 @@ class UNNotificationInterruptionLevel(enum.Enum):
89
104
  Critical = 3
90
105
 
91
106
 
92
- class NotificationCenterDelegate(NSObject): # type:ignore
107
+ class NotificationCenterDelegate(NSObject): # type: ignore
93
108
  """Delegate to handle user interactions with notifications"""
94
109
 
95
110
  @objc_method # type:ignore
@@ -172,9 +187,8 @@ class CocoaNotificationCenter(DesktopNotifierBase):
172
187
 
173
188
  def on_auth_completed(granted: bool, error: objc_id) -> None:
174
189
  ns_error = py_from_ns(error)
175
- if ns_error:
176
- ns_error.retain()
177
- future.set_result((granted, ns_error))
190
+ error_str = str(ns_error.localizedDescription) if ns_error else ""
191
+ future.set_result((granted, error_str))
178
192
 
179
193
  self.nc.requestAuthorizationWithOptions(
180
194
  UNAuthorizationOptionAlert
@@ -183,17 +197,16 @@ class CocoaNotificationCenter(DesktopNotifierBase):
183
197
  completionHandler=on_auth_completed,
184
198
  )
185
199
 
186
- has_authorization, error = await asyncio.wrap_future(future)
200
+ granted, error_str = await asyncio.wrap_future(future)
187
201
 
188
- if error:
189
- log_nserror(error, "Authorisation denied")
190
- error.autorelease() # type:ignore[attr-defined]
202
+ if error_str:
203
+ logger.warning("Authorisation denied: %s", error_str)
191
204
 
192
- return has_authorization
205
+ return granted
193
206
 
194
207
  async def has_authorisation(self) -> bool:
195
208
  """Whether we have authorisation to send notifications."""
196
- future: Future[UNNotificationSettings] = Future() # type:ignore[valid-type]
209
+ future: Future[UNNotificationSettings] = Future() # type:ignore
197
210
 
198
211
  def handler(settings: objc_id) -> None:
199
212
  settings = py_from_ns(settings)
@@ -203,12 +216,12 @@ class CocoaNotificationCenter(DesktopNotifierBase):
203
216
  self.nc.getNotificationSettingsWithCompletionHandler(handler)
204
217
 
205
218
  settings = await asyncio.wrap_future(future)
206
- authorized = settings.authorizationStatus in ( # type:ignore[attr-defined]
219
+ authorized = settings.authorizationStatus in ( # type:ignore
207
220
  UNAuthorizationStatusAuthorized,
208
221
  UNAuthorizationStatusProvisional,
209
222
  UNAuthorizationStatusEphemeral,
210
223
  )
211
- settings.autorelease() # type:ignore[attr-defined]
224
+ settings.release() # type:ignore
212
225
 
213
226
  return authorized
214
227
 
@@ -270,7 +283,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
270
283
  platform_nid, content=content, trigger=None
271
284
  )
272
285
 
273
- future: Future[NSError] = Future() # type:ignore[valid-type]
286
+ future: Future[NSError] = Future() # type:ignore
274
287
 
275
288
  def handler(error: objc_id) -> None:
276
289
  ns_error = py_from_ns(error)
@@ -287,8 +300,27 @@ class CocoaNotificationCenter(DesktopNotifierBase):
287
300
  error = await asyncio.wrap_future(future)
288
301
 
289
302
  if error:
290
- log_nserror(error, "Error when scheduling notification")
291
- error.autorelease() # type:ignore[attr-defined]
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
292
324
 
293
325
  notification.identifier = platform_nid
294
326
 
@@ -312,10 +344,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
312
344
  # Retrieve existing categories. We do not cache this value because it may be
313
345
  # modified by other Python processes using desktop-notifier.
314
346
  categories = await self._get_notification_categories()
315
- category_ids = set(
316
- py_from_ns(c.identifier)
317
- for c in categories.allObjects() # type:ignore[attr-defined]
318
- )
347
+ category_ids = set(py_from_ns(c.identifier) for c in categories.allObjects()) # type: ignore
319
348
 
320
349
  # Register new category if necessary.
321
350
  if category_id not in category_ids:
@@ -339,7 +368,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
339
368
  actions.append(action)
340
369
 
341
370
  # Add category for new set of buttons.
342
- new_categories = categories.setByAddingObject( # type:ignore[attr-defined]
371
+ new_categories = categories.setByAddingObject( # type: ignore
343
372
  UNNotificationCategory.categoryWithIdentifier(
344
373
  category_id,
345
374
  actions=actions,
@@ -351,9 +380,9 @@ class CocoaNotificationCenter(DesktopNotifierBase):
351
380
 
352
381
  return category_id
353
382
 
354
- async def _get_notification_categories(self) -> NSSet: # type:ignore[valid-type]
383
+ async def _get_notification_categories(self) -> NSSet: # type:ignore
355
384
  """Returns the registered notification categories for this app / Python."""
356
- future: Future[NSSet] = Future() # type:ignore[valid-type]
385
+ future: Future[NSSet] = Future() # type:ignore
357
386
 
358
387
  def handler(categories: objc_id) -> None:
359
388
  categories = py_from_ns(categories)
@@ -363,7 +392,7 @@ class CocoaNotificationCenter(DesktopNotifierBase):
363
392
  self.nc.getNotificationCategoriesWithCompletionHandler(handler)
364
393
 
365
394
  categories = await asyncio.wrap_future(future)
366
- categories.autorelease() # type:ignore[attr-defined]
395
+ categories.autorelease() # type:ignore
367
396
 
368
397
  return categories
369
398
 
@@ -404,13 +433,3 @@ class CocoaNotificationCenter(DesktopNotifierBase):
404
433
  capabilities.add(Capability.URGENCY)
405
434
 
406
435
  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
- Asynchronous desktop notification API
3
+ Desktop notifications for Windows, Linux, macOS, iOS and iPadOS.
4
4
  """
5
5
 
6
6
  from __future__ import annotations
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
  from typing import (
16
16
  Type,
17
17
  Callable,
18
+ Coroutine,
18
19
  List,
19
20
  Any,
20
21
  TypeVar,
@@ -125,10 +126,11 @@ class DesktopNotifier:
125
126
  Linux, this should correspond to the application name in a desktop entry. On
126
127
  macOS, this argument is ignored and the app is identified by the bundle ID of
127
128
  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.
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).
132
134
  :param notification_limit: Maximum number of notifications to keep in the system's
133
135
  notification center. This may be ignored by some implementations.
134
136
  """
@@ -138,9 +140,11 @@ class DesktopNotifier:
138
140
  def __init__(
139
141
  self,
140
142
  app_name: str = "Python",
141
- app_icon: Icon | Path | str | None = DEFAULT_ICON,
143
+ app_icon: Path | str | Icon | None = DEFAULT_ICON,
142
144
  notification_limit: int | None = None,
143
145
  ) -> None:
146
+ impl_cls = get_implementation_class()
147
+
144
148
  if isinstance(app_icon, str):
145
149
  warnings.warn(
146
150
  message="Pass an Icon instance instead of a string. "
@@ -162,12 +166,29 @@ class DesktopNotifier:
162
166
 
163
167
  self.app_icon = app_icon
164
168
 
165
- impl_cls = get_implementation_class()
169
+ self._lock = asyncio.Lock()
166
170
  self._impl = impl_cls(app_name, notification_limit)
167
171
  self._did_request_authorisation = False
168
172
 
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
+
169
177
  self._capabilities: frozenset[Capability] | None = None
170
178
 
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
+
171
192
  @property
172
193
  def app_name(self) -> str:
173
194
  """The application name"""
@@ -190,8 +211,9 @@ class DesktopNotifier:
190
211
 
191
212
  :returns: Whether authorisation has been granted.
192
213
  """
193
- self._did_request_authorisation = True
194
- return await self._impl.request_authorisation()
214
+ async with self._lock:
215
+ self._did_request_authorisation = True
216
+ return await self._impl.request_authorisation()
195
217
 
196
218
  async def has_authorisation(self) -> bool:
197
219
  """Returns whether we have authorisation to send notifications."""
@@ -201,31 +223,26 @@ class DesktopNotifier:
201
223
  """
202
224
  Sends a desktop notification.
203
225
 
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).
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.
212
229
 
213
230
  :param notification: The notification to send.
214
- :returns: The passed notification instance with a unique identifier populated.
215
231
  """
216
232
  if not notification.icon:
217
233
  notification.icon = self.app_icon
218
234
 
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()
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()
223
240
 
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)
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)
227
244
 
228
- return notification
245
+ return notification
229
246
 
230
247
  async def send(
231
248
  self,
@@ -245,9 +262,16 @@ class DesktopNotifier:
245
262
  """
246
263
  Sends a desktop notification
247
264
 
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`.
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).
251
275
 
252
276
  :returns: The scheduled notification instance.
253
277
  """
@@ -267,6 +291,52 @@ class DesktopNotifier:
267
291
  )
268
292
  return await self.send_notification(notification)
269
293
 
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
+
270
340
  @property
271
341
  def current_notifications(self) -> List[Notification]:
272
342
  """A list of all currently displayed notifications for this app"""
@@ -278,19 +348,22 @@ class DesktopNotifier:
278
348
 
279
349
  :param notification: Notification to clear.
280
350
  """
281
- await self._impl.clear(notification)
351
+ async with self._lock:
352
+ await self._impl.clear(notification)
282
353
 
283
354
  async def clear_all(self) -> None:
284
355
  """
285
356
  Removes all currently displayed notifications for this app from the notification
286
357
  center.
287
358
  """
288
- await self._impl.clear_all()
359
+ async with self._lock:
360
+ await self._impl.clear_all()
289
361
 
290
- async def get_capabilities(self) -> frozenset[Capability]:
362
+ @property
363
+ def capabilities(self) -> frozenset[Capability]:
291
364
  """
292
- Returns which functionality is supported by the implementation.
365
+ Returns which functionality us supported by the implementation.
293
366
  """
294
367
  if not self._capabilities:
295
- self._capabilities = await self._impl.get_capabilities()
368
+ self._capabilities = self._run_coro_sync(self._impl.get_capabilities())
296
369
  return self._capabilities
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: desktop-notifier
3
- Version: 5.0.0
3
+ Version: 5.0.0.dev0
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.2; extra == "docs"
44
+ Requires-Dist: sphinx-autoapi==3.1.1; 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,7 +9,6 @@ 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
13
12
  src/desktop_notifier/winrt.py
14
13
  src/desktop_notifier.egg-info/PKG-INFO
15
14
  src/desktop_notifier.egg-info/SOURCES.txt
@@ -18,5 +17,4 @@ src/desktop_notifier.egg-info/requires.txt
18
17
  src/desktop_notifier.egg-info/top_level.txt
19
18
  src/desktop_notifier/resources/__init__.py
20
19
  src/desktop_notifier/resources/python.png
21
- tests/test_api.py
22
- tests/test_sync_api.py
20
+ tests/test_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.2
30
+ sphinx-autoapi==3.1.1
31
31
  sphinx-mdinclude==0.6.1
@@ -110,6 +110,32 @@ 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
+
113
139
  @pytest.mark.asyncio
114
140
  @pytest.mark.skipif(
115
141
  sys.platform.startswith("win"),
@@ -1,137 +0,0 @@
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,66 +0,0 @@
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