diff --git a/CHANGELOG.md b/CHANGELOG.md index cb8bbac7..c09d76ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Cancel or Back during an NZBGet download asks first.** A menu offers + three choices: stop it and remove it and its files from NZBGet (what a press + used to do), go back but keep it downloading in NZBGet, or keep watching + the download + ([Cancel and Back](https://appz4fun.github.io/NeNeTeePee-Stream-Kodi/features/nzbget-backend/#cancel-and-back)). - **Read a release's NFO and MediaInfo from the picker.** Left or Right on a release opens a viewer over the list ([NFO and MediaInfo viewer](https://appz4fun.github.io/NeNeTeePee-Stream-Kodi/features/nfo-viewer/)): diff --git a/docs-site/features/nzbget-backend.md b/docs-site/features/nzbget-backend.md index dc07efab..ce9c2148 100644 --- a/docs-site/features/nzbget-backend.md +++ b/docs-site/features/nzbget-backend.md @@ -245,7 +245,8 @@ shared duplicate keys and descending scores. Only this legacy path can use the existing one-shot FORCE rescue. Authentication, timeout, or other errors do not trigger individual appends because a bulk submission may already have succeeded. -If you cancel the play, NeNeTeePee-Stream-Kodi stops what's downloading: it +If you cancel the play and choose to stop the download (see +[Cancel and Back](#cancel-and-back)), NeNeTeePee-Stream-Kodi stops what's downloading: it removes your pick and any backup NZBGet promoted or queued. The backups NZBGet parked in its history (status `dupe`) stay there: they don't download, and if you play the same release again within a day they're reused instead of @@ -433,9 +434,27 @@ One of those is still used if its upload's first listing fails: the add-on then asks the next indexer that lists the same upload. The download dialog is the add-on's own window. It has no progress bar, since -the first line carries the percent, and room for eight lines. Cancel, Back -and Escape stop the play. If the window cannot be opened, Kodi's own progress -dialog is used and shows the first four lines. +the first line carries the percent, and room for eight lines. If the window +cannot be opened, Kodi's own progress dialog is used and shows the first four +lines. + +#### Cancel and Back + +Cancel, Back, Escape and Stop don't stop the download straight away. They open +a menu that asks what you meant: + +![The cancel menu over the download dialog](../images/download-cancel-menu.png) + +| Choice | What happens | +| --- | --- | +| **Yes, stop it and remove it and its files from NZBGet** | The play stops and its downloads are removed from NZBGet, as described under [Smart Duplicates failover](#smart-duplicates-failover). | +| **Yes, go back but keep it downloading in NZBGet** | You go back to where you were. Nothing is removed: the download keeps running in NZBGet, and a toast says "Left downloading in NZBGet". Play the release again once it has finished and it plays from the completed folder. | +| **No, keep watching the download** | The menu closes and the download dialog carries on. Back on the menu itself does the same. | + +If you go back while the copies are still being sent, the add-on finishes +sending them first, then leaves without removing anything. + +![Back, keep watching, then Back again and leave it downloading](../images/download-cancel-menu.gif) Once NZBGet has the copies, the dialog shows these lines: diff --git a/docs-site/images/download-cancel-menu.gif b/docs-site/images/download-cancel-menu.gif new file mode 100644 index 00000000..caade2c7 Binary files /dev/null and b/docs-site/images/download-cancel-menu.gif differ diff --git a/docs-site/images/download-cancel-menu.png b/docs-site/images/download-cancel-menu.png new file mode 100644 index 00000000..fbc9ec96 Binary files /dev/null and b/docs-site/images/download-cancel-menu.png differ diff --git a/repo/plugin.video.nzbdav/resources/language/resource.language.en_gb/strings.po b/repo/plugin.video.nzbdav/resources/language/resource.language.en_gb/strings.po index a81b57ff..23526c7a 100644 --- a/repo/plugin.video.nzbdav/resources/language/resource.language.en_gb/strings.po +++ b/repo/plugin.video.nzbdav/resources/language/resource.language.en_gb/strings.po @@ -2912,3 +2912,27 @@ msgstr "" msgctxt "#30788" msgid "{} posts that are not this release" msgstr "" + +msgctxt "#30789" +msgid "Stop this download?" +msgstr "" + +msgctxt "#30790" +msgid "Yes, stop it and remove it and its files from NZBGet" +msgstr "" + +msgctxt "#30791" +msgid "Yes, go back but keep it downloading in NZBGet" +msgstr "" + +msgctxt "#30792" +msgid "No, keep watching the download" +msgstr "" + +msgctxt "#30793" +msgid "Left downloading in NZBGet" +msgstr "" + +msgctxt "#30794" +msgid "Going back. The download keeps running in NZBGet." +msgstr "" diff --git a/repo/plugin.video.nzbdav/resources/lib/i18n.py b/repo/plugin.video.nzbdav/resources/lib/i18n.py index 4384f6ef..0fc4b39d 100644 --- a/repo/plugin.video.nzbdav/resources/lib/i18n.py +++ b/repo/plugin.video.nzbdav/resources/lib/i18n.py @@ -236,6 +236,12 @@ 30693: "Repair needs {} parity blocks", 30694: "Cancel", 30695: "Cancelling...", + 30789: "Stop this download?", + 30790: "Yes, stop it and remove it and its files from NZBGet", + 30791: "Yes, go back but keep it downloading in NZBGet", + 30792: "No, keep watching the download", + 30793: "Left downloading in NZBGet", + 30794: "Going back. The download keeps running in NZBGet.", 30696: "not downloading 1 duplicate", 30697: "not downloading {} duplicates", 30700: "{} copies ({} listings on {} indexers)", diff --git a/repo/plugin.video.nzbdav/resources/lib/nzbget_dialog.py b/repo/plugin.video.nzbdav/resources/lib/nzbget_dialog.py index 31522843..2a8984c4 100644 --- a/repo/plugin.video.nzbdav/resources/lib/nzbget_dialog.py +++ b/repo/plugin.video.nzbdav/resources/lib/nzbget_dialog.py @@ -14,17 +14,29 @@ never stops a download. Cancel is read from a Home window property the window's Cancel button sets -(on a click and on Back). That is a plain read, so it is seen at once from -any thread; a script callback would only arrive when the polling thread next -waits. ``onAction`` and ``onClick`` set the same flag for the keys the -property does not cover. +(on a click and on Back; the button always has the focus). That is a plain +read, so it is seen at once from any thread; a script callback would only +arrive when the polling thread next waits. ``onAction`` covers only the keys +the property does not: Escape (previous menu) and Stop. Back and a click also +reach ``onAction`` / ``onClick``, late; taking those too would count one press +twice and ask again after the menu was answered. + +A press does not stop the download by itself: ``iscanceled`` first asks what +the press meant (``ask_cancel_choice``). Stop it and remove it from NZBGet, +go back and leave it downloading (``detached`` turns True, ``iscanceled`` +stays False, and the resolve leaves without deleting anything), or carry on +watching (the press is forgotten). Only the thread that opened the dialog +asks; any other thread that polls it sees no cancel until the answer is in. """ import os +import threading import xbmc import xbmcgui +from resources.lib.i18n import string as _string + WINDOW_XML = "download-dialog.xml" # How many lines the window has room for (``nzbget_progress`` asks). MAX_LINES = 8 @@ -33,9 +45,80 @@ _HOME_WINDOW = 10000 _ACTION_PREVIOUS_MENU = 10 _ACTION_STOP = 13 -_ACTION_NAV_BACK = 92 -_CANCEL_ACTIONS = frozenset((_ACTION_PREVIOUS_MENU, _ACTION_STOP, _ACTION_NAV_BACK)) +# Back (92) and a click on Cancel are seen through CANCEL_PROPERTY. +_CANCEL_ACTIONS = frozenset((_ACTION_PREVIOUS_MENU, _ACTION_STOP)) _LINE_BREAK = "[CR]" +# The cancel menu's rows, in the order it lists them. +CHOICE_STOP = 0 +CHOICE_DETACH = 1 +CHOICE_RESUME = 2 +_STOPPED = "stop" +_DETACHED = "detach" + + +def ask_cancel_choice(): + """Ask what a Cancel or Back press meant; one of the ``CHOICE_*`` values. + + Back on the menu itself (Kodi's ``-1``) is "no, carry on". A menu Kodi + refuses to show, or an answer that is not one of its rows, stops the + download as the press used to, so a cancel always stays possible. + """ + try: + choice = xbmcgui.Dialog().select( + _string(30789), [_string(30790), _string(30791), _string(30792)] + ) + except Exception as exc: # pylint: disable=broad-except + xbmc.log( + "NeNeTeePee-Stream-Kodi: cancel menu unavailable, stopping the " + "download: {}".format(exc), + xbmc.LOGWARNING, + ) + return CHOICE_STOP + if choice == -1: + return CHOICE_RESUME + if choice in (CHOICE_STOP, CHOICE_DETACH, CHOICE_RESUME): + return choice + return CHOICE_STOP + + +class _CancelGate: + """Turns a raw Cancel/Back press into the answer from the cancel menu.""" + + def __init__(self): + self._lock = threading.Lock() + self._owner = threading.get_ident() + self.state = None + + def claim(self): + """The calling thread is the one that asks (the one showing the dialog).""" + self._owner = threading.get_ident() + self.state = None + + def check(self, pressed, forget_press, on_detach=None): + """True when the download is to stop; asks once per press.""" + if self.state == _STOPPED: + return True + if self.state == _DETACHED or not pressed(): + return False + if threading.get_ident() != self._owner: + return False + if not self._lock.acquire(False): # pylint: disable=consider-using-with + return False + try: + if self.state is not None or not pressed(): + return self.state == _STOPPED + choice = ask_cancel_choice() + if choice == CHOICE_STOP: + self.state = _STOPPED + return True + forget_press() + if choice == CHOICE_DETACH: + self.state = _DETACHED + if on_detach is not None: + on_detach() + return False + finally: + self._lock.release() def split_message(message): @@ -64,11 +147,18 @@ def __init__(self, *args, **kwargs): super().__init__(*args) self._canceled = False self._shown = False + self._gate = _CancelGate() + + @property + def detached(self): + """True once the user chose to go back and leave it downloading.""" + return self._gate.state == _DETACHED def create(self, heading, message=""): """Show the window with ``heading`` and the first ``message``.""" _home().clearProperty(CANCEL_PROPERTY) self._canceled = False + self._gate.claim() self.setProperty("heading", str(heading or "")) self._set_message(message) self.show() @@ -86,13 +176,21 @@ def _set_message(self, message): self.setProperty("body", body) def iscanceled(self): - """True once Cancel or Back was pressed.""" - if self._canceled: - return True - if _home().getProperty(CANCEL_PROPERTY) == "1": + """True once Cancel or Back was pressed and the menu said stop it.""" + return self._gate.check(self._pressed, self._forget_press, self._on_detach) + + def _pressed(self): + if not self._canceled and _home().getProperty(CANCEL_PROPERTY) == "1": self._canceled = True return self._canceled + def _forget_press(self): + self._canceled = False + _home().clearProperty(CANCEL_PROPERTY) + + def _on_detach(self): + self._set_message(_string(30794)) + def close(self): """Close the window and forget the cancel mark.""" try: @@ -103,13 +201,13 @@ def close(self): _home().clearProperty(CANCEL_PROPERTY) def onAction(self, action): # pylint: disable=invalid-name - """Back, Escape and Stop cancel; nothing else closes the window.""" - if action.getId() in _CANCEL_ACTIONS: - self._canceled = True + """Escape and Stop ask to cancel; nothing else closes the window. - def onClick(self, control_id): # pylint: disable=invalid-name - """A click on Cancel.""" - if control_id == CANCEL_BUTTON_ID: + Back is not taken here: the Cancel button's ```` already set + the property for it, and this callback can arrive after the menu + for that press was answered. + """ + if action.getId() in _CANCEL_ACTIONS: self._canceled = True @@ -139,6 +237,62 @@ def open_dialog(heading, message=""): "Kodi's progress dialog: {}".format(exc), xbmc.LOGWARNING, ) - dialog = xbmcgui.DialogProgress() + dialog = KodiProgressDialog() dialog.create(heading, message) return dialog + + +class KodiProgressDialog: + """Kodi's progress dialog, with the same cancel menu as the own window. + + Kodi's dialog cannot forget a Cancel press, so "carry on" closes it and + opens a fresh one with the same text. + """ + + def __init__(self): + self._dialog = xbmcgui.DialogProgress() + self._gate = _CancelGate() + self._text = ("", "", 0) + + @property + def detached(self): + """True once the user chose to go back and leave it downloading.""" + return self._gate.state == _DETACHED + + def create(self, heading, message=""): + """Open Kodi's dialog with ``heading`` and ``message``.""" + self._gate.claim() + self._text = (heading, message, 0) + self._dialog.create(heading, message) + + def update(self, percent, message=None): + """Move the bar and, when given, replace the text.""" + heading, last, _percent = self._text + self._text = (heading, last if message is None else message, percent) + if message is None: + self._dialog.update(percent) + else: + self._dialog.update(percent, message) + + def iscanceled(self): + """True once Cancel was pressed and the menu said stop it.""" + return self._gate.check( + lambda: self._dialog.iscanceled() is True, self._reopen, self._on_detach + ) + + def _reopen(self): + heading, message, percent = self._text + try: + self._dialog.close() + except Exception: # pylint: disable=broad-except + pass + self._dialog = xbmcgui.DialogProgress() + self._dialog.create(heading, message) + self._dialog.update(percent, message) + + def _on_detach(self): + self.update(self._text[2], _string(30794)) + + def close(self): + """Close Kodi's dialog.""" + self._dialog.close() diff --git a/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver.py b/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver.py index 1da058e3..62d34423 100644 --- a/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver.py +++ b/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver.py @@ -165,6 +165,9 @@ def poll_nzbget_job( "nzbid": state["current"], "paused_nzbids": state["paused_nzbids"], } + if _dialog_detached(dialog): + # "Go back but keep it downloading": nothing is deleted. + return {"outcome": "detached", "nzbid": state["current"]} terminal = _poll_tick(state, dialog, settings_getter, dupe_key, fleet) if terminal is not None: return terminal @@ -669,6 +672,17 @@ def _handle_poll_failure( if outcome in ("timeout", "aborted"): on_failure(_string(30101)) return True, True + if outcome == "detached": + # The user went back and left the download running: no deletes, and + # no cancel event (a backup append still in flight must not be + # deleted as a late cancel). + xbmc.log( + "NeNeTeePee-Stream-Kodi: left the NZBGet download running " + "(nzbid {}) on the user's word.".format(nzbid), + xbmc.LOGINFO, + ) + on_failure(_string(30793)) + return True, True if outcome == "canceled": if cancel_event is not None: cancel_event.set() # stop the backup worker first @@ -819,6 +833,11 @@ def _dialog_canceled(dialog): return False +def _dialog_detached(dialog): + """True once the cancel menu's "go back, keep it downloading" was chosen.""" + return getattr(dialog, "detached", False) is True + + def _confirm_redownload(folder): """Ask whether to download a release whose finished files were deleted. @@ -910,6 +929,11 @@ def _reuse_or_submit(ctx, nzb_url, title, completed_job, meta): if reuse_url: ctx.on_success(reuse_url) return False + if _dialog_detached(ctx.dialog): + # The user went back while the finished files were looked for: that + # is no reason to send the release to NZBGet again. + ctx.on_failure(None) + return False if reuse_url is SMB_UNREADABLE: # The completed files are visible but never became readable (the # stale-SMB-session case). Re-submitting the SUCCESS row would only @@ -1060,6 +1084,12 @@ def _submit_poll_resolve(ctx, nzb_url, title, download_pubdate, download_size): return False else: nzbid, error = _submit_pick(ctx, nzb_url, title, dupe_key) + if not nzbid and _dialog_detached(ctx.dialog): + # The user went back before anything was queued (for example while + # the fleet looked for a completed copy's files): nothing to play, + # nothing to diagnose. + ctx.on_failure(None) + return False completed_url = getattr(ctx, "bulk_completed_url", None) if completed_url: ctx.on_success(completed_url) @@ -1225,6 +1255,10 @@ def _play_completed_download( """ record_download(title, download_pubdate, download_size) _record_fleet_pubdates(getattr(ctx, "dupe", None), title, job_id) + if _dialog_detached(ctx.dialog): + # Finished while the user was choosing to go back: leave it there. + ctx.on_failure(None) + return video_url = _resolve_completed_smb( dest_dir, ctx, @@ -1241,7 +1275,9 @@ def _play_completed_download( ctx.on_failure(None) return if not video_url: - ctx.on_failure(_string(30223)) + # Going back from the cancel menu while the file settled is not a + # missing video. + ctx.on_failure(None if _dialog_detached(ctx.dialog) else _string(30223)) return ctx.on_success(video_url) diff --git a/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver_smb.py b/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver_smb.py index c3b4f9e4..dba2d133 100644 --- a/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver_smb.py +++ b/repo/plugin.video.nzbdav/resources/lib/nzbget_resolver_smb.py @@ -336,7 +336,7 @@ def _drive_resolve_dialog(dialog, now, deadline, budget): """ if dialog is None: return False - if dialog.iscanceled(): + if dialog.iscanceled() or _core._dialog_detached(dialog): return True elapsed = budget - max(0.0, deadline - now) percent = int(min(100.0, elapsed * 100.0 / budget)) if budget else 100 diff --git a/tests/test_nzbget_parity_dialog.py b/tests/test_nzbget_parity_dialog.py index 9525ffcb..a4e36019 100644 --- a/tests/test_nzbget_parity_dialog.py +++ b/tests/test_nzbget_parity_dialog.py @@ -2,7 +2,12 @@ # Copyright (C) 2026 nzbdav contributors """Parity in the NZBGet progress text, and the add-on's own download dialog.""" +# open_dialog may return either dialog class; these tests check which one it +# returned before using the window-only calls. +# pylint: disable=no-member + import os +import threading from unittest.mock import MagicMock, patch from resources.lib import nzbget_api, nzbget_dialog, nzbget_progress, nzbget_resolver @@ -315,7 +320,9 @@ def _home(): def _open(home): with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): - return nzbget_dialog.open_dialog("Add-on", "Finding copies...") + dialog = nzbget_dialog.open_dialog("Add-on", "Finding copies...") + assert isinstance(dialog, nzbget_dialog.DownloadDialog) + return dialog def test_the_first_line_is_the_headline_and_the_rest_the_body(): @@ -363,8 +370,9 @@ def test_the_cancel_button_and_back_are_seen_through_the_home_property(): assert dialog.iscanceled() is True -def test_back_escape_and_stop_cancel_and_other_keys_do_not(): - for action_id, canceled in ((92, True), (10, True), (13, True), (7, False)): +def test_escape_and_stop_cancel_and_other_keys_do_not(): + # Back (92) is seen through the property its sets, not here. + for action_id, canceled in ((10, True), (13, True), (92, False), (7, False)): home = _home() dialog = _open(home) dialog.onAction(_Action(action_id)) @@ -372,13 +380,13 @@ def test_back_escape_and_stop_cancel_and_other_keys_do_not(): assert dialog.iscanceled() is canceled, action_id -def test_a_click_cancels_only_on_the_cancel_button(): +def test_a_click_is_seen_through_the_property_alone(): home = _home() dialog = _open(home) + assert not hasattr(nzbget_dialog.DownloadDialog, "onClick") with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): - dialog.onClick(3) assert dialog.iscanceled() is False - dialog.onClick(nzbget_dialog.CANCEL_BUTTON_ID) + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") # assert dialog.iscanceled() is True @@ -406,7 +414,8 @@ def test_kodis_dialog_is_used_when_the_window_cannot_open(): ) as log: dialog = nzbget_dialog.open_dialog("Add-on", "Finding copies...") - assert dialog is progress.return_value + assert isinstance(dialog, nzbget_dialog.KodiProgressDialog) + assert dialog._dialog is progress.return_value progress.return_value.create.assert_called_once_with("Add-on", "Finding copies...") assert "no skin file" in log.call_args.args[0] # Kodi's dialog has no room for the extra lines. @@ -479,8 +488,6 @@ def test_the_own_dialog_names_every_indexer_and_kodis_stops_at_its_width(): for name in names ) - import threading - own = MagicMock() own.max_lines = 8 progress = _FleetProgress(own, threading.Event()) @@ -496,3 +503,144 @@ def test_the_own_dialog_names_every_indexer_and_kodis_stops_at_its_width(): progress.report = report progress.update("send", 8, 8) assert "Indexer Number 08" not in kodi_dialog.update.call_args.args[1] + + +# --- the cancel menu ---------------------------------------------------------- + + +def _choose(choice): + return patch.object(nzbget_dialog, "ask_cancel_choice", return_value=choice) + + +def test_cancel_menu_stop_cancels_and_stays_canceled(): + home = _home() + dialog = _open(home) + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_STOP) as ask: + assert dialog.iscanceled() is True + assert dialog.iscanceled() is True + assert ask.call_count == 1 + assert dialog.detached is False + + +def test_cancel_menu_resume_forgets_the_press(): + home = _home() + dialog = _open(home) + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_RESUME): + assert dialog.iscanceled() is False + assert home.getProperty(nzbget_dialog.CANCEL_PROPERTY) == "" + assert dialog.detached is False + # Nothing pressed since: no second question. + with _choose(nzbget_dialog.CHOICE_STOP) as ask: + assert dialog.iscanceled() is False + ask.assert_not_called() + # A new press asks again. + dialog.onAction(_Action(13)) + with _choose(nzbget_dialog.CHOICE_STOP): + assert dialog.iscanceled() is True + + +def test_cancel_menu_detach_goes_back_without_canceling(): + home = _home() + dialog = _open(home) + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_DETACH): + assert dialog.iscanceled() is False + assert dialog.detached is True + assert home.getProperty(nzbget_dialog.CANCEL_PROPERTY) == "" + assert dialog.getProperty("headline") == nzbget_dialog._string(30794) + # Another press after going back never asks or cancels. + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_STOP) as ask: + assert dialog.iscanceled() is False + ask.assert_not_called() + + +def test_only_the_dialogs_own_thread_asks(): + home = _home() + dialog = _open(home) + seen = [] + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_STOP) as ask: + worker = threading.Thread(target=lambda: seen.append(dialog.iscanceled())) + worker.start() + worker.join() + ask.assert_not_called() + assert seen == [False] + assert dialog.iscanceled() is True + + +def test_ask_cancel_choice_maps_kodis_answers(): + for answer, choice in ( + (0, nzbget_dialog.CHOICE_STOP), + (1, nzbget_dialog.CHOICE_DETACH), + (2, nzbget_dialog.CHOICE_RESUME), + (-1, nzbget_dialog.CHOICE_RESUME), + (7, nzbget_dialog.CHOICE_STOP), + ): + with patch.object(nzbget_dialog.xbmcgui, "Dialog") as dialog_cls: + dialog_cls.return_value.select.return_value = answer + assert nzbget_dialog.ask_cancel_choice() == choice, answer + labels = dialog_cls.return_value.select.call_args.args[1] + assert len(labels) == 3 + with patch.object(nzbget_dialog.xbmcgui, "Dialog", side_effect=RuntimeError("x")): + with patch.object(nzbget_dialog.xbmc, "log"): + assert nzbget_dialog.ask_cancel_choice() == nzbget_dialog.CHOICE_STOP + + +def test_kodis_dialog_resume_reopens_and_detach_keeps_it(): + with patch.object(nzbget_dialog.xbmcgui, "DialogProgress") as progress: + first, second = MagicMock(), MagicMock() + progress.side_effect = [first, second] + first.iscanceled.return_value = True + second.iscanceled.return_value = False + dialog = nzbget_dialog.KodiProgressDialog() + dialog.create("Add-on", "Finding copies...") + dialog.update(40, "Copy 1 - downloading 40%") + with _choose(nzbget_dialog.CHOICE_RESUME): + assert dialog.iscanceled() is False + first.close.assert_called_once() + second.create.assert_called_once_with("Add-on", "Copy 1 - downloading 40%") + second.update.assert_called_with(40, "Copy 1 - downloading 40%") + second.iscanceled.return_value = True + third = MagicMock() + progress.side_effect = [third] + third.iscanceled.return_value = False + with _choose(nzbget_dialog.CHOICE_DETACH): + assert dialog.iscanceled() is False + assert dialog.detached is True + + +def test_a_late_back_callback_for_the_answered_press_does_not_ask_again(): + home = _home() + dialog = _open(home) + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + # The window's set the property; Kodi delivers onAction later. + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_RESUME): + assert dialog.iscanceled() is False + dialog.onAction(_Action(92)) # the same press, delivered late + with _choose(nzbget_dialog.CHOICE_STOP) as ask: + assert dialog.iscanceled() is False + ask.assert_not_called() + # The next press is a new one. + home.setProperty(nzbget_dialog.CANCEL_PROPERTY, "1") + with _choose(nzbget_dialog.CHOICE_STOP): + assert dialog.iscanceled() is True + + +def test_stop_asks_again_after_keep_watching(): + home = _home() + dialog = _open(home) + with patch.object(nzbget_dialog.xbmcgui, "Window", return_value=home): + dialog.onAction(_Action(13)) + with _choose(nzbget_dialog.CHOICE_RESUME): + assert dialog.iscanceled() is False + dialog.onAction(_Action(13)) + with _choose(nzbget_dialog.CHOICE_STOP): + assert dialog.iscanceled() is True diff --git a/tests/test_nzbget_resolver.py b/tests/test_nzbget_resolver.py index bf1ab1fb..8d7e7840 100644 --- a/tests/test_nzbget_resolver.py +++ b/tests/test_nzbget_resolver.py @@ -69,6 +69,7 @@ def _fake_nzb(url, **_kw): class _Dialog: def __init__(self): self.canceled = False + self.detached = False self.lines = [] def iscanceled(self): @@ -3669,3 +3670,123 @@ def test_queue_era_successes_are_never_stale(): "queue_era_nzbids": [9], } assert _stale_successes("k", _settings({}), fleet) == (7,) + + +# --- the cancel menu's "go back, keep it downloading" ------------------------ + + +def test_poll_returns_detached_when_the_user_went_back(): + def getter(k, d=""): + return {"nzbget_url": "http://box"}.get(k, d) + + dialog = _Dialog() + dialog.detached = True + with patch( + "resources.lib.nzbget_resolver.nzbget_api.group_status", + return_value={"present": True, "status": "DOWNLOADING", "percent": 10}, + ) as group: + result = poll_nzbget_job( + 42, dialog, _Monitor(), timeout=60, settings_getter=getter + ) + assert result == {"outcome": "detached", "nzbid": 42} + group.assert_not_called() + + +def test_handle_poll_failure_detached_deletes_nothing(): + import threading + + ev = threading.Event() + messages = [] + with patch("resources.lib.nzbget_resolver.nzbget_api.cancel_jobs") as cancel, patch( + "resources.lib.nzbget_resolver.nzbget_api.cancel_queued_jobs" + ) as cancel_queued: + handled, leave = _handle_poll_failure( + "detached", 5, _settings({}), messages.append, cancel_event=ev + ) + assert (handled, leave) == (True, True) + assert not ev.is_set() + _time_module.sleep(0.05) + cancel.assert_not_called() + cancel_queued.assert_not_called() + assert messages == ["Left downloading in NZBGet"] + + +def test_resolve_detached_resolves_false_and_keeps_the_job(): + plugin = sys.modules["xbmcplugin"] + plugin.setResolvedUrl = MagicMock() + with patch( + "resources.lib.nzbget_resolver.nzbget_api.append_nzb", + return_value=(42, None), + ), patch( + "resources.lib.nzbget_resolver.poll_nzbget_job", + return_value={"outcome": "detached", "nzbid": 42}, + ), patch( + "resources.lib.nzbget_resolver.nzbget_api.cancel_jobs" + ) as cancel: + resolve_and_play_nzbget( + 7, + {"nzburl": "http://i/x.nzb", "title": "X"}, + settings_getter=_full_settings(), + ) + _time_module.sleep(0.05) + cancel.assert_not_called() + assert plugin.setResolvedUrl.call_args[0][1] is False + + +def test_a_finished_download_is_not_played_after_going_back(): + from resources.lib import nzbget_resolver + + ctx = MagicMock() + ctx.dialog = _Dialog() + ctx.dialog.detached = True + ctx.dupe = None + with patch.object(nzbget_resolver, "record_download"), patch.object( + nzbget_resolver, "_resolve_completed_smb" + ) as smb: + nzbget_resolver._play_completed_download(ctx, "/dl/X", "X", None, None) + smb.assert_not_called() + ctx.on_failure.assert_called_once_with(None) + ctx.on_success.assert_not_called() + + +def test_going_back_during_the_reuse_probe_sends_nothing(): + from resources.lib import nzbget_resolver + + ctx = MagicMock() + ctx.season_pack_record = None + ctx.dialog = _Dialog() + ctx.dialog.detached = True + with patch.object( + nzbget_resolver, "_gone_completed_folder", return_value=None + ), patch.object( + nzbget_resolver, "_reuse_completed_job", return_value=None + ), patch.object( + nzbget_resolver, "_submit_poll_resolve" + ) as submit: + leave = nzbget_resolver._reuse_or_submit( + ctx, "http://i/x.nzb", "X", {"dest_dir": "/dl/X"}, (None, None) + ) + assert leave is False + submit.assert_not_called() + ctx.on_failure.assert_called_once_with(None) + + +def test_going_back_during_the_fleets_completed_copy_check_ends_quietly(): + from resources.lib import nzbget_resolver + + ctx = MagicMock() + ctx.dupe = {"key": "k"} + ctx.dialog = _Dialog() + ctx.dialog.detached = True + ctx.cancel_event.is_set.return_value = False + ctx.bulk_completed_url = None + with patch( + "resources.lib.nzbget_fleet_run.submit_fleet", + return_value=(None, "No readable video in the completed download"), + ), patch.object(nzbget_resolver, "poll_nzbget_job") as poll: + leave = nzbget_resolver._submit_poll_resolve( + ctx, "http://i/x.nzb", "X", None, None + ) + assert leave is False + poll.assert_not_called() + ctx.on_failure.assert_called_once_with(None)