from __future__ import annotations from typing import Any, Dict, Sequence import json import pipeline as ctx from API import HydrusNetwork as hydrus_wrapper from ._shared import Cmdlet, CmdletArg, normalize_hash, get_hash_for_operation, fetch_hydrus_metadata, should_show_help, get_field from SYS.logger import log CMDLET = Cmdlet( name="delete-note", summary="Delete a named note from a Hydrus file.", usage="i | del-note [-hash ] ", alias=["del-note"], arg=[ ], detail=[ "- Removes the note with the given name from the Hydrus file.", ], ) def _run(result: Any, args: Sequence[str], config: Dict[str, Any]) -> int: # Help if should_show_help(args): log(json.dumps(CMDLET, ensure_ascii=False, indent=2)) return 0 if not args: log("Requires the note name/key to delete") return 1 override_hash: str | None = None rest: list[str] = [] i = 0 while i < len(args): a = args[i] low = str(a).lower() if low in {"-hash", "--hash", "hash"} and i + 1 < len(args): override_hash = str(args[i + 1]).strip() i += 2 continue rest.append(a) i += 1 if not rest: log("Requires the note name/key to delete") return 1 name = str(rest[0] or '').strip() if not name: log("Requires a non-empty note name/key") return 1 # Handle @N selection which creates a list - extract the first item if isinstance(result, list) and len(result) > 0: result = result[0] hash_hex = get_hash_for_operation(override_hash, result) if not hash_hex: log("Selected result does not include a Hydrus hash") return 1 try: client = hydrus_wrapper.get_client(config) except Exception as exc: log(f"Hydrus client unavailable: {exc}") return 1 if client is None: log("Hydrus client unavailable") return 1 try: service_name = "my notes" client.delete_notes(hash_hex, [name], service_name) except Exception as exc: log(f"Hydrus delete-note failed: {exc}") return 1 # Refresh notes view if we're operating on the current subject try: from cmdlets import get_note as get_note_cmd # type: ignore except Exception: get_note_cmd = None if get_note_cmd: try: subject = ctx.get_last_result_subject() if subject is not None: def norm(val: Any) -> str: return str(val).lower() target_hash = norm(hash_hex) if hash_hex else None subj_hashes = [] if isinstance(subject, dict): subj_hashes = [norm(v) for v in [subject.get("hydrus_hash"), subject.get("hash"), subject.get("hash_hex"), subject.get("file_hash")] if v] else: subj_hashes = [norm(get_field(subject, f)) for f in ("hydrus_hash", "hash", "hash_hex", "file_hash") if get_field(subject, f)] if target_hash and target_hash in subj_hashes: get_note_cmd.get_notes(subject, ["-hash", hash_hex], config) return 0 except Exception: pass log(f"Deleted note '{name}'") return 0