diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..06f2ad0e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,232 @@ +# Build release artifacts when a version tag is pushed (v*). +# Linux : .deb + tar.gz + AppImage + SHA256SUMS (PySide6, validated). +# Windows: PyInstaller onedir + zip + Inno Setup installer (continue-on-error until CI is stable). +# macOS : PyInstaller .app + zip (continue-on-error, unvalidated without a macOS machine). +# +# workflow_dispatch: manual trigger for CI validation without creating a tag or release. +# Tags with '-' (e.g. v2.0.0-rc1) are published as GitHub pre-releases. + +name: Release + +on: + push: + tags: + - "v*" + workflow_dispatch: + inputs: + version: + description: "Version to build (e.g. 2.0.0-rc1)" + required: true + default: "2.0.0-dev" + +permissions: + contents: write + +jobs: + version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.v.outputs.version }} + steps: + - id: v + run: | + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "version=${{ github.event.inputs.version }}" >> "$GITHUB_OUTPUT" + else + ref="${GITHUB_REF_NAME}" + echo "version=${ref#v}" >> "$GITHUB_OUTPUT" + fi + + linux: + needs: version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y dpkg-dev gettext + + - name: Download appimagetool + run: | + arch="$(uname -m)" + mkdir -p tools + wget -q -O "tools/appimagetool-${arch}.AppImage" \ + "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${arch}.AppImage" + chmod +x "tools/appimagetool-${arch}.AppImage" + + - name: Build Linux artifacts + run: | + chmod +x packaging/linux/*.sh + ./packaging/linux/release.sh "${{ needs.version.outputs.version }}" + + - name: Upload Linux artifacts + uses: actions/upload-artifact@v7.0.2 + with: + name: linux-${{ needs.version.outputs.version }} + path: | + dist/netneighbor_*.deb + dist/netneighbor-*.tar.gz + dist/NetNeighbor-*.AppImage + dist/SHA256SUMS-*.txt + + windows: + needs: version + runs-on: windows-latest + continue-on-error: true + steps: + - uses: actions/checkout@v7.0.1 + + - uses: actions/setup-python@v7.1.0 + with: + python-version: "3.12" + + - name: Install Inno Setup + run: choco install innosetup --no-progress -y + + - name: Build Windows bundle + run: | + .\packaging\windows\build.ps1 -Version ${{ needs.version.outputs.version }} + + - name: Build Windows installer + run: | + .\packaging\windows\build_installer.ps1 -Version ${{ needs.version.outputs.version }} + + - name: Upload Windows artifacts + uses: actions/upload-artifact@v7.0.2 + with: + name: windows-${{ needs.version.outputs.version }} + path: dist/NetNeighbor-*-win64-setup.exe + + macos-arm64: + needs: version + runs-on: macos-latest + continue-on-error: true + steps: + - uses: actions/checkout@v7.0.1 + + - uses: actions/setup-python@v7.1.0 + with: + python-version: "3.12" + + - name: Install Python dependencies + run: python3 -m pip install -r requirements.txt pyinstaller + + - name: Install create-dmg + run: brew install create-dmg + + - name: Build macOS arm64 app bundle + DMG + run: | + bash packaging/macos/build_app.sh "${{ needs.version.outputs.version }}" arm64 + + - name: Smoke test arm64 binary + run: | + APP="dist/NetNeighbor.app/Contents/MacOS/NetNeighbor" + echo "Launching $APP for 5 s..." + "$APP" & + PID=$! + sleep 5 + if kill -0 "$PID" 2>/dev/null; then + kill "$PID" + echo "PASS: process still alive after 5 s" + else + wait "$PID"; CODE=$? + # 0 = clean exit, 124 = killed by timeout — both acceptable + if [ "$CODE" -eq 0 ] || [ "$CODE" -eq 124 ]; then + echo "PASS: process exited cleanly (code $CODE)" + else + echo "FAIL: process crashed (exit code $CODE)" + exit 1 + fi + fi + + - name: Cleanup .app bundle (DMG only in release) + run: rm -rf dist/NetNeighbor.app + + - name: Upload macOS arm64 artifacts + uses: actions/upload-artifact@v7.0.2 + with: + name: macos-arm64-${{ needs.version.outputs.version }} + path: dist/NetNeighbor-*-macos-arm64.dmg + + macos-intel: + needs: version + runs-on: macos-15-intel + continue-on-error: true + steps: + - uses: actions/checkout@v7.0.1 + + - uses: actions/setup-python@v7.1.0 + with: + python-version: "3.11" + + - name: Install Python dependencies + # PySide6 6.5.x is the last series supporting macOS 11 (Big Sur). + # PySide6 6.6+ raised the minimum to macOS 12. + # PySide6 6.5.x requires Python <3.12, so we use Python 3.11. + run: python3 -m pip install "PySide6>=6.5,<6.6" -r requirements.txt pyinstaller + + - name: Install create-dmg + run: brew install create-dmg + + - name: Build macOS Intel app bundle + DMG + run: | + bash packaging/macos/build_app.sh "${{ needs.version.outputs.version }}" x86_64 + + - name: Smoke test Intel binary + run: | + APP="dist/NetNeighbor.app/Contents/MacOS/NetNeighbor" + echo "Launching $APP for 5 s..." + "$APP" & + PID=$! + sleep 5 + if kill -0 "$PID" 2>/dev/null; then + kill "$PID" + echo "PASS: process still alive after 5 s" + else + wait "$PID"; CODE=$? + if [ "$CODE" -eq 0 ] || [ "$CODE" -eq 124 ]; then + echo "PASS: process exited cleanly (code $CODE)" + else + echo "FAIL: process crashed (exit code $CODE)" + exit 1 + fi + fi + + - name: Cleanup .app bundle (DMG only in release) + run: rm -rf dist/NetNeighbor.app + + - name: Upload macOS Intel artifacts + uses: actions/upload-artifact@v7.0.2 + with: + name: macos-intel-${{ needs.version.outputs.version }} + path: dist/NetNeighbor-*-macos-intel.dmg + + github-release: + needs: [version, linux, windows, macos-arm64, macos-intel] + runs-on: ubuntu-latest + if: always() && needs.linux.result == 'success' && github.event_name == 'push' + steps: + - uses: actions/download-artifact@v8.0.2 + with: + path: release-assets + merge-multiple: true + + - name: Flatten release files + run: | + mkdir -p dist-flat + find release-assets -type f \( \ + -name '*.deb' -o -name '*.tar.gz' -o -name '*.AppImage' -o \ + -name '*.zip' -o -name '*.dmg' -o -name '*.exe' -o -name 'SHA256SUMS-*.txt' \ + \) -exec cp {} dist-flat/ \; + + - name: Attach to GitHub Release + uses: softprops/action-gh-release@v3.0.4 + with: + tag_name: ${{ github.ref_name }} + files: dist-flat/* + generate_release_notes: true + prerelease: ${{ contains(github.ref_name, '-') }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 0abc5444..89d45164 100644 --- a/.gitignore +++ b/.gitignore @@ -1,234 +1,59 @@ -# Byte-compiled / optimized / DLL files +# Python bytecode __pycache__/ *.py[codz] *$py.class -# C extensions -*.so +# Virtual environments +.venv/ +venv/ +env/ +env.bak/ +venv.bak/ +.venv-i18n-test/ -# Distribution / packaging -.Python +# Build / distribution build/ -develop-eggs/ dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ *.egg-info/ -.installed.cfg *.egg MANIFEST -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports +# Test / coverage htmlcov/ -.tox/ -.nox/ .coverage .coverage.* .cache -nosetests.xml coverage.xml *.cover -*.py.cover .hypothesis/ .pytest_cache/ -cover/ - -# Translations -# .mo and .pot are typically ignored in Python projects but NetNeighbor needs -# them committed: .mo for running from source, .pot for translators. -# !locale/ exceptions override the generic rules for this project only. -*.mo -*.pot -!locale/**/*.mo -!locale/netneighbor.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -# Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -# poetry.lock -# poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -# pdm.lock -# pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -# pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# Redis -*.rdb -*.aof -*.pid - -# RabbitMQ -mnesia/ -rabbitmq/ -rabbitmq-data/ - -# ActiveMQ -activemq-data/ - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy +# Type / lint caches .mypy_cache/ .dmypy.json dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -# .idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore -# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, -# you could uncomment the following to ignore the entire vscode folder -# .vscode/ -# Temporary file for partial code execution -tempCodeRunnerFile.py - -# Ruff stuff: .ruff_cache/ +.pytype/ +.pyre/ -# PyPI configuration file +# Logs and secrets +*.log +.env +.envrc .pypirc +log/ -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ +# IDE +tempCodeRunnerFile.py +.pdm-python +.pdm-build/ -# Streamlit -.streamlit/secrets.toml +# Sphinx +docs/_build/ -# appimagetool binary (downloaded locally, not committed) +# NetNeighbor — project-specific tools/appimagetool-*.AppImage - -# AppImage build staging dist/appimage-build/ -# Screenshots (user-generated, not committed to repo) - -# Claude Code project directory (local AI assistant config, not for the repo) +# Claude Code local config (not for the repo) .claude/ diff --git a/.venv-i18n-test/bin/Activate.ps1 b/.venv-i18n-test/bin/Activate.ps1 deleted file mode 100644 index b49d77ba..00000000 --- a/.venv-i18n-test/bin/Activate.ps1 +++ /dev/null @@ -1,247 +0,0 @@ -<# -.Synopsis -Activate a Python virtual environment for the current PowerShell session. - -.Description -Pushes the python executable for a virtual environment to the front of the -$Env:PATH environment variable and sets the prompt to signify that you are -in a Python virtual environment. Makes use of the command line switches as -well as the `pyvenv.cfg` file values present in the virtual environment. - -.Parameter VenvDir -Path to the directory that contains the virtual environment to activate. The -default value for this is the parent of the directory that the Activate.ps1 -script is located within. - -.Parameter Prompt -The prompt prefix to display when this virtual environment is activated. By -default, this prompt is the name of the virtual environment folder (VenvDir) -surrounded by parentheses and followed by a single space (ie. '(.venv) '). - -.Example -Activate.ps1 -Activates the Python virtual environment that contains the Activate.ps1 script. - -.Example -Activate.ps1 -Verbose -Activates the Python virtual environment that contains the Activate.ps1 script, -and shows extra information about the activation as it executes. - -.Example -Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv -Activates the Python virtual environment located in the specified location. - -.Example -Activate.ps1 -Prompt "MyPython" -Activates the Python virtual environment that contains the Activate.ps1 script, -and prefixes the current prompt with the specified string (surrounded in -parentheses) while the virtual environment is active. - -.Notes -On Windows, it may be required to enable this Activate.ps1 script by setting the -execution policy for the user. You can do this by issuing the following PowerShell -command: - -PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - -For more information on Execution Policies: -https://go.microsoft.com/fwlink/?LinkID=135170 - -#> -Param( - [Parameter(Mandatory = $false)] - [String] - $VenvDir, - [Parameter(Mandatory = $false)] - [String] - $Prompt -) - -<# Function declarations --------------------------------------------------- #> - -<# -.Synopsis -Remove all shell session elements added by the Activate script, including the -addition of the virtual environment's Python executable from the beginning of -the PATH variable. - -.Parameter NonDestructive -If present, do not remove this function from the global namespace for the -session. - -#> -function global:deactivate ([switch]$NonDestructive) { - # Revert to original values - - # The prior prompt: - if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) { - Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt - Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT - } - - # The prior PYTHONHOME: - if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) { - Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME - Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME - } - - # The prior PATH: - if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) { - Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH - Remove-Item -Path Env:_OLD_VIRTUAL_PATH - } - - # Just remove the VIRTUAL_ENV altogether: - if (Test-Path -Path Env:VIRTUAL_ENV) { - Remove-Item -Path env:VIRTUAL_ENV - } - - # Just remove VIRTUAL_ENV_PROMPT altogether. - if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) { - Remove-Item -Path env:VIRTUAL_ENV_PROMPT - } - - # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether: - if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) { - Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force - } - - # Leave deactivate function in the global namespace if requested: - if (-not $NonDestructive) { - Remove-Item -Path function:deactivate - } -} - -<# -.Description -Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the -given folder, and returns them in a map. - -For each line in the pyvenv.cfg file, if that line can be parsed into exactly -two strings separated by `=` (with any amount of whitespace surrounding the =) -then it is considered a `key = value` line. The left hand string is the key, -the right hand is the value. - -If the value starts with a `'` or a `"` then the first and last character is -stripped from the value before being captured. - -.Parameter ConfigDir -Path to the directory that contains the `pyvenv.cfg` file. -#> -function Get-PyVenvConfig( - [String] - $ConfigDir -) { - Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg" - - # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue). - $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue - - # An empty map will be returned if no config file is found. - $pyvenvConfig = @{ } - - if ($pyvenvConfigPath) { - - Write-Verbose "File exists, parse `key = value` lines" - $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath - - $pyvenvConfigContent | ForEach-Object { - $keyval = $PSItem -split "\s*=\s*", 2 - if ($keyval[0] -and $keyval[1]) { - $val = $keyval[1] - - # Remove extraneous quotations around a string value. - if ("'""".Contains($val.Substring(0, 1))) { - $val = $val.Substring(1, $val.Length - 2) - } - - $pyvenvConfig[$keyval[0]] = $val - Write-Verbose "Adding Key: '$($keyval[0])'='$val'" - } - } - } - return $pyvenvConfig -} - - -<# Begin Activate script --------------------------------------------------- #> - -# Determine the containing directory of this script -$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition -$VenvExecDir = Get-Item -Path $VenvExecPath - -Write-Verbose "Activation script is located in path: '$VenvExecPath'" -Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)" -Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)" - -# Set values required in priority: CmdLine, ConfigFile, Default -# First, get the location of the virtual environment, it might not be -# VenvExecDir if specified on the command line. -if ($VenvDir) { - Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values" -} -else { - Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir." - $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") - Write-Verbose "VenvDir=$VenvDir" -} - -# Next, read the `pyvenv.cfg` file to determine any required value such -# as `prompt`. -$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir - -# Next, set the prompt from the command line, or the config file, or -# just use the name of the virtual environment folder. -if ($Prompt) { - Write-Verbose "Prompt specified as argument, using '$Prompt'" -} -else { - Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value" - if ($pyvenvCfg -and $pyvenvCfg['prompt']) { - Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'" - $Prompt = $pyvenvCfg['prompt']; - } - else { - Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)" - Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'" - $Prompt = Split-Path -Path $venvDir -Leaf - } -} - -Write-Verbose "Prompt = '$Prompt'" -Write-Verbose "VenvDir='$VenvDir'" - -# Deactivate any currently active virtual environment, but leave the -# deactivate function in place. -deactivate -nondestructive - -# Now set the environment variable VIRTUAL_ENV, used by many tools to determine -# that there is an activated venv. -$env:VIRTUAL_ENV = $VenvDir - -if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) { - - Write-Verbose "Setting prompt to '$Prompt'" - - # Set the prompt to include the env name - # Make sure _OLD_VIRTUAL_PROMPT is global - function global:_OLD_VIRTUAL_PROMPT { "" } - Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT - New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt - - function global:prompt { - Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) " - _OLD_VIRTUAL_PROMPT - } - $env:VIRTUAL_ENV_PROMPT = $Prompt -} - -# Clear PYTHONHOME -if (Test-Path -Path Env:PYTHONHOME) { - Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME - Remove-Item -Path Env:PYTHONHOME -} - -# Add the venv to the PATH -Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH -$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH" diff --git a/.venv-i18n-test/bin/activate b/.venv-i18n-test/bin/activate deleted file mode 100644 index 43b0828b..00000000 --- a/.venv-i18n-test/bin/activate +++ /dev/null @@ -1,70 +0,0 @@ -# This file must be used with "source bin/activate" *from bash* -# You cannot run it directly - -deactivate () { - # reset old environment variables - if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then - PATH="${_OLD_VIRTUAL_PATH:-}" - export PATH - unset _OLD_VIRTUAL_PATH - fi - if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then - PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" - export PYTHONHOME - unset _OLD_VIRTUAL_PYTHONHOME - fi - - # Call hash to forget past commands. Without forgetting - # past commands the $PATH changes we made may not be respected - hash -r 2> /dev/null - - if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then - PS1="${_OLD_VIRTUAL_PS1:-}" - export PS1 - unset _OLD_VIRTUAL_PS1 - fi - - unset VIRTUAL_ENV - unset VIRTUAL_ENV_PROMPT - if [ ! "${1:-}" = "nondestructive" ] ; then - # Self destruct! - unset -f deactivate - fi -} - -# unset irrelevant variables -deactivate nondestructive - -# on Windows, a path can contain colons and backslashes and has to be converted: -if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then - # transform D:\path\to\venv to /d/path/to/venv on MSYS - # and to /cygdrive/d/path/to/venv on Cygwin - export VIRTUAL_ENV=$(cygpath /home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test) -else - # use the path as-is - export VIRTUAL_ENV=/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test -fi - -_OLD_VIRTUAL_PATH="$PATH" -PATH="$VIRTUAL_ENV/"bin":$PATH" -export PATH - -# unset PYTHONHOME if set -# this will fail if PYTHONHOME is set to the empty string (which is bad anyway) -# could use `if (set -u; : $PYTHONHOME) ;` in bash -if [ -n "${PYTHONHOME:-}" ] ; then - _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" - unset PYTHONHOME -fi - -if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then - _OLD_VIRTUAL_PS1="${PS1:-}" - PS1='(.venv-i18n-test) '"${PS1:-}" - export PS1 - VIRTUAL_ENV_PROMPT='(.venv-i18n-test) ' - export VIRTUAL_ENV_PROMPT -fi - -# Call hash to forget past commands. Without forgetting -# past commands the $PATH changes we made may not be respected -hash -r 2> /dev/null diff --git a/.venv-i18n-test/bin/activate.csh b/.venv-i18n-test/bin/activate.csh deleted file mode 100644 index 877072c9..00000000 --- a/.venv-i18n-test/bin/activate.csh +++ /dev/null @@ -1,27 +0,0 @@ -# This file must be used with "source bin/activate.csh" *from csh*. -# You cannot run it directly. - -# Created by Davide Di Blasi . -# Ported to Python 3.3 venv by Andrew Svetlov - -alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate' - -# Unset irrelevant variables. -deactivate nondestructive - -setenv VIRTUAL_ENV /home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test - -set _OLD_VIRTUAL_PATH="$PATH" -setenv PATH "$VIRTUAL_ENV/"bin":$PATH" - - -set _OLD_VIRTUAL_PROMPT="$prompt" - -if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then - set prompt = '(.venv-i18n-test) '"$prompt" - setenv VIRTUAL_ENV_PROMPT '(.venv-i18n-test) ' -endif - -alias pydoc python -m pydoc - -rehash diff --git a/.venv-i18n-test/bin/activate.fish b/.venv-i18n-test/bin/activate.fish deleted file mode 100644 index 7003f0c5..00000000 --- a/.venv-i18n-test/bin/activate.fish +++ /dev/null @@ -1,69 +0,0 @@ -# This file must be used with "source /bin/activate.fish" *from fish* -# (https://fishshell.com/). You cannot run it directly. - -function deactivate -d "Exit virtual environment and return to normal shell environment" - # reset old environment variables - if test -n "$_OLD_VIRTUAL_PATH" - set -gx PATH $_OLD_VIRTUAL_PATH - set -e _OLD_VIRTUAL_PATH - end - if test -n "$_OLD_VIRTUAL_PYTHONHOME" - set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME - set -e _OLD_VIRTUAL_PYTHONHOME - end - - if test -n "$_OLD_FISH_PROMPT_OVERRIDE" - set -e _OLD_FISH_PROMPT_OVERRIDE - # prevents error when using nested fish instances (Issue #93858) - if functions -q _old_fish_prompt - functions -e fish_prompt - functions -c _old_fish_prompt fish_prompt - functions -e _old_fish_prompt - end - end - - set -e VIRTUAL_ENV - set -e VIRTUAL_ENV_PROMPT - if test "$argv[1]" != "nondestructive" - # Self-destruct! - functions -e deactivate - end -end - -# Unset irrelevant variables. -deactivate nondestructive - -set -gx VIRTUAL_ENV /home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test - -set -gx _OLD_VIRTUAL_PATH $PATH -set -gx PATH "$VIRTUAL_ENV/"bin $PATH - -# Unset PYTHONHOME if set. -if set -q PYTHONHOME - set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME - set -e PYTHONHOME -end - -if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" - # fish uses a function instead of an env var to generate the prompt. - - # Save the current fish_prompt function as the function _old_fish_prompt. - functions -c fish_prompt _old_fish_prompt - - # With the original prompt function renamed, we can override with our own. - function fish_prompt - # Save the return status of the last command. - set -l old_status $status - - # Output the venv prompt; color taken from the blue of the Python logo. - printf "%s%s%s" (set_color 4B8BBE) '(.venv-i18n-test) ' (set_color normal) - - # Restore the return status of the previous command. - echo "exit $old_status" | . - # Output the original/"old" prompt. - _old_fish_prompt - end - - set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" - set -gx VIRTUAL_ENV_PROMPT '(.venv-i18n-test) ' -end diff --git a/.venv-i18n-test/bin/pip b/.venv-i18n-test/bin/pip deleted file mode 100755 index 7a95dd71..00000000 --- a/.venv-i18n-test/bin/pip +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/.venv-i18n-test/bin/pip3 b/.venv-i18n-test/bin/pip3 deleted file mode 100755 index 7a95dd71..00000000 --- a/.venv-i18n-test/bin/pip3 +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/.venv-i18n-test/bin/pip3.12 b/.venv-i18n-test/bin/pip3.12 deleted file mode 100755 index 7a95dd71..00000000 --- a/.venv-i18n-test/bin/pip3.12 +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/.venv-i18n-test/bin/python b/.venv-i18n-test/bin/python deleted file mode 120000 index b8a0adbb..00000000 --- a/.venv-i18n-test/bin/python +++ /dev/null @@ -1 +0,0 @@ -python3 \ No newline at end of file diff --git a/.venv-i18n-test/bin/python3 b/.venv-i18n-test/bin/python3 deleted file mode 120000 index ae65fdaa..00000000 --- a/.venv-i18n-test/bin/python3 +++ /dev/null @@ -1 +0,0 @@ -/usr/bin/python3 \ No newline at end of file diff --git a/.venv-i18n-test/bin/python3.12 b/.venv-i18n-test/bin/python3.12 deleted file mode 120000 index b8a0adbb..00000000 --- a/.venv-i18n-test/bin/python3.12 +++ /dev/null @@ -1 +0,0 @@ -python3 \ No newline at end of file diff --git a/.venv-i18n-test/bin/wsdiscover b/.venv-i18n-test/bin/wsdiscover deleted file mode 100755 index 9d50eb09..00000000 --- a/.venv-i18n-test/bin/wsdiscover +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from wsdiscovery.cmdline import discover -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(discover()) diff --git a/.venv-i18n-test/bin/wspublish b/.venv-i18n-test/bin/wspublish deleted file mode 100755 index ca59e15a..00000000 --- a/.venv-i18n-test/bin/wspublish +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from wsdiscovery.cmdline import publish -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(publish()) diff --git a/.venv-i18n-test/lib64 b/.venv-i18n-test/lib64 deleted file mode 120000 index 7951405f..00000000 --- a/.venv-i18n-test/lib64 +++ /dev/null @@ -1 +0,0 @@ -lib \ No newline at end of file diff --git a/.venv-i18n-test/pyvenv.cfg b/.venv-i18n-test/pyvenv.cfg deleted file mode 100644 index 3bffa732..00000000 --- a/.venv-i18n-test/pyvenv.cfg +++ /dev/null @@ -1,5 +0,0 @@ -home = /usr/bin -include-system-site-packages = false -version = 3.12.3 -executable = /usr/bin/python3.12 -command = /usr/bin/python3 -m venv /home/luc/Documents/GitHub/NetNeighbor/.venv-i18n-test diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..1e26040b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.terminal.useEnvFile": true +} \ No newline at end of file diff --git a/README.md b/README.md index 83db2168..97dd3154 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ # NetNeighbor -NetNeighbor is a Linux desktop application that discovers and monitors devices on your -local network — a modern equivalent of the Windows Network Neighborhood experience. +NetNeighbor discovers and monitors devices on your local network — a modern equivalent of the Windows Network Neighborhood experience. Runs on Windows, Linux and macOS. -**Current release: 1.0.0** +![VERSION](https://img.shields.io/badge/dynamic/json?label=NetNeighbor&query=$.version&color=green&style=plastic&url=https://raw.githubusercontent.com/luc-github/NetNeighbor/refs/heads/2.X/info.json) +![GitHub last commit (branch)](https://img.shields.io/github/last-commit/luc-github/NetNeighbor/2.X?style=plastic) +[![github-ci](https://github.com/luc-github/ESP3D-TFT/workflows/build-ci/badge.svg)](https://github.com/luc-github/NetNeighbor/actions/workflows/release.yml) -![NetNeighbor main window](docs/screenshots/overview-hero.png) + +![NetNeighbor main window](docs/images/overview-hero.png) ## Features @@ -14,72 +16,93 @@ local network — a modern equivalent of the Windows Network Neighborhood experi - **List and icon grid** views with sidebar categories (by type or location) - **Open devices** in one click — HTTP, HTTPS, SMB, SSH, FTP, SFTP, Telnet with configurable priority - **Per-device overrides** — custom name, type, location, icon, and connection commands +- **Icon packs** — switch between icon themes; install community packs or create your own - **System tray** — minimize to tray, start minimized, session autostart - **Localised** — French, Spanish, German, Italian, Dutch, Japanese, Chinese (Simplified/Traditional) -- **Packaged** as `.deb` (Ubuntu/Mint/Debian), `.AppImage`, and tarball +- **Packaged** as `.exe` + installer (Windows), `.dmg` (macOS), `.deb` (Ubuntu/Mint/Debian), `.AppImage`, and tarball + +> [!WARNING] +>### Disclaimer +> The software is provided 'as is,' without any warranty of any kind, expressed or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the authors or copyright holders be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software. +>It is essential that you carefully read and understand this disclaimer before using this software and its components. If you do not agree with any part of this disclaimer, please refrain from using the software. + ## Download Latest release: [GitHub Releases](https://github.com/luc-github/NetNeighbor/releases) -Available formats: `.deb` · `.AppImage` · `.tar.gz` +Available formats: `.exe` · `.dmg` (Apple Silicon & Intel) · `.deb` · `.AppImage` · `.tar.gz` ## Requirements -- Linux desktop with GTK 3 -- Python 3.10+ +| Platform | Requirement | +|----------|-------------| +| Windows | Windows 10 or later | +| Linux | Ubuntu 22.04+, Linux Mint 21+, Debian 12+, or equivalent | +| macOS (Apple Silicon) | macOS 12 (Monterey) or later | +| macOS (Intel) | macOS 11 (Big Sur) or later | +| From source | Python 3.10+ · PySide6 6.5+ | -### Ubuntu / Linux Mint / Debian +## Install -```bash -sudo apt install -y python3-gi python3-gi-cairo gir1.2-gtk-3.0 -sudo apt install -y samba-common-bin # NetBIOS names -sudo apt install -y gir1.2-ayatanaappindicator3-0.1 # system tray +**Windows installer:** +``` +NetNeighbor-2.x.y-win64-setup.exe ``` -These dependencies are installed automatically when using the `.deb` package. +> **Note:** the installer is not code-signed. Windows Defender SmartScreen may show a warning — click **More info** → **Run anyway**. -## Install +**macOS:** + +Open `NetNeighbor-2.x.y-macos-arm64.dmg` (Apple Silicon) or `NetNeighbor-2.x.y-macos-intel.dmg` (Intel), then drag NetNeighbor to Applications. + +> **Note:** the app is not notarized. On first launch Gatekeeper may block it — right-click → **Open** → **Open**, or run `xattr -cr /Applications/NetNeighbor.app` in Terminal. -**`.deb` package (recommended):** +**`.deb` package (recommended, Linux):** ```bash -sudo dpkg -i netneighbor_1.0.0_amd64.deb +sudo dpkg -i netneighbor_2.x.y_amd64.deb ``` -**`.AppImage`:** +**`.AppImage` (Linux):** ```bash -chmod +x NetNeighbor-1.0.0-x86_64.AppImage -./NetNeighbor-1.0.0-x86_64.AppImage +chmod +x NetNeighbor-2.x.y-x86_64.AppImage +./NetNeighbor-2.x.y-x86_64.AppImage ``` -**Tarball:** +**Tarball (Linux):** ```bash -tar -xzf netneighbor-1.0.0.tar.gz -cd netneighbor-1.0.0 +tar -xzf netneighbor-2.x.y.tar.gz +cd netneighbor-2.x.y bash install-user-desktop.sh # optional: add menu shortcut bash run.sh ``` ## Run from source +**Linux / macOS:** ```bash -python -m venv .venv --system-site-packages +python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt python main.py ``` -Demo data is enabled by default. Disable with: +**Windows:** ```bash -NETNEIGHBOR_DEMO=0 python main.py +python -m venv .venv +.venv\Scripts\activate +pip install -r requirements.txt +python main.py ``` ## Documentation -User documentation: [`USER_DOCUMENTATION.md`](USER_DOCUMENTATION.md) +User documentation: [`USER_DOCUMENTATION.md`](docs/USER_DOCUMENTATION.md) Developer documentation: [`docs/README.md`](docs/README.md) +Common problems (device not listed, icon not loading, device going offline): [Troubleshooting](docs/USER_DOCUMENTATION.md#troubleshooting) + ## Translations | Language | Code | Status | @@ -95,24 +118,44 @@ Developer documentation: [`docs/README.md`](docs/README.md) Compile after editing a `.po` file: ```bash -msgfmt locale/fr/LC_MESSAGES/netneighbor.po -o locale/fr/LC_MESSAGES/netneighbor.mo +msgfmt app/locale/fr/LC_MESSAGES/netneighbor.po -o app/locale/fr/LC_MESSAGES/netneighbor.mo ``` Test in a specific language: ```bash -LANG=fr_FR.UTF-8 python main.py +LANG=fr_FR.UTF-8 python app/main.py ``` -Full i18n workflow: [`docs/I18N.md`](docs/I18N.md) +Full i18n workflow: [`docs/contributing/I18N.md`](docs/contributing/I18N.md) + +## Icon packs + +Five community icon packs are available in [`icons_packs/`](icons_packs/): + +| Pack | Style | +|------|-------| +| [Cartoon](icons_packs/cartoon/) | Funny cartoon-style icons | +| [Clay 3D](icons_packs/clay3d/) | Colourful 3D clay-style icons | +| [Dark RGB](icons_packs/darkrgb/) | Dark theme with RGB accent colours | +| [OSX Aqua](icons_packs/osx_aqua/) | macOS Aqua-inspired look | +| [Pinky](icons_packs/pinky/) | Pink glossy-style icons | +| [White Frost](icons_packs/whitefrost/) | Flat white / frosted glass | +| [Windows 11 Fluent](icons_packs/win11fluent/) | Windows 11 Fluent Design | + +Copy a pack folder to `~/.config/netneighbor_icon_packs/`, rename `infopack.json` → `iconpack.json` and `{name}_preview.png` → `preview.png`, then select it in **Preferences → General → Icon pack**. + +Full instructions and pack format: [`icons_packs/README.md`](icons_packs/README.md) + +--- ## Autodetection and corrections Device names and types are inferred from protocol announcements — they are best-effort. Use right-click → **Type / Rename / Location / Icon** for per-device corrections. -Community rule overlays: [`docs/COMMUNITY_OVERRIDES.md`](docs/COMMUNITY_OVERRIDES.md). +Community rule overlays: [`docs/contributing/COMMUNITY_OVERRIDES.md`](docs/contributing/COMMUNITY_OVERRIDES.md). -## Pending work +## Pending work and roadmap -[`docs/TODO.md`](docs/TODO.md) +[`docs/ROADMAP.md`](docs/ROADMAP.md) -Contribution and maintenance notes: [`docs/MAINTENANCE.md`](docs/MAINTENANCE.md) +Contribution and maintenance notes: [`docs/operations/MAINTENANCE.md`](docs/operations/MAINTENANCE.md) diff --git a/USER_DOCUMENTATION.md b/USER_DOCUMENTATION.md deleted file mode 100644 index 36172721..00000000 --- a/USER_DOCUMENTATION.md +++ /dev/null @@ -1,206 +0,0 @@ -# NetNeighbor — User Documentation - -## What is NetNeighbor? - -NetNeighbor discovers and monitors devices on your local network. -It listens for device announcements (SSDP, mDNS/Bonjour, WS-Discovery, NetBIOS) and -displays them with icons or in a list — no active port scan required. - -Previously-seen devices appear instantly at startup from the local cache; live discovery -updates them within a few seconds. - -One NetNeighbor instance is allowed at a time; a second launch raises the existing window. - ---- - -## Main window - -![Main window — icon grid view](docs/screenshots/main-grid.png) - -- **List view** and **icon grid** — toggle from the View menu or toolbar -- **Sidebar**: categories grouped by device type or location (View → Arrange) -- **Search bar**: filter by name or type -- **F11**: toggle fullscreen (useful on small screens in icon grid) -- **View → Reload**: force an immediate refresh of all discovery protocols - -![View menu](docs/screenshots/menu-view.png) - -![Main window — list view](docs/screenshots/main-list.png) - ---- - -## Opening devices - -**Double-click** or right-click → **Open** launches the best connection for that device. - -Priority order: `HTTP → HTTPS → SMB → SSH → FTP → SFTP → Telnet` - -For each scheme the resolution follows: -1. **Override** command (from the device's Options tab) — replaces the auto-detected default -2. **Detected** default (URL advertised by discovery) -3. **Additional** command (from the device's Options tab) — adds to the submenu without replacing -4. **Custom command** (from Preferences → External applications…) -5. Nothing — Open is disabled - -When a device has **two or more** connection targets, right-click shows **Open ▶** with a submenu -listing all of them with labels (`HTTP`, `SSH (Admin)`, `HTTP (override)`, etc.). - ---- - -## Right-click menu - -![Right-click context menu](docs/screenshots/context-menu.png) - -| Action | Description | -|--------|-------------| -| **Open** / **Open ▶** | Launch connection (single target or submenu) | -| **Details…** | Full details dialog with protocol fields, options, etc. | -| **Monitor** | Keep the device visible when offline (greyed tile) | -| **Type** | Override the auto-detected device type | -| **Rename** | Set a display name for this device | -| **Location** | Tag the device with a room or location label | -| **Icon** | Choose system, bundled, or custom icon | -| **Run custom command** | Execute the custom command set in Preferences → External applications… | - ---- - -## Device details dialog - -### Overview tab - -![Device details — Overview tab](docs/screenshots/device-details.png) - -Summary of discovered fields: IP, port, name, type, location, last seen, services. - -### Options tab - -![Device details — Options tab](docs/screenshots/device-options.png) - -Per-device connection commands. Click **+ Add command** to add a row: - -| Field | Description | -|-------|-------------| -| **Scheme** | `http`, `https`, `smb`, `ftp`, `ssh`, `sftp`, `telnet` | -| **Mode** | **Override** — replaces the auto-detected default for this scheme on double-click. **Additional** — adds an extra entry in the Open submenu. | -| **Label** | Optional display name shown in the submenu (e.g. `Admin`, `NAS shares`). When empty, the label is auto-generated (`HTTP (override)`, `SSH`, …). | -| **IP** | Leave empty to use the device's discovered IP. Fill in to connect to a different address. | -| **Port** | Leave empty or `0` to use the scheme default port. | - -Click **− Remove** to delete a row (confirmation required). - -Available placeholders for the custom command field: `{ip} {port} {name} {type} {category} {url}` - -### Protocol tabs (SSDP, mDNS, WSD…) - -Raw fields received from each discovery protocol. **SSDP details** includes parsed XML when available. - ---- - -## Preferences - -Open with **View → Preferences**. - -### General options - -| Setting | Description | -|---------|-------------| -| **Notifications** | Enable/disable desktop notifications for device online/offline transitions | -| **Close to tray** | Hide the window instead of quitting when the window is closed (requires tray icon) | -| **Start minimized to tray** | Start hidden to the panel; open from the tray icon | -| **Start NetNeighbor when logging in** | Add/remove a session autostart entry (`~/.config/autostart/`) | - -### Location presets - -![Location presets dialog](docs/screenshots/location-presets.png) - -**Preferences → Location presets…** manages the list of location labels available in the -right-click → Location menu. - -| Button | Action | -|--------|--------| -| **Add** | Create a new location label | -| **Rename** | Edit the selected label | -| **Remove** | Delete the selected label (confirmation required) | -| **Restore defaults** | Reset the list to the built-in defaults | - -Labels are stored in `~/.config/netneighbor/ui_prefs.json`. - -### Type presets - -![Type presets dialog](docs/screenshots/type-presets.png) - -**Preferences → Type presets…** manages the list of device types available in the -right-click → Type menu. Each entry has a **Label** (display name) and a **Type ID** -(internal slug used for icon lookup). - -| Button | Action | -|--------|--------| -| **Add** | Create a new type entry (label + slug) | -| **Rename** | Edit the selected entry | -| **Remove** | Delete the selected entry (confirmation required) | -| **Restore defaults** | Reset to the 14 built-in device types | - -### External applications - -![External applications dialog](docs/screenshots/external-applications.png) - -**Preferences → External applications…** overrides the command used to open devices -**per scheme** (HTTP, HTTPS, SMB, FTP, SSH, Telnet, SFTP). -Leave a field empty to use the system default (`xdg-open` for HTTP/HTTPS, file manager -for SMB/FTP/SFTP, terminal for SSH/Telnet). - -Placeholders: `{url}`, `{ip}`, `{port}`, `{name}`, `{type}`, `{category}` - -**Reset** restores the built-in default for that scheme (confirmation required). - -**Custom command** at the bottom sets the command run by **right-click → Run custom command** — -useful for port scans, terminal launchers, etc. Same placeholders apply. - ---- - -## System tray - -![System tray menu](docs/screenshots/tray-menu.png) - -When the tray icon is active, the main window uses a **client-side title bar** with Maximize and -Close buttons. Minimize-to-tray is available from the tray icon menu or by closing the window with -**Close to tray** enabled. - -Tray menu: **Open** / **Minimize to tray** / **Quit** - ---- - -## Autodetection is heuristic - -Device names and types are inferred from SSDP, mDNS, and cached data. They are best-effort and -may not match every device or firmware revision. - -Corrections: - -1. **Per-device overrides**: right-click → Type / Rename / Location / Icon — stored in preferences, - applied after discovery. -2. **User rule overlays**: JSON files in `~/.config/netneighbor/` extend mDNS and SSDP matching - (see [`docs/COMMUNITY_OVERRIDES.md`](docs/COMMUNITY_OVERRIDES.md)). - ---- - -## Troubleshooting - -**Device does not appear:** -- Confirm the device is on the same local network segment -- Allow UDP 1900 (SSDP multicast) through local firewall -- Wait a few seconds after startup; use View → Reload - -**Device appears/disappears:** -- SSDP `byebye` causes immediate offline; timeout-based offline if announcements stop -- Devices that sleep will disappear when their TTL expires - -**Open is disabled:** -- No connection target was found; check the device's IP/services in Details -- Add a command manually in the device's Options tab - -**NetBIOS names not showing:** -- Install `samba-common-bin` (`sudo apt install samba-common-bin`) - -**No tray icon:** -- Install `gir1.2-ayatanaappindicator3-0.1` or `gir1.2-appindicator3-0.1` diff --git a/VERSION b/VERSION index 3eefcb9d..3e3c2f1e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0 +2.1.1 diff --git a/app.py b/app.py deleted file mode 100644 index dc4b53b2..00000000 --- a/app.py +++ /dev/null @@ -1,437 +0,0 @@ -# File app.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""GTK application bootstrap for NetNeighbor.""" - -import argparse -import logging -import os -from pathlib import Path -import socket -import threading -import tempfile -import time -import json - -import gi - -gi.require_version("Gtk", "3.0") -from gi.repository import GLib, Gtk - -from discovery.manager import DiscoveryManager -from i18n import setup_i18n -from utils.discovery_config import load_discovery_protocol_config, normalize_information_precedence_list -from ui.icons import resolve_app_icon_path -from ui.main_window import MainWindow - -try: - import fcntl -except ImportError: # pragma: no cover - non-POSIX environment - fcntl = None - - -class SingleInstanceLock: - """Ensures only one process instance runs on Linux.""" - - def __init__(self, app_id: str) -> None: - self._enabled = os.name == "posix" and fcntl is not None - lock_name = app_id.replace(".", "_") + ".lock" - self._lock_path = Path(tempfile.gettempdir()) / lock_name - self._handle = None - - def acquire(self) -> bool: - if not self._enabled: - return True - - self._lock_path.parent.mkdir(parents=True, exist_ok=True) - self._handle = self._lock_path.open("w", encoding="utf-8") - try: - fcntl.flock(self._handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - self._handle.close() - self._handle = None - return False - - self._handle.write(str(os.getpid())) - self._handle.flush() - return True - - def release(self) -> None: - if not self._enabled or self._handle is None: - return - try: - fcntl.flock(self._handle.fileno(), fcntl.LOCK_UN) - finally: - self._handle.close() - self._handle = None - - -class InstanceActivationServer: - def __init__(self, app_id: str, on_activate) -> None: - self._enabled = os.name == "posix" - socket_name = app_id.replace(".", "_") + ".sock" - self._socket_path = Path(tempfile.gettempdir()) / socket_name - self._on_activate = on_activate - self._server: socket.socket | None = None - self._thread: threading.Thread | None = None - self._stop = threading.Event() - - def start(self) -> None: - if not self._enabled: - return - - try: - self._socket_path.unlink(missing_ok=True) - self._server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - self._server.bind(str(self._socket_path)) - self._server.listen(1) - self._server.settimeout(0.5) - except OSError: - self.stop() - return - - self._thread = threading.Thread(target=self._serve, daemon=True) - self._thread.start() - - def _serve(self) -> None: - if self._server is None: - return - while not self._stop.is_set(): - try: - conn, _ = self._server.accept() - except socket.timeout: - continue - except OSError: - break - with conn: - try: - data = conn.recv(64).decode("utf-8").strip() - except OSError: - data = "" - if data == "ACTIVATE": - GLib.idle_add(self._on_activate) - try: - conn.sendall(b"OK") - except OSError: - pass - - def stop(self) -> None: - self._stop.set() - if self._server is not None: - try: - self._server.close() - except OSError: - pass - self._server = None - if self._thread is not None: - self._thread.join(timeout=1.0) - self._thread = None - if self._enabled: - self._socket_path.unlink(missing_ok=True) - - -def request_existing_instance_activation(app_id: str) -> bool: - if os.name != "posix": - return False - socket_path = Path(tempfile.gettempdir()) / (app_id.replace(".", "_") + ".sock") - if not socket_path.exists(): - return False - try: - with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: - client.settimeout(1.0) - client.connect(str(socket_path)) - client.sendall(b"ACTIVATE") - reply = client.recv(16).decode("utf-8").strip() - return reply == "OK" - except OSError: - return False - - -def _suppress_gdk_freeze_critical() -> None: - """Permanently silence the spurious Gdk-CRITICAL from GTK 3's dialog freeze/thaw bug. - - GTK 3 has a long-standing bug where ``gdk_window_thaw_toplevel_updates_libgtk_only`` - is called one extra time when nested ``Gtk.Dialog.run()`` calls are used, triggering: - Gdk-CRITICAL: gdk_window_thaw_toplevel_updates: assertion - 'window->update_and_descendants_freeze_count > 0' failed - This is harmless (the assert just fires, no state is corrupted) but noisy. - Install a permanent GLib log handler that drops this one specific message. - """ - _NEEDLE = "gdk_window_thaw_toplevel_updates" - - def _filter(domain, level, message, _user_data): - if message and _NEEDLE in message: - return - GLib.log_default_handler(domain, level, message, None) - - GLib.log_set_handler( - "Gdk", - GLib.LogLevelFlags.LEVEL_CRITICAL, - _filter, - None, - ) - - -class NetNeighborApplication(Gtk.Application): - def __init__(self, *, start_minimized_to_tray: bool = False) -> None: - self._app_id = "io.esp3d.netneighbor" - self._cli_start_minimized_to_tray = bool(start_minimized_to_tray) - setup_i18n() - super().__init__(application_id=self._app_id) - proto_cfg = load_discovery_protocol_config() - mdns_cfg = proto_cfg.get("mdns") - ssdp_cfg = proto_cfg.get("ssdp") - wsd_cfg = proto_cfg.get("wsd") - nmb_cfg = proto_cfg.get("nmb") - wsdd_cfg = proto_cfg.get("wsdd") - if not isinstance(mdns_cfg, dict): - mdns_cfg = {} - if not isinstance(ssdp_cfg, dict): - ssdp_cfg = {} - if not isinstance(wsd_cfg, dict): - wsd_cfg = {} - if not isinstance(nmb_cfg, dict): - nmb_cfg = {} - if not isinstance(wsdd_cfg, dict): - wsdd_cfg = {} - mdns_q = mdns_cfg.get("query") if isinstance(mdns_cfg.get("query"), dict) else {} - ssdp_q = ssdp_cfg.get("query") if isinstance(ssdp_cfg.get("query"), dict) else {} - wsd_q = wsd_cfg.get("query") if isinstance(wsd_cfg.get("query"), dict) else {} - nmb_q = nmb_cfg.get("query") if isinstance(nmb_cfg.get("query"), dict) else {} - wx_q = wsdd_cfg.get("query") if isinstance(wsdd_cfg.get("query"), dict) else {} - merge_cfg = proto_cfg.get("merge") if isinstance(proto_cfg.get("merge"), dict) else {} - protocol_order = merge_cfg.get("protocol_order") - order_list: list[str] | None = None - if isinstance(protocol_order, list) and protocol_order: - order_list = [str(x).strip().lower() for x in protocol_order if isinstance(x, str) and str(x).strip()] - order_list = list(dict.fromkeys(order_list)) - ipc = merge_cfg.get("information_precedence") - information_precedence = normalize_information_precedence_list(ipc if isinstance(ipc, list) else None) - wsdd_listen = wx_q.get("listen") if isinstance(wx_q.get("listen"), str) else "" - wsdd_listen = str(wsdd_listen).strip() - enable_wsdd_socket = bool(wsdd_cfg.get("enabled", False)) and bool(wsdd_listen) - show_ip_in_device_list = bool(merge_cfg.get("show_ip_in_device_list", True)) - self._manager = DiscoveryManager( - enable_ssdp=bool(ssdp_cfg.get("enabled", True)), - enable_mdns=bool(mdns_cfg.get("enabled", True)), - enable_ssdp_rules=bool(ssdp_cfg.get("rules", True)), - enable_mdns_rules=bool(mdns_cfg.get("rules", True)), - ssdp_query_interval_seconds=ssdp_q.get("interval_seconds"), - ssdp_mx_seconds=ssdp_q.get("mx_seconds"), - ssdp_descriptor_http_min_interval_seconds=ssdp_q.get("descriptor_http_min_interval_seconds"), - mdns_enumeration_timeout_seconds=mdns_q.get("enumeration_timeout_seconds"), - mdns_enumeration_interval_seconds=mdns_q.get("enumeration_interval_seconds"), - mdns_service_info_timeout_ms=mdns_q.get("service_info_timeout_ms"), - enable_wsd=bool(wsd_cfg.get("enabled", True)), - wsd_interval_seconds=wsd_q.get("interval_seconds"), - wsd_timeout_seconds=wsd_q.get("timeout_seconds"), - enable_wsdd_socket=enable_wsdd_socket, - wsdd_listen=wsdd_listen or None, - wsdd_interval_seconds=wx_q.get("interval_seconds"), - wsdd_socket_timeout_seconds=wx_q.get("socket_timeout_seconds"), - wsdd_probe_each_poll=bool(wx_q.get("probe_each_poll", True)), - enable_nmb=bool(nmb_cfg.get("enabled", True)), - nmb_interval_seconds=nmb_q.get("interval_seconds"), - nmb_timeout_seconds=nmb_q.get("timeout_seconds"), - nmb_argv=nmb_q.get("argv") if isinstance(nmb_q.get("argv"), list) else None, - nmb_directed_ips=nmb_q.get("directed_ips") if isinstance(nmb_q.get("directed_ips"), list) else None, - protocol_merge_order=order_list, - information_precedence=information_precedence, - ) - startup_refresh_seconds = proto_cfg.get("startup_refresh_seconds") - if not isinstance(startup_refresh_seconds, list) or not startup_refresh_seconds: - startup_refresh_seconds = [15, 30, 60, 120, 300, 600] - self._startup_refresh_seconds = [int(v) for v in startup_refresh_seconds] - self._information_precedence = information_precedence - self._show_ip_in_device_list = show_ip_in_device_list - self._window: MainWindow | None = None - self._instance_lock = SingleInstanceLock(self._app_id) - self._activation_server = InstanceActivationServer(self._app_id, self._present_window) - self._set_default_app_icon() - # Disable GTK's "use header bar in dialogs" setting globally so that all - # Gtk.Dialog instances use traditional title bars + action-area buttons. - # This must be done before any dialog is created. - try: - Gtk.Settings.get_default().set_property("gtk-dialogs-use-header", False) - except Exception: - pass - _suppress_gdk_freeze_critical() - - def do_activate(self) -> None: - created = False - if self._window is None: - created = True - self._window = MainWindow( - application=self, - discovery_manager=self._manager, - startup_refresh_seconds=self._startup_refresh_seconds, - information_precedence=self._information_precedence, - show_ip_in_device_list=self._show_ip_in_device_list, - cli_start_minimized_to_tray=self._cli_start_minimized_to_tray, - ) - # Do not steal focus before the tray/minimize idle runs (CLI/session autostart). - if created and self._cli_start_minimized_to_tray: - return - self._present_window() - - def _present_window(self) -> bool: - if self._window is not None: - self._window.show_all() - self._window.deiconify() - self._window.present() - try: - event_time = Gtk.get_current_event_time() - if event_time == 0: - event_time = int(time.monotonic() * 1000) & 0xFFFFFFFF - self._window.present_with_time(event_time) - except Exception: - pass - self._window.set_urgency_hint(True) - GLib.timeout_add(250, self._clear_urgency_hint) - self._window.grab_focus() - return False - - def _clear_urgency_hint(self) -> bool: - if self._window is not None: - self._window.set_urgency_hint(False) - return False - - def _set_default_app_icon(self) -> None: - icon_path = resolve_app_icon_path() - if icon_path is None: - return - try: - Gtk.Window.set_default_icon_from_file(str(icon_path)) - except Exception: - return - - -def main(argv: list[str] | None = None) -> int: - import sys - - if argv is None: - argv = sys.argv - - parser = argparse.ArgumentParser( - prog=Path(argv[0]).name if argv else "netneighbor", - description="NetNeighbor — LAN discovery (SSDP/mDNS, GTK)", - ) - parser.add_argument( - "--start-minimized-to-tray", - action="store_true", - help="Start with the main window hidden in the tray (session autostart; same as prefs when tray exists).", - ) - parsed, gtk_remainder = parser.parse_known_args(argv[1:]) - gtk_argv = [argv[0], *gtk_remainder] - - _setup_logging() - app = NetNeighborApplication(start_minimized_to_tray=parsed.start_minimized_to_tray) - if not app._instance_lock.acquire(): - if request_existing_instance_activation(app._app_id): - print("NetNeighbor is already running. Existing window activated.") - return 0 - print("NetNeighbor is already running.") - return 1 - app._activation_server.start() - try: - return app.run(gtk_argv) - finally: - app._activation_server.stop() - app._instance_lock.release() - - -def _setup_logging() -> None: - env_level_name = os.getenv("NETNEIGHBOR_LOG_LEVEL") - config = _load_logging_config() - default_level_name = str(config.get("default", "INFO")).upper() - if env_level_name: - default_level_name = env_level_name.upper() - level = _to_level(default_level_name, logging.INFO) - log_dir = Path.home() / ".cache" / "netneighbor" - log_dir.mkdir(parents=True, exist_ok=True) - log_file = log_dir / "netneighbor.log" - - root_logger = logging.getLogger() - if root_logger.handlers: - root_logger.setLevel(level) - _apply_named_log_levels(config) - return - - formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(name)s | %(message)s") - file_handler = logging.FileHandler(log_file, encoding="utf-8") - file_handler.setFormatter(formatter) - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - - root_logger.setLevel(level) - root_logger.addHandler(file_handler) - root_logger.addHandler(stream_handler) - _apply_named_log_levels(config) - logging.getLogger(__name__).info("Logging initialized at %s (%s)", default_level_name, log_file) - - -_LOG_LEVEL_OFF = 100 # above CRITICAL (50): suppress all standard levels - - -def _to_level(level_name: str, fallback: int) -> int: - normalized = str(level_name).strip().upper() - if normalized in {"NONE", "OFF", "DISABLED", "SILENT"}: - return _LOG_LEVEL_OFF - resolved = getattr(logging, normalized, None) - if isinstance(resolved, int): - return resolved - return fallback - - -def _load_logging_config() -> dict: - config_dir = Path.home() / ".config" / "netneighbor" - config_path = config_dir / "logging.json" - default_config = { - "default": "NONE", - "app": "NONE", - "device_list": "NONE", - "ssdp": "NONE", - "mdns": "NONE", - "wsd": "NONE", - "wsdd": "NONE", - "nmb": "NONE", - } - try: - config_dir.mkdir(parents=True, exist_ok=True) - if not config_path.exists(): - config_path.write_text(json.dumps(default_config, indent=2, sort_keys=True), encoding="utf-8") - return dict(default_config) - parsed = json.loads(config_path.read_text(encoding="utf-8")) - if not isinstance(parsed, dict): - return dict(default_config) - merged = dict(default_config) - merged.update(parsed) - return merged - except (OSError, json.JSONDecodeError): - return dict(default_config) - - -def _apply_named_log_levels(config: dict) -> None: - app_level = _to_level(str(config.get("app", config.get("default", "INFO"))), logging.INFO) - ssdp_level = _to_level(str(config.get("ssdp", config.get("default", "INFO"))), logging.INFO) - mdns_level = _to_level(str(config.get("mdns", config.get("default", "INFO"))), logging.INFO) - wsd_level = _to_level(str(config.get("wsd", config.get("default", "INFO"))), logging.INFO) - wsdd_level = _to_level(str(config.get("wsdd", config.get("default", "INFO"))), logging.INFO) - nmb_level = _to_level(str(config.get("nmb", config.get("default", "INFO"))), logging.INFO) - device_list_level = _to_level(str(config.get("device_list", config.get("default", "INFO"))), logging.INFO) - - for logger_name in ("app", "ui", "utils", "discovery.manager", "model"): - logging.getLogger(logger_name).setLevel(app_level) - logging.getLogger("discovery.ssdp").setLevel(ssdp_level) - logging.getLogger("discovery.mdns").setLevel(mdns_level) - logging.getLogger("discovery.wsd").setLevel(wsd_level) - logging.getLogger("discovery.wsdd_client").setLevel(wsdd_level) - logging.getLogger("discovery.netbios").setLevel(nmb_level) - # Manager-side messages tied to a protocol (device add/update, SSDP merge) use child loggers. - logging.getLogger("discovery.manager.ssdp").setLevel(ssdp_level) - logging.getLogger("discovery.manager.mdns").setLevel(mdns_level) - logging.getLogger("discovery.manager.wsd").setLevel(wsd_level) - logging.getLogger("discovery.manager.wsdd").setLevel(wsdd_level) - logging.getLogger("discovery.manager.nmb").setLevel(nmb_level) - logging.getLogger("ui.device_list").setLevel(device_list_level) diff --git a/app/app_qt.py b/app/app_qt.py new file mode 100644 index 00000000..7a3b16e2 --- /dev/null +++ b/app/app_qt.py @@ -0,0 +1,281 @@ +# File app_qt.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Application bootstrap — NetNeighbor 2.0 (PySide6).""" + +from __future__ import annotations + +import argparse +import logging +import os +import sys +from pathlib import Path + + +def main(argv: list[str] | None = None) -> int: + if argv is None: + argv = sys.argv + + parser = argparse.ArgumentParser( + prog=Path(argv[0]).name if argv else "netneighbor", + description="NetNeighbor — LAN discovery", + ) + parser.add_argument( + "--qt-diag-toplevels", + action="store_true", + help="Log extra Qt top-level QWidget/QWindow (set NETNEIGHBOR_DEBUG_TOPLEVEL; uses INFO lines)", + ) + parser.add_argument( + "--qt-native-style", + action="store_true", + help="Use the native OS widget style instead of Fusion", + ) + parser.add_argument( + "--theme-light", + action="store_true", + help="Force light theme (overrides OS setting, Fusion only)", + ) + parser.add_argument( + "--theme-dark", + action="store_true", + help="Force dark theme (overrides OS setting, Fusion only)", + ) + parser.add_argument( + "--start-minimized-to-tray", + action="store_true", + help="Start hidden in the system tray (autostart mode)", + ) + args, _unknown = parser.parse_known_args(argv[1:]) + if args.qt_diag_toplevels: + os.environ["NETNEIGHBOR_DEBUG_TOPLEVEL"] = "1" + + if sys.platform == "win32": + try: + import ctypes + + # Must run before QApplication / any HWND so the taskbar uses our icon, not python.exe. + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("io.esp3d.netneighbor.qt.1") + except OSError: + pass + + from PySide6.QtCore import QTimer + from PySide6.QtGui import QIcon + from PySide6.QtWidgets import QApplication, QSystemTrayIcon + + from discovery.manager import DiscoveryManager + from i18n import setup_i18n + from model.device import Device + from ui.icons import resolve_app_icon_paths_in_order + from ui import MainThreadScheduler, NetNeighborMainWindow, NetNeighborTray + from utils.app_logging import setup_logging + from utils.discovery_config import discovery_manager_kwargs, load_discovery_protocol_config + from utils.qt_single_instance import create_activation_listener, send_activate_to_primary + + setup_logging(log_name="app_qt") + setup_i18n() + _log = logging.getLogger("app_qt") + _log.info("NetNeighbor Qt bootstrap (logging to ~/.cache/netneighbor/netneighbor.log)") + + app = QApplication(argv) + app.setApplicationName("NetNeighbor") + app.setApplicationDisplayName("NetNeighbor") + + # Load Qt's own translations so standard buttons (Ok, Cancel, Close, Save…) are localised. + # Use the same language as gettext (env vars LANGUAGE/LANG), not QLocale.system() which + # reads the Windows locale and ignores LANGUAGE. + from PySide6.QtCore import QLibraryInfo, QLocale, QTranslator + from i18n import active_language + _qt_translator = QTranslator(app) + _qt_translations_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath) + _active_lang = active_language() + if _active_lang: + _qt_locale = QLocale(_active_lang) + elif sys.platform == "darwin": + # QLocale.system() crashes on macOS 11 (Big Sur) with PySide6 6.5.x — + # null ptr in pyStringToQString, uncatchable SIGSEGV. + # Use the LANG env var (set in main.py) as a safe fallback. + _sys_lang = os.environ.get("LANG", "en_US.UTF-8").split(".")[0] + _qt_locale = QLocale(_sys_lang.replace("_", "-")) if _sys_lang and _sys_lang != "C" else QLocale(QLocale.Language.English) + else: + _qt_locale = QLocale.system() + if _qt_translator.load(_qt_locale, "qtbase", "_", _qt_translations_path): + app.installTranslator(_qt_translator) + _log.debug("Qt base translator loaded for %s", _qt_locale.name()) + else: + _log.debug("Qt base translator not found for %s (standard buttons stay in English)", _qt_locale.name()) + if not args.qt_native_style: + from PySide6.QtCore import Qt + from ui.app_theme import setup_fusion_theme + app.setStyle("Fusion") + if args.theme_dark: + forced: Qt.ColorScheme | None = Qt.ColorScheme.Dark + elif args.theme_light: + forced = Qt.ColorScheme.Light + else: + from utils.ui_prefs import load_ui_preferences + _theme_pref = load_ui_preferences().get("theme", "auto") + if _theme_pref == "light": + forced = Qt.ColorScheme.Light + elif _theme_pref == "dark": + forced = Qt.ColorScheme.Dark + else: + forced = None + setup_fusion_theme(app, forced_scheme=forced) + + # Bundled config files are the single source of truth for device classification (no Python + # fallback duplicates them). If one is missing/corrupt the install is broken — tell the user + # to reinstall instead of silently running with no rules. + from utils.config_integrity import check_bundled_config_integrity + _config_problems = check_bundled_config_integrity() + if _config_problems: + from PySide6.QtWidgets import QMessageBox + _log.error("Corrupted installation — %s", _config_problems) + QMessageBox.critical( + None, + _("Corrupted installation"), + _( + "NetNeighbor cannot start because required files are missing or corrupted:\n\n" + "{details}\n\nPlease reinstall the program." + ).format(details="\n".join(_config_problems)), + ) + return 1 + + for icon_path in resolve_app_icon_paths_in_order(): + app_icon = QIcon(str(icon_path)) + if not app_icon.isNull(): + app.setWindowIcon(app_icon) + break + + if send_activate_to_primary(): + print("NetNeighbor is already running - existing window brought to the foreground.") + return 0 + + scheduler = MainThreadScheduler(app) + + proto_cfg = load_discovery_protocol_config() + dm_kw = discovery_manager_kwargs(proto_cfg) + dm_kw["schedule_on_main_thread"] = lambda fn: scheduler.invoke.emit(fn) + manager = DiscoveryManager(**dm_kw) + + window = NetNeighborMainWindow( + discovery_manager=manager, + information_precedence=list(dm_kw["information_precedence"]), + ) + app._qt_main_window = window + + activation_server = create_activation_listener(app, on_activate=window.bring_to_front) + if activation_server is None: + _log.warning("Single-instance server unavailable (pipe busy or stale).") + if send_activate_to_primary(): + print("NetNeighbor is already running - existing window brought to the foreground.") + return 0 + else: + app._qt_activation_server = activation_server + + def on_devices(devices: list[Device]) -> None: + def update() -> None: + window.set_devices(devices) + + scheduler.invoke.emit(update) + + manager.add_listener(on_devices) + + window.resize(960, 520) + app_icon = app.windowIcon() + if not app_icon.isNull(): + window.setWindowIcon(app_icon) + + _tray: NetNeighborTray | None = None + if QSystemTrayIcon.isSystemTrayAvailable(): + _tray = NetNeighborTray(app.windowIcon(), window, parent=app) + _tray.show() + app._qt_tray = _tray + + # Hide the window when --start-minimized-to-tray is set, even if the system + # tray is not ready yet (common at login time on macOS before the menu bar + # is available). A retry timer creates the tray once it becomes available. + _start_hidden = args.start_minimized_to_tray + if not _start_hidden: + window.show() + + if args.start_minimized_to_tray and _tray is None: + def _retry_tray() -> None: + if getattr(app, "_qt_tray", None) is not None: + return + if QSystemTrayIcon.isSystemTrayAvailable(): + tray = NetNeighborTray(app.windowIcon(), window, parent=app) + tray.show() + app._qt_tray = tray # type: ignore[attr-defined] + else: + QTimer.singleShot(2000, _retry_tray) + QTimer.singleShot(2000, _retry_tray) + + if sys.platform == "darwin": + # On macOS, clicking the Dock icon when the window is hidden fires + # QEvent.Type.ApplicationActivate. Handle it so the window reappears. + # At login macOS also sends ApplicationActivate automatically — guard + # against this by only reacting once the window has been shown at least + # once by a real user action (tray click, single-instance activation…). + from PySide6.QtCore import QEvent, QObject + + # True from the start for normal launches; False until user shows window + # for minimized launches. Tracked via QEvent.Type.Show on the window. + _window_was_shown = [not _start_hidden] + + class _DockClickFilter(QObject): + def eventFilter(self, obj: QObject, event: QEvent) -> bool: + if event.type() == QEvent.Type.ApplicationActivate: + if _window_was_shown[0] and not window.isVisible(): + window.bring_to_front() + elif event.type() == QEvent.Type.Show: + _window_was_shown[0] = True + return False + + app._qt_dock_filter = _DockClickFilter(app) + app.installEventFilter(app._qt_dock_filter) + window.installEventFilter(app._qt_dock_filter) + + if os.environ.get("NETNEIGHBOR_DEBUG_TOPLEVEL"): + from ui.main_window import _debug_log_extra_top_level_widgets + + QTimer.singleShot(2500, lambda: _debug_log_extra_top_level_widgets("idle 2.5s after show")) + + startup_refresh_seconds = proto_cfg.get("startup_refresh_seconds") + if not isinstance(startup_refresh_seconds, list) or not startup_refresh_seconds: + startup_refresh_seconds = [15, 30, 60, 120, 300, 600] + startup_refresh_seconds = [int(v) for v in startup_refresh_seconds] + + def _run_startup_refresh_once(delay_seconds: int) -> None: + try: + _log.info("Startup discovery refresh (+%ss from launch)", delay_seconds) + manager.refresh() + except Exception: + _log.debug("Startup auto-refresh failed at +%ss", delay_seconds, exc_info=True) + + def _start_discovery() -> None: + """Run in a background thread so the Qt event loop (and overlay) stay responsive.""" + import threading as _threading + def _run() -> None: + manager.start() + try: + manager.refresh() + except Exception: + _log.debug("Post-start discovery refresh failed", exc_info=True) + _threading.Thread(target=_run, daemon=True, name="discovery-start").start() + + for delay in startup_refresh_seconds: + if delay > 0: + QTimer.singleShot(delay * 1000, lambda d=delay: _run_startup_refresh_once(d)) + + # Defer start until the first event-loop tick so the window (and overlay) paint first. + QTimer.singleShot(0, _start_discovery) + + try: + return int(app.exec()) + finally: + manager.stop() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/app/assets/badge.png b/app/assets/badge.png new file mode 100644 index 00000000..71d264b9 Binary files /dev/null and b/app/assets/badge.png differ diff --git a/app/assets/iconpack.json b/app/assets/iconpack.json new file mode 100644 index 00000000..bb228e5a --- /dev/null +++ b/app/assets/iconpack.json @@ -0,0 +1,9 @@ +{ + "name": "NetNeighbor", + "owner": "Luc Lebosse", + "resolutions": "16,32,48,64,96,128,256,512,1024", + "version": "2.0", + "date": "2026-05-19", + "repository": "https://github.com/luc-github/NetNeighbor", + "license": "lgpl3" +} diff --git a/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg b/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg new file mode 100644 index 00000000..c050a260 --- /dev/null +++ b/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg @@ -0,0 +1 @@ +../../../../svg/netneighbor-tray.svg \ No newline at end of file diff --git a/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg b/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg new file mode 100644 index 00000000..d7b60097 --- /dev/null +++ b/app/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg @@ -0,0 +1 @@ +../../../../svg/netneighbor_icon.svg \ No newline at end of file diff --git a/app/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg b/app/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg new file mode 100644 index 00000000..9ba0f327 --- /dev/null +++ b/app/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg @@ -0,0 +1 @@ +../../../../svg/netneighbor-tray-symbolic.svg \ No newline at end of file diff --git a/app/assets/icons/logo-installer.png b/app/assets/icons/logo-installer.png new file mode 100644 index 00000000..38f05e9e Binary files /dev/null and b/app/assets/icons/logo-installer.png differ diff --git a/assets/icons/logo.png b/app/assets/icons/logo.png similarity index 100% rename from assets/icons/logo.png rename to app/assets/icons/logo.png diff --git a/app/assets/icons/netneighbor.ico b/app/assets/icons/netneighbor.ico new file mode 100644 index 00000000..5c032f0f Binary files /dev/null and b/app/assets/icons/netneighbor.ico differ diff --git a/app/assets/icons/netneighbor/1024/network-3dprinter.png b/app/assets/icons/netneighbor/1024/network-3dprinter.png new file mode 100644 index 00000000..fef8e424 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/1024/network-action-camera.png b/app/assets/icons/netneighbor/1024/network-action-camera.png new file mode 100644 index 00000000..c2f0d395 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/1024/network-aio-pc.png b/app/assets/icons/netneighbor/1024/network-aio-pc.png new file mode 100644 index 00000000..970ca0df Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-air-conditioner.png b/app/assets/icons/netneighbor/1024/network-air-conditioner.png new file mode 100644 index 00000000..a11f6428 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/1024/network-airpurifier.png b/app/assets/icons/netneighbor/1024/network-airpurifier.png new file mode 100644 index 00000000..bd5a46f9 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/1024/network-alarm-hub.png b/app/assets/icons/netneighbor/1024/network-alarm-hub.png new file mode 100644 index 00000000..eb517250 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/1024/network-applewatch.png b/app/assets/icons/netneighbor/1024/network-applewatch.png new file mode 100644 index 00000000..77626135 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/1024/network-card-reader.png b/app/assets/icons/netneighbor/1024/network-card-reader.png new file mode 100644 index 00000000..e3deaf4b Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/1024/network-cloud-server.png b/app/assets/icons/netneighbor/1024/network-cloud-server.png new file mode 100644 index 00000000..f9705ac5 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/1024/network-cnc-pendant.png b/app/assets/icons/netneighbor/1024/network-cnc-pendant.png new file mode 100644 index 00000000..1642c9e7 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/1024/network-desktop-pc.png b/app/assets/icons/netneighbor/1024/network-desktop-pc.png new file mode 100644 index 00000000..2f53ed2c Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-dishwasher.png b/app/assets/icons/netneighbor/1024/network-dishwasher.png new file mode 100644 index 00000000..ba520c6b Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/1024/network-drawing-tablet.png b/app/assets/icons/netneighbor/1024/network-drawing-tablet.png new file mode 100644 index 00000000..2619e537 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/1024/network-drone.png b/app/assets/icons/netneighbor/1024/network-drone.png new file mode 100644 index 00000000..754fd57f Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-drone.png differ diff --git a/app/assets/icons/netneighbor/1024/network-earbuds.png b/app/assets/icons/netneighbor/1024/network-earbuds.png new file mode 100644 index 00000000..0f41558c Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/1024/network-external-hdd.png b/app/assets/icons/netneighbor/1024/network-external-hdd.png new file mode 100644 index 00000000..c77b291d Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/1024/network-firewall.png b/app/assets/icons/netneighbor/1024/network-firewall.png new file mode 100644 index 00000000..085efd08 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/1024/network-gaming-console.png b/app/assets/icons/netneighbor/1024/network-gaming-console.png new file mode 100644 index 00000000..9acc44b4 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/1024/network-gaming-headset.png b/app/assets/icons/netneighbor/1024/network-gaming-headset.png new file mode 100644 index 00000000..2f170ed1 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/1024/network-gaming-keyboard.png b/app/assets/icons/netneighbor/1024/network-gaming-keyboard.png new file mode 100644 index 00000000..fe0e1b08 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/1024/network-gaming-pc.png b/app/assets/icons/netneighbor/1024/network-gaming-pc.png new file mode 100644 index 00000000..19504d0c Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-hifi-amplifier.png b/app/assets/icons/netneighbor/1024/network-hifi-amplifier.png new file mode 100644 index 00000000..77e76237 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/1024/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/1024/network-hifi-stereo-system.png new file mode 100644 index 00000000..0ea700eb Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/1024/network-home-appliance.png b/app/assets/icons/netneighbor/1024/network-home-appliance.png new file mode 100644 index 00000000..0d83d790 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/1024/network-home-hub.png b/app/assets/icons/netneighbor/1024/network-home-hub.png new file mode 100644 index 00000000..9e73ed42 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/1024/network-home-server-tower.png b/app/assets/icons/netneighbor/1024/network-home-server-tower.png new file mode 100644 index 00000000..cfafd2c8 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/1024/network-imac-display.png b/app/assets/icons/netneighbor/1024/network-imac-display.png new file mode 100644 index 00000000..54fac04d Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/1024/network-ip-camera.png b/app/assets/icons/netneighbor/1024/network-ip-camera.png new file mode 100644 index 00000000..5f554bc2 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/1024/network-ipad.png b/app/assets/icons/netneighbor/1024/network-ipad.png new file mode 100644 index 00000000..a8c51abb Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/1024/network-laptop-wifi.png b/app/assets/icons/netneighbor/1024/network-laptop-wifi.png new file mode 100644 index 00000000..d33e2293 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/1024/network-macmini-led.png b/app/assets/icons/netneighbor/1024/network-macmini-led.png new file mode 100644 index 00000000..68365406 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/1024/network-macmini.png b/app/assets/icons/netneighbor/1024/network-macmini.png new file mode 100644 index 00000000..c5935197 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/1024/network-media-server.png b/app/assets/icons/netneighbor/1024/network-media-server.png new file mode 100644 index 00000000..edcee52e Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/1024/network-mesh-node.png b/app/assets/icons/netneighbor/1024/network-mesh-node.png new file mode 100644 index 00000000..b6804edb Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/1024/network-mfp-printer.png b/app/assets/icons/netneighbor/1024/network-mfp-printer.png new file mode 100644 index 00000000..a8e54d4b Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/1024/network-mfp-v2.png b/app/assets/icons/netneighbor/1024/network-mfp-v2.png new file mode 100644 index 00000000..4650bbe5 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/1024/network-microwave.png b/app/assets/icons/netneighbor/1024/network-microwave.png new file mode 100644 index 00000000..ce9a4323 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/1024/network-mini-pc-generic.png b/app/assets/icons/netneighbor/1024/network-mini-pc-generic.png new file mode 100644 index 00000000..0b95f276 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/1024/network-minicnc.png b/app/assets/icons/netneighbor/1024/network-minicnc.png new file mode 100644 index 00000000..4764b1c1 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-monitor.png b/app/assets/icons/netneighbor/1024/network-monitor.png new file mode 100644 index 00000000..66c35b17 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/1024/network-motion-sensor.png b/app/assets/icons/netneighbor/1024/network-motion-sensor.png new file mode 100644 index 00000000..d53dcf49 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/1024/network-multi-functions-printer.png b/app/assets/icons/netneighbor/1024/network-multi-functions-printer.png new file mode 100644 index 00000000..671648f0 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/1024/network-nas.png b/app/assets/icons/netneighbor/1024/network-nas.png new file mode 100644 index 00000000..5506d482 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-nas.png differ diff --git a/app/assets/icons/netneighbor/1024/network-nvr-dvr.png b/app/assets/icons/netneighbor/1024/network-nvr-dvr.png new file mode 100644 index 00000000..37289c10 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/1024/network-oven.png b/app/assets/icons/netneighbor/1024/network-oven.png new file mode 100644 index 00000000..3d107019 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-oven.png differ diff --git a/app/assets/icons/netneighbor/1024/network-portable-media-player.png b/app/assets/icons/netneighbor/1024/network-portable-media-player.png new file mode 100644 index 00000000..3963a64c Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/1024/network-printer.png b/app/assets/icons/netneighbor/1024/network-printer.png new file mode 100644 index 00000000..637ea83b Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-printer.png differ diff --git a/app/assets/icons/netneighbor/1024/network-rack-cabinet.png b/app/assets/icons/netneighbor/1024/network-rack-cabinet.png new file mode 100644 index 00000000..823da0e6 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/1024/network-rj45-plc.png b/app/assets/icons/netneighbor/1024/network-rj45-plc.png new file mode 100644 index 00000000..04974cdd Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-robot-vacuum.png b/app/assets/icons/netneighbor/1024/network-robot-vacuum.png new file mode 100644 index 00000000..d6797061 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/1024/network-router-modem.png b/app/assets/icons/netneighbor/1024/network-router-modem.png new file mode 100644 index 00000000..7ed20ad7 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/1024/network-scanner.png b/app/assets/icons/netneighbor/1024/network-scanner.png new file mode 100644 index 00000000..a2d64393 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/1024/network-server.png b/app/assets/icons/netneighbor/1024/network-server.png new file mode 100644 index 00000000..c7cd0c2a Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-server.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-bulb.png b/app/assets/icons/netneighbor/1024/network-smart-bulb.png new file mode 100644 index 00000000..0cacbffc Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-cabinet.png b/app/assets/icons/netneighbor/1024/network-smart-cabinet.png new file mode 100644 index 00000000..251a1e2a Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-fridge.png b/app/assets/icons/netneighbor/1024/network-smart-fridge.png new file mode 100644 index 00000000..5cba3d71 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-glasses.png b/app/assets/icons/netneighbor/1024/network-smart-glasses.png new file mode 100644 index 00000000..1b128b8e Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-lock.png b/app/assets/icons/netneighbor/1024/network-smart-lock.png new file mode 100644 index 00000000..9920f22e Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-plug.png b/app/assets/icons/netneighbor/1024/network-smart-plug.png new file mode 100644 index 00000000..7623bf1e Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-speaker.png b/app/assets/icons/netneighbor/1024/network-smart-speaker.png new file mode 100644 index 00000000..1703aff2 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smart-switch.png b/app/assets/icons/netneighbor/1024/network-smart-switch.png new file mode 100644 index 00000000..0a4532e7 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smartphone.png b/app/assets/icons/netneighbor/1024/network-smartphone.png new file mode 100644 index 00000000..fec65de9 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smarttv.png b/app/assets/icons/netneighbor/1024/network-smarttv.png new file mode 100644 index 00000000..a4adb045 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smartwatch.png b/app/assets/icons/netneighbor/1024/network-smartwatch.png new file mode 100644 index 00000000..ed67e282 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/1024/network-smoke-detector.png b/app/assets/icons/netneighbor/1024/network-smoke-detector.png new file mode 100644 index 00000000..d766702c Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/1024/network-soundbar.png b/app/assets/icons/netneighbor/1024/network-soundbar.png new file mode 100644 index 00000000..7faea4dd Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/1024/network-stick-vacuum.png b/app/assets/icons/netneighbor/1024/network-stick-vacuum.png new file mode 100644 index 00000000..32c96131 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/1024/network-switch.png b/app/assets/icons/netneighbor/1024/network-switch.png new file mode 100644 index 00000000..6a2f6381 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-switch.png differ diff --git a/app/assets/icons/netneighbor/1024/network-thermostat.png b/app/assets/icons/netneighbor/1024/network-thermostat.png new file mode 100644 index 00000000..7113bea5 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/1024/network-touchscreen-panel.png b/app/assets/icons/netneighbor/1024/network-touchscreen-panel.png new file mode 100644 index 00000000..324fcaf3 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/1024/network-tv-media-player.png b/app/assets/icons/netneighbor/1024/network-tv-media-player.png new file mode 100644 index 00000000..665837d1 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/1024/network-unknown-device-v4.png b/app/assets/icons/netneighbor/1024/network-unknown-device-v4.png new file mode 100644 index 00000000..369bfbd6 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/1024/network-usb-drive.png b/app/assets/icons/netneighbor/1024/network-usb-drive.png new file mode 100644 index 00000000..d6fb1074 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/1024/network-video-doorbell.png b/app/assets/icons/netneighbor/1024/network-video-doorbell.png new file mode 100644 index 00000000..d8ac6422 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/1024/network-voip-phone.png b/app/assets/icons/netneighbor/1024/network-voip-phone.png new file mode 100644 index 00000000..f29ef40e Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/1024/network-vr-headset.png b/app/assets/icons/netneighbor/1024/network-vr-headset.png new file mode 100644 index 00000000..de89b0e8 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/1024/network-weather-station.png b/app/assets/icons/netneighbor/1024/network-weather-station.png new file mode 100644 index 00000000..105ac52d Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/1024/network-webcam.png b/app/assets/icons/netneighbor/1024/network-webcam.png new file mode 100644 index 00000000..85b36f50 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/1024/network-webcam2.png b/app/assets/icons/netneighbor/1024/network-webcam2.png new file mode 100644 index 00000000..8290ed19 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/1024/network-wifi-ap.png b/app/assets/icons/netneighbor/1024/network-wifi-ap.png new file mode 100644 index 00000000..a1d37b51 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/1024/network-wifi-plc.png b/app/assets/icons/netneighbor/1024/network-wifi-plc.png new file mode 100644 index 00000000..bb2702d5 Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/1024/network-wireless-mouse.png b/app/assets/icons/netneighbor/1024/network-wireless-mouse.png new file mode 100644 index 00000000..58d1e2bd Binary files /dev/null and b/app/assets/icons/netneighbor/1024/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/128/network-3dprinter.png b/app/assets/icons/netneighbor/128/network-3dprinter.png new file mode 100644 index 00000000..47396ca2 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/128/network-action-camera.png b/app/assets/icons/netneighbor/128/network-action-camera.png new file mode 100644 index 00000000..23ec3984 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/128/network-aio-pc.png b/app/assets/icons/netneighbor/128/network-aio-pc.png new file mode 100644 index 00000000..aea7a557 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/128/network-air-conditioner.png b/app/assets/icons/netneighbor/128/network-air-conditioner.png new file mode 100644 index 00000000..38f99441 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/128/network-airpurifier.png b/app/assets/icons/netneighbor/128/network-airpurifier.png new file mode 100644 index 00000000..ceda5d07 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/128/network-alarm-hub.png b/app/assets/icons/netneighbor/128/network-alarm-hub.png new file mode 100644 index 00000000..86bae321 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/128/network-applewatch.png b/app/assets/icons/netneighbor/128/network-applewatch.png new file mode 100644 index 00000000..92204e8f Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/128/network-card-reader.png b/app/assets/icons/netneighbor/128/network-card-reader.png new file mode 100644 index 00000000..9be541a7 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/128/network-cloud-server.png b/app/assets/icons/netneighbor/128/network-cloud-server.png new file mode 100644 index 00000000..7c159d1b Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/128/network-cnc-pendant.png b/app/assets/icons/netneighbor/128/network-cnc-pendant.png new file mode 100644 index 00000000..c632a3ab Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/128/network-desktop-pc.png b/app/assets/icons/netneighbor/128/network-desktop-pc.png new file mode 100644 index 00000000..284f5a56 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/128/network-dishwasher.png b/app/assets/icons/netneighbor/128/network-dishwasher.png new file mode 100644 index 00000000..ba8d2baf Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/128/network-drawing-tablet.png b/app/assets/icons/netneighbor/128/network-drawing-tablet.png new file mode 100644 index 00000000..0b6932fa Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/128/network-drone.png b/app/assets/icons/netneighbor/128/network-drone.png new file mode 100644 index 00000000..5a74c6cc Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-drone.png differ diff --git a/app/assets/icons/netneighbor/128/network-earbuds.png b/app/assets/icons/netneighbor/128/network-earbuds.png new file mode 100644 index 00000000..ae70ee08 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/128/network-external-hdd.png b/app/assets/icons/netneighbor/128/network-external-hdd.png new file mode 100644 index 00000000..088f2e4d Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/128/network-firewall.png b/app/assets/icons/netneighbor/128/network-firewall.png new file mode 100644 index 00000000..9b7691fe Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/128/network-gaming-console.png b/app/assets/icons/netneighbor/128/network-gaming-console.png new file mode 100644 index 00000000..a1f56605 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/128/network-gaming-headset.png b/app/assets/icons/netneighbor/128/network-gaming-headset.png new file mode 100644 index 00000000..668e7c1f Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/128/network-gaming-keyboard.png b/app/assets/icons/netneighbor/128/network-gaming-keyboard.png new file mode 100644 index 00000000..11865d24 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/128/network-gaming-pc.png b/app/assets/icons/netneighbor/128/network-gaming-pc.png new file mode 100644 index 00000000..6911e05a Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/128/network-hifi-amplifier.png b/app/assets/icons/netneighbor/128/network-hifi-amplifier.png new file mode 100644 index 00000000..2ce5f37c Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/128/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/128/network-hifi-stereo-system.png new file mode 100644 index 00000000..48558355 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/128/network-home-appliance.png b/app/assets/icons/netneighbor/128/network-home-appliance.png new file mode 100644 index 00000000..ba2e0501 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/128/network-home-hub.png b/app/assets/icons/netneighbor/128/network-home-hub.png new file mode 100644 index 00000000..11f238f5 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/128/network-home-server-tower.png b/app/assets/icons/netneighbor/128/network-home-server-tower.png new file mode 100644 index 00000000..5be58484 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/128/network-imac-display.png b/app/assets/icons/netneighbor/128/network-imac-display.png new file mode 100644 index 00000000..13336eab Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/128/network-ip-camera.png b/app/assets/icons/netneighbor/128/network-ip-camera.png new file mode 100644 index 00000000..6a12736d Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/128/network-ipad.png b/app/assets/icons/netneighbor/128/network-ipad.png new file mode 100644 index 00000000..c10389d8 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/128/network-laptop-wifi.png b/app/assets/icons/netneighbor/128/network-laptop-wifi.png new file mode 100644 index 00000000..a992cfb9 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/128/network-macmini-led.png b/app/assets/icons/netneighbor/128/network-macmini-led.png new file mode 100644 index 00000000..6a662b9d Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/128/network-macmini.png b/app/assets/icons/netneighbor/128/network-macmini.png new file mode 100644 index 00000000..e5b89898 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/128/network-media-server.png b/app/assets/icons/netneighbor/128/network-media-server.png new file mode 100644 index 00000000..a711048e Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/128/network-mesh-node.png b/app/assets/icons/netneighbor/128/network-mesh-node.png new file mode 100644 index 00000000..147edf67 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/128/network-mfp-printer.png b/app/assets/icons/netneighbor/128/network-mfp-printer.png new file mode 100644 index 00000000..ec330961 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/128/network-mfp-v2.png b/app/assets/icons/netneighbor/128/network-mfp-v2.png new file mode 100644 index 00000000..76ba0984 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/128/network-microwave.png b/app/assets/icons/netneighbor/128/network-microwave.png new file mode 100644 index 00000000..6ccbc3c2 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/128/network-mini-pc-generic.png b/app/assets/icons/netneighbor/128/network-mini-pc-generic.png new file mode 100644 index 00000000..222e66d1 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/128/network-minicnc.png b/app/assets/icons/netneighbor/128/network-minicnc.png new file mode 100644 index 00000000..6c6b09e1 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/128/network-monitor.png b/app/assets/icons/netneighbor/128/network-monitor.png new file mode 100644 index 00000000..aae86312 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/128/network-motion-sensor.png b/app/assets/icons/netneighbor/128/network-motion-sensor.png new file mode 100644 index 00000000..06cd286a Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/128/network-multi-functions-printer.png b/app/assets/icons/netneighbor/128/network-multi-functions-printer.png new file mode 100644 index 00000000..fdb979eb Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/128/network-nas.png b/app/assets/icons/netneighbor/128/network-nas.png new file mode 100644 index 00000000..ef3a972f Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-nas.png differ diff --git a/app/assets/icons/netneighbor/128/network-nvr-dvr.png b/app/assets/icons/netneighbor/128/network-nvr-dvr.png new file mode 100644 index 00000000..4ef0f253 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/128/network-oven.png b/app/assets/icons/netneighbor/128/network-oven.png new file mode 100644 index 00000000..27d53174 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-oven.png differ diff --git a/app/assets/icons/netneighbor/128/network-portable-media-player.png b/app/assets/icons/netneighbor/128/network-portable-media-player.png new file mode 100644 index 00000000..5ca1cd93 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/128/network-printer.png b/app/assets/icons/netneighbor/128/network-printer.png new file mode 100644 index 00000000..b86d3ebf Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-printer.png differ diff --git a/app/assets/icons/netneighbor/128/network-rack-cabinet.png b/app/assets/icons/netneighbor/128/network-rack-cabinet.png new file mode 100644 index 00000000..04f2c122 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/128/network-rj45-plc.png b/app/assets/icons/netneighbor/128/network-rj45-plc.png new file mode 100644 index 00000000..3642975a Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/128/network-robot-vacuum.png b/app/assets/icons/netneighbor/128/network-robot-vacuum.png new file mode 100644 index 00000000..b673fc16 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/128/network-router-modem.png b/app/assets/icons/netneighbor/128/network-router-modem.png new file mode 100644 index 00000000..b896de54 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/128/network-scanner.png b/app/assets/icons/netneighbor/128/network-scanner.png new file mode 100644 index 00000000..12e8baa6 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/128/network-server.png b/app/assets/icons/netneighbor/128/network-server.png new file mode 100644 index 00000000..21b94bb0 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-server.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-bulb.png b/app/assets/icons/netneighbor/128/network-smart-bulb.png new file mode 100644 index 00000000..d2a39840 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-cabinet.png b/app/assets/icons/netneighbor/128/network-smart-cabinet.png new file mode 100644 index 00000000..605eb274 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-fridge.png b/app/assets/icons/netneighbor/128/network-smart-fridge.png new file mode 100644 index 00000000..afe2afb1 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-glasses.png b/app/assets/icons/netneighbor/128/network-smart-glasses.png new file mode 100644 index 00000000..e3f341b7 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-lock.png b/app/assets/icons/netneighbor/128/network-smart-lock.png new file mode 100644 index 00000000..765f8721 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-plug.png b/app/assets/icons/netneighbor/128/network-smart-plug.png new file mode 100644 index 00000000..4e794b20 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-speaker.png b/app/assets/icons/netneighbor/128/network-smart-speaker.png new file mode 100644 index 00000000..1207e7b1 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/128/network-smart-switch.png b/app/assets/icons/netneighbor/128/network-smart-switch.png new file mode 100644 index 00000000..a9c1d84e Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/128/network-smartphone.png b/app/assets/icons/netneighbor/128/network-smartphone.png new file mode 100644 index 00000000..c27d4bda Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/128/network-smarttv.png b/app/assets/icons/netneighbor/128/network-smarttv.png new file mode 100644 index 00000000..176ec758 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/128/network-smartwatch.png b/app/assets/icons/netneighbor/128/network-smartwatch.png new file mode 100644 index 00000000..ca871dd2 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/128/network-smoke-detector.png b/app/assets/icons/netneighbor/128/network-smoke-detector.png new file mode 100644 index 00000000..3175c900 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/128/network-soundbar.png b/app/assets/icons/netneighbor/128/network-soundbar.png new file mode 100644 index 00000000..0158a71b Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/128/network-stick-vacuum.png b/app/assets/icons/netneighbor/128/network-stick-vacuum.png new file mode 100644 index 00000000..81a87dc7 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/128/network-switch.png b/app/assets/icons/netneighbor/128/network-switch.png new file mode 100644 index 00000000..0219e760 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-switch.png differ diff --git a/app/assets/icons/netneighbor/128/network-thermostat.png b/app/assets/icons/netneighbor/128/network-thermostat.png new file mode 100644 index 00000000..796775bc Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/128/network-touchscreen-panel.png b/app/assets/icons/netneighbor/128/network-touchscreen-panel.png new file mode 100644 index 00000000..64b6546c Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/128/network-tv-media-player.png b/app/assets/icons/netneighbor/128/network-tv-media-player.png new file mode 100644 index 00000000..3d196fce Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/128/network-unknown-device-v4.png b/app/assets/icons/netneighbor/128/network-unknown-device-v4.png new file mode 100644 index 00000000..e3dff66c Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/128/network-usb-drive.png b/app/assets/icons/netneighbor/128/network-usb-drive.png new file mode 100644 index 00000000..d14a516b Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/128/network-video-doorbell.png b/app/assets/icons/netneighbor/128/network-video-doorbell.png new file mode 100644 index 00000000..3bff3eb2 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/128/network-voip-phone.png b/app/assets/icons/netneighbor/128/network-voip-phone.png new file mode 100644 index 00000000..c0e092cb Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/128/network-vr-headset.png b/app/assets/icons/netneighbor/128/network-vr-headset.png new file mode 100644 index 00000000..99274fba Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/128/network-weather-station.png b/app/assets/icons/netneighbor/128/network-weather-station.png new file mode 100644 index 00000000..bb3fbc66 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/128/network-webcam.png b/app/assets/icons/netneighbor/128/network-webcam.png new file mode 100644 index 00000000..40d7dd17 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/128/network-webcam2.png b/app/assets/icons/netneighbor/128/network-webcam2.png new file mode 100644 index 00000000..5285f508 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/128/network-wifi-ap.png b/app/assets/icons/netneighbor/128/network-wifi-ap.png new file mode 100644 index 00000000..7bdffc9f Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/128/network-wifi-plc.png b/app/assets/icons/netneighbor/128/network-wifi-plc.png new file mode 100644 index 00000000..082da9d1 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/128/network-wireless-mouse.png b/app/assets/icons/netneighbor/128/network-wireless-mouse.png new file mode 100644 index 00000000..af483312 Binary files /dev/null and b/app/assets/icons/netneighbor/128/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/16/network-3dprinter.png b/app/assets/icons/netneighbor/16/network-3dprinter.png new file mode 100644 index 00000000..c7a6b942 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/16/network-action-camera.png b/app/assets/icons/netneighbor/16/network-action-camera.png new file mode 100644 index 00000000..dcb3ceb1 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/16/network-aio-pc.png b/app/assets/icons/netneighbor/16/network-aio-pc.png new file mode 100644 index 00000000..267e68a9 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/16/network-air-conditioner.png b/app/assets/icons/netneighbor/16/network-air-conditioner.png new file mode 100644 index 00000000..caaf908b Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/16/network-airpurifier.png b/app/assets/icons/netneighbor/16/network-airpurifier.png new file mode 100644 index 00000000..2f251b93 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/16/network-alarm-hub.png b/app/assets/icons/netneighbor/16/network-alarm-hub.png new file mode 100644 index 00000000..9ef49301 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/16/network-applewatch.png b/app/assets/icons/netneighbor/16/network-applewatch.png new file mode 100644 index 00000000..3ed6de75 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/16/network-card-reader.png b/app/assets/icons/netneighbor/16/network-card-reader.png new file mode 100644 index 00000000..2f268ae3 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/16/network-cloud-server.png b/app/assets/icons/netneighbor/16/network-cloud-server.png new file mode 100644 index 00000000..c9d6efae Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/16/network-cnc-pendant.png b/app/assets/icons/netneighbor/16/network-cnc-pendant.png new file mode 100644 index 00000000..79619054 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/16/network-desktop-pc.png b/app/assets/icons/netneighbor/16/network-desktop-pc.png new file mode 100644 index 00000000..6c7b94a8 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/16/network-dishwasher.png b/app/assets/icons/netneighbor/16/network-dishwasher.png new file mode 100644 index 00000000..979591b6 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/16/network-drawing-tablet.png b/app/assets/icons/netneighbor/16/network-drawing-tablet.png new file mode 100644 index 00000000..1fde62eb Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/16/network-drone.png b/app/assets/icons/netneighbor/16/network-drone.png new file mode 100644 index 00000000..27c78afe Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-drone.png differ diff --git a/app/assets/icons/netneighbor/16/network-earbuds.png b/app/assets/icons/netneighbor/16/network-earbuds.png new file mode 100644 index 00000000..1ee67f22 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/16/network-external-hdd.png b/app/assets/icons/netneighbor/16/network-external-hdd.png new file mode 100644 index 00000000..c3e3896a Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/16/network-firewall.png b/app/assets/icons/netneighbor/16/network-firewall.png new file mode 100644 index 00000000..ba8cbc01 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/16/network-gaming-console.png b/app/assets/icons/netneighbor/16/network-gaming-console.png new file mode 100644 index 00000000..09a68c7e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/16/network-gaming-headset.png b/app/assets/icons/netneighbor/16/network-gaming-headset.png new file mode 100644 index 00000000..a9413f08 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/16/network-gaming-keyboard.png b/app/assets/icons/netneighbor/16/network-gaming-keyboard.png new file mode 100644 index 00000000..ff5457a0 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/16/network-gaming-pc.png b/app/assets/icons/netneighbor/16/network-gaming-pc.png new file mode 100644 index 00000000..c051e18f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/16/network-hifi-amplifier.png b/app/assets/icons/netneighbor/16/network-hifi-amplifier.png new file mode 100644 index 00000000..4b2b9861 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/16/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/16/network-hifi-stereo-system.png new file mode 100644 index 00000000..5dafd837 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/16/network-home-appliance.png b/app/assets/icons/netneighbor/16/network-home-appliance.png new file mode 100644 index 00000000..7728424c Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/16/network-home-hub.png b/app/assets/icons/netneighbor/16/network-home-hub.png new file mode 100644 index 00000000..6f8c6a10 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/16/network-home-server-tower.png b/app/assets/icons/netneighbor/16/network-home-server-tower.png new file mode 100644 index 00000000..1bc211ff Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/16/network-imac-display.png b/app/assets/icons/netneighbor/16/network-imac-display.png new file mode 100644 index 00000000..1f6885ce Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/16/network-ip-camera.png b/app/assets/icons/netneighbor/16/network-ip-camera.png new file mode 100644 index 00000000..bdee2fe3 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/16/network-ipad.png b/app/assets/icons/netneighbor/16/network-ipad.png new file mode 100644 index 00000000..1831ff3e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/16/network-laptop-wifi.png b/app/assets/icons/netneighbor/16/network-laptop-wifi.png new file mode 100644 index 00000000..222384e1 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/16/network-macmini-led.png b/app/assets/icons/netneighbor/16/network-macmini-led.png new file mode 100644 index 00000000..f0814b67 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/16/network-macmini.png b/app/assets/icons/netneighbor/16/network-macmini.png new file mode 100644 index 00000000..6313cdb1 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/16/network-media-server.png b/app/assets/icons/netneighbor/16/network-media-server.png new file mode 100644 index 00000000..060676de Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/16/network-mesh-node.png b/app/assets/icons/netneighbor/16/network-mesh-node.png new file mode 100644 index 00000000..dc846d6c Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/16/network-mfp-printer.png b/app/assets/icons/netneighbor/16/network-mfp-printer.png new file mode 100644 index 00000000..c291c20b Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/16/network-mfp-v2.png b/app/assets/icons/netneighbor/16/network-mfp-v2.png new file mode 100644 index 00000000..40285d5b Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/16/network-microwave.png b/app/assets/icons/netneighbor/16/network-microwave.png new file mode 100644 index 00000000..9ea6ba8a Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/16/network-mini-pc-generic.png b/app/assets/icons/netneighbor/16/network-mini-pc-generic.png new file mode 100644 index 00000000..883a47e9 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/16/network-minicnc.png b/app/assets/icons/netneighbor/16/network-minicnc.png new file mode 100644 index 00000000..ccaba4fd Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/16/network-monitor.png b/app/assets/icons/netneighbor/16/network-monitor.png new file mode 100644 index 00000000..14222d12 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/16/network-motion-sensor.png b/app/assets/icons/netneighbor/16/network-motion-sensor.png new file mode 100644 index 00000000..af0802bf Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/16/network-multi-functions-printer.png b/app/assets/icons/netneighbor/16/network-multi-functions-printer.png new file mode 100644 index 00000000..f96ee61f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/16/network-nas.png b/app/assets/icons/netneighbor/16/network-nas.png new file mode 100644 index 00000000..6e9ecd8c Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-nas.png differ diff --git a/app/assets/icons/netneighbor/16/network-nvr-dvr.png b/app/assets/icons/netneighbor/16/network-nvr-dvr.png new file mode 100644 index 00000000..2e0f25a4 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/16/network-oven.png b/app/assets/icons/netneighbor/16/network-oven.png new file mode 100644 index 00000000..b50f700d Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-oven.png differ diff --git a/app/assets/icons/netneighbor/16/network-portable-media-player.png b/app/assets/icons/netneighbor/16/network-portable-media-player.png new file mode 100644 index 00000000..62769d3f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/16/network-printer.png b/app/assets/icons/netneighbor/16/network-printer.png new file mode 100644 index 00000000..9d2783aa Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-printer.png differ diff --git a/app/assets/icons/netneighbor/16/network-rack-cabinet.png b/app/assets/icons/netneighbor/16/network-rack-cabinet.png new file mode 100644 index 00000000..8cbd92ad Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/16/network-rj45-plc.png b/app/assets/icons/netneighbor/16/network-rj45-plc.png new file mode 100644 index 00000000..f7d899a1 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/16/network-robot-vacuum.png b/app/assets/icons/netneighbor/16/network-robot-vacuum.png new file mode 100644 index 00000000..37739c7e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/16/network-router-modem.png b/app/assets/icons/netneighbor/16/network-router-modem.png new file mode 100644 index 00000000..97e264bb Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/16/network-scanner.png b/app/assets/icons/netneighbor/16/network-scanner.png new file mode 100644 index 00000000..10b799f0 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/16/network-server.png b/app/assets/icons/netneighbor/16/network-server.png new file mode 100644 index 00000000..7b3065f9 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-server.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-bulb.png b/app/assets/icons/netneighbor/16/network-smart-bulb.png new file mode 100644 index 00000000..abe4c07e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-cabinet.png b/app/assets/icons/netneighbor/16/network-smart-cabinet.png new file mode 100644 index 00000000..87d46267 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-fridge.png b/app/assets/icons/netneighbor/16/network-smart-fridge.png new file mode 100644 index 00000000..ff9033c6 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-glasses.png b/app/assets/icons/netneighbor/16/network-smart-glasses.png new file mode 100644 index 00000000..4df4ef76 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-lock.png b/app/assets/icons/netneighbor/16/network-smart-lock.png new file mode 100644 index 00000000..1195339f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-plug.png b/app/assets/icons/netneighbor/16/network-smart-plug.png new file mode 100644 index 00000000..ac05523f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-speaker.png b/app/assets/icons/netneighbor/16/network-smart-speaker.png new file mode 100644 index 00000000..336be8de Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/16/network-smart-switch.png b/app/assets/icons/netneighbor/16/network-smart-switch.png new file mode 100644 index 00000000..ed89efd4 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/16/network-smartphone.png b/app/assets/icons/netneighbor/16/network-smartphone.png new file mode 100644 index 00000000..4fb95f2b Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/16/network-smarttv.png b/app/assets/icons/netneighbor/16/network-smarttv.png new file mode 100644 index 00000000..c94a6da9 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/16/network-smartwatch.png b/app/assets/icons/netneighbor/16/network-smartwatch.png new file mode 100644 index 00000000..b8d1e762 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/16/network-smoke-detector.png b/app/assets/icons/netneighbor/16/network-smoke-detector.png new file mode 100644 index 00000000..db78c65c Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/16/network-soundbar.png b/app/assets/icons/netneighbor/16/network-soundbar.png new file mode 100644 index 00000000..ea422ca8 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/16/network-stick-vacuum.png b/app/assets/icons/netneighbor/16/network-stick-vacuum.png new file mode 100644 index 00000000..967d289e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/16/network-switch.png b/app/assets/icons/netneighbor/16/network-switch.png new file mode 100644 index 00000000..91ea931d Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-switch.png differ diff --git a/app/assets/icons/netneighbor/16/network-thermostat.png b/app/assets/icons/netneighbor/16/network-thermostat.png new file mode 100644 index 00000000..96c40aea Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/16/network-touchscreen-panel.png b/app/assets/icons/netneighbor/16/network-touchscreen-panel.png new file mode 100644 index 00000000..a788fd4f Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/16/network-tv-media-player.png b/app/assets/icons/netneighbor/16/network-tv-media-player.png new file mode 100644 index 00000000..d4407237 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/16/network-unknown-device-v4.png b/app/assets/icons/netneighbor/16/network-unknown-device-v4.png new file mode 100644 index 00000000..c0d2016b Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/16/network-usb-drive.png b/app/assets/icons/netneighbor/16/network-usb-drive.png new file mode 100644 index 00000000..9abda13a Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/16/network-video-doorbell.png b/app/assets/icons/netneighbor/16/network-video-doorbell.png new file mode 100644 index 00000000..c92433e3 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/16/network-voip-phone.png b/app/assets/icons/netneighbor/16/network-voip-phone.png new file mode 100644 index 00000000..c09354b7 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/16/network-vr-headset.png b/app/assets/icons/netneighbor/16/network-vr-headset.png new file mode 100644 index 00000000..1211d5b2 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/16/network-weather-station.png b/app/assets/icons/netneighbor/16/network-weather-station.png new file mode 100644 index 00000000..9e332c2e Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/16/network-webcam.png b/app/assets/icons/netneighbor/16/network-webcam.png new file mode 100644 index 00000000..a346fa50 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/16/network-webcam2.png b/app/assets/icons/netneighbor/16/network-webcam2.png new file mode 100644 index 00000000..23dcb70c Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/16/network-wifi-ap.png b/app/assets/icons/netneighbor/16/network-wifi-ap.png new file mode 100644 index 00000000..78eebbbf Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/16/network-wifi-plc.png b/app/assets/icons/netneighbor/16/network-wifi-plc.png new file mode 100644 index 00000000..0951760d Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/16/network-wireless-mouse.png b/app/assets/icons/netneighbor/16/network-wireless-mouse.png new file mode 100644 index 00000000..8390dad6 Binary files /dev/null and b/app/assets/icons/netneighbor/16/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/22/network-3dprinter.png b/app/assets/icons/netneighbor/22/network-3dprinter.png new file mode 100644 index 00000000..f6f340f1 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/22/network-action-camera.png b/app/assets/icons/netneighbor/22/network-action-camera.png new file mode 100644 index 00000000..5b23d245 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/22/network-aio-pc.png b/app/assets/icons/netneighbor/22/network-aio-pc.png new file mode 100644 index 00000000..8d00a904 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/22/network-air-conditioner.png b/app/assets/icons/netneighbor/22/network-air-conditioner.png new file mode 100644 index 00000000..c8992c86 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/22/network-airpurifier.png b/app/assets/icons/netneighbor/22/network-airpurifier.png new file mode 100644 index 00000000..e7b51ad6 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/22/network-alarm-hub.png b/app/assets/icons/netneighbor/22/network-alarm-hub.png new file mode 100644 index 00000000..eacc24e5 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/22/network-applewatch.png b/app/assets/icons/netneighbor/22/network-applewatch.png new file mode 100644 index 00000000..6f8156f0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/22/network-card-reader.png b/app/assets/icons/netneighbor/22/network-card-reader.png new file mode 100644 index 00000000..498dbf9b Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/22/network-cloud-server.png b/app/assets/icons/netneighbor/22/network-cloud-server.png new file mode 100644 index 00000000..43b0a3d5 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/22/network-cnc-pendant.png b/app/assets/icons/netneighbor/22/network-cnc-pendant.png new file mode 100644 index 00000000..b9bf1c91 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/22/network-desktop-pc.png b/app/assets/icons/netneighbor/22/network-desktop-pc.png new file mode 100644 index 00000000..2947fbe7 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/22/network-dishwasher.png b/app/assets/icons/netneighbor/22/network-dishwasher.png new file mode 100644 index 00000000..e2a891c2 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/22/network-drawing-tablet.png b/app/assets/icons/netneighbor/22/network-drawing-tablet.png new file mode 100644 index 00000000..0c8a8ca4 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/22/network-drone.png b/app/assets/icons/netneighbor/22/network-drone.png new file mode 100644 index 00000000..40f42b33 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-drone.png differ diff --git a/app/assets/icons/netneighbor/22/network-earbuds.png b/app/assets/icons/netneighbor/22/network-earbuds.png new file mode 100644 index 00000000..f721de61 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/22/network-external-hdd.png b/app/assets/icons/netneighbor/22/network-external-hdd.png new file mode 100644 index 00000000..879debcf Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/22/network-firewall.png b/app/assets/icons/netneighbor/22/network-firewall.png new file mode 100644 index 00000000..f5e26702 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/22/network-gaming-console.png b/app/assets/icons/netneighbor/22/network-gaming-console.png new file mode 100644 index 00000000..e6c8bf6f Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/22/network-gaming-headset.png b/app/assets/icons/netneighbor/22/network-gaming-headset.png new file mode 100644 index 00000000..86a9432e Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/22/network-gaming-keyboard.png b/app/assets/icons/netneighbor/22/network-gaming-keyboard.png new file mode 100644 index 00000000..7d17e083 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/22/network-gaming-pc.png b/app/assets/icons/netneighbor/22/network-gaming-pc.png new file mode 100644 index 00000000..f7c99ec0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/22/network-hifi-amplifier.png b/app/assets/icons/netneighbor/22/network-hifi-amplifier.png new file mode 100644 index 00000000..2cfb790c Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/22/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/22/network-hifi-stereo-system.png new file mode 100644 index 00000000..e4c23a80 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/22/network-home-appliance.png b/app/assets/icons/netneighbor/22/network-home-appliance.png new file mode 100644 index 00000000..171ceafa Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/22/network-home-hub.png b/app/assets/icons/netneighbor/22/network-home-hub.png new file mode 100644 index 00000000..dda450a5 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/22/network-home-server-tower.png b/app/assets/icons/netneighbor/22/network-home-server-tower.png new file mode 100644 index 00000000..823a6807 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/22/network-imac-display.png b/app/assets/icons/netneighbor/22/network-imac-display.png new file mode 100644 index 00000000..1162627d Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/22/network-ip-camera.png b/app/assets/icons/netneighbor/22/network-ip-camera.png new file mode 100644 index 00000000..3929af4b Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/22/network-ipad.png b/app/assets/icons/netneighbor/22/network-ipad.png new file mode 100644 index 00000000..0fc257cd Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/22/network-laptop-wifi.png b/app/assets/icons/netneighbor/22/network-laptop-wifi.png new file mode 100644 index 00000000..e34553d5 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/22/network-macmini-led.png b/app/assets/icons/netneighbor/22/network-macmini-led.png new file mode 100644 index 00000000..6d6b3640 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/22/network-macmini.png b/app/assets/icons/netneighbor/22/network-macmini.png new file mode 100644 index 00000000..278dbd19 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/22/network-media-server.png b/app/assets/icons/netneighbor/22/network-media-server.png new file mode 100644 index 00000000..c57da43f Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/22/network-mesh-node.png b/app/assets/icons/netneighbor/22/network-mesh-node.png new file mode 100644 index 00000000..f8583094 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/22/network-mfp-printer.png b/app/assets/icons/netneighbor/22/network-mfp-printer.png new file mode 100644 index 00000000..273f50c7 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/22/network-mfp-v2.png b/app/assets/icons/netneighbor/22/network-mfp-v2.png new file mode 100644 index 00000000..928fd572 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/22/network-microwave.png b/app/assets/icons/netneighbor/22/network-microwave.png new file mode 100644 index 00000000..663e390c Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/22/network-mini-pc-generic.png b/app/assets/icons/netneighbor/22/network-mini-pc-generic.png new file mode 100644 index 00000000..022556f0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/22/network-minicnc.png b/app/assets/icons/netneighbor/22/network-minicnc.png new file mode 100644 index 00000000..d2a3bb6b Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/22/network-monitor.png b/app/assets/icons/netneighbor/22/network-monitor.png new file mode 100644 index 00000000..a4796d55 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/22/network-motion-sensor.png b/app/assets/icons/netneighbor/22/network-motion-sensor.png new file mode 100644 index 00000000..75182fcc Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/22/network-multi-functions-printer.png b/app/assets/icons/netneighbor/22/network-multi-functions-printer.png new file mode 100644 index 00000000..1a6797ce Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/22/network-nas.png b/app/assets/icons/netneighbor/22/network-nas.png new file mode 100644 index 00000000..dd7cc439 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-nas.png differ diff --git a/app/assets/icons/netneighbor/22/network-nvr-dvr.png b/app/assets/icons/netneighbor/22/network-nvr-dvr.png new file mode 100644 index 00000000..d8c4f89e Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/22/network-oven.png b/app/assets/icons/netneighbor/22/network-oven.png new file mode 100644 index 00000000..2c0ba8ed Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-oven.png differ diff --git a/app/assets/icons/netneighbor/22/network-portable-media-player.png b/app/assets/icons/netneighbor/22/network-portable-media-player.png new file mode 100644 index 00000000..8a27fe08 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/22/network-printer.png b/app/assets/icons/netneighbor/22/network-printer.png new file mode 100644 index 00000000..50fcfb51 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-printer.png differ diff --git a/app/assets/icons/netneighbor/22/network-rack-cabinet.png b/app/assets/icons/netneighbor/22/network-rack-cabinet.png new file mode 100644 index 00000000..47acd598 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/22/network-rj45-plc.png b/app/assets/icons/netneighbor/22/network-rj45-plc.png new file mode 100644 index 00000000..23d45320 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/22/network-robot-vacuum.png b/app/assets/icons/netneighbor/22/network-robot-vacuum.png new file mode 100644 index 00000000..2b4c5f8f Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/22/network-router-modem.png b/app/assets/icons/netneighbor/22/network-router-modem.png new file mode 100644 index 00000000..b8ed401e Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/22/network-scanner.png b/app/assets/icons/netneighbor/22/network-scanner.png new file mode 100644 index 00000000..73013190 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/22/network-server.png b/app/assets/icons/netneighbor/22/network-server.png new file mode 100644 index 00000000..f57c6f6c Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-server.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-bulb.png b/app/assets/icons/netneighbor/22/network-smart-bulb.png new file mode 100644 index 00000000..716a987b Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-cabinet.png b/app/assets/icons/netneighbor/22/network-smart-cabinet.png new file mode 100644 index 00000000..c93015a9 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-fridge.png b/app/assets/icons/netneighbor/22/network-smart-fridge.png new file mode 100644 index 00000000..a90a0b81 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-glasses.png b/app/assets/icons/netneighbor/22/network-smart-glasses.png new file mode 100644 index 00000000..8b039602 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-lock.png b/app/assets/icons/netneighbor/22/network-smart-lock.png new file mode 100644 index 00000000..0aa71864 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-plug.png b/app/assets/icons/netneighbor/22/network-smart-plug.png new file mode 100644 index 00000000..53d39d7e Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-speaker.png b/app/assets/icons/netneighbor/22/network-smart-speaker.png new file mode 100644 index 00000000..cb65b471 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/22/network-smart-switch.png b/app/assets/icons/netneighbor/22/network-smart-switch.png new file mode 100644 index 00000000..47021979 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/22/network-smartphone.png b/app/assets/icons/netneighbor/22/network-smartphone.png new file mode 100644 index 00000000..45a09ac2 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/22/network-smarttv.png b/app/assets/icons/netneighbor/22/network-smarttv.png new file mode 100644 index 00000000..505103ba Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/22/network-smartwatch.png b/app/assets/icons/netneighbor/22/network-smartwatch.png new file mode 100644 index 00000000..839d45a0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/22/network-smoke-detector.png b/app/assets/icons/netneighbor/22/network-smoke-detector.png new file mode 100644 index 00000000..90110ff7 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/22/network-soundbar.png b/app/assets/icons/netneighbor/22/network-soundbar.png new file mode 100644 index 00000000..a5066459 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/22/network-stick-vacuum.png b/app/assets/icons/netneighbor/22/network-stick-vacuum.png new file mode 100644 index 00000000..b9148521 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/22/network-switch.png b/app/assets/icons/netneighbor/22/network-switch.png new file mode 100644 index 00000000..7f8cfc03 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-switch.png differ diff --git a/app/assets/icons/netneighbor/22/network-thermostat.png b/app/assets/icons/netneighbor/22/network-thermostat.png new file mode 100644 index 00000000..dc105d99 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/22/network-touchscreen-panel.png b/app/assets/icons/netneighbor/22/network-touchscreen-panel.png new file mode 100644 index 00000000..bd6a01b8 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/22/network-tv-media-player.png b/app/assets/icons/netneighbor/22/network-tv-media-player.png new file mode 100644 index 00000000..3114a4cc Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/22/network-unknown-device-v4.png b/app/assets/icons/netneighbor/22/network-unknown-device-v4.png new file mode 100644 index 00000000..38d0f8d0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/22/network-usb-drive.png b/app/assets/icons/netneighbor/22/network-usb-drive.png new file mode 100644 index 00000000..2a15ce59 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/22/network-video-doorbell.png b/app/assets/icons/netneighbor/22/network-video-doorbell.png new file mode 100644 index 00000000..c53dd7c4 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/22/network-voip-phone.png b/app/assets/icons/netneighbor/22/network-voip-phone.png new file mode 100644 index 00000000..86bb7290 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/22/network-vr-headset.png b/app/assets/icons/netneighbor/22/network-vr-headset.png new file mode 100644 index 00000000..b78b41d0 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/22/network-weather-station.png b/app/assets/icons/netneighbor/22/network-weather-station.png new file mode 100644 index 00000000..4ead7dc8 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/22/network-webcam.png b/app/assets/icons/netneighbor/22/network-webcam.png new file mode 100644 index 00000000..4ab81300 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/22/network-webcam2.png b/app/assets/icons/netneighbor/22/network-webcam2.png new file mode 100644 index 00000000..01bcef75 Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/22/network-wifi-ap.png b/app/assets/icons/netneighbor/22/network-wifi-ap.png new file mode 100644 index 00000000..2c6ac23d Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/22/network-wifi-plc.png b/app/assets/icons/netneighbor/22/network-wifi-plc.png new file mode 100644 index 00000000..9fe5341e Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/22/network-wireless-mouse.png b/app/assets/icons/netneighbor/22/network-wireless-mouse.png new file mode 100644 index 00000000..fd4d6acd Binary files /dev/null and b/app/assets/icons/netneighbor/22/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/256/network-3dprinter.png b/app/assets/icons/netneighbor/256/network-3dprinter.png new file mode 100644 index 00000000..1a7108c4 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/256/network-action-camera.png b/app/assets/icons/netneighbor/256/network-action-camera.png new file mode 100644 index 00000000..2f8f1bc2 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/256/network-aio-pc.png b/app/assets/icons/netneighbor/256/network-aio-pc.png new file mode 100644 index 00000000..0130f50d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/256/network-air-conditioner.png b/app/assets/icons/netneighbor/256/network-air-conditioner.png new file mode 100644 index 00000000..1ada4b0f Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/256/network-airpurifier.png b/app/assets/icons/netneighbor/256/network-airpurifier.png new file mode 100644 index 00000000..c7e04725 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/256/network-alarm-hub.png b/app/assets/icons/netneighbor/256/network-alarm-hub.png new file mode 100644 index 00000000..441bece0 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/256/network-applewatch.png b/app/assets/icons/netneighbor/256/network-applewatch.png new file mode 100644 index 00000000..1bfb4127 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/256/network-card-reader.png b/app/assets/icons/netneighbor/256/network-card-reader.png new file mode 100644 index 00000000..b8b16726 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/256/network-cloud-server.png b/app/assets/icons/netneighbor/256/network-cloud-server.png new file mode 100644 index 00000000..b6401641 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/256/network-cnc-pendant.png b/app/assets/icons/netneighbor/256/network-cnc-pendant.png new file mode 100644 index 00000000..6c3a490e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/256/network-desktop-pc.png b/app/assets/icons/netneighbor/256/network-desktop-pc.png new file mode 100644 index 00000000..2e9ac5c8 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/256/network-dishwasher.png b/app/assets/icons/netneighbor/256/network-dishwasher.png new file mode 100644 index 00000000..a402dc99 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/256/network-drawing-tablet.png b/app/assets/icons/netneighbor/256/network-drawing-tablet.png new file mode 100644 index 00000000..7841a437 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/256/network-drone.png b/app/assets/icons/netneighbor/256/network-drone.png new file mode 100644 index 00000000..28c43fb5 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-drone.png differ diff --git a/app/assets/icons/netneighbor/256/network-earbuds.png b/app/assets/icons/netneighbor/256/network-earbuds.png new file mode 100644 index 00000000..66d74e2f Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/256/network-external-hdd.png b/app/assets/icons/netneighbor/256/network-external-hdd.png new file mode 100644 index 00000000..c35574a3 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/256/network-firewall.png b/app/assets/icons/netneighbor/256/network-firewall.png new file mode 100644 index 00000000..2798f526 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/256/network-gaming-console.png b/app/assets/icons/netneighbor/256/network-gaming-console.png new file mode 100644 index 00000000..7a7b281e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/256/network-gaming-headset.png b/app/assets/icons/netneighbor/256/network-gaming-headset.png new file mode 100644 index 00000000..4664479d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/256/network-gaming-keyboard.png b/app/assets/icons/netneighbor/256/network-gaming-keyboard.png new file mode 100644 index 00000000..67156488 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/256/network-gaming-pc.png b/app/assets/icons/netneighbor/256/network-gaming-pc.png new file mode 100644 index 00000000..50d95bed Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/256/network-hifi-amplifier.png b/app/assets/icons/netneighbor/256/network-hifi-amplifier.png new file mode 100644 index 00000000..9361341d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/256/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/256/network-hifi-stereo-system.png new file mode 100644 index 00000000..c3fea83e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/256/network-home-appliance.png b/app/assets/icons/netneighbor/256/network-home-appliance.png new file mode 100644 index 00000000..c499ab7e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/256/network-home-hub.png b/app/assets/icons/netneighbor/256/network-home-hub.png new file mode 100644 index 00000000..9ef9ff07 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/256/network-home-server-tower.png b/app/assets/icons/netneighbor/256/network-home-server-tower.png new file mode 100644 index 00000000..bde327be Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/256/network-imac-display.png b/app/assets/icons/netneighbor/256/network-imac-display.png new file mode 100644 index 00000000..75b56710 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/256/network-ip-camera.png b/app/assets/icons/netneighbor/256/network-ip-camera.png new file mode 100644 index 00000000..cb2380a3 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/256/network-ipad.png b/app/assets/icons/netneighbor/256/network-ipad.png new file mode 100644 index 00000000..59943034 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/256/network-laptop-wifi.png b/app/assets/icons/netneighbor/256/network-laptop-wifi.png new file mode 100644 index 00000000..15c3f47a Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/256/network-macmini-led.png b/app/assets/icons/netneighbor/256/network-macmini-led.png new file mode 100644 index 00000000..ea41cdba Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/256/network-macmini.png b/app/assets/icons/netneighbor/256/network-macmini.png new file mode 100644 index 00000000..4a268855 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/256/network-media-server.png b/app/assets/icons/netneighbor/256/network-media-server.png new file mode 100644 index 00000000..ad6d24fd Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/256/network-mesh-node.png b/app/assets/icons/netneighbor/256/network-mesh-node.png new file mode 100644 index 00000000..8e54192c Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/256/network-mfp-printer.png b/app/assets/icons/netneighbor/256/network-mfp-printer.png new file mode 100644 index 00000000..1a686559 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/256/network-mfp-v2.png b/app/assets/icons/netneighbor/256/network-mfp-v2.png new file mode 100644 index 00000000..ab9783a6 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/256/network-microwave.png b/app/assets/icons/netneighbor/256/network-microwave.png new file mode 100644 index 00000000..e0c85a84 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/256/network-mini-pc-generic.png b/app/assets/icons/netneighbor/256/network-mini-pc-generic.png new file mode 100644 index 00000000..54992420 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/256/network-minicnc.png b/app/assets/icons/netneighbor/256/network-minicnc.png new file mode 100644 index 00000000..99a6b95d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/256/network-monitor.png b/app/assets/icons/netneighbor/256/network-monitor.png new file mode 100644 index 00000000..989c9e44 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/256/network-motion-sensor.png b/app/assets/icons/netneighbor/256/network-motion-sensor.png new file mode 100644 index 00000000..91da4249 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/256/network-multi-functions-printer.png b/app/assets/icons/netneighbor/256/network-multi-functions-printer.png new file mode 100644 index 00000000..83e6b88a Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/256/network-nas.png b/app/assets/icons/netneighbor/256/network-nas.png new file mode 100644 index 00000000..d4f2b251 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-nas.png differ diff --git a/app/assets/icons/netneighbor/256/network-nvr-dvr.png b/app/assets/icons/netneighbor/256/network-nvr-dvr.png new file mode 100644 index 00000000..18943ff5 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/256/network-oven.png b/app/assets/icons/netneighbor/256/network-oven.png new file mode 100644 index 00000000..21763311 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-oven.png differ diff --git a/app/assets/icons/netneighbor/256/network-portable-media-player.png b/app/assets/icons/netneighbor/256/network-portable-media-player.png new file mode 100644 index 00000000..6144bbb7 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/256/network-printer.png b/app/assets/icons/netneighbor/256/network-printer.png new file mode 100644 index 00000000..505ee217 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-printer.png differ diff --git a/app/assets/icons/netneighbor/256/network-rack-cabinet.png b/app/assets/icons/netneighbor/256/network-rack-cabinet.png new file mode 100644 index 00000000..2fda315c Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/256/network-rj45-plc.png b/app/assets/icons/netneighbor/256/network-rj45-plc.png new file mode 100644 index 00000000..2484b20d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/256/network-robot-vacuum.png b/app/assets/icons/netneighbor/256/network-robot-vacuum.png new file mode 100644 index 00000000..d133ece6 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/256/network-router-modem.png b/app/assets/icons/netneighbor/256/network-router-modem.png new file mode 100644 index 00000000..02af18ca Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/256/network-scanner.png b/app/assets/icons/netneighbor/256/network-scanner.png new file mode 100644 index 00000000..3a43a507 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/256/network-server.png b/app/assets/icons/netneighbor/256/network-server.png new file mode 100644 index 00000000..2e764208 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-server.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-bulb.png b/app/assets/icons/netneighbor/256/network-smart-bulb.png new file mode 100644 index 00000000..5aaba8e4 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-cabinet.png b/app/assets/icons/netneighbor/256/network-smart-cabinet.png new file mode 100644 index 00000000..c2355c08 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-fridge.png b/app/assets/icons/netneighbor/256/network-smart-fridge.png new file mode 100644 index 00000000..ee1b9333 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-glasses.png b/app/assets/icons/netneighbor/256/network-smart-glasses.png new file mode 100644 index 00000000..942b4540 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-lock.png b/app/assets/icons/netneighbor/256/network-smart-lock.png new file mode 100644 index 00000000..9881683c Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-plug.png b/app/assets/icons/netneighbor/256/network-smart-plug.png new file mode 100644 index 00000000..ca9e6c85 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-speaker.png b/app/assets/icons/netneighbor/256/network-smart-speaker.png new file mode 100644 index 00000000..697296d2 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/256/network-smart-switch.png b/app/assets/icons/netneighbor/256/network-smart-switch.png new file mode 100644 index 00000000..e2ac6928 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/256/network-smartphone.png b/app/assets/icons/netneighbor/256/network-smartphone.png new file mode 100644 index 00000000..ca48094c Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/256/network-smarttv.png b/app/assets/icons/netneighbor/256/network-smarttv.png new file mode 100644 index 00000000..84094e00 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/256/network-smartwatch.png b/app/assets/icons/netneighbor/256/network-smartwatch.png new file mode 100644 index 00000000..9bf085f5 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/256/network-smoke-detector.png b/app/assets/icons/netneighbor/256/network-smoke-detector.png new file mode 100644 index 00000000..8a48a02e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/256/network-soundbar.png b/app/assets/icons/netneighbor/256/network-soundbar.png new file mode 100644 index 00000000..f2580207 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/256/network-stick-vacuum.png b/app/assets/icons/netneighbor/256/network-stick-vacuum.png new file mode 100644 index 00000000..6a06e9a8 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/256/network-switch.png b/app/assets/icons/netneighbor/256/network-switch.png new file mode 100644 index 00000000..01f8e755 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-switch.png differ diff --git a/app/assets/icons/netneighbor/256/network-thermostat.png b/app/assets/icons/netneighbor/256/network-thermostat.png new file mode 100644 index 00000000..11e787cd Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/256/network-touchscreen-panel.png b/app/assets/icons/netneighbor/256/network-touchscreen-panel.png new file mode 100644 index 00000000..c3e0fe40 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/256/network-tv-media-player.png b/app/assets/icons/netneighbor/256/network-tv-media-player.png new file mode 100644 index 00000000..6c4c0b2e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/256/network-unknown-device-v4.png b/app/assets/icons/netneighbor/256/network-unknown-device-v4.png new file mode 100644 index 00000000..1dc438d2 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/256/network-usb-drive.png b/app/assets/icons/netneighbor/256/network-usb-drive.png new file mode 100644 index 00000000..8c03b8d8 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/256/network-video-doorbell.png b/app/assets/icons/netneighbor/256/network-video-doorbell.png new file mode 100644 index 00000000..d646a7ce Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/256/network-voip-phone.png b/app/assets/icons/netneighbor/256/network-voip-phone.png new file mode 100644 index 00000000..c8a61a5a Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/256/network-vr-headset.png b/app/assets/icons/netneighbor/256/network-vr-headset.png new file mode 100644 index 00000000..df5d85ce Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/256/network-weather-station.png b/app/assets/icons/netneighbor/256/network-weather-station.png new file mode 100644 index 00000000..40466be2 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/256/network-webcam.png b/app/assets/icons/netneighbor/256/network-webcam.png new file mode 100644 index 00000000..88765118 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/256/network-webcam2.png b/app/assets/icons/netneighbor/256/network-webcam2.png new file mode 100644 index 00000000..4eb07d3e Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/256/network-wifi-ap.png b/app/assets/icons/netneighbor/256/network-wifi-ap.png new file mode 100644 index 00000000..f09ccaf0 Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/256/network-wifi-plc.png b/app/assets/icons/netneighbor/256/network-wifi-plc.png new file mode 100644 index 00000000..902e3b3d Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/256/network-wireless-mouse.png b/app/assets/icons/netneighbor/256/network-wireless-mouse.png new file mode 100644 index 00000000..1c25dc9f Binary files /dev/null and b/app/assets/icons/netneighbor/256/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/32/network-3dprinter.png b/app/assets/icons/netneighbor/32/network-3dprinter.png new file mode 100644 index 00000000..5836b427 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/32/network-action-camera.png b/app/assets/icons/netneighbor/32/network-action-camera.png new file mode 100644 index 00000000..879d46b9 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/32/network-aio-pc.png b/app/assets/icons/netneighbor/32/network-aio-pc.png new file mode 100644 index 00000000..80f2e3e0 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/32/network-air-conditioner.png b/app/assets/icons/netneighbor/32/network-air-conditioner.png new file mode 100644 index 00000000..d30762e5 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/32/network-airpurifier.png b/app/assets/icons/netneighbor/32/network-airpurifier.png new file mode 100644 index 00000000..7f31b1bb Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/32/network-alarm-hub.png b/app/assets/icons/netneighbor/32/network-alarm-hub.png new file mode 100644 index 00000000..291dddfb Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/32/network-applewatch.png b/app/assets/icons/netneighbor/32/network-applewatch.png new file mode 100644 index 00000000..e90d1b42 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/32/network-card-reader.png b/app/assets/icons/netneighbor/32/network-card-reader.png new file mode 100644 index 00000000..b5c969a2 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/32/network-cloud-server.png b/app/assets/icons/netneighbor/32/network-cloud-server.png new file mode 100644 index 00000000..e3b83b72 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/32/network-cnc-pendant.png b/app/assets/icons/netneighbor/32/network-cnc-pendant.png new file mode 100644 index 00000000..a31b0d8f Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/32/network-desktop-pc.png b/app/assets/icons/netneighbor/32/network-desktop-pc.png new file mode 100644 index 00000000..8ce94137 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/32/network-dishwasher.png b/app/assets/icons/netneighbor/32/network-dishwasher.png new file mode 100644 index 00000000..cef0109b Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/32/network-drawing-tablet.png b/app/assets/icons/netneighbor/32/network-drawing-tablet.png new file mode 100644 index 00000000..fca0920f Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/32/network-drone.png b/app/assets/icons/netneighbor/32/network-drone.png new file mode 100644 index 00000000..7a6e16de Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-drone.png differ diff --git a/app/assets/icons/netneighbor/32/network-earbuds.png b/app/assets/icons/netneighbor/32/network-earbuds.png new file mode 100644 index 00000000..8b8045dd Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/32/network-external-hdd.png b/app/assets/icons/netneighbor/32/network-external-hdd.png new file mode 100644 index 00000000..e8b12e5e Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/32/network-firewall.png b/app/assets/icons/netneighbor/32/network-firewall.png new file mode 100644 index 00000000..3977992b Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/32/network-gaming-console.png b/app/assets/icons/netneighbor/32/network-gaming-console.png new file mode 100644 index 00000000..3f95f3aa Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/32/network-gaming-headset.png b/app/assets/icons/netneighbor/32/network-gaming-headset.png new file mode 100644 index 00000000..05d5c59d Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/32/network-gaming-keyboard.png b/app/assets/icons/netneighbor/32/network-gaming-keyboard.png new file mode 100644 index 00000000..03d58cc7 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/32/network-gaming-pc.png b/app/assets/icons/netneighbor/32/network-gaming-pc.png new file mode 100644 index 00000000..f117a6c6 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/32/network-hifi-amplifier.png b/app/assets/icons/netneighbor/32/network-hifi-amplifier.png new file mode 100644 index 00000000..2d426bd3 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/32/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/32/network-hifi-stereo-system.png new file mode 100644 index 00000000..b008253d Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/32/network-home-appliance.png b/app/assets/icons/netneighbor/32/network-home-appliance.png new file mode 100644 index 00000000..8288ec20 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/32/network-home-hub.png b/app/assets/icons/netneighbor/32/network-home-hub.png new file mode 100644 index 00000000..da565f47 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/32/network-home-server-tower.png b/app/assets/icons/netneighbor/32/network-home-server-tower.png new file mode 100644 index 00000000..b921acd4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/32/network-imac-display.png b/app/assets/icons/netneighbor/32/network-imac-display.png new file mode 100644 index 00000000..67f5c1c4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/32/network-ip-camera.png b/app/assets/icons/netneighbor/32/network-ip-camera.png new file mode 100644 index 00000000..3f2da217 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/32/network-ipad.png b/app/assets/icons/netneighbor/32/network-ipad.png new file mode 100644 index 00000000..f24a19fa Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/32/network-laptop-wifi.png b/app/assets/icons/netneighbor/32/network-laptop-wifi.png new file mode 100644 index 00000000..84cc9951 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/32/network-macmini-led.png b/app/assets/icons/netneighbor/32/network-macmini-led.png new file mode 100644 index 00000000..1cc9fc1f Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/32/network-macmini.png b/app/assets/icons/netneighbor/32/network-macmini.png new file mode 100644 index 00000000..7d57bfc4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/32/network-media-server.png b/app/assets/icons/netneighbor/32/network-media-server.png new file mode 100644 index 00000000..79604f17 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/32/network-mesh-node.png b/app/assets/icons/netneighbor/32/network-mesh-node.png new file mode 100644 index 00000000..714cf3dd Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/32/network-mfp-printer.png b/app/assets/icons/netneighbor/32/network-mfp-printer.png new file mode 100644 index 00000000..a22bf30c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/32/network-mfp-v2.png b/app/assets/icons/netneighbor/32/network-mfp-v2.png new file mode 100644 index 00000000..e77a7c64 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/32/network-microwave.png b/app/assets/icons/netneighbor/32/network-microwave.png new file mode 100644 index 00000000..d940b4b6 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/32/network-mini-pc-generic.png b/app/assets/icons/netneighbor/32/network-mini-pc-generic.png new file mode 100644 index 00000000..08c94c08 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/32/network-minicnc.png b/app/assets/icons/netneighbor/32/network-minicnc.png new file mode 100644 index 00000000..376abf6d Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/32/network-monitor.png b/app/assets/icons/netneighbor/32/network-monitor.png new file mode 100644 index 00000000..f147ca1d Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/32/network-motion-sensor.png b/app/assets/icons/netneighbor/32/network-motion-sensor.png new file mode 100644 index 00000000..1d24de08 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/32/network-multi-functions-printer.png b/app/assets/icons/netneighbor/32/network-multi-functions-printer.png new file mode 100644 index 00000000..1d9be2ad Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/32/network-nas.png b/app/assets/icons/netneighbor/32/network-nas.png new file mode 100644 index 00000000..d1f87901 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-nas.png differ diff --git a/app/assets/icons/netneighbor/32/network-nvr-dvr.png b/app/assets/icons/netneighbor/32/network-nvr-dvr.png new file mode 100644 index 00000000..c8049c78 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/32/network-oven.png b/app/assets/icons/netneighbor/32/network-oven.png new file mode 100644 index 00000000..09733b3b Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-oven.png differ diff --git a/app/assets/icons/netneighbor/32/network-portable-media-player.png b/app/assets/icons/netneighbor/32/network-portable-media-player.png new file mode 100644 index 00000000..266d4c9c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/32/network-printer.png b/app/assets/icons/netneighbor/32/network-printer.png new file mode 100644 index 00000000..8cb92481 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-printer.png differ diff --git a/app/assets/icons/netneighbor/32/network-rack-cabinet.png b/app/assets/icons/netneighbor/32/network-rack-cabinet.png new file mode 100644 index 00000000..1a709e00 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/32/network-rj45-plc.png b/app/assets/icons/netneighbor/32/network-rj45-plc.png new file mode 100644 index 00000000..6331b8fb Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/32/network-robot-vacuum.png b/app/assets/icons/netneighbor/32/network-robot-vacuum.png new file mode 100644 index 00000000..0510ed4b Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/32/network-router-modem.png b/app/assets/icons/netneighbor/32/network-router-modem.png new file mode 100644 index 00000000..74e66b9c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/32/network-scanner.png b/app/assets/icons/netneighbor/32/network-scanner.png new file mode 100644 index 00000000..7b66dbd0 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/32/network-server.png b/app/assets/icons/netneighbor/32/network-server.png new file mode 100644 index 00000000..e0664f48 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-server.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-bulb.png b/app/assets/icons/netneighbor/32/network-smart-bulb.png new file mode 100644 index 00000000..e2482f40 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-cabinet.png b/app/assets/icons/netneighbor/32/network-smart-cabinet.png new file mode 100644 index 00000000..a891b3a8 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-fridge.png b/app/assets/icons/netneighbor/32/network-smart-fridge.png new file mode 100644 index 00000000..92dec612 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-glasses.png b/app/assets/icons/netneighbor/32/network-smart-glasses.png new file mode 100644 index 00000000..d6afba3c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-lock.png b/app/assets/icons/netneighbor/32/network-smart-lock.png new file mode 100644 index 00000000..62cd71be Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-plug.png b/app/assets/icons/netneighbor/32/network-smart-plug.png new file mode 100644 index 00000000..6c26af1f Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-speaker.png b/app/assets/icons/netneighbor/32/network-smart-speaker.png new file mode 100644 index 00000000..f81d7160 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/32/network-smart-switch.png b/app/assets/icons/netneighbor/32/network-smart-switch.png new file mode 100644 index 00000000..d49c8fb3 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/32/network-smartphone.png b/app/assets/icons/netneighbor/32/network-smartphone.png new file mode 100644 index 00000000..cfc397db Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/32/network-smarttv.png b/app/assets/icons/netneighbor/32/network-smarttv.png new file mode 100644 index 00000000..0bef0c8c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/32/network-smartwatch.png b/app/assets/icons/netneighbor/32/network-smartwatch.png new file mode 100644 index 00000000..278812d5 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/32/network-smoke-detector.png b/app/assets/icons/netneighbor/32/network-smoke-detector.png new file mode 100644 index 00000000..0d382f87 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/32/network-soundbar.png b/app/assets/icons/netneighbor/32/network-soundbar.png new file mode 100644 index 00000000..581a8a4e Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/32/network-stick-vacuum.png b/app/assets/icons/netneighbor/32/network-stick-vacuum.png new file mode 100644 index 00000000..cd9efad4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/32/network-switch.png b/app/assets/icons/netneighbor/32/network-switch.png new file mode 100644 index 00000000..0193d59e Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-switch.png differ diff --git a/app/assets/icons/netneighbor/32/network-thermostat.png b/app/assets/icons/netneighbor/32/network-thermostat.png new file mode 100644 index 00000000..702b5d63 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/32/network-touchscreen-panel.png b/app/assets/icons/netneighbor/32/network-touchscreen-panel.png new file mode 100644 index 00000000..6d65c2b7 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/32/network-tv-media-player.png b/app/assets/icons/netneighbor/32/network-tv-media-player.png new file mode 100644 index 00000000..5930d420 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/32/network-unknown-device-v4.png b/app/assets/icons/netneighbor/32/network-unknown-device-v4.png new file mode 100644 index 00000000..e9c337e4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/32/network-usb-drive.png b/app/assets/icons/netneighbor/32/network-usb-drive.png new file mode 100644 index 00000000..010d864c Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/32/network-video-doorbell.png b/app/assets/icons/netneighbor/32/network-video-doorbell.png new file mode 100644 index 00000000..a56da720 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/32/network-voip-phone.png b/app/assets/icons/netneighbor/32/network-voip-phone.png new file mode 100644 index 00000000..cce81931 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/32/network-vr-headset.png b/app/assets/icons/netneighbor/32/network-vr-headset.png new file mode 100644 index 00000000..2897e5a4 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/32/network-weather-station.png b/app/assets/icons/netneighbor/32/network-weather-station.png new file mode 100644 index 00000000..6f74af86 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/32/network-webcam.png b/app/assets/icons/netneighbor/32/network-webcam.png new file mode 100644 index 00000000..b0ec78b0 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/32/network-webcam2.png b/app/assets/icons/netneighbor/32/network-webcam2.png new file mode 100644 index 00000000..ba8c47fc Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/32/network-wifi-ap.png b/app/assets/icons/netneighbor/32/network-wifi-ap.png new file mode 100644 index 00000000..c269bbc2 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/32/network-wifi-plc.png b/app/assets/icons/netneighbor/32/network-wifi-plc.png new file mode 100644 index 00000000..275efd67 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/32/network-wireless-mouse.png b/app/assets/icons/netneighbor/32/network-wireless-mouse.png new file mode 100644 index 00000000..e486a1b6 Binary files /dev/null and b/app/assets/icons/netneighbor/32/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/48/network-3dprinter.png b/app/assets/icons/netneighbor/48/network-3dprinter.png new file mode 100644 index 00000000..05d6f313 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/48/network-action-camera.png b/app/assets/icons/netneighbor/48/network-action-camera.png new file mode 100644 index 00000000..4793716b Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/48/network-aio-pc.png b/app/assets/icons/netneighbor/48/network-aio-pc.png new file mode 100644 index 00000000..b641b3cd Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/48/network-air-conditioner.png b/app/assets/icons/netneighbor/48/network-air-conditioner.png new file mode 100644 index 00000000..f5e9243e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/48/network-airpurifier.png b/app/assets/icons/netneighbor/48/network-airpurifier.png new file mode 100644 index 00000000..cde9b073 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/48/network-alarm-hub.png b/app/assets/icons/netneighbor/48/network-alarm-hub.png new file mode 100644 index 00000000..9dae06fd Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/48/network-applewatch.png b/app/assets/icons/netneighbor/48/network-applewatch.png new file mode 100644 index 00000000..59059cb0 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/48/network-card-reader.png b/app/assets/icons/netneighbor/48/network-card-reader.png new file mode 100644 index 00000000..dbaeefcb Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/48/network-cloud-server.png b/app/assets/icons/netneighbor/48/network-cloud-server.png new file mode 100644 index 00000000..06b219e2 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/48/network-cnc-pendant.png b/app/assets/icons/netneighbor/48/network-cnc-pendant.png new file mode 100644 index 00000000..e0b49963 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/48/network-desktop-pc.png b/app/assets/icons/netneighbor/48/network-desktop-pc.png new file mode 100644 index 00000000..82512bf5 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/48/network-dishwasher.png b/app/assets/icons/netneighbor/48/network-dishwasher.png new file mode 100644 index 00000000..74aa2cd1 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/48/network-drawing-tablet.png b/app/assets/icons/netneighbor/48/network-drawing-tablet.png new file mode 100644 index 00000000..b2404293 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/48/network-drone.png b/app/assets/icons/netneighbor/48/network-drone.png new file mode 100644 index 00000000..211f9ae1 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-drone.png differ diff --git a/app/assets/icons/netneighbor/48/network-earbuds.png b/app/assets/icons/netneighbor/48/network-earbuds.png new file mode 100644 index 00000000..7d1c8a84 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/48/network-external-hdd.png b/app/assets/icons/netneighbor/48/network-external-hdd.png new file mode 100644 index 00000000..2556b96b Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/48/network-firewall.png b/app/assets/icons/netneighbor/48/network-firewall.png new file mode 100644 index 00000000..d1556bfd Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/48/network-gaming-console.png b/app/assets/icons/netneighbor/48/network-gaming-console.png new file mode 100644 index 00000000..abd9b947 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/48/network-gaming-headset.png b/app/assets/icons/netneighbor/48/network-gaming-headset.png new file mode 100644 index 00000000..113e480e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/48/network-gaming-keyboard.png b/app/assets/icons/netneighbor/48/network-gaming-keyboard.png new file mode 100644 index 00000000..031f051c Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/48/network-gaming-pc.png b/app/assets/icons/netneighbor/48/network-gaming-pc.png new file mode 100644 index 00000000..ea5b8625 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/48/network-hifi-amplifier.png b/app/assets/icons/netneighbor/48/network-hifi-amplifier.png new file mode 100644 index 00000000..7a38d4b8 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/48/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/48/network-hifi-stereo-system.png new file mode 100644 index 00000000..4b5fab93 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/48/network-home-appliance.png b/app/assets/icons/netneighbor/48/network-home-appliance.png new file mode 100644 index 00000000..b8c3b4d4 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/48/network-home-hub.png b/app/assets/icons/netneighbor/48/network-home-hub.png new file mode 100644 index 00000000..0a4b77da Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/48/network-home-server-tower.png b/app/assets/icons/netneighbor/48/network-home-server-tower.png new file mode 100644 index 00000000..491d863c Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/48/network-imac-display.png b/app/assets/icons/netneighbor/48/network-imac-display.png new file mode 100644 index 00000000..c8b16b3b Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/48/network-ip-camera.png b/app/assets/icons/netneighbor/48/network-ip-camera.png new file mode 100644 index 00000000..c4496172 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/48/network-ipad.png b/app/assets/icons/netneighbor/48/network-ipad.png new file mode 100644 index 00000000..873efb49 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/48/network-laptop-wifi.png b/app/assets/icons/netneighbor/48/network-laptop-wifi.png new file mode 100644 index 00000000..3e2f00e5 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/48/network-macmini-led.png b/app/assets/icons/netneighbor/48/network-macmini-led.png new file mode 100644 index 00000000..ca97d02f Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/48/network-macmini.png b/app/assets/icons/netneighbor/48/network-macmini.png new file mode 100644 index 00000000..d441f446 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/48/network-media-server.png b/app/assets/icons/netneighbor/48/network-media-server.png new file mode 100644 index 00000000..c2ac64d5 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/48/network-mesh-node.png b/app/assets/icons/netneighbor/48/network-mesh-node.png new file mode 100644 index 00000000..a0fe3be9 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/48/network-mfp-printer.png b/app/assets/icons/netneighbor/48/network-mfp-printer.png new file mode 100644 index 00000000..531ac1ec Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/48/network-mfp-v2.png b/app/assets/icons/netneighbor/48/network-mfp-v2.png new file mode 100644 index 00000000..72c21e21 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/48/network-microwave.png b/app/assets/icons/netneighbor/48/network-microwave.png new file mode 100644 index 00000000..221b2ce6 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/48/network-mini-pc-generic.png b/app/assets/icons/netneighbor/48/network-mini-pc-generic.png new file mode 100644 index 00000000..e945d40a Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/48/network-minicnc.png b/app/assets/icons/netneighbor/48/network-minicnc.png new file mode 100644 index 00000000..5a74010e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/48/network-monitor.png b/app/assets/icons/netneighbor/48/network-monitor.png new file mode 100644 index 00000000..d48b6cb1 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/48/network-motion-sensor.png b/app/assets/icons/netneighbor/48/network-motion-sensor.png new file mode 100644 index 00000000..1125544c Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/48/network-multi-functions-printer.png b/app/assets/icons/netneighbor/48/network-multi-functions-printer.png new file mode 100644 index 00000000..4eaaf054 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/48/network-nas.png b/app/assets/icons/netneighbor/48/network-nas.png new file mode 100644 index 00000000..454dc9bf Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-nas.png differ diff --git a/app/assets/icons/netneighbor/48/network-nvr-dvr.png b/app/assets/icons/netneighbor/48/network-nvr-dvr.png new file mode 100644 index 00000000..88ba3011 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/48/network-oven.png b/app/assets/icons/netneighbor/48/network-oven.png new file mode 100644 index 00000000..2e1f470a Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-oven.png differ diff --git a/app/assets/icons/netneighbor/48/network-portable-media-player.png b/app/assets/icons/netneighbor/48/network-portable-media-player.png new file mode 100644 index 00000000..278cdca5 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/48/network-printer.png b/app/assets/icons/netneighbor/48/network-printer.png new file mode 100644 index 00000000..6d78df45 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-printer.png differ diff --git a/app/assets/icons/netneighbor/48/network-rack-cabinet.png b/app/assets/icons/netneighbor/48/network-rack-cabinet.png new file mode 100644 index 00000000..44869c9c Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/48/network-rj45-plc.png b/app/assets/icons/netneighbor/48/network-rj45-plc.png new file mode 100644 index 00000000..98c98e55 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/48/network-robot-vacuum.png b/app/assets/icons/netneighbor/48/network-robot-vacuum.png new file mode 100644 index 00000000..c1b7eaa8 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/48/network-router-modem.png b/app/assets/icons/netneighbor/48/network-router-modem.png new file mode 100644 index 00000000..b9da0a65 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/48/network-scanner.png b/app/assets/icons/netneighbor/48/network-scanner.png new file mode 100644 index 00000000..199992fc Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/48/network-server.png b/app/assets/icons/netneighbor/48/network-server.png new file mode 100644 index 00000000..4f916f7e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-server.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-bulb.png b/app/assets/icons/netneighbor/48/network-smart-bulb.png new file mode 100644 index 00000000..adbf9db7 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-cabinet.png b/app/assets/icons/netneighbor/48/network-smart-cabinet.png new file mode 100644 index 00000000..e75c56a5 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-fridge.png b/app/assets/icons/netneighbor/48/network-smart-fridge.png new file mode 100644 index 00000000..28b60c50 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-glasses.png b/app/assets/icons/netneighbor/48/network-smart-glasses.png new file mode 100644 index 00000000..d3f304fb Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-lock.png b/app/assets/icons/netneighbor/48/network-smart-lock.png new file mode 100644 index 00000000..844f3232 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-plug.png b/app/assets/icons/netneighbor/48/network-smart-plug.png new file mode 100644 index 00000000..6b1eab19 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-speaker.png b/app/assets/icons/netneighbor/48/network-smart-speaker.png new file mode 100644 index 00000000..63b3d30a Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/48/network-smart-switch.png b/app/assets/icons/netneighbor/48/network-smart-switch.png new file mode 100644 index 00000000..fa2e9c3d Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/48/network-smartphone.png b/app/assets/icons/netneighbor/48/network-smartphone.png new file mode 100644 index 00000000..674cea16 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/48/network-smarttv.png b/app/assets/icons/netneighbor/48/network-smarttv.png new file mode 100644 index 00000000..d78df2fc Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/48/network-smartwatch.png b/app/assets/icons/netneighbor/48/network-smartwatch.png new file mode 100644 index 00000000..e2355abc Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/48/network-smoke-detector.png b/app/assets/icons/netneighbor/48/network-smoke-detector.png new file mode 100644 index 00000000..1243e889 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/48/network-soundbar.png b/app/assets/icons/netneighbor/48/network-soundbar.png new file mode 100644 index 00000000..44237a7f Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/48/network-stick-vacuum.png b/app/assets/icons/netneighbor/48/network-stick-vacuum.png new file mode 100644 index 00000000..7d1e19d1 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/48/network-switch.png b/app/assets/icons/netneighbor/48/network-switch.png new file mode 100644 index 00000000..ac2ff5be Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-switch.png differ diff --git a/app/assets/icons/netneighbor/48/network-thermostat.png b/app/assets/icons/netneighbor/48/network-thermostat.png new file mode 100644 index 00000000..23a07a1e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/48/network-touchscreen-panel.png b/app/assets/icons/netneighbor/48/network-touchscreen-panel.png new file mode 100644 index 00000000..5072dd2b Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/48/network-tv-media-player.png b/app/assets/icons/netneighbor/48/network-tv-media-player.png new file mode 100644 index 00000000..35eacfb1 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/48/network-unknown-device-v4.png b/app/assets/icons/netneighbor/48/network-unknown-device-v4.png new file mode 100644 index 00000000..559302dc Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/48/network-usb-drive.png b/app/assets/icons/netneighbor/48/network-usb-drive.png new file mode 100644 index 00000000..0c595a8e Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/48/network-video-doorbell.png b/app/assets/icons/netneighbor/48/network-video-doorbell.png new file mode 100644 index 00000000..7460a907 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/48/network-voip-phone.png b/app/assets/icons/netneighbor/48/network-voip-phone.png new file mode 100644 index 00000000..a4102bee Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/48/network-vr-headset.png b/app/assets/icons/netneighbor/48/network-vr-headset.png new file mode 100644 index 00000000..03373954 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/48/network-weather-station.png b/app/assets/icons/netneighbor/48/network-weather-station.png new file mode 100644 index 00000000..5f028941 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/48/network-webcam.png b/app/assets/icons/netneighbor/48/network-webcam.png new file mode 100644 index 00000000..41d4c966 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/48/network-webcam2.png b/app/assets/icons/netneighbor/48/network-webcam2.png new file mode 100644 index 00000000..d11d9e6d Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/48/network-wifi-ap.png b/app/assets/icons/netneighbor/48/network-wifi-ap.png new file mode 100644 index 00000000..ab497bc8 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/48/network-wifi-plc.png b/app/assets/icons/netneighbor/48/network-wifi-plc.png new file mode 100644 index 00000000..e6946886 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/48/network-wireless-mouse.png b/app/assets/icons/netneighbor/48/network-wireless-mouse.png new file mode 100644 index 00000000..de4dd6e2 Binary files /dev/null and b/app/assets/icons/netneighbor/48/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/512/network-3dprinter.png b/app/assets/icons/netneighbor/512/network-3dprinter.png new file mode 100644 index 00000000..2a3f16d5 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/512/network-action-camera.png b/app/assets/icons/netneighbor/512/network-action-camera.png new file mode 100644 index 00000000..dfc99b44 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/512/network-aio-pc.png b/app/assets/icons/netneighbor/512/network-aio-pc.png new file mode 100644 index 00000000..495dea25 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/512/network-air-conditioner.png b/app/assets/icons/netneighbor/512/network-air-conditioner.png new file mode 100644 index 00000000..540e33ca Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/512/network-airpurifier.png b/app/assets/icons/netneighbor/512/network-airpurifier.png new file mode 100644 index 00000000..7abb1644 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/512/network-alarm-hub.png b/app/assets/icons/netneighbor/512/network-alarm-hub.png new file mode 100644 index 00000000..83e8bd28 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/512/network-applewatch.png b/app/assets/icons/netneighbor/512/network-applewatch.png new file mode 100644 index 00000000..6905da5c Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/512/network-card-reader.png b/app/assets/icons/netneighbor/512/network-card-reader.png new file mode 100644 index 00000000..e4220a14 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/512/network-cloud-server.png b/app/assets/icons/netneighbor/512/network-cloud-server.png new file mode 100644 index 00000000..357f94a2 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/512/network-cnc-pendant.png b/app/assets/icons/netneighbor/512/network-cnc-pendant.png new file mode 100644 index 00000000..bbcf697c Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/512/network-desktop-pc.png b/app/assets/icons/netneighbor/512/network-desktop-pc.png new file mode 100644 index 00000000..a44470f9 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/512/network-dishwasher.png b/app/assets/icons/netneighbor/512/network-dishwasher.png new file mode 100644 index 00000000..032b2815 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/512/network-drawing-tablet.png b/app/assets/icons/netneighbor/512/network-drawing-tablet.png new file mode 100644 index 00000000..e578b334 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/512/network-drone.png b/app/assets/icons/netneighbor/512/network-drone.png new file mode 100644 index 00000000..ddd8ffd9 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-drone.png differ diff --git a/app/assets/icons/netneighbor/512/network-earbuds.png b/app/assets/icons/netneighbor/512/network-earbuds.png new file mode 100644 index 00000000..9a1735ab Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/512/network-external-hdd.png b/app/assets/icons/netneighbor/512/network-external-hdd.png new file mode 100644 index 00000000..e10dc860 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/512/network-firewall.png b/app/assets/icons/netneighbor/512/network-firewall.png new file mode 100644 index 00000000..4a2d9bff Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/512/network-gaming-console.png b/app/assets/icons/netneighbor/512/network-gaming-console.png new file mode 100644 index 00000000..bb916b92 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/512/network-gaming-headset.png b/app/assets/icons/netneighbor/512/network-gaming-headset.png new file mode 100644 index 00000000..052c1837 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/512/network-gaming-keyboard.png b/app/assets/icons/netneighbor/512/network-gaming-keyboard.png new file mode 100644 index 00000000..92d2aca2 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/512/network-gaming-pc.png b/app/assets/icons/netneighbor/512/network-gaming-pc.png new file mode 100644 index 00000000..1a6eede0 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/512/network-hifi-amplifier.png b/app/assets/icons/netneighbor/512/network-hifi-amplifier.png new file mode 100644 index 00000000..d76f50c9 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/512/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/512/network-hifi-stereo-system.png new file mode 100644 index 00000000..3cab0bd6 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/512/network-home-appliance.png b/app/assets/icons/netneighbor/512/network-home-appliance.png new file mode 100644 index 00000000..a54c78fb Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/512/network-home-hub.png b/app/assets/icons/netneighbor/512/network-home-hub.png new file mode 100644 index 00000000..4c16482d Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/512/network-home-server-tower.png b/app/assets/icons/netneighbor/512/network-home-server-tower.png new file mode 100644 index 00000000..d5b309ad Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/512/network-imac-display.png b/app/assets/icons/netneighbor/512/network-imac-display.png new file mode 100644 index 00000000..4dec2e8f Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/512/network-ip-camera.png b/app/assets/icons/netneighbor/512/network-ip-camera.png new file mode 100644 index 00000000..577c6a61 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/512/network-ipad.png b/app/assets/icons/netneighbor/512/network-ipad.png new file mode 100644 index 00000000..01dfdc91 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/512/network-laptop-wifi.png b/app/assets/icons/netneighbor/512/network-laptop-wifi.png new file mode 100644 index 00000000..29048baa Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/512/network-macmini-led.png b/app/assets/icons/netneighbor/512/network-macmini-led.png new file mode 100644 index 00000000..467f7b96 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/512/network-macmini.png b/app/assets/icons/netneighbor/512/network-macmini.png new file mode 100644 index 00000000..72026574 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/512/network-media-server.png b/app/assets/icons/netneighbor/512/network-media-server.png new file mode 100644 index 00000000..b4be8068 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/512/network-mesh-node.png b/app/assets/icons/netneighbor/512/network-mesh-node.png new file mode 100644 index 00000000..c6200745 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/512/network-mfp-printer.png b/app/assets/icons/netneighbor/512/network-mfp-printer.png new file mode 100644 index 00000000..a64015e0 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/512/network-mfp-v2.png b/app/assets/icons/netneighbor/512/network-mfp-v2.png new file mode 100644 index 00000000..a52c4610 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/512/network-microwave.png b/app/assets/icons/netneighbor/512/network-microwave.png new file mode 100644 index 00000000..8477676e Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/512/network-mini-pc-generic.png b/app/assets/icons/netneighbor/512/network-mini-pc-generic.png new file mode 100644 index 00000000..b388fb8b Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/512/network-minicnc.png b/app/assets/icons/netneighbor/512/network-minicnc.png new file mode 100644 index 00000000..4fe33c9c Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/512/network-monitor.png b/app/assets/icons/netneighbor/512/network-monitor.png new file mode 100644 index 00000000..b9bab396 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/512/network-motion-sensor.png b/app/assets/icons/netneighbor/512/network-motion-sensor.png new file mode 100644 index 00000000..70991898 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/512/network-multi-functions-printer.png b/app/assets/icons/netneighbor/512/network-multi-functions-printer.png new file mode 100644 index 00000000..1df5bb91 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/512/network-nas.png b/app/assets/icons/netneighbor/512/network-nas.png new file mode 100644 index 00000000..2bc7f955 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-nas.png differ diff --git a/app/assets/icons/netneighbor/512/network-nvr-dvr.png b/app/assets/icons/netneighbor/512/network-nvr-dvr.png new file mode 100644 index 00000000..2dc07731 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/512/network-oven.png b/app/assets/icons/netneighbor/512/network-oven.png new file mode 100644 index 00000000..3ec878e9 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-oven.png differ diff --git a/app/assets/icons/netneighbor/512/network-portable-media-player.png b/app/assets/icons/netneighbor/512/network-portable-media-player.png new file mode 100644 index 00000000..c639bbad Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/512/network-printer.png b/app/assets/icons/netneighbor/512/network-printer.png new file mode 100644 index 00000000..3b7752cc Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-printer.png differ diff --git a/app/assets/icons/netneighbor/512/network-rack-cabinet.png b/app/assets/icons/netneighbor/512/network-rack-cabinet.png new file mode 100644 index 00000000..1cdfc69d Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/512/network-rj45-plc.png b/app/assets/icons/netneighbor/512/network-rj45-plc.png new file mode 100644 index 00000000..058cde65 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/512/network-robot-vacuum.png b/app/assets/icons/netneighbor/512/network-robot-vacuum.png new file mode 100644 index 00000000..177810ec Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/512/network-router-modem.png b/app/assets/icons/netneighbor/512/network-router-modem.png new file mode 100644 index 00000000..56c9f84f Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/512/network-scanner.png b/app/assets/icons/netneighbor/512/network-scanner.png new file mode 100644 index 00000000..d8b79d7a Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/512/network-server.png b/app/assets/icons/netneighbor/512/network-server.png new file mode 100644 index 00000000..ce2171c3 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-server.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-bulb.png b/app/assets/icons/netneighbor/512/network-smart-bulb.png new file mode 100644 index 00000000..e6b53498 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-cabinet.png b/app/assets/icons/netneighbor/512/network-smart-cabinet.png new file mode 100644 index 00000000..c6269ecf Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-fridge.png b/app/assets/icons/netneighbor/512/network-smart-fridge.png new file mode 100644 index 00000000..4ac5a7e8 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-glasses.png b/app/assets/icons/netneighbor/512/network-smart-glasses.png new file mode 100644 index 00000000..ecd9618f Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-lock.png b/app/assets/icons/netneighbor/512/network-smart-lock.png new file mode 100644 index 00000000..e8d7bf39 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-plug.png b/app/assets/icons/netneighbor/512/network-smart-plug.png new file mode 100644 index 00000000..ca90fa7b Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-speaker.png b/app/assets/icons/netneighbor/512/network-smart-speaker.png new file mode 100644 index 00000000..a42c7f77 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/512/network-smart-switch.png b/app/assets/icons/netneighbor/512/network-smart-switch.png new file mode 100644 index 00000000..b8c646e6 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/512/network-smartphone.png b/app/assets/icons/netneighbor/512/network-smartphone.png new file mode 100644 index 00000000..223a4154 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/512/network-smarttv.png b/app/assets/icons/netneighbor/512/network-smarttv.png new file mode 100644 index 00000000..3d5bc16d Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/512/network-smartwatch.png b/app/assets/icons/netneighbor/512/network-smartwatch.png new file mode 100644 index 00000000..20a53e46 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/512/network-smoke-detector.png b/app/assets/icons/netneighbor/512/network-smoke-detector.png new file mode 100644 index 00000000..e4f11d28 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/512/network-soundbar.png b/app/assets/icons/netneighbor/512/network-soundbar.png new file mode 100644 index 00000000..bc67772e Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/512/network-stick-vacuum.png b/app/assets/icons/netneighbor/512/network-stick-vacuum.png new file mode 100644 index 00000000..bbeb65c6 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/512/network-switch.png b/app/assets/icons/netneighbor/512/network-switch.png new file mode 100644 index 00000000..e24becc5 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-switch.png differ diff --git a/app/assets/icons/netneighbor/512/network-thermostat.png b/app/assets/icons/netneighbor/512/network-thermostat.png new file mode 100644 index 00000000..d24ea315 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/512/network-touchscreen-panel.png b/app/assets/icons/netneighbor/512/network-touchscreen-panel.png new file mode 100644 index 00000000..9809c2fd Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/512/network-tv-media-player.png b/app/assets/icons/netneighbor/512/network-tv-media-player.png new file mode 100644 index 00000000..a446d3f0 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/512/network-unknown-device-v4.png b/app/assets/icons/netneighbor/512/network-unknown-device-v4.png new file mode 100644 index 00000000..533f323d Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/512/network-usb-drive.png b/app/assets/icons/netneighbor/512/network-usb-drive.png new file mode 100644 index 00000000..410c24e8 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/512/network-video-doorbell.png b/app/assets/icons/netneighbor/512/network-video-doorbell.png new file mode 100644 index 00000000..a7753f4f Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/512/network-voip-phone.png b/app/assets/icons/netneighbor/512/network-voip-phone.png new file mode 100644 index 00000000..2d9ae5e1 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/512/network-vr-headset.png b/app/assets/icons/netneighbor/512/network-vr-headset.png new file mode 100644 index 00000000..1affeda7 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/512/network-weather-station.png b/app/assets/icons/netneighbor/512/network-weather-station.png new file mode 100644 index 00000000..ff841ccd Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/512/network-webcam.png b/app/assets/icons/netneighbor/512/network-webcam.png new file mode 100644 index 00000000..da758d5c Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/512/network-webcam2.png b/app/assets/icons/netneighbor/512/network-webcam2.png new file mode 100644 index 00000000..b7e260f7 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/512/network-wifi-ap.png b/app/assets/icons/netneighbor/512/network-wifi-ap.png new file mode 100644 index 00000000..7dbe0293 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/512/network-wifi-plc.png b/app/assets/icons/netneighbor/512/network-wifi-plc.png new file mode 100644 index 00000000..55468eeb Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/512/network-wireless-mouse.png b/app/assets/icons/netneighbor/512/network-wireless-mouse.png new file mode 100644 index 00000000..139368c2 Binary files /dev/null and b/app/assets/icons/netneighbor/512/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/64/network-3dprinter.png b/app/assets/icons/netneighbor/64/network-3dprinter.png new file mode 100644 index 00000000..273f0262 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/64/network-action-camera.png b/app/assets/icons/netneighbor/64/network-action-camera.png new file mode 100644 index 00000000..1546da12 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/64/network-aio-pc.png b/app/assets/icons/netneighbor/64/network-aio-pc.png new file mode 100644 index 00000000..e4dcfd81 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/64/network-air-conditioner.png b/app/assets/icons/netneighbor/64/network-air-conditioner.png new file mode 100644 index 00000000..a5799bca Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/64/network-airpurifier.png b/app/assets/icons/netneighbor/64/network-airpurifier.png new file mode 100644 index 00000000..e22bd4dd Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/64/network-alarm-hub.png b/app/assets/icons/netneighbor/64/network-alarm-hub.png new file mode 100644 index 00000000..9a8fae1d Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/64/network-applewatch.png b/app/assets/icons/netneighbor/64/network-applewatch.png new file mode 100644 index 00000000..3f92b5cb Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/64/network-card-reader.png b/app/assets/icons/netneighbor/64/network-card-reader.png new file mode 100644 index 00000000..7b9b34fd Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/64/network-cloud-server.png b/app/assets/icons/netneighbor/64/network-cloud-server.png new file mode 100644 index 00000000..d388fbf3 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/64/network-cnc-pendant.png b/app/assets/icons/netneighbor/64/network-cnc-pendant.png new file mode 100644 index 00000000..b4f83563 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/64/network-desktop-pc.png b/app/assets/icons/netneighbor/64/network-desktop-pc.png new file mode 100644 index 00000000..fdf78aba Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/64/network-dishwasher.png b/app/assets/icons/netneighbor/64/network-dishwasher.png new file mode 100644 index 00000000..51621270 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/64/network-drawing-tablet.png b/app/assets/icons/netneighbor/64/network-drawing-tablet.png new file mode 100644 index 00000000..f213dbe3 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/64/network-drone.png b/app/assets/icons/netneighbor/64/network-drone.png new file mode 100644 index 00000000..9433d982 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-drone.png differ diff --git a/app/assets/icons/netneighbor/64/network-earbuds.png b/app/assets/icons/netneighbor/64/network-earbuds.png new file mode 100644 index 00000000..f33de8e7 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/64/network-external-hdd.png b/app/assets/icons/netneighbor/64/network-external-hdd.png new file mode 100644 index 00000000..e8ad7427 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/64/network-firewall.png b/app/assets/icons/netneighbor/64/network-firewall.png new file mode 100644 index 00000000..747b7350 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/64/network-gaming-console.png b/app/assets/icons/netneighbor/64/network-gaming-console.png new file mode 100644 index 00000000..a2bc79c0 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/64/network-gaming-headset.png b/app/assets/icons/netneighbor/64/network-gaming-headset.png new file mode 100644 index 00000000..1b45d9f3 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/64/network-gaming-keyboard.png b/app/assets/icons/netneighbor/64/network-gaming-keyboard.png new file mode 100644 index 00000000..20ab9f93 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/64/network-gaming-pc.png b/app/assets/icons/netneighbor/64/network-gaming-pc.png new file mode 100644 index 00000000..fb7d574a Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/64/network-hifi-amplifier.png b/app/assets/icons/netneighbor/64/network-hifi-amplifier.png new file mode 100644 index 00000000..4684c2ee Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/64/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/64/network-hifi-stereo-system.png new file mode 100644 index 00000000..b6571954 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/64/network-home-appliance.png b/app/assets/icons/netneighbor/64/network-home-appliance.png new file mode 100644 index 00000000..87fdd9b8 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/64/network-home-hub.png b/app/assets/icons/netneighbor/64/network-home-hub.png new file mode 100644 index 00000000..1b9364f0 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/64/network-home-server-tower.png b/app/assets/icons/netneighbor/64/network-home-server-tower.png new file mode 100644 index 00000000..8feef307 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/64/network-imac-display.png b/app/assets/icons/netneighbor/64/network-imac-display.png new file mode 100644 index 00000000..d217717b Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/64/network-ip-camera.png b/app/assets/icons/netneighbor/64/network-ip-camera.png new file mode 100644 index 00000000..1028f241 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/64/network-ipad.png b/app/assets/icons/netneighbor/64/network-ipad.png new file mode 100644 index 00000000..4fb069ae Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/64/network-laptop-wifi.png b/app/assets/icons/netneighbor/64/network-laptop-wifi.png new file mode 100644 index 00000000..b4b0562f Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/64/network-macmini-led.png b/app/assets/icons/netneighbor/64/network-macmini-led.png new file mode 100644 index 00000000..dbc407ea Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/64/network-macmini.png b/app/assets/icons/netneighbor/64/network-macmini.png new file mode 100644 index 00000000..93d32702 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/64/network-media-server.png b/app/assets/icons/netneighbor/64/network-media-server.png new file mode 100644 index 00000000..2d35a2e1 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/64/network-mesh-node.png b/app/assets/icons/netneighbor/64/network-mesh-node.png new file mode 100644 index 00000000..31ceaf3f Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/64/network-mfp-printer.png b/app/assets/icons/netneighbor/64/network-mfp-printer.png new file mode 100644 index 00000000..7872acd5 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/64/network-mfp-v2.png b/app/assets/icons/netneighbor/64/network-mfp-v2.png new file mode 100644 index 00000000..3bacaec0 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/64/network-microwave.png b/app/assets/icons/netneighbor/64/network-microwave.png new file mode 100644 index 00000000..99f0bbb8 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/64/network-mini-pc-generic.png b/app/assets/icons/netneighbor/64/network-mini-pc-generic.png new file mode 100644 index 00000000..aaba52b1 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/64/network-minicnc.png b/app/assets/icons/netneighbor/64/network-minicnc.png new file mode 100644 index 00000000..9d6d8373 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/64/network-monitor.png b/app/assets/icons/netneighbor/64/network-monitor.png new file mode 100644 index 00000000..2d67690f Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/64/network-motion-sensor.png b/app/assets/icons/netneighbor/64/network-motion-sensor.png new file mode 100644 index 00000000..270241ec Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/64/network-multi-functions-printer.png b/app/assets/icons/netneighbor/64/network-multi-functions-printer.png new file mode 100644 index 00000000..27c688f8 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/64/network-nas.png b/app/assets/icons/netneighbor/64/network-nas.png new file mode 100644 index 00000000..078e7b83 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-nas.png differ diff --git a/app/assets/icons/netneighbor/64/network-nvr-dvr.png b/app/assets/icons/netneighbor/64/network-nvr-dvr.png new file mode 100644 index 00000000..2d890bf7 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/64/network-oven.png b/app/assets/icons/netneighbor/64/network-oven.png new file mode 100644 index 00000000..68714c77 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-oven.png differ diff --git a/app/assets/icons/netneighbor/64/network-portable-media-player.png b/app/assets/icons/netneighbor/64/network-portable-media-player.png new file mode 100644 index 00000000..f3efbf1f Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/64/network-printer.png b/app/assets/icons/netneighbor/64/network-printer.png new file mode 100644 index 00000000..6184247d Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-printer.png differ diff --git a/app/assets/icons/netneighbor/64/network-rack-cabinet.png b/app/assets/icons/netneighbor/64/network-rack-cabinet.png new file mode 100644 index 00000000..c921a486 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/64/network-rj45-plc.png b/app/assets/icons/netneighbor/64/network-rj45-plc.png new file mode 100644 index 00000000..4c8897ed Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/64/network-robot-vacuum.png b/app/assets/icons/netneighbor/64/network-robot-vacuum.png new file mode 100644 index 00000000..4d353b4c Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/64/network-router-modem.png b/app/assets/icons/netneighbor/64/network-router-modem.png new file mode 100644 index 00000000..713cc7bf Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/64/network-scanner.png b/app/assets/icons/netneighbor/64/network-scanner.png new file mode 100644 index 00000000..be8a0540 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/64/network-server.png b/app/assets/icons/netneighbor/64/network-server.png new file mode 100644 index 00000000..695d9761 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-server.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-bulb.png b/app/assets/icons/netneighbor/64/network-smart-bulb.png new file mode 100644 index 00000000..b82f4cdb Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-cabinet.png b/app/assets/icons/netneighbor/64/network-smart-cabinet.png new file mode 100644 index 00000000..04dfe63a Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-fridge.png b/app/assets/icons/netneighbor/64/network-smart-fridge.png new file mode 100644 index 00000000..1fe1e4cf Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-glasses.png b/app/assets/icons/netneighbor/64/network-smart-glasses.png new file mode 100644 index 00000000..e73afb14 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-lock.png b/app/assets/icons/netneighbor/64/network-smart-lock.png new file mode 100644 index 00000000..d2490ea2 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-plug.png b/app/assets/icons/netneighbor/64/network-smart-plug.png new file mode 100644 index 00000000..466c7f60 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-speaker.png b/app/assets/icons/netneighbor/64/network-smart-speaker.png new file mode 100644 index 00000000..c0a7997c Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/64/network-smart-switch.png b/app/assets/icons/netneighbor/64/network-smart-switch.png new file mode 100644 index 00000000..0365f21e Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/64/network-smartphone.png b/app/assets/icons/netneighbor/64/network-smartphone.png new file mode 100644 index 00000000..1edbeb66 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/64/network-smarttv.png b/app/assets/icons/netneighbor/64/network-smarttv.png new file mode 100644 index 00000000..4f664b86 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/64/network-smartwatch.png b/app/assets/icons/netneighbor/64/network-smartwatch.png new file mode 100644 index 00000000..faf89d78 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/64/network-smoke-detector.png b/app/assets/icons/netneighbor/64/network-smoke-detector.png new file mode 100644 index 00000000..fa0eeab9 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/64/network-soundbar.png b/app/assets/icons/netneighbor/64/network-soundbar.png new file mode 100644 index 00000000..1f1bd5b3 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/64/network-stick-vacuum.png b/app/assets/icons/netneighbor/64/network-stick-vacuum.png new file mode 100644 index 00000000..0645d3bc Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/64/network-switch.png b/app/assets/icons/netneighbor/64/network-switch.png new file mode 100644 index 00000000..f4beb1b6 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-switch.png differ diff --git a/app/assets/icons/netneighbor/64/network-thermostat.png b/app/assets/icons/netneighbor/64/network-thermostat.png new file mode 100644 index 00000000..34a3f2e5 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/64/network-touchscreen-panel.png b/app/assets/icons/netneighbor/64/network-touchscreen-panel.png new file mode 100644 index 00000000..c8f74212 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/64/network-tv-media-player.png b/app/assets/icons/netneighbor/64/network-tv-media-player.png new file mode 100644 index 00000000..d284ecaf Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/64/network-unknown-device-v4.png b/app/assets/icons/netneighbor/64/network-unknown-device-v4.png new file mode 100644 index 00000000..c7404ec4 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/64/network-usb-drive.png b/app/assets/icons/netneighbor/64/network-usb-drive.png new file mode 100644 index 00000000..af307328 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/64/network-video-doorbell.png b/app/assets/icons/netneighbor/64/network-video-doorbell.png new file mode 100644 index 00000000..218aa037 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/64/network-voip-phone.png b/app/assets/icons/netneighbor/64/network-voip-phone.png new file mode 100644 index 00000000..f42b53c6 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/64/network-vr-headset.png b/app/assets/icons/netneighbor/64/network-vr-headset.png new file mode 100644 index 00000000..fc1ed614 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/64/network-weather-station.png b/app/assets/icons/netneighbor/64/network-weather-station.png new file mode 100644 index 00000000..f8cf8b36 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/64/network-webcam.png b/app/assets/icons/netneighbor/64/network-webcam.png new file mode 100644 index 00000000..1078e7e0 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/64/network-webcam2.png b/app/assets/icons/netneighbor/64/network-webcam2.png new file mode 100644 index 00000000..3a1fe9ae Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/64/network-wifi-ap.png b/app/assets/icons/netneighbor/64/network-wifi-ap.png new file mode 100644 index 00000000..abd6290c Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/64/network-wifi-plc.png b/app/assets/icons/netneighbor/64/network-wifi-plc.png new file mode 100644 index 00000000..51c83234 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/64/network-wireless-mouse.png b/app/assets/icons/netneighbor/64/network-wireless-mouse.png new file mode 100644 index 00000000..8b737818 Binary files /dev/null and b/app/assets/icons/netneighbor/64/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/96/network-3dprinter.png b/app/assets/icons/netneighbor/96/network-3dprinter.png new file mode 100644 index 00000000..7392b01c Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-3dprinter.png differ diff --git a/app/assets/icons/netneighbor/96/network-action-camera.png b/app/assets/icons/netneighbor/96/network-action-camera.png new file mode 100644 index 00000000..05fa1af2 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-action-camera.png differ diff --git a/app/assets/icons/netneighbor/96/network-aio-pc.png b/app/assets/icons/netneighbor/96/network-aio-pc.png new file mode 100644 index 00000000..068373ff Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-aio-pc.png differ diff --git a/app/assets/icons/netneighbor/96/network-air-conditioner.png b/app/assets/icons/netneighbor/96/network-air-conditioner.png new file mode 100644 index 00000000..c5ee1270 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-air-conditioner.png differ diff --git a/app/assets/icons/netneighbor/96/network-airpurifier.png b/app/assets/icons/netneighbor/96/network-airpurifier.png new file mode 100644 index 00000000..1f346e22 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-airpurifier.png differ diff --git a/app/assets/icons/netneighbor/96/network-alarm-hub.png b/app/assets/icons/netneighbor/96/network-alarm-hub.png new file mode 100644 index 00000000..df7837a0 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-alarm-hub.png differ diff --git a/app/assets/icons/netneighbor/96/network-applewatch.png b/app/assets/icons/netneighbor/96/network-applewatch.png new file mode 100644 index 00000000..62c74b4e Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-applewatch.png differ diff --git a/app/assets/icons/netneighbor/96/network-card-reader.png b/app/assets/icons/netneighbor/96/network-card-reader.png new file mode 100644 index 00000000..5e53f91c Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-card-reader.png differ diff --git a/app/assets/icons/netneighbor/96/network-cloud-server.png b/app/assets/icons/netneighbor/96/network-cloud-server.png new file mode 100644 index 00000000..c832621f Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-cloud-server.png differ diff --git a/app/assets/icons/netneighbor/96/network-cnc-pendant.png b/app/assets/icons/netneighbor/96/network-cnc-pendant.png new file mode 100644 index 00000000..78418ed3 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-cnc-pendant.png differ diff --git a/app/assets/icons/netneighbor/96/network-desktop-pc.png b/app/assets/icons/netneighbor/96/network-desktop-pc.png new file mode 100644 index 00000000..e3de540a Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-desktop-pc.png differ diff --git a/app/assets/icons/netneighbor/96/network-dishwasher.png b/app/assets/icons/netneighbor/96/network-dishwasher.png new file mode 100644 index 00000000..a62c2a8f Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-dishwasher.png differ diff --git a/app/assets/icons/netneighbor/96/network-drawing-tablet.png b/app/assets/icons/netneighbor/96/network-drawing-tablet.png new file mode 100644 index 00000000..00153072 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-drawing-tablet.png differ diff --git a/app/assets/icons/netneighbor/96/network-drone.png b/app/assets/icons/netneighbor/96/network-drone.png new file mode 100644 index 00000000..203884e2 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-drone.png differ diff --git a/app/assets/icons/netneighbor/96/network-earbuds.png b/app/assets/icons/netneighbor/96/network-earbuds.png new file mode 100644 index 00000000..2ff06738 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-earbuds.png differ diff --git a/app/assets/icons/netneighbor/96/network-external-hdd.png b/app/assets/icons/netneighbor/96/network-external-hdd.png new file mode 100644 index 00000000..07ea54e9 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-external-hdd.png differ diff --git a/app/assets/icons/netneighbor/96/network-firewall.png b/app/assets/icons/netneighbor/96/network-firewall.png new file mode 100644 index 00000000..08ece3de Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-firewall.png differ diff --git a/app/assets/icons/netneighbor/96/network-gaming-console.png b/app/assets/icons/netneighbor/96/network-gaming-console.png new file mode 100644 index 00000000..37150cbd Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-gaming-console.png differ diff --git a/app/assets/icons/netneighbor/96/network-gaming-headset.png b/app/assets/icons/netneighbor/96/network-gaming-headset.png new file mode 100644 index 00000000..e313a7a3 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-gaming-headset.png differ diff --git a/app/assets/icons/netneighbor/96/network-gaming-keyboard.png b/app/assets/icons/netneighbor/96/network-gaming-keyboard.png new file mode 100644 index 00000000..5c250230 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-gaming-keyboard.png differ diff --git a/app/assets/icons/netneighbor/96/network-gaming-pc.png b/app/assets/icons/netneighbor/96/network-gaming-pc.png new file mode 100644 index 00000000..791f6084 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-gaming-pc.png differ diff --git a/app/assets/icons/netneighbor/96/network-hifi-amplifier.png b/app/assets/icons/netneighbor/96/network-hifi-amplifier.png new file mode 100644 index 00000000..9b66cca5 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-hifi-amplifier.png differ diff --git a/app/assets/icons/netneighbor/96/network-hifi-stereo-system.png b/app/assets/icons/netneighbor/96/network-hifi-stereo-system.png new file mode 100644 index 00000000..3e4bef18 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-hifi-stereo-system.png differ diff --git a/app/assets/icons/netneighbor/96/network-home-appliance.png b/app/assets/icons/netneighbor/96/network-home-appliance.png new file mode 100644 index 00000000..f1efb405 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-home-appliance.png differ diff --git a/app/assets/icons/netneighbor/96/network-home-hub.png b/app/assets/icons/netneighbor/96/network-home-hub.png new file mode 100644 index 00000000..6bb7f633 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-home-hub.png differ diff --git a/app/assets/icons/netneighbor/96/network-home-server-tower.png b/app/assets/icons/netneighbor/96/network-home-server-tower.png new file mode 100644 index 00000000..dd07edd8 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-home-server-tower.png differ diff --git a/app/assets/icons/netneighbor/96/network-imac-display.png b/app/assets/icons/netneighbor/96/network-imac-display.png new file mode 100644 index 00000000..efef1cb8 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-imac-display.png differ diff --git a/app/assets/icons/netneighbor/96/network-ip-camera.png b/app/assets/icons/netneighbor/96/network-ip-camera.png new file mode 100644 index 00000000..d6699e3f Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-ip-camera.png differ diff --git a/app/assets/icons/netneighbor/96/network-ipad.png b/app/assets/icons/netneighbor/96/network-ipad.png new file mode 100644 index 00000000..75fce79a Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-ipad.png differ diff --git a/app/assets/icons/netneighbor/96/network-laptop-wifi.png b/app/assets/icons/netneighbor/96/network-laptop-wifi.png new file mode 100644 index 00000000..e1d1142e Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-laptop-wifi.png differ diff --git a/app/assets/icons/netneighbor/96/network-macmini-led.png b/app/assets/icons/netneighbor/96/network-macmini-led.png new file mode 100644 index 00000000..a160565c Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-macmini-led.png differ diff --git a/app/assets/icons/netneighbor/96/network-macmini.png b/app/assets/icons/netneighbor/96/network-macmini.png new file mode 100644 index 00000000..696b1df8 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-macmini.png differ diff --git a/app/assets/icons/netneighbor/96/network-media-server.png b/app/assets/icons/netneighbor/96/network-media-server.png new file mode 100644 index 00000000..44cf5977 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-media-server.png differ diff --git a/app/assets/icons/netneighbor/96/network-mesh-node.png b/app/assets/icons/netneighbor/96/network-mesh-node.png new file mode 100644 index 00000000..0acc7f5b Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-mesh-node.png differ diff --git a/app/assets/icons/netneighbor/96/network-mfp-printer.png b/app/assets/icons/netneighbor/96/network-mfp-printer.png new file mode 100644 index 00000000..c32fcd3e Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-mfp-printer.png differ diff --git a/app/assets/icons/netneighbor/96/network-mfp-v2.png b/app/assets/icons/netneighbor/96/network-mfp-v2.png new file mode 100644 index 00000000..e08163de Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-mfp-v2.png differ diff --git a/app/assets/icons/netneighbor/96/network-microwave.png b/app/assets/icons/netneighbor/96/network-microwave.png new file mode 100644 index 00000000..44ff273a Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-microwave.png differ diff --git a/app/assets/icons/netneighbor/96/network-mini-pc-generic.png b/app/assets/icons/netneighbor/96/network-mini-pc-generic.png new file mode 100644 index 00000000..23e4e881 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-mini-pc-generic.png differ diff --git a/app/assets/icons/netneighbor/96/network-minicnc.png b/app/assets/icons/netneighbor/96/network-minicnc.png new file mode 100644 index 00000000..43dfc1a5 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-minicnc.png differ diff --git a/app/assets/icons/netneighbor/96/network-monitor.png b/app/assets/icons/netneighbor/96/network-monitor.png new file mode 100644 index 00000000..74c11907 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-monitor.png differ diff --git a/app/assets/icons/netneighbor/96/network-motion-sensor.png b/app/assets/icons/netneighbor/96/network-motion-sensor.png new file mode 100644 index 00000000..0399ffe8 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-motion-sensor.png differ diff --git a/app/assets/icons/netneighbor/96/network-multi-functions-printer.png b/app/assets/icons/netneighbor/96/network-multi-functions-printer.png new file mode 100644 index 00000000..829cf3e5 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-multi-functions-printer.png differ diff --git a/app/assets/icons/netneighbor/96/network-nas.png b/app/assets/icons/netneighbor/96/network-nas.png new file mode 100644 index 00000000..5aafa04a Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-nas.png differ diff --git a/app/assets/icons/netneighbor/96/network-nvr-dvr.png b/app/assets/icons/netneighbor/96/network-nvr-dvr.png new file mode 100644 index 00000000..e08e78d0 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-nvr-dvr.png differ diff --git a/app/assets/icons/netneighbor/96/network-oven.png b/app/assets/icons/netneighbor/96/network-oven.png new file mode 100644 index 00000000..6ca122be Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-oven.png differ diff --git a/app/assets/icons/netneighbor/96/network-portable-media-player.png b/app/assets/icons/netneighbor/96/network-portable-media-player.png new file mode 100644 index 00000000..20318c7b Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-portable-media-player.png differ diff --git a/app/assets/icons/netneighbor/96/network-printer.png b/app/assets/icons/netneighbor/96/network-printer.png new file mode 100644 index 00000000..900b2475 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-printer.png differ diff --git a/app/assets/icons/netneighbor/96/network-rack-cabinet.png b/app/assets/icons/netneighbor/96/network-rack-cabinet.png new file mode 100644 index 00000000..5c4470a2 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-rack-cabinet.png differ diff --git a/app/assets/icons/netneighbor/96/network-rj45-plc.png b/app/assets/icons/netneighbor/96/network-rj45-plc.png new file mode 100644 index 00000000..e1abcb73 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-rj45-plc.png differ diff --git a/app/assets/icons/netneighbor/96/network-robot-vacuum.png b/app/assets/icons/netneighbor/96/network-robot-vacuum.png new file mode 100644 index 00000000..198f2f29 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-robot-vacuum.png differ diff --git a/app/assets/icons/netneighbor/96/network-router-modem.png b/app/assets/icons/netneighbor/96/network-router-modem.png new file mode 100644 index 00000000..c4c3f475 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-router-modem.png differ diff --git a/app/assets/icons/netneighbor/96/network-scanner.png b/app/assets/icons/netneighbor/96/network-scanner.png new file mode 100644 index 00000000..478307cc Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-scanner.png differ diff --git a/app/assets/icons/netneighbor/96/network-server.png b/app/assets/icons/netneighbor/96/network-server.png new file mode 100644 index 00000000..c3329da2 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-server.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-bulb.png b/app/assets/icons/netneighbor/96/network-smart-bulb.png new file mode 100644 index 00000000..d44fb32b Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-bulb.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-cabinet.png b/app/assets/icons/netneighbor/96/network-smart-cabinet.png new file mode 100644 index 00000000..773bb442 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-cabinet.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-fridge.png b/app/assets/icons/netneighbor/96/network-smart-fridge.png new file mode 100644 index 00000000..e605f32b Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-fridge.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-glasses.png b/app/assets/icons/netneighbor/96/network-smart-glasses.png new file mode 100644 index 00000000..2fa1d9d4 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-glasses.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-lock.png b/app/assets/icons/netneighbor/96/network-smart-lock.png new file mode 100644 index 00000000..d3535251 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-lock.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-plug.png b/app/assets/icons/netneighbor/96/network-smart-plug.png new file mode 100644 index 00000000..cabcca2e Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-plug.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-speaker.png b/app/assets/icons/netneighbor/96/network-smart-speaker.png new file mode 100644 index 00000000..8ec079f1 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-speaker.png differ diff --git a/app/assets/icons/netneighbor/96/network-smart-switch.png b/app/assets/icons/netneighbor/96/network-smart-switch.png new file mode 100644 index 00000000..5ebdf9d0 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smart-switch.png differ diff --git a/app/assets/icons/netneighbor/96/network-smartphone.png b/app/assets/icons/netneighbor/96/network-smartphone.png new file mode 100644 index 00000000..bdd18477 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smartphone.png differ diff --git a/app/assets/icons/netneighbor/96/network-smarttv.png b/app/assets/icons/netneighbor/96/network-smarttv.png new file mode 100644 index 00000000..90bf5f3c Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smarttv.png differ diff --git a/app/assets/icons/netneighbor/96/network-smartwatch.png b/app/assets/icons/netneighbor/96/network-smartwatch.png new file mode 100644 index 00000000..bf383a9e Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smartwatch.png differ diff --git a/app/assets/icons/netneighbor/96/network-smoke-detector.png b/app/assets/icons/netneighbor/96/network-smoke-detector.png new file mode 100644 index 00000000..d03ad8ba Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-smoke-detector.png differ diff --git a/app/assets/icons/netneighbor/96/network-soundbar.png b/app/assets/icons/netneighbor/96/network-soundbar.png new file mode 100644 index 00000000..0a619cd4 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-soundbar.png differ diff --git a/app/assets/icons/netneighbor/96/network-stick-vacuum.png b/app/assets/icons/netneighbor/96/network-stick-vacuum.png new file mode 100644 index 00000000..fb7f2943 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-stick-vacuum.png differ diff --git a/app/assets/icons/netneighbor/96/network-switch.png b/app/assets/icons/netneighbor/96/network-switch.png new file mode 100644 index 00000000..34741918 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-switch.png differ diff --git a/app/assets/icons/netneighbor/96/network-thermostat.png b/app/assets/icons/netneighbor/96/network-thermostat.png new file mode 100644 index 00000000..c89c0fff Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-thermostat.png differ diff --git a/app/assets/icons/netneighbor/96/network-touchscreen-panel.png b/app/assets/icons/netneighbor/96/network-touchscreen-panel.png new file mode 100644 index 00000000..8502cb46 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-touchscreen-panel.png differ diff --git a/app/assets/icons/netneighbor/96/network-tv-media-player.png b/app/assets/icons/netneighbor/96/network-tv-media-player.png new file mode 100644 index 00000000..21a6eb70 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-tv-media-player.png differ diff --git a/app/assets/icons/netneighbor/96/network-unknown-device-v4.png b/app/assets/icons/netneighbor/96/network-unknown-device-v4.png new file mode 100644 index 00000000..2c0b1d39 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-unknown-device-v4.png differ diff --git a/app/assets/icons/netneighbor/96/network-usb-drive.png b/app/assets/icons/netneighbor/96/network-usb-drive.png new file mode 100644 index 00000000..8fe2abb4 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-usb-drive.png differ diff --git a/app/assets/icons/netneighbor/96/network-video-doorbell.png b/app/assets/icons/netneighbor/96/network-video-doorbell.png new file mode 100644 index 00000000..4f8f1439 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-video-doorbell.png differ diff --git a/app/assets/icons/netneighbor/96/network-voip-phone.png b/app/assets/icons/netneighbor/96/network-voip-phone.png new file mode 100644 index 00000000..bf50a1ad Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-voip-phone.png differ diff --git a/app/assets/icons/netneighbor/96/network-vr-headset.png b/app/assets/icons/netneighbor/96/network-vr-headset.png new file mode 100644 index 00000000..6adefb22 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-vr-headset.png differ diff --git a/app/assets/icons/netneighbor/96/network-weather-station.png b/app/assets/icons/netneighbor/96/network-weather-station.png new file mode 100644 index 00000000..cfa43123 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-weather-station.png differ diff --git a/app/assets/icons/netneighbor/96/network-webcam.png b/app/assets/icons/netneighbor/96/network-webcam.png new file mode 100644 index 00000000..17c6382f Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-webcam.png differ diff --git a/app/assets/icons/netneighbor/96/network-webcam2.png b/app/assets/icons/netneighbor/96/network-webcam2.png new file mode 100644 index 00000000..9401888b Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-webcam2.png differ diff --git a/app/assets/icons/netneighbor/96/network-wifi-ap.png b/app/assets/icons/netneighbor/96/network-wifi-ap.png new file mode 100644 index 00000000..e5917812 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-wifi-ap.png differ diff --git a/app/assets/icons/netneighbor/96/network-wifi-plc.png b/app/assets/icons/netneighbor/96/network-wifi-plc.png new file mode 100644 index 00000000..f02baa12 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-wifi-plc.png differ diff --git a/app/assets/icons/netneighbor/96/network-wireless-mouse.png b/app/assets/icons/netneighbor/96/network-wireless-mouse.png new file mode 100644 index 00000000..6b3603b5 Binary files /dev/null and b/app/assets/icons/netneighbor/96/network-wireless-mouse.png differ diff --git a/app/assets/icons/netneighbor/README.txt b/app/assets/icons/netneighbor/README.txt new file mode 100644 index 00000000..5e47442d --- /dev/null +++ b/app/assets/icons/netneighbor/README.txt @@ -0,0 +1,19 @@ +Bundled device-type icons (all platforms) +========================================== + +Place PNGs under square folders named ``NxN`` (e.g. ``1024x1024``, ``64x64``, +``16x16``). Subfolder names are discovered automatically; any ladder of sizes +works. + +Basenames used per device **type** are defined in **``config/icons.json``** +(ordered fallback list per slug). GTK and Qt read the same file; optional user +overlay: ``~/.config/netneighbor/icons.json`` (same ``types`` shape). + +Example:: + + netneighbor/512x512/printer-network.png + netneighbor/64x64/printer-network.png + +Optional: flat ``.png`` or ``.svg`` in this directory. + +User-selected icons: ``~/.config/netneighbor/custom_icons/*.png`` (see app docs). diff --git a/app/assets/icons/netneighbor/iconpack.json b/app/assets/icons/netneighbor/iconpack.json new file mode 100644 index 00000000..f31b501b --- /dev/null +++ b/app/assets/icons/netneighbor/iconpack.json @@ -0,0 +1,9 @@ +{ +'name' : 'Metalic Grey', +'owner' : 'Luc Lebosse', +'resolutions' : '16,22,32,48,64,96,128,256,512,1024', +'version' : '1.0', +'date' : '2026-05-19', +'repository' : 'https://github.com/luc-github/NetNeighbor/icons_packs/win11fluent', +'license' : 'lgpl3' +} diff --git a/app/assets/icons/netneighbor/icons.md b/app/assets/icons/netneighbor/icons.md new file mode 100644 index 00000000..232cb66f --- /dev/null +++ b/app/assets/icons/netneighbor/icons.md @@ -0,0 +1,29 @@ + + +|Type|image| +|-|-| +|camera|camera-photo.png| +|cnc|| +|computer|computer.png| +|esp32|hardware.png| +|homeappliance|network\_local.png| +|http|nfs.png| +|mediaserver|network\_local.png + package\_multimedia.png| +|multifunction\_printer|network\_local.png + printer.png + scanner.png
| +|networkprinter|
network\_local.png + printer2.png| +|printer|printer.png| +|scanner|scanner.png| +|nas|network\_local.png| +|3dprinter|| +|router|nertwork-server.png| +|smartdevice|multimedia-player.png| +|smartspeaker|| +|smarttv|tv.png| +|unknown|| +|laptop|computer-laptop.png| +|server|network-wired.png | +|modem|modem.png| +|phone|sms.png| + + + diff --git a/app/assets/icons/netneighbor/preview.png b/app/assets/icons/netneighbor/preview.png new file mode 100644 index 00000000..d57fb231 Binary files /dev/null and b/app/assets/icons/netneighbor/preview.png differ diff --git a/app/assets/spinner/spinner-0.svg b/app/assets/spinner/spinner-0.svg new file mode 100644 index 00000000..000ec895 --- /dev/null +++ b/app/assets/spinner/spinner-0.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-1.svg b/app/assets/spinner/spinner-1.svg new file mode 100644 index 00000000..cc7ca480 --- /dev/null +++ b/app/assets/spinner/spinner-1.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-2.svg b/app/assets/spinner/spinner-2.svg new file mode 100644 index 00000000..f2a2d657 --- /dev/null +++ b/app/assets/spinner/spinner-2.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-3.svg b/app/assets/spinner/spinner-3.svg new file mode 100644 index 00000000..2296f1df --- /dev/null +++ b/app/assets/spinner/spinner-3.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-4.svg b/app/assets/spinner/spinner-4.svg new file mode 100644 index 00000000..b40d6fee --- /dev/null +++ b/app/assets/spinner/spinner-4.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-5.svg b/app/assets/spinner/spinner-5.svg new file mode 100644 index 00000000..000ec895 --- /dev/null +++ b/app/assets/spinner/spinner-5.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-6.svg b/app/assets/spinner/spinner-6.svg new file mode 100644 index 00000000..e3a9b065 --- /dev/null +++ b/app/assets/spinner/spinner-6.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-7.svg b/app/assets/spinner/spinner-7.svg new file mode 100644 index 00000000..b40d6fee --- /dev/null +++ b/app/assets/spinner/spinner-7.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-8.svg b/app/assets/spinner/spinner-8.svg new file mode 100644 index 00000000..41e5bb9f --- /dev/null +++ b/app/assets/spinner/spinner-8.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/assets/spinner/spinner-9.svg b/app/assets/spinner/spinner-9.svg new file mode 100644 index 00000000..1121373f --- /dev/null +++ b/app/assets/spinner/spinner-9.svg @@ -0,0 +1,39 @@ + + Logo NetNeightbor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/svg/netneighbor-tray-symbolic.svg b/app/assets/svg/netneighbor-tray-symbolic.svg similarity index 100% rename from assets/svg/netneighbor-tray-symbolic.svg rename to app/assets/svg/netneighbor-tray-symbolic.svg diff --git a/assets/svg/netneighbor-tray.svg b/app/assets/svg/netneighbor-tray.svg similarity index 100% rename from assets/svg/netneighbor-tray.svg rename to app/assets/svg/netneighbor-tray.svg diff --git a/app/assets/svg/netneighbor.ico b/app/assets/svg/netneighbor.ico new file mode 100644 index 00000000..5c032f0f Binary files /dev/null and b/app/assets/svg/netneighbor.ico differ diff --git a/assets/svg/netneighbor_icon.svg b/app/assets/svg/netneighbor_icon.svg similarity index 100% rename from assets/svg/netneighbor_icon.svg rename to app/assets/svg/netneighbor_icon.svg diff --git a/app/config/default_commands.json b/app/config/default_commands.json new file mode 100644 index 00000000..ee67c1a0 --- /dev/null +++ b/app/config/default_commands.json @@ -0,0 +1,34 @@ +{ + "version": 2, + "comment": "Per-OS defaults for Tools / External applications (scheme to command). Placeholders: {ip} {port} {name} {type} {category} {url}. A template of just {url} opens the full discovered URL (port + path) with the system default handler. localsmb:// (WNetAddConnection2) and localhttp://, localhttps:// are Windows-native pseudo-schemes opened via ShellExecute (no console flash) — append :{port} to override the port. localspotify: opens the Spotify desktop app when installed, otherwise the web player (any OS).", + "linux": { + "http": "xdg-open {url}", + "https": "xdg-open {url}", + "smb": "nemo smb://{ip}", + "ftp": "nemo ftp://{ip}", + "ssh": "x-terminal-emulator -e ssh -p {port} {ip}", + "telnet": "x-terminal-emulator -e nc {ip} {port}", + "sftp": "nemo sftp://{ip}", + "spotify": "localspotify:" + }, + "darwin": { + "http": "open {url}", + "https": "open {url}", + "smb": "open smb://{ip}", + "ftp": "open ftp://{ip}", + "ssh": "open ssh://{ip}:{port}", + "telnet": "open telnet://{ip}:{port}", + "sftp": "open sftp://{ip}", + "spotify": "localspotify:" + }, + "win32": { + "http": "{url}", + "https": "{url}", + "smb": "localsmb://{ip}", + "ftp": "localftp://{ip}", + "ssh": "cmd.exe /k ssh -p {port} {ip}", + "telnet": "cmd.exe /k telnet {ip} {port}", + "sftp": "localsftp://{ip}", + "spotify": "localspotify:" + } +} diff --git a/data/device_types.json b/app/config/device_types.json similarity index 93% rename from data/device_types.json rename to app/config/device_types.json index 0a9a4aad..db1146e0 100644 --- a/data/device_types.json +++ b/app/config/device_types.json @@ -30,6 +30,13 @@ "default_port": 445, "info_url": null }, + "_device-info._tcp": { + "label": "Device info", + "category": "Unknown Devices", + "icon": "unknown.png", + "default_port": 0, + "info_url": null + }, "_airplay._tcp": { "label": "AirPlay Speaker", "category": "Smart Speakers", diff --git a/app/config/discovery.json b/app/config/discovery.json new file mode 100644 index 00000000..26fe3fbf --- /dev/null +++ b/app/config/discovery.json @@ -0,0 +1,68 @@ +{ + "mdns": { + "enabled": true, + "query": { + "enumeration_interval_seconds": 240, + "enumeration_timeout_seconds": 2.5, + "service_info_timeout_ms": 2500 + }, + "rules": true + }, + "merge": { + "information_precedence": [ + "user_override", + "ssdp_live", + "ssdp_profile_cache", + "mdns", + "nmb_live", + "wsdd_live", + "wsd_live" + ], + "protocol_order": [ + "ssdp", + "wsd", + "wsdd", + "nmb", + "mdns" + ], + "show_ip_in_device_list": true + }, + "nmb": { + "enabled": true, + "query": { + "argv": [ + "-S", + "*" + ], + "interval_seconds": 60.0, + "timeout_seconds": 10.0 + } + }, + "ssdp": { + "enabled": true, + "query": { + "descriptor_http_min_interval_seconds": 5.0, + "interval_seconds": 60, + "msearch_directed_ips": [], + "mx_seconds": 5 + }, + "rules": true + }, + "startup_refresh_seconds": "5, 15, 30, 60, 120, 300, 600", + "wsd": { + "enabled": true, + "query": { + "interval_seconds": 90.0, + "timeout_seconds": 8.0 + } + }, + "wsdd": { + "enabled": true, + "query": { + "interval_seconds": 60.0, + "listen": "", + "probe_each_poll": true, + "socket_timeout_seconds": 4.0 + } + } +} diff --git a/app/config/icons.json b/app/config/icons.json new file mode 100644 index 00000000..fa292b67 --- /dev/null +++ b/app/config/icons.json @@ -0,0 +1,31 @@ +{ + "version": 1, + "comment": "Per device-type slug: ordered list of PNG basenames WITHOUT the .png suffix (e.g. printer -> netneighbor/64x64/printer.png). Same stem for each discovered size folder under assets/icons/netneighbor/. User overlay may write either stem or full stem.png. No system icons.", + "types": { + "3dprinter": ["network-3dprinter"], + "camera": ["network-webcam"], + "cnc": ["network-minicnc"], + "computer": ["network-desktop-pc", "network-gaming-pc", "network-laptop-wifi"], + "esp32": ["network-touchscreen-panel"], + "homeappliance": ["network-home-appliance"], + "http": ["network-cloud-server"], + "mediaserver": ["network-media-server"], + "multifunction_printer": ["network-mfp-v2"], + "nas": ["network-nas"], + "networkprinter": ["network-printer"], + "printer": ["network-scanner"], + "router": ["network-home-server-tower"], + "scanner": ["network-scanner"], + "server": ["network-home-server-tower"], + "rackserver": ["network-server"], + "desktop": ["network-desktop-pc"], + "minipc": ["network-macmini", "network-mini-pc-generic"], + "allinone": ["network-imac-display", "network-aio-pc"], + "laptop": ["network-laptop-wifi"], + "smartdevice": ["network-mesh-node"], + "smartphone": ["network-smartphone"], + "smartspeaker": ["network-smart-speaker"], + "smarttv": ["network-smarttv"], + "unknown": ["network-unknown-device-v4"] + } +} diff --git a/app/config/logging.json b/app/config/logging.json new file mode 100644 index 00000000..30774a9b --- /dev/null +++ b/app/config/logging.json @@ -0,0 +1,12 @@ +{ + "app": "NONE", + "app_qt": "NONE", + "default": "NONE", + "device_list": "NONE", + "mdns": "NONE", + "nmb": "NONE", + "ssdp": "NONE", + "ui": "NONE", + "wsd": "NONE", + "wsdd": "NONE" +} diff --git a/app/config/mdns_rules.json b/app/config/mdns_rules.json new file mode 100644 index 00000000..2869cc7e --- /dev/null +++ b/app/config/mdns_rules.json @@ -0,0 +1,128 @@ +{ + "summary_from_txt": [ + { + "label": "Manufacturer", + "keys": ["mfg", "manufacturer", "make"] + }, + { + "label": "Model", + "keys": ["mdl", "model", "product"] + } + ], + "type_rules": [ + { + "contains_any": [ + "model=rackmac", + "type=rackserver" + ], + "type": "rackserver" + }, + { + "contains_any": [ + "model=server", + "model=xserve", + "type=server" + ], + "type": "server" + }, + { + "contains_any": [ + "model=nas", + "type=nas" + ], + "type": "nas" + }, + { + "contains_any": [ + "model=macpro", + "type=desktop" + ], + "type": "desktop" + }, + { + "contains_any": [ + "model=macmini", + "type=minipc" + ], + "type": "minipc" + }, + { + "contains_any": [ + "model=imac", + "type=allinone" + ], + "type": "allinone" + }, + { + "contains_any": [ + "model=macbook", + "type=laptop" + ], + "type": "laptop" + }, + { + "contains_any": [ + "_nearbypresence._tcp", + "target=android_", + "model=iphone", + "rpmd=iphone", + "type=smartphone" + ], + "type": "smartphone" + }, + { + "_doc": "Google Cast TXT md= (model): TVs and TV dongles (e.g. md=Aquos-TVT23C, md=BRAVIA 4K, md=Chromecast) but not Chromecast Audio / Nest speakers.", + "contains_any": [ + "type=smarttv" + ], + "matches_any": [ + "\\bmd=[^=]*tv", + "\\bmd=[^=]*bravia", + "\\bmd=chromecast(?! audio)" + ], + "type": "smarttv" + }, + { + "contains_any": [ + "laserjet" + ], + "type": "networkprinter" + }, + { + "contains_any": [ + "grbl", + "fluidnc", + "_cnc._tcp", + "laser", + "milling", + "cutter" + ], + "type": "cnc" + }, + { + "contains_any": [ + "marlin", + "repetier", + "smoothieware", + "klipper", + "octoprint", + "_octoprint._tcp", + "_klipper._tcp", + "prusa", + "bambu", + "ultimaker", + "3dprinter", + "3d printer" + ], + "type": "3dprinter" + }, + { + "contains_any": [ + "synology", + "qnap", + "nas" + ], + "type": "nas" + } + ] +} diff --git a/app/config/ssdp_rules.json b/app/config/ssdp_rules.json new file mode 100644 index 00000000..bf3a7a4e --- /dev/null +++ b/app/config/ssdp_rules.json @@ -0,0 +1,186 @@ +{ + "name_rules": { + "fallback_fields": [ + "friendlyName", + "displayName" + ], + "prefer_display_name_when_no_friendly_name": true + }, + "information_rules": { + "concat_fields": [ + "roomName", + "displayName" + ], + "separator": " / " + }, + "type_rules": [ + { + "contains_any": [ + "smartspeaker-audio", + "sonos" + ], + "type": "smartspeaker" + }, + { + "contains_any": [ + "dial-multiscreen", + "chromecast", + "googletv", + "android tv" + ], + "type": "smarttv" + }, + { + "contains_any": [ + "camera", + "onvif", + "ipcam", + "surveillance" + ], + "type": "camera" + }, + { + "contains_any": [ + "washer", + "dryer", + "refrigerator", + "oven", + "dishwasher", + "home appliance" + ], + "type": "homeappliance" + }, + { + "contains_any": [ + "cnc", + "grbl", + "fluidnc", + "laser", + "milling", + "cutter" + ], + "type": "cnc" + }, + { + "contains_any": [ + "3d printer", + "3dprinter", + "repetier", + "marlin", + "smoothieware", + "klipper", + "octoprint", + "ultimaker", + "prusa", + "bambu" + ], + "type": "3dprinter" + }, + { + "_comment": "ESP3D fallback: an ESP3D controller (friendlyName 'esp3d' or modelNumber 'ESP3D x.x') with no machine-specific keyword above stays an ESP3D Device rather than 'unknown'. Placed after cnc/3dprinter so a configured target wins.", + "contains_any": [ + "esp3d" + ], + "type": "esp32" + }, + { + "contains_any": [ + "iot", + "smart device", + "smartdevice" + ], + "type": "smartdevice" + }, + { + "contains_any": [ + "printer-network", + "ipp", + "ipps", + "airprint", + "network printer", + "print service", + "urn:schemas-upnp-org:device:printer" + ], + "type": "networkprinter" + }, + { + "contains_any": [ + "wifialliance", + "wfadevice", + "wfawlanconfig" + ], + "type": "router" + }, + { + "contains_any": [ + "synology", + "qnap", + "nas" + ], + "type": "nas" + } + ], + "_base_type_rules_doc": "Coarse fallbacks, evaluated by _infer_type against a NARROW haystack (ST/USN/SERVER/modelName/manufacturer only — NOT friendly/room names) so loose tokens like 'wan' don't match free-form device names. These fire only when no curated type_rules above matched. modelType==nas is exact and first so a DLNA-capable NAS stays 'nas'.", + "base_type_rules": [ + { + "equals_field": { + "modelType": [ + "nas" + ] + }, + "type": "nas" + }, + { + "contains_any": [ + "sonos" + ], + "type": "mediaserver" + }, + { + "contains_any": [ + "mediaserver", + "contentdirectory", + "mediarenderer", + "dial-multiscreen", + "urn:dial-multiscreen-org:service:dial", + "googletv", + "android tv", + "chromecast" + ], + "type": "mediaserver" + }, + { + "contains_any": [ + "wan", + "internetgatewaydevice", + "router", + "gateway", + "wifialliance", + "wfadevice", + "wfawlanconfig" + ], + "type": "router" + }, + { + "contains_any": [ + "synology", + "qnap", + "nas" + ], + "type": "nas" + }, + { + "contains_any": [ + "printer" + ], + "type": "printer" + }, + { + "contains_any": [ + "basic", + "computer" + ], + "type": "computer" + } + ] +} diff --git a/app/config/wsd_rules.json b/app/config/wsd_rules.json new file mode 100644 index 00000000..0508bdb8 --- /dev/null +++ b/app/config/wsd_rules.json @@ -0,0 +1,26 @@ +{ + "_comment": "WSD type classification from DPWS service QNames. Each rule lists predicates in match_any; a predicate matches a QName when ALL of its present operators match (local_eq / local_endswith / local_contains_any compare the lowercased localname; ns_contains searches the lowercased namespace). A rule matches the host if ANY of its QNames satisfies ANY predicate. Final type is chosen by precedence order; default applies when nothing matches or no QNames are advertised. Windows often lists print QNames alongside a DPWS Device QName, so 'computer' wins over 'networkprinter'.", + "qname_rules": [ + { + "type": "computer", + "match_any": [ + { "local_eq": ["device"], "ns_contains": ["devprof"] }, + { "local_eq": ["computer", "computerdevice"] } + ] + }, + { + "type": "networkprinter", + "match_any": [ + { "local_eq": ["printdevice", "printer"] }, + { "local_endswith": ["printdevice", "printer"] }, + { "ns_contains": ["printdevice"] }, + { "ns_contains": ["/wdp/"], "local_contains_any": ["print", "printer", "printdevice", "fax"] }, + { "ns_contains": ["microsoft.com/windows"], "local_contains_any": ["printdevice", "printer", "fax"] }, + { "local_eq": ["scanner", "fax", "faxdevice"] }, + { "local_endswith": ["scannerdevice"] } + ] + } + ], + "precedence": ["computer", "networkprinter"], + "default": "computer" +} diff --git a/app/discovery/__init__.py b/app/discovery/__init__.py new file mode 100644 index 00000000..f21c0546 --- /dev/null +++ b/app/discovery/__init__.py @@ -0,0 +1,13 @@ +# File __init__.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Discovery protocol package.""" + +from .manager import DiscoveryManager, PresenceTransitionHook, PresenceTransitionKind + +__all__ = [ + "DiscoveryManager", + "PresenceTransitionHook", + "PresenceTransitionKind", +] diff --git a/discovery/base.py b/app/discovery/base.py similarity index 90% rename from discovery/base.py rename to app/discovery/base.py index 6bf813dd..3be6c4e7 100644 --- a/discovery/base.py +++ b/app/discovery/base.py @@ -1,5 +1,5 @@ -# File base.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File base.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Base protocol contract for discovery providers.""" diff --git a/app/discovery/manager.py b/app/discovery/manager.py new file mode 100644 index 00000000..c3edaf81 --- /dev/null +++ b/app/discovery/manager.py @@ -0,0 +1,3778 @@ +# File manager.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Orchestrates all protocol providers and keeps a simple device cache.""" + +from collections.abc import Callable +from datetime import datetime, timedelta, timezone +import ipaddress +import logging +import threading +from urllib.parse import urljoin, urlparse, urlunparse +from typing import Literal + +from discovery.base import BaseDiscovery +from discovery.mdns import MDNSDiscovery +from discovery.ssdp import SSDPDiscovery +from discovery.netbios import NetbiosDiscovery +from discovery.wsdd_client import WsddSocketDiscovery +from discovery.wsd import WSDiscovery, is_synthetic_wsd_display_name +from model.device import Device +from utils.discovery_cache import CACHE_MAX_AGE_HOURS, load_discovery_cache, save_nmb_name_cache, save_wsd_device_cache +from utils.discovery_config import category_for_device_type, normalize_information_precedence_list +from utils.device_bundles import normalize_mac_for_bundle_merge +from utils.discovery_identity import ( + normalize_monitored_name, + normalize_monitored_uid, + upnp_identity_from_udn, + upnp_identity_from_usn, + uuid_urn_if_present, +) +from utils.local_host import is_local_host_ip +from utils.neighbor_mac import lookup_mac_from_neighbor_cache +from utils.location_label import is_plausible_room_location +from utils.scheduling import ScheduleMainFn + +AnticipatoryDescriptorSource = Literal["ssdp_profile_cache", "mdns_txt"] + +PresenceTransitionKind = Literal["online", "offline"] +PresenceTransitionHook = Callable[[Device, PresenceTransitionKind], None] +_IDENTITY_HOLD_SECONDS = 3.0 +_PERIODIC_PROBE_INTERVAL_S = 180.0 +# Coalesce burst ``_notify()`` calls (mDNS / merge can fire many times per 100 ms window). +_NOTIFY_DEBOUNCE_SECONDS = 0.08 +# Retry WSD NMB probes when ARP cache is cold at device arrival time. +_WSD_NMB_RETRY_INTERVAL_S = 30.0 +_WSD_NMB_MAX_RETRIES = 6 + + +# Device.metadata key: MAC seen in the neighbour (ARP/ND) cache for the row's IP when a +# protocol last confirmed it live. Lets probes detect that DHCP handed the IP to another +# host, whose answers would otherwise keep a stale row (e.g. an old NetBIOS name) online. +_PINNED_MAC_KEY = "_pinned_mac" +_FROM_CACHE_FLAGS = ("from_ssdp_cache", "from_nmb_cache", "from_wsd_cache") + + +def _descriptor_url_with_ip(descriptor_template: str, ip_s: str) -> str | None: + """Rebuild SSDP LOCATION-style URL with ``ip_s`` as host (same path/port/query as template).""" + t = (descriptor_template or "").strip() + if not t: + return None + try: + addr = ipaddress.ip_address(ip_s.strip()) + except ValueError: + return None + p = urlparse(t) + if not p.scheme or not p.netloc: + return None + port = p.port + if isinstance(addr, ipaddress.IPv6Address): + host = f"[{addr.compressed}]" + else: + host = addr.compressed + netloc = f"{host}:{port}" if port is not None else host + return urlunparse((p.scheme, netloc, p.path or "/", p.params, p.query, p.fragment)) + + +def _http_base_url_for_descriptor(ip_s: str, port: int, *, https: bool = False) -> str | None: + """Build ``http(s)://host[:port]/`` for resolving relative descriptor paths from mDNS TXT.""" + try: + addr = ipaddress.ip_address(ip_s.strip()) + except ValueError: + return None + scheme = "https" if https else "http" + default_port = 443 if https else 80 + if isinstance(addr, ipaddress.IPv6Address): + h = f"[{addr.compressed}]" + else: + h = addr.compressed + p = int(port) if port else 0 + if p > 0 and p != default_port: + netloc = f"{h}:{p}" + else: + netloc = h + return urlunparse((scheme, netloc, "/", "", "", "")) + + +def _normalize_mdns_relative_descriptor_path(raw: str) -> str | None: + s = (raw or "").strip() + if not s: + return None + if s.startswith(("http://", "https://")): + return s + low = s.lower() + if ".xml" not in low: + return None + if s.startswith("/"): + return s + # Some TXT records use ``description.xml`` without a leading slash. + return "/" + s.lstrip("/") + + +def _join_descriptor_base_and_path(base_url: str, absolute_path: str) -> str | None: + """Like URL concatenation but preserves non-default port (``urljoin`` strips it for absolute paths).""" + path = absolute_path if absolute_path.startswith("/") else f"/{absolute_path}" + try: + p = urlparse(base_url) + except ValueError: + return None + if not p.scheme or not p.netloc: + return None + return urlunparse((p.scheme, p.netloc, path, "", "", "")) + + +_VALID_COMMAND_SCHEMES = frozenset(("http", "https", "smb", "ftp", "ssh", "sftp", "telnet", "spotify", "custom")) +# "disabled" hides the auto-detected entry of that scheme (and, for "custom", the global +# custom command) for this device; its ip/port/label are ignored. +_VALID_COMMAND_MODES = frozenset(("override", "additional", "disabled")) + + +def _normalize_command_list(raw: object) -> list[dict]: + """Validate and normalize a list of per-device command dicts.""" + if not isinstance(raw, list): + return [] + result = [] + for c in raw: + if not isinstance(c, dict): + continue + scheme = str(c.get("scheme", "")).strip().lower() + if scheme not in _VALID_COMMAND_SCHEMES: + continue + mode = str(c.get("mode", "override")).strip().lower() + if mode not in _VALID_COMMAND_MODES: + mode = "override" + result.append({ + "scheme": scheme, + "ip": str(c.get("ip", "")).strip(), + "port": int(c.get("port", 0) or 0), + "mode": mode, + "label": str(c.get("label", "")).strip(), + }) + return result + + +class DiscoveryManager: + def __init__( + self, + demo_mode: bool = False, + enable_ssdp: bool = True, + enable_mdns: bool = True, + enable_ssdp_rules: bool = True, + enable_mdns_rules: bool = True, + ssdp_query_interval_seconds: int | None = None, + ssdp_mx_seconds: int | None = None, + ssdp_descriptor_http_min_interval_seconds: float | None = None, + ssdp_msearch_directed_ips: list[str] | None = None, + mdns_enumeration_timeout_seconds: float | None = None, + mdns_enumeration_interval_seconds: int | None = None, + mdns_service_info_timeout_ms: int | None = None, + enable_wsd: bool = True, + wsd_interval_seconds: float | None = None, + wsd_timeout_seconds: float | None = None, + enable_wsdd_socket: bool = False, + wsdd_listen: str | None = None, + wsdd_interval_seconds: float | None = None, + wsdd_socket_timeout_seconds: float | None = None, + wsdd_probe_each_poll: bool = True, + enable_nmb: bool = True, + nmb_interval_seconds: float | None = None, + nmb_timeout_seconds: float | None = None, + nmb_argv: list[str] | None = None, + nmb_directed_ips: list[str] | None = None, + protocol_merge_order: list[str] | None = None, + information_precedence: list[str] | None = None, + schedule_on_main_thread: ScheduleMainFn | None = None, + ) -> None: + self._logger = logging.getLogger(__name__) + self._ssdp_logger = logging.getLogger(f"{__name__}.ssdp") + self._mdns_logger = logging.getLogger(f"{__name__}.mdns") + self._wsd_logger = logging.getLogger(f"{__name__}.wsd") + self._wsdd_logger = logging.getLogger(f"{__name__}.wsdd") + self._nmb_logger = logging.getLogger(f"{__name__}.nmb") + self._protocol_merge_order: list[str] = ( + list(protocol_merge_order) + if protocol_merge_order + else ["ssdp", "wsd", "wsdd", "nmb", "mdns"] + ) + self._information_precedence: list[str] = ( + list(information_precedence) + if information_precedence + else normalize_information_precedence_list(None) + ) + self._schedule_on_main_thread: ScheduleMainFn = ( + schedule_on_main_thread if schedule_on_main_thread is not None else (lambda fn: fn()) + ) + self._logger.debug("merge.information_precedence (manager) = %s", self._information_precedence) + protocols: list[BaseDiscovery] = [] + if enable_ssdp: + protocols.append( + SSDPDiscovery( + rules_enabled=enable_ssdp_rules, + query_interval_seconds=ssdp_query_interval_seconds, + mx_seconds=ssdp_mx_seconds, + descriptor_http_min_interval_seconds=ssdp_descriptor_http_min_interval_seconds, + msearch_directed_ips=ssdp_msearch_directed_ips, + ephemeral_msearch_probe_ips=self._ssdp_probe_ips_from_mdns_without_ssdp, + ) + ) + if enable_mdns: + protocols.append( + MDNSDiscovery( + rules_enabled=enable_mdns_rules, + enumeration_timeout_seconds=mdns_enumeration_timeout_seconds, + enumeration_interval_seconds=mdns_enumeration_interval_seconds, + service_info_timeout_ms=mdns_service_info_timeout_ms, + schedule_on_main_thread=self._schedule_on_main_thread, + ) + ) + if enable_wsd: + protocols.append( + WSDiscovery( + interval_seconds=wsd_interval_seconds, + timeout_seconds=wsd_timeout_seconds, + ) + ) + if enable_wsdd_socket and (wsdd_listen or "").strip(): + protocols.append( + WsddSocketDiscovery( + listen=(wsdd_listen or "").strip(), + interval_seconds=wsdd_interval_seconds, + socket_timeout_seconds=wsdd_socket_timeout_seconds, + probe_each_poll=wsdd_probe_each_poll, + ) + ) + if enable_nmb: + protocols.append( + NetbiosDiscovery( + interval_seconds=nmb_interval_seconds, + timeout_seconds=nmb_timeout_seconds, + argv=nmb_argv, + directed_ips=nmb_directed_ips, + ) + ) + self._protocols = protocols + self._ssdp_discovery: SSDPDiscovery | None = None + self._nmb_discovery: NetbiosDiscovery | None = None + for _p in protocols: + if isinstance(_p, SSDPDiscovery): + self._ssdp_discovery = _p + if isinstance(_p, NetbiosDiscovery): + self._nmb_discovery = _p + self._anticipatory_fetch_attempted: set[str] = set() + self._anticipatory_reentrant: set[str] = set() + self._devices: dict[str, Device] = {} + self._arrival_sequence = 0 + self._listeners: list[Callable[[list[Device]], None]] = [] + self._notify_debounce_lock = threading.Lock() + self._notify_debounce_timer: threading.Timer | None = None + self._periodic_probe_lock = threading.Lock() + self._periodic_probe_timer: threading.Timer | None = None + self._stopped: bool = False + self._wsd_nmb_retry_lock = threading.Lock() + self._wsd_nmb_retry_timer: threading.Timer | None = None + self._wsd_nmb_pending: dict[str, tuple[str, int]] = {} # device_key → (mac, retry_count) + self._wsd_nmb_probed: dict[str, str] = {} # device_key → target_v4 (for cleanup on offline) + self._presence_hooks: list[PresenceTransitionHook] = [] + self._type_overrides: dict[str, str] = {} + self._name_overrides: dict[str, str] = {} + self._location_overrides: dict[str, str] = {} + self._url_overrides: dict[str, str] = {} + self._device_commands: dict[str, list[dict]] = {} # key → [{scheme,ip,port,mode,label}] + self._custom_command_overrides: dict[str, str] = {} # key → command template + self._field_mapping_rules: dict[str, dict[str, list[str]]] = {} + self._monitored_overrides: dict[str, bool] = {} + self._hidden_overrides: dict[str, bool] = {} + self._last_seen_overrides: dict[str, str] = {} + # One "online" notification per LAN host until it goes offline (SSDP + mDNS rows share IP). + self._presence_announced_hosts: set[str] = set() + self._identity_pending: dict[str, tuple[datetime, Device]] = {} + self._ssdp_profile_cache_lock = threading.Lock() + self._ssdp_profile_cache_by_ip: dict[str, dict] + self._ssdp_profile_cache_emit_rows: list[tuple[str, dict]] + self._ssdp_profile_cache_by_ip, self._ssdp_profile_cache_emit_rows = ( + self._load_ssdp_profile_cache_by_ip() + ) + self._nmb_name_cache: dict[str, dict] = self._load_nmb_name_cache() + self._wsd_device_cache: dict[str, dict] = self._load_wsd_device_cache() + self._demo_mode = demo_mode + self._location_prefs_need_reapply = False + self._location_prefs_dirty_callback: Callable[[], None] | None = None + # Discovered-location policy: casefolded label -> configured spelling. + # Permissive until the UI pushes the configured list via set_location_policy. + self._allowed_locations: dict[str, str] = {} + self._auto_add_discovered_locations = True + + for protocol in self._protocols: + protocol.set_callback(self._on_protocol_event) + + def set_location_prefs_dirty_callback(self, callback: Callable[[], None] | None) -> None: + self._location_prefs_dirty_callback = callback + + def add_listener(self, callback: Callable[[list[Device]], None]) -> None: + self._listeners.append(callback) + callback(self.devices) + + def register_presence_transition_hook(self, hook: PresenceTransitionHook) -> None: + """Notify when a device becomes reachable or unreachable (same identity row). + + Fires only on transitions: newly online (including back from offline), or offline from + online. Silent for first-seen rows that are already offline (e.g. restored monitored + ghosts). Plugins should treat callbacks as potentially running on a discovery thread — + marshal to the UI thread before touching GUI toolkit APIs. + + Reserved for future automation / plugins; core code does not register hooks today. + """ + self._presence_hooks.append(hook) + + def unregister_presence_transition_hook(self, hook: PresenceTransitionHook) -> None: + try: + self._presence_hooks.remove(hook) + except ValueError: + pass + + @property + def devices(self) -> list[Device]: + # Invariant: only *followed* devices stay visible (greyed out) when offline. + # A non-monitored device that is offline must never reach the UI — it should + # have been dropped at probe time, but pops keyed on a mutated ``d.key`` can + # miss and, once a row is offline, the ``elif d.online`` guards never retry + # removal. Filtering here is the single source of truth and self-heals those + # stuck rows. + rows = [d for d in self._devices_snapshot() if d.online or d.monitored] + return sorted(rows, key=lambda device: (device.category, device.name.lower())) + + def _devices_snapshot(self) -> list[Device]: + """Copy of live rows — safe while discovery threads mutate ``_devices``.""" + return list(self._devices.values()) + + def start(self) -> None: + self._stopped = False + self._logger.info("Starting discovery protocols: %s", [p.source for p in self._protocols]) + self._emit_cached_devices() + self._start_tcp_probes_for_cached_devices() + if not self._protocols: + self._logger.warning("No discovery protocols enabled (check ~/.config/netneighbor/discovery.json)") + return + for protocol in self._protocols: + protocol.start() + self._schedule_periodic_probe() + + def stop(self) -> None: + self._stopped = True + with self._notify_debounce_lock: + if self._notify_debounce_timer is not None: + self._notify_debounce_timer.cancel() + self._notify_debounce_timer = None + with self._periodic_probe_lock: + if self._periodic_probe_timer is not None: + self._periodic_probe_timer.cancel() + self._periodic_probe_timer = None + with self._wsd_nmb_retry_lock: + if self._wsd_nmb_retry_timer is not None: + self._wsd_nmb_retry_timer.cancel() + self._wsd_nmb_retry_timer = None + self._wsd_nmb_pending.clear() + self._wsd_nmb_probed.clear() + self._logger.info("Stopping discovery protocols") + for protocol in self._protocols: + protocol.stop() + self._identity_pending.clear() + self._presence_announced_hosts.clear() + + def refresh(self) -> None: + self._logger.debug("Manual refresh requested") + for protocol in self._protocols: + protocol.refresh() + + def _schedule_periodic_probe(self) -> None: + def _tick() -> None: + if self._stopped: + return + self._logger.debug("Periodic ping probe tick") + self._start_ping_probes_for_live_devices() + self._schedule_periodic_probe() + + timer = threading.Timer(_PERIODIC_PROBE_INTERVAL_S, _tick) + timer.daemon = True + with self._periodic_probe_lock: + if self._stopped: + return + self._periodic_probe_timer = timer + timer.start() + + def _ssdp_probe_ips_from_mdns_without_ssdp(self) -> list[str]: + """IPv4 addresses with live mDNS rows but no SSDP row (unicast M-SEARCH fills NOTIFY gaps).""" + ssdp_ips: set[str] = set() + for d in self._devices.values(): + if d.source == "ssdp" and d.online: + sip = str(d.ip).strip() + if not sip: + continue + try: + addr = ipaddress.ip_address(sip) + except ValueError: + ssdp_ips.add(sip) + continue + ssdp_ips.add(addr.compressed) + seen: set[str] = set() + out: list[str] = [] + for d in self._devices.values(): + if d.source != "mdns" or not d.online: + continue + sip = str(d.ip).strip() + if not sip: + continue + try: + addr = ipaddress.ip_address(sip) + except ValueError: + continue + if not isinstance(addr, ipaddress.IPv4Address) or addr.is_loopback: + continue + canon = addr.compressed + if canon in ssdp_ips: + continue + if canon not in seen: + seen.add(canon) + out.append(canon) + return out + + def _device_event_logger(self, source: str) -> logging.Logger: + if source == "ssdp": + return self._ssdp_logger + if source == "mdns": + return self._mdns_logger + if source == "wsd": + return self._wsd_logger + if source == "wsdd": + return self._wsdd_logger + if source == "nmb": + return self._nmb_logger + return self._logger + + def add_or_update_device(self, device: Device) -> None: + sip = str(device.ip).strip() + if sip in {"", "0.0.0.0"}: + self._device_event_logger(device.source).debug( + "Ignoring device with placeholder IP: source=%s name=%s port=%s online=%s", + device.source, + device.name, + device.port, + device.online, + ) + return + # Loopback addresses are always the local machine — never useful as + # network neighbours. Drop them unconditionally. + try: + if ipaddress.ip_address(sip).is_loopback: + self._device_event_logger(device.source).debug( + "Ignoring loopback device: source=%s ip=%s name=%s", + device.source, + sip, + device.name, + ) + return + except ValueError: + pass + # WSD/WSDD devices without a resolvable MAC are suppressed: they cannot be + # merged with the IPv4 entry for the same host and would appear as a duplicate. + # Offline events are still processed so a previously stored device can go offline. + if device.source in {"wsd", "wsdd"} and device.online: + if not self._mac_for_device_identity(device): + self._device_event_logger(device.source).debug( + "Suppressing WSD/WSDD device without MAC: ip=%s name=%s", + device.ip, + device.name, + ) + return + + if self._should_hold_for_stable_identity(device): + return + + override_key = self._make_override_key_for_device(device) + existing_seen = self._last_seen_overrides.get(override_key) + if not existing_seen: + existing_seen = self._last_seen_overrides.get(self._make_override_key(device.source, device.ip, device.port)) + if device.online: + now = datetime.now(timezone.utc) + device.last_seen = now + self._last_seen_overrides[override_key] = now.isoformat() + elif existing_seen: + try: + device.last_seen = datetime.fromisoformat(existing_seen) + except ValueError: + pass + + existing_key = device.key + existing = self._devices.get(existing_key) + if existing is None and device.source == "ssdp": + ep_key, ep_existing = self._find_existing_ssdp_by_endpoint(device) + # Keep device.key when no endpoint matches: (None, None) would store every new + # SSDP row under the None key, so two descriptors of one host (e.g. MediaTek + # tvdevice :56790 + DIAL :8008) would keep overwriting each other. + if ep_existing is not None: + existing_key, existing = ep_key, ep_existing + + self._hydrate_mdns_from_ssdp_profile_cache(device, existing) + self._hydrate_ssdp_from_profile_cache(device) + self._schedule_anticipatory_descriptor_fetch(device) + self._apply_field_mapping_rules(device) + self._apply_local_host_identity(device) + self._apply_type_override(device) + self._apply_name_override(device) + self._apply_location_override(device) + self._apply_url_override(device) + self._apply_device_commands(device) + self._apply_custom_command_override(device) + self._apply_monitored_override(device) + self._apply_hidden_override(device) + + prev_online: bool | None = existing.online if existing is not None else None + old_key_to_drop: str | None = None + + if existing is not None: + # Preserve user-follow choice across updates. + device.monitored = existing.monitored + device.hidden = existing.hidden + if device.online is False and existing.last_seen: + device.last_seen = existing.last_seen + # A known type from another source completes (does not get replaced by) an unknown one. + # "unknown" is an absence of classification, not a verdict, so a higher-priority source + # that cannot classify the device must not clobber a type a lower-priority source knows + # (mirrors _supplement_missing_user_location for location). Conflicts between two *known* + # types still follow protocol precedence elsewhere. + self._preserve_known_type_across_sources(device, existing) + if device.source == "ssdp": + self._ssdp_logger.debug( + "SSDP merge candidate for %s:%s old_name=%s new_name=%s", + device.ip, + device.port, + existing.name, + device.name, + ) + device.metadata = self._merge_ssdp_metadata(existing.metadata, device.metadata, existing.name, device.name) + if not self._has_effective_name_override(existing): + device.name = self._pick_ssdp_name(existing.name, device.name, existing.metadata, device.metadata) + elif self._find_name_override_value(device) is None and self._resolved_field_rule_name(device): + # Field rule already applied above (_apply_field_mapping_rules) — keep it. + self._ssdp_logger.debug("SSDP name preserved: name field rule is active") + else: + device.name = existing.name + self._ssdp_logger.debug("SSDP name preserved: user override is active") + device.icon = existing.icon or device.icon + if not device.url and existing.url: + device.url = existing.url + if existing_key != device.key: + old_key_to_drop = existing_key + existing_key = device.key + + if not isinstance(device.metadata, dict): + device.metadata = {} + existing_arrival = None + if isinstance(existing, Device) and isinstance(existing.metadata, dict): + candidate = existing.metadata.get("_arrival_index") + if isinstance(candidate, int): + existing_arrival = candidate + if existing_arrival is None: + self._arrival_sequence += 1 + existing_arrival = self._arrival_sequence + device.metadata["_arrival_index"] = existing_arrival + self._supplement_missing_user_location(device, existing) + self._pin_identity_mac(device, existing) + # Assign new key before removing old key so the device is never absent from _devices. + self._devices[existing_key] = device + if old_key_to_drop is not None: + self._devices.pop(old_key_to_drop, None) + self._reapply_field_rules_to_ip_siblings(device) + self._maybe_queue_nmb_probe_for_synthetic_wsd(device) + self._run_location_reapply_sweep() + device_log = self._device_event_logger(device.source) + device_log.info( + "Device %s: source=%s name=%s ip=%s port=%s type=%s category=%s online=%s", + "updated" if existing else "added", + device.source, + device.name, + device.ip, + device.port, + device.type, + device.category, + device.online, + ) + device_log.debug( + "Device %s: %s %s:%s [%s] online=%s category=%s", + "updated" if existing else "added", + device.source, + device.ip, + device.port, + device.name, + device.online, + device.category, + ) + uloc = device.metadata.get("user_location") if isinstance(device.metadata, dict) else None + device_log.debug( + "Device appearance: ip=%s port=%s type=%s icon=%s user_location=%r", + device.ip, + device.port, + device.type, + device.icon, + uloc, + ) + self._emit_presence_hooks_if_transition(device, prev_online, device.online) + # A live device that just went offline drops from the list unless it is + # followed (monitored stays greyed out). Only true online→offline + # transitions trigger this — devices restored from cache as offline + # (prev_online is None) are kept so live discovery can confirm them. + if prev_online is True and not device.online and not device.monitored: + self._devices.pop(existing_key, None) + if device.source == "nmb" and device.online: + name = (device.name or "").strip() + if name: + sip = str(device.ip).strip() + from utils.neighbor_mac import lookup_mac_from_neighbor_cache + mac = lookup_mac_from_neighbor_cache(sip) or device.metadata.get(_PINNED_MAC_KEY) or None + save_nmb_name_cache(sip, name, mac) + self._nmb_name_cache[sip] = {"name": name} + if device.source == "wsd" and device.online: + name = (device.name or "").strip() + if name and not is_synthetic_wsd_display_name(name): + dev_key = device.key + md = device.metadata if isinstance(device.metadata, dict) else {} + row = { + "name": name, + "ip": str(device.ip), + "port": int(device.port or 0), + "type": device.type or "", + "category": device.category or "", + "url": device.url or "", + "wsd_epr": md.get("wsd_epr", ""), + "wsd_xaddrs": md.get("wsd_xaddrs") or [], + "wsd_types": md.get("wsd_types") or [], + "wsd_scopes": md.get("wsd_scopes") or [], + } + if md.get(_PINNED_MAC_KEY): + row["mac"] = md[_PINNED_MAC_KEY] + save_wsd_device_cache(dev_key, row) + self._wsd_device_cache[dev_key] = row + self._notify() + + def _maybe_queue_nmb_probe_for_synthetic_wsd(self, device: Device) -> None: + """Queue ``nmblookup -A`` / ``nbtstat -A`` on the LAN IPv4 for synthetic WSD/wsdd labels. + + Broadcast browse often misses PCs; directed ``-A`` matches what you'd run manually. + If discovery only has IPv6 (e.g. link-local), resolve IPv4 from kernel neighbor/MAC + tables—same source as ``ip neigh``—then probe that address for the NetBIOS name. + When ARP cache is cold at arrival, the device is queued for periodic retry. + """ + nmb = self._nmb_discovery + if nmb is None: + return + if (device.source or "").strip().lower() not in {"wsd", "wsdd"}: + return + dev_key = device.key + if not device.online: + # Clean up probe state for this device when it goes offline. + with self._wsd_nmb_retry_lock: + self._wsd_nmb_pending.pop(dev_key, None) + probed_v4 = self._wsd_nmb_probed.pop(dev_key, None) + if probed_v4: + nmb.remove_directed_ip(probed_v4) + return + if (device.type or "").strip().lower() != "computer": + return + if not is_synthetic_wsd_display_name(device.name): + return + sip = str(device.ip).strip() + base = sip.split("%", 1)[0].strip() + if not base: + return + try: + a = ipaddress.ip_address(base) + except ValueError: + return + target_v4: str | None = None + if isinstance(a, ipaddress.IPv4Address): + if a.is_loopback or not a.is_private: + return + target_v4 = base + elif isinstance(a, ipaddress.IPv6Address): + from utils.details_payload import resolve_mac_for_device + from utils.neighbor_mac import lookup_ipv4_for_mac + + mac = resolve_mac_for_device(device) + if not mac: + return + target_v4 = lookup_ipv4_for_mac(mac) + if not target_v4: + with self._wsd_nmb_retry_lock: + if dev_key not in self._wsd_nmb_pending: + self._wsd_nmb_pending[dev_key] = (mac, 0) + self._logger.debug( + "wsd_nmb: IPv4 not in ARP cache yet for mac=%s key=%s — scheduling retry", + mac, dev_key, + ) + self._schedule_wsd_nmb_retry_locked() + return + else: + return + nmb.suggest_directed_ip(target_v4) + with self._wsd_nmb_retry_lock: + self._wsd_nmb_probed[dev_key] = target_v4 + + def _schedule_wsd_nmb_retry_locked(self) -> None: + """Schedule the next retry tick (must be called with ``_wsd_nmb_retry_lock`` held).""" + if self._stopped or not self._wsd_nmb_pending: + return + if self._wsd_nmb_retry_timer is not None: + return + t = threading.Timer(_WSD_NMB_RETRY_INTERVAL_S, self._retry_wsd_nmb_probes_once) + t.daemon = True + self._wsd_nmb_retry_timer = t + t.start() + + def _retry_wsd_nmb_probes_once(self) -> None: + """Fire pending WSD NMB probes whose IPv4 can now be resolved from ARP cache.""" + from utils.neighbor_mac import lookup_ipv4_for_mac + + with self._wsd_nmb_retry_lock: + self._wsd_nmb_retry_timer = None + if self._stopped: + return + still_pending: dict[str, tuple[str, int]] = {} + for dev_key, (mac, attempts) in list(self._wsd_nmb_pending.items()): + target_v4 = lookup_ipv4_for_mac(mac) + if target_v4: + self._logger.debug( + "wsd_nmb retry: resolved mac=%s → %s (attempt %d), queuing NMB probe", + mac, target_v4, attempts + 1, + ) + nmb = self._nmb_discovery + if nmb is not None: + nmb.suggest_directed_ip(target_v4) + self._wsd_nmb_probed[dev_key] = target_v4 + else: + next_attempts = attempts + 1 + if next_attempts < _WSD_NMB_MAX_RETRIES: + still_pending[dev_key] = (mac, next_attempts) + self._logger.debug( + "wsd_nmb retry %d/%d: mac=%s still not in ARP cache", + next_attempts, _WSD_NMB_MAX_RETRIES, mac, + ) + else: + self._logger.debug( + "wsd_nmb retry: giving up after %d attempts for mac=%s", + _WSD_NMB_MAX_RETRIES, mac, + ) + self._wsd_nmb_pending = still_pending + self._schedule_wsd_nmb_retry_locked() + + def _load_ssdp_profile_cache_by_ip(self) -> tuple[dict[str, dict], list[tuple[str, dict]]]: + """Build SSDP profile cache indexes from disk. + + Returns ``(by_location_host, emit_rows)``: + + - ``by_location_host``: last row per LOCATION hostname — used for ``.get(ip)`` hydration + (legacy behaviour). + - ``emit_rows``: **every** cache entry that resolves a hostname, in iteration order — used + to pre-populate the device store at startup. Multiple UPnP rows often share the same + LOCATION host (e.g. coordinator URL); indexing only by host would drop the others and the + UI would show a single device until live SSDP re-fills, with apparent IP ``replacement``. + """ + by_host: dict[str, dict] = {} + emit_rows: list[tuple[str, dict]] = [] + ignored_logged: set[tuple[str, str]] = set() + cache_blob = load_discovery_cache() + raw = cache_blob.get("ssdp_profile_cache") + if not isinstance(raw, dict): + return by_host, emit_rows + entries = raw.get("entries") + if not isinstance(entries, dict): + return by_host, emit_rows + for _key, row in entries.items(): + if not isinstance(row, dict): + continue + candidate_urls: list[str] = [] + ssdp_loc = row.get("ssdp_location") + if isinstance(ssdp_loc, str) and ssdp_loc.strip(): + candidate_urls.append(ssdp_loc.strip()) + for u in (row.get("url"), (row.get("xml_fields") or {}).get("presentationURL")): + if isinstance(u, str) and u.strip(): + candidate_urls.append(u.strip()) + # Fallback from raw xml LOCATION URL if present in row. + if not candidate_urls: + raw_xml = row.get("raw_xml") + if isinstance(raw_xml, str) and "URLBase>" in raw_xml: + start = raw_xml.find("URLBase>") + end = raw_xml.find("") + if start >= 0 and end > start: + candidate_urls.append(raw_xml[start + 8 : end].strip()) + host = "" + for u in candidate_urls: + try: + p = urlparse(u) + except ValueError: + continue + if p.hostname: + host = str(p.hostname).strip() + break + if not host: + continue + row_copy = dict(row) + emit_rows.append((host, row_copy)) + prev = by_host.get(host) + if prev is None or self._ssdp_profile_row_richness(row_copy) >= self._ssdp_profile_row_richness(prev): + by_host[host] = row_copy + kept, ignored = row_copy, prev + else: + kept, ignored = prev, row_copy + ignore_note = (host, str(ignored.get("ssdp_location") if ignored else "")) + if ( + ignored is not None + and kept.get("ssdp_location") != ignored.get("ssdp_location") + and ignore_note not in ignored_logged + ): + ignored_logged.add(ignore_note) + self._ssdp_logger.debug( + "SSDP profile cache index for %s: kept %s name=%r richness(icon,fields)=%s, " + "ignored %s name=%r richness=%s\nignored XML:\n%s", + host, + kept.get("ssdp_location"), + kept.get("name"), + self._ssdp_profile_row_richness(kept), + ignored.get("ssdp_location"), + ignored.get("name"), + self._ssdp_profile_row_richness(ignored), + str(ignored.get("raw_xml") or "(none)").strip(), + ) + return by_host, emit_rows + + @staticmethod + def _ssdp_profile_row_richness(row: dict) -> tuple[int, int]: + """Rank cached SSDP profiles of one host: a descriptor with an icon (vendor descriptor, + e.g. Sharp DIAL :8008) beats a bare SoC placeholder one (e.g. "Mediatek_MTXXXX").""" + xf = row.get("xml_fields") if isinstance(row.get("xml_fields"), dict) else {} + icon = xf.get("iconURL") or row.get("iconURL") + return (1 if isinstance(icon, str) and icon.strip() else 0, len(xf)) + + def _load_nmb_name_cache(self) -> dict[str, dict]: + """Load NMB-resolved hostnames from the discovery cache.""" + cache_blob = load_discovery_cache() + raw = cache_blob.get("nmb_name_cache") + if not isinstance(raw, dict): + return {} + entries = raw.get("entries") + if not isinstance(entries, dict): + return {} + return {k: v for k, v in entries.items() if isinstance(v, dict)} + + def _load_wsd_device_cache(self) -> dict[str, dict]: + """Load WSD device rows from the discovery cache.""" + cache_blob = load_discovery_cache() + raw = cache_blob.get("wsd_device_cache") + if not isinstance(raw, dict): + return {} + entries = raw.get("entries") + if not isinstance(entries, dict): + return {} + return {k: v for k, v in entries.items() if isinstance(v, dict)} + + def _emit_cached_devices(self) -> None: + """Pre-populate the device store from the SSDP profile disk cache before protocols start. + + Iterates the cached SSDP profiles and emits each as a synthetic ``ssdp`` device so that + previously-seen devices appear in the UI immediately at startup — without waiting 5-15 s + for live discovery to respond. + + Cache entries older than 24 h are skipped (same TTL as the cache GC). Once live + protocol events arrive they overwrite these entries: a live SSDP row shares the same + Device key (``ssdp:udn:…`` when a UDN is present, else ``ssdp:{ip}:{port}``) and simply + replaces the pre-populated entry via the normal ``add_or_update_device`` pipeline. + """ + now = datetime.now(timezone.utc) + _cache_max_age_s = CACHE_MAX_AGE_HOURS * 3600 + emitted = 0 + for sip, row in self._ssdp_profile_cache_emit_rows: + if not isinstance(row, dict): + continue + # TTL guard — skip entries not updated within the retention window. + updated_raw = row.get("updated_at") + updated_dt: datetime | None = None + if isinstance(updated_raw, str): + try: + updated_dt = datetime.fromisoformat(updated_raw) + if updated_dt.tzinfo is None: + updated_dt = updated_dt.replace(tzinfo=timezone.utc) + if (now - updated_dt).total_seconds() > _cache_max_age_s: + self._logger.debug("_emit_cached_devices: skipping stale entry ip=%s updated_at=%s", sip, updated_raw) + continue + except ValueError: + pass # malformed timestamp → include the entry rather than skip it + name = self._ssdp_profile_display_name(row) + if not name: + name = f"Device ({sip})" + device_type = row.get("type") or "unknown" + if not isinstance(device_type, str): + device_type = "unknown" + device_category = row.get("category") or category_for_device_type(device_type) + if not isinstance(device_category, str): + device_category = category_for_device_type(device_type) + # Derive port from ssdp_location URL (e.g. "http://192.168.1.103:8008/…"). + port = 0 + ssdp_loc = row.get("ssdp_location") + if isinstance(ssdp_loc, str) and ssdp_loc.strip(): + try: + parsed = urlparse(ssdp_loc.strip()) + if parsed.port: + port = parsed.port + except Exception: + pass + # Build metadata mirrors a lean SSDP device event so hydration / details work. + metadata: dict = {"from_ssdp_cache": True} + xml_fields = row.get("xml_fields") + if isinstance(xml_fields, dict): + metadata["xml_fields"] = dict(xml_fields) + raw_xml = row.get("raw_xml") + if isinstance(raw_xml, str) and raw_xml.strip(): + metadata["xml"] = raw_xml + if isinstance(ssdp_loc, str) and ssdp_loc.strip(): + metadata["location"] = ssdp_loc.strip() + usn_row = row.get("usn") + if isinstance(usn_row, str) and usn_row.strip(): + metadata["usn"] = usn_row.strip() + url = row.get("url") + device = Device( + name=name, + ip=sip, + port=port, + type=device_type, + category=device_category, + source="ssdp", + url=url if isinstance(url, str) and url.strip() else None, + metadata=metadata, + last_seen=updated_dt if updated_dt is not None else datetime.now(timezone.utc), + online=True, + ) + self.add_or_update_device(device) + emitted += 1 + self._logger.info( + "_emit_cached_devices: pre-populated %d device(s) from %d SSDP profile cache row(s)", + emitted, + len(self._ssdp_profile_cache_emit_rows), + ) + + # Emit NMB-cached hostnames so computers appear with their real name immediately. + nmb_emitted = 0 + for sip, row in self._nmb_name_cache.items(): + if not isinstance(row, dict): + continue + updated_raw = row.get("updated_at") + if isinstance(updated_raw, str): + try: + updated_dt = datetime.fromisoformat(updated_raw) + if updated_dt.tzinfo is None: + updated_dt = updated_dt.replace(tzinfo=timezone.utc) + if (now - updated_dt).total_seconds() > _cache_max_age_s: + continue + except ValueError: + pass + name = row.get("name") + if not isinstance(name, str) or not name.strip(): + continue + nmb_meta: dict = {"from_nmb_cache": True} + cached_mac = row.get("mac") + cached_mac = normalize_mac_for_bundle_merge(cached_mac) if isinstance(cached_mac, str) else "" + if cached_mac: + nmb_meta[_PINNED_MAC_KEY] = cached_mac + device = Device( + name=name, + ip=sip, + port=445, + type="computer", + category=category_for_device_type("computer"), + source="nmb", + url=None, + metadata=nmb_meta, + online=True, + ) + self.add_or_update_device(device) + nmb_emitted += 1 + if nmb_emitted: + self._logger.info("_emit_cached_devices: pre-populated %d NMB name(s)", nmb_emitted) + + # Emit cached WSD devices so they appear immediately on restart. + wsd_emitted = 0 + for dev_key, row in self._wsd_device_cache.items(): + if not isinstance(row, dict): + continue + updated_raw = row.get("updated_at") + if isinstance(updated_raw, str): + try: + updated_dt = datetime.fromisoformat(updated_raw) + if updated_dt.tzinfo is None: + updated_dt = updated_dt.replace(tzinfo=timezone.utc) + if (now - updated_dt).total_seconds() > _cache_max_age_s: + continue + except ValueError: + pass + name = row.get("name") + ip = row.get("ip") + if not isinstance(name, str) or not name.strip(): + continue + if not isinstance(ip, str) or not ip.strip(): + continue + epr = row.get("wsd_epr", "") + metadata: dict = { + "from_wsd_cache": True, + "wsd_epr": epr, + "wsd_xaddrs": row.get("wsd_xaddrs") or [], + "wsd_types": row.get("wsd_types") or [], + "wsd_scopes": row.get("wsd_scopes") or [], + } + cached_mac = row.get("mac") + cached_mac = normalize_mac_for_bundle_merge(cached_mac) if isinstance(cached_mac, str) else "" + if cached_mac: + metadata[_PINNED_MAC_KEY] = cached_mac + device_type = row.get("type") or "computer" + device_category = row.get("category") or category_for_device_type(device_type) + url = row.get("url") or None + device = Device( + name=name, + ip=ip, + port=int(row.get("port") or 5357), + type=device_type, + category=device_category, + source="wsd", + url=url if url else None, + metadata=metadata, + online=True, + ) + self.add_or_update_device(device) + wsd_emitted += 1 + if wsd_emitted: + self._logger.info("_emit_cached_devices: pre-populated %d WSD device(s)", wsd_emitted) + + def _pin_identity_mac(self, device: Device, existing: Device | None) -> None: + """Record which MAC answered for ``device.ip`` when the row was confirmed live. + + Rows replayed from the disk cache keep the MAC stored with them (they prove nothing + about who holds the IP now); offline events and ARP misses inherit the prior pin + as long as the IP is unchanged. + """ + md = device.metadata + if not isinstance(md, dict): + return + sip = str(device.ip).strip() + prior = "" + if isinstance(existing, Device) and str(existing.ip).strip() == sip: + prior_md = existing.metadata if isinstance(existing.metadata, dict) else {} + prior = str(prior_md.get(_PINNED_MAC_KEY) or "") + from_cache = any(md.get(flag) for flag in _FROM_CACHE_FLAGS) + live_mac = "" + if device.online and not from_cache: + hit = lookup_mac_from_neighbor_cache(sip) + live_mac = normalize_mac_for_bundle_merge(hit) if hit else "" + pinned = live_mac or str(md.get(_PINNED_MAC_KEY) or "") or prior + if pinned: + md[_PINNED_MAC_KEY] = pinned + + def _drop_rows_with_changed_identity(self, ip: str) -> bool: + """Retire rows at *ip* whose pinned MAC no longer matches who answers there. + + Called right after a probe got an answer from *ip* (so the neighbour cache is + fresh). A mismatch means the address now belongs to another host: the reply + proves nothing about the stale row, which must not stay online, nor merge into + the new occupant's bundle (whose MAC it would otherwise borrow). Followed rows + are kept greyed out; others are dropped. Returns True when something changed. + """ + hit = lookup_mac_from_neighbor_cache(ip) + current = normalize_mac_for_bundle_merge(hit) if hit else "" + if not current: + return False + changed = False + for store_key, d in list(self._devices.items()): + if str(d.ip).strip().split("%", 1)[0] != ip: + continue + md = d.metadata if isinstance(d.metadata, dict) else {} + pinned = str(md.get(_PINNED_MAC_KEY) or "") + if not pinned or pinned == current: + continue + self._logger.info( + "Identity changed at %s: row %s (%s) pinned MAC %s, now answered by %s → retired", + ip, + store_key, + d.name, + pinned, + current, + ) + changed = True + if d.monitored: + d.online = False + else: + self._devices.pop(store_key, None) + return changed + + def _start_tcp_probes_for_cached_devices(self) -> None: + """Background TCP probe to quickly validate cached devices at startup. + + Devices that do not respond within 1.5 s are marked offline before live protocol + discovery completes, giving the UI a clean picture within ~5 s of startup. + Only devices with a usable port (>0, non-loopback, non-link-local) are probed. + If a live protocol has already confirmed a device online since the probe started, + the TCP result is discarded to avoid a false offline flip. + """ + from utils.tcp_probe import probe_devices_background + + targets: list[tuple[str, int]] = [] + seen: set[tuple[str, int]] = set() + for d in list(self._devices.values()): + if not d.online: + continue + ip = str(d.ip).strip() + port = int(d.port or 0) + if not ip or port <= 0: + continue + try: + addr = ipaddress.ip_address(ip) + if addr.is_loopback: + continue + if isinstance(addr, ipaddress.IPv6Address) and addr.is_link_local: + continue + except ValueError: + continue + key = (ip, port) + if key not in seen: + seen.add(key) + targets.append(key) + + if not targets: + return + + self._logger.info("TCP probe: validating %d cached endpoint(s)", len(targets)) + probe_start = datetime.now(timezone.utc) + + def _on_result(ip: str, port: int, reachable: bool) -> None: + def apply() -> None: + changed = False + now = datetime.now(timezone.utc) + if reachable and self._drop_rows_with_changed_identity(ip): + changed = True + for store_key, d in list(self._devices.items()): + sip = str(d.ip).strip() + dport = int(d.port or 0) + if sip != ip or dport != port: + continue + if reachable: + if d.online: + d.last_seen = now + changed = True + elif d.online and not (d.last_seen and d.last_seen > probe_start): + # Only mark offline if no protocol has confirmed online since probe start. + d.online = False + changed = True + # Followed devices stay (greyed out); others drop from the list. + # Pop by the storage key, not d.key: a merged/re-keyed row may + # compute a different key and silently survive a pop(d.key). + if not d.monitored: + self._devices.pop(store_key, None) + if changed: + if reachable: + self._logger.debug("TCP probe: %s:%s reachable", ip, port) + else: + self._logger.info("TCP probe: %s:%s unreachable → offline", ip, port) + self._notify() + self._schedule_on_main_thread(apply) + + probe_devices_background(targets, _on_result, timeout_s=1.5, max_workers=8) + + def _start_ping_probes_for_live_devices(self) -> None: + """Periodic ICMP ping probe — detects offline devices regardless of port.""" + from utils.tcp_probe import ping_ips_background + + ip_set: set[str] = set() + for d in list(self._devices.values()): + if not d.online: + continue + ip = str(d.ip).strip().split("%", 1)[0] + if not ip or ip in {"0.0.0.0", "::"}: + continue + try: + ipaddress.ip_address(ip) + except ValueError: + continue + ip_set.add(ip) + + if not ip_set: + return + + self._logger.info("Periodic ping probe: checking %d IP(s)", len(ip_set)) + probe_start = datetime.now(timezone.utc) + + def _on_result(ip: str, reachable: bool) -> None: + def apply() -> None: + changed = False + now = datetime.now(timezone.utc) + if reachable and self._drop_rows_with_changed_identity(ip): + changed = True + for store_key, d in list(self._devices.items()): + if str(d.ip).strip().split("%", 1)[0] != ip: + continue + if reachable: + if d.online: + d.last_seen = now + changed = True + elif d.online and not (d.last_seen and d.last_seen > probe_start): + d.online = False + changed = True + # Followed devices stay (greyed out); others drop from the list. + # Pop by the storage key, not d.key: a merged/re-keyed row may + # compute a different key and silently survive a pop(d.key). + if not d.monitored: + self._devices.pop(store_key, None) + if changed: + if reachable: + self._logger.debug("Ping probe: %s reachable", ip) + else: + self._logger.info("Ping probe: %s unreachable → offline", ip) + self._notify() + self._schedule_on_main_thread(apply) + + ping_ips_background(list(ip_set), _on_result, timeout_s=2.0) + + def _ssdp_profile_display_name(self, row: dict) -> str: + """Best-effort human label from persisted SSDP profile (disk cache).""" + n = row.get("name") + if isinstance(n, str) and n.strip(): + return n.strip() + xf = row.get("xml_fields") if isinstance(row.get("xml_fields"), dict) else {} + for key in ("friendlyName", "displayName"): + value = xf.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + def _preserve_known_type_across_sources(self, device: Device, existing: Device) -> None: + """Keep a previously-known type/category when the incoming update is ``unknown``. + + Classification is cross-source: a higher-priority protocol (e.g. SSDP) that returns + ``unknown`` should complete — not overwrite — a type a lower-priority protocol (e.g. mDNS) + already determined. Only fills the absence; two known types are resolved elsewhere. + """ + new_t = (device.type or "").strip().lower() + if new_t and new_t != "unknown": + return + old_t = (existing.type or "").strip().lower() + if not old_t or old_t == "unknown": + return + device.type = existing.type + device.category = existing.category or category_for_device_type(old_t) + + def _hydrate_mdns_from_ssdp_profile_cache(self, device: Device, prior_row: Device | None = None) -> None: + """Merge SSDP disk-cache hints onto an mDNS row. + + Precedence among inputs (see ``merge.information_precedence`` in ``~/.config/netneighbor/discovery.json``): + user prefs override SSDP live; SSDP live overrides this disk cache; this cache overrides plain mDNS + naming/type inference. + + **Rule 0** — user name / location prefs override everything (see + :meth:`_has_effective_name_override`, :meth:`_apply_name_override`). + **Rule 1** — persisted SSDP ``friendlyName`` / profile ``name`` overrides mDNS naming unless rule 0 applies. + """ + if device.source != "mdns": + return + sip = str(device.ip).strip() + if not sip: + return + row = self._ssdp_profile_cache_by_ip.get(sip) + if not isinstance(row, dict): + return + if not isinstance(device.metadata, dict): + device.metadata = {} + xml_fields = row.get("xml_fields") + if isinstance(xml_fields, dict): + md_xml = device.metadata.get("xml_fields") + if not isinstance(md_xml, dict): + md_xml = {} + for key, value in xml_fields.items(): + if key not in md_xml and value: + md_xml[key] = value + if md_xml: + device.metadata["xml_fields"] = md_xml + # Also carry over raw XML and SSDP location so the "Device data" tab + # appears in details even when there is no live SSDP device. + if not device.metadata.get("xml"): + raw_xml = row.get("raw_xml") + if isinstance(raw_xml, str) and raw_xml.strip(): + device.metadata["xml"] = raw_xml + if not device.metadata.get("location"): + ssdp_loc = row.get("ssdp_location") + if isinstance(ssdp_loc, str) and ssdp_loc.strip(): + device.metadata["location"] = ssdp_loc + cached_display = self._ssdp_profile_display_name(row) + if cached_display and not self._has_effective_name_override(device, prior_row): + # Rule 1 vs mDNS; skipped when rule 0 applies (see _has_effective_name_override). + device.name = cached_display + self._apply_ssdp_cache_type_to_mdns(device, row) + + def _hydrate_ssdp_from_profile_cache(self, device: Device) -> None: + """Pre-populate empty xml_fields on a live SSDP device from the disk profile cache. + + When the live XML fetch has not yet completed (or previously failed), the + cached xml_fields from a prior successful fetch are used as an immediate + starting point so the details panel is never blank. The live fetch result + will overwrite these values once it arrives (higher-precedence merge path). + """ + if device.source != "ssdp": + return + sip = str(device.ip).strip() + if not sip: + return + row = self._ssdp_profile_cache_by_ip.get(sip) + if not isinstance(row, dict): + return + if not isinstance(device.metadata, dict): + device.metadata = {} + cached_xml = row.get("xml_fields") + if not isinstance(cached_xml, dict) or not cached_xml: + return + md_xml = device.metadata.get("xml_fields") + if not isinstance(md_xml, dict): + md_xml = {} + for key, value in cached_xml.items(): + if key not in md_xml and value: + md_xml[key] = value + if md_xml: + device.metadata["xml_fields"] = md_xml + if not device.metadata.get("xml"): + raw_xml = row.get("raw_xml") + if isinstance(raw_xml, str) and raw_xml.strip(): + device.metadata["xml"] = raw_xml + if not device.metadata.get("location"): + ssdp_loc = row.get("ssdp_location") + if isinstance(ssdp_loc, str) and ssdp_loc.strip(): + device.metadata["location"] = ssdp_loc + + def _apply_ssdp_cache_type_to_mdns(self, device: Device, row: dict) -> None: + """Use SSDP profile-cache type hints after merging ``xml_fields`` (not only when mDNS type is unknown). + + Samba ``_smb._tcp`` is inferred as ``computer`` before UUID/MAC may arrive; disk cache may already + hold ``modelType: NAS`` or a richer ``type`` from a prior SSDP observation. + """ + md = device.metadata if isinstance(device.metadata, dict) else {} + xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} + mt = (xf.get("modelType") or "").strip().lower() + if mt == "nas": + device.type = "nas" + device.category = category_for_device_type("nas") + return + cached = row.get("type") + if not isinstance(cached, str) or not cached.strip(): + return + ct = cached.strip().lower() + cur = str(device.type or "").strip().lower() + if cur == "unknown": + device.type = ct + device.category = category_for_device_type(ct) + return + # "esp32" is a low-confidence fallback ("ESP3D board, machine unknown"): let a stronger + # cached/cross-source type (cnc, 3dprinter, nas, …) replace it, same as the other weak types. + weak = {"unknown", "http", "https", "computer", "esp32"} + if cur in weak and self._cross_protocol_type_rank(ct) > self._cross_protocol_type_rank(cur): + device.type = ct + device.category = category_for_device_type(ct) + + def _mdns_web_endpoint(self, md: dict, device: Device) -> tuple[int, bool]: + """HTTP(S) port from merged mDNS ``_http._tcp`` / ``_https._tcp`` rows.""" + services = md.get("services") if isinstance(md.get("services"), list) else [] + https_p = 0 + http_p = 0 + for svc in services: + if not isinstance(svc, dict): + continue + name = str(svc.get("service", "")).lower() + port = int(svc.get("port", 0) or 0) + if port <= 0: + continue + if "_https._tcp" in name: + https_p = https_p or port + if "_http._tcp" in name: + http_p = http_p or port + if https_p: + return (https_p, True) + if http_p: + return (http_p, False) + dp = int(device.port or 0) + if dp > 0: + return (dp, False) + return (80, False) + + def _collect_mdns_descriptor_candidates(self, md: dict, ip: str, fallback_port: int, fallback_https: bool) -> list[tuple[int, str]]: + scored: dict[str, int] = {} + + def push(url: str) -> None: + u = (url or "").strip() + if not u: + return + q = self._ssdp_location_quality_score(u) + if q < 2: + return + prev = scored.get(u) + if prev is None or q > prev: + scored[u] = q + + def push_relative(path_fragment: str, port: int, https: bool) -> None: + norm = _normalize_mdns_relative_descriptor_path(path_fragment) + if not norm: + return + if norm.startswith(("http://", "https://")): + push(norm) + return + base = _http_base_url_for_descriptor(ip, port, https=https) + if not base: + return + full = _join_descriptor_base_and_path(base, norm) + if full: + push(full) + + agg_port, agg_https = int(fallback_port or 0), fallback_https + if agg_port <= 0: + agg_port = 80 + + combined = md.get("txt") if isinstance(md.get("txt"), dict) else {} + if isinstance(combined, dict): + for _key, val in combined.items(): + if not isinstance(val, str): + continue + v = val.strip() + if v.startswith(("http://", "https://")): + push(v) + for pk in ("path", "rp", "description_path", "descriptor_path", "device_description"): + raw = combined.get(pk) + if isinstance(raw, str) and raw.strip(): + push_relative(raw, agg_port, agg_https) + for _key, val in combined.items(): + if not isinstance(val, str): + continue + v = val.strip() + if ".xml" not in v.lower(): + continue + if v.startswith(("http://", "https://")): + continue + lk = str(_key).lower() + if lk in {"path", "rp", "description_path", "descriptor_path", "device_description"}: + continue + push_relative(v, agg_port, agg_https) + + services = md.get("services") if isinstance(md.get("services"), list) else [] + for svc in services: + if not isinstance(svc, dict): + continue + stxt = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} + if not stxt: + continue + sn = str(svc.get("service", "")).lower() + sport = int(svc.get("port", 0) or 0) + if sport <= 0: + sport = agg_port + if "_https._tcp" in sn: + svc_https = True + elif "_http._tcp" in sn: + svc_https = False + else: + svc_https = agg_https + + for _key, val in stxt.items(): + if not isinstance(val, str): + continue + v = val.strip() + if v.startswith(("http://", "https://")): + push(v) + for pk in ("path", "rp", "description_path", "descriptor_path", "device_description"): + raw = stxt.get(pk) + if isinstance(raw, str) and raw.strip(): + push_relative(raw, sport, svc_https) + for key, val in stxt.items(): + if not isinstance(val, str): + continue + v = val.strip() + if ".xml" not in v.lower(): + continue + if v.startswith(("http://", "https://")): + continue + lk = str(key).lower() + if lk in {"path", "rp", "description_path", "descriptor_path", "device_description"}: + continue + push_relative(v, sport, svc_https) + + return sorted(((q, u) for u, q in scored.items()), key=lambda t: t[0], reverse=True) + + def _best_mdns_descriptor_template(self, device: Device) -> str | None: + """Full descriptor URL if mDNS TXT advertises a UPnP XML path (often faster than waiting for SSDP).""" + if device.source != "mdns": + return None + md = device.metadata if isinstance(device.metadata, dict) else {} + sip = str(device.ip).strip() + if not sip: + return None + port, https = self._mdns_web_endpoint(md, device) + candidates = self._collect_mdns_descriptor_candidates(md, sip, port, https) + if not candidates: + return None + return candidates[0][1] + + def _resolve_anticipatory_descriptor_for_mdns( + self, device: Device, sip: str + ) -> tuple[str, AnticipatoryDescriptorSource] | None: + """Choose descriptor GET URL for anticipatory fetch — **one precedence chain**. + + The HTTP GET target is not ambiguous: we never blend SSDP cache with mDNS as competing URLs. + + 1. ``ssdp_profile_cache``: persisted SSDP ``LOCATION`` from disk profile cache (same path/query as + prior SSDP observation); host rewritten to ``sip``. + 2. ``mdns_txt``: only when (1) has no usable ``ssdp_location`` — TXT may advertise the descriptor + before SSDP has run / populated cache. + """ + with self._ssdp_profile_cache_lock: + self._ssdp_profile_cache_by_ip, self._ssdp_profile_cache_emit_rows = ( + self._load_ssdp_profile_cache_by_ip() + ) + row = self._ssdp_profile_cache_by_ip.get(sip) + loc = row.get("ssdp_location") if isinstance(row, dict) else None + loc_s = loc.strip() if isinstance(loc, str) and loc.strip() else "" + if loc_s: + url_new = _descriptor_url_with_ip(loc_s, sip) + if url_new: + return (url_new, "ssdp_profile_cache") + mdns_tpl = self._best_mdns_descriptor_template(device) + if mdns_tpl: + url_new = _descriptor_url_with_ip(mdns_tpl, sip) + if url_new: + return (url_new, "mdns_txt") + return None + + def _schedule_anticipatory_descriptor_fetch(self, device: Device) -> None: + """Prefetch UPnP descriptor XML for mDNS hosts when we can build the URL early. + + Resolution uses :meth:`_resolve_anticipatory_descriptor_for_mdns` (single source-of-truth chain). + """ + if device.source != "mdns": + return + if not device.online: + self._anticipatory_fetch_attempted.discard(device.key) + return + ssdp = self._ssdp_discovery + if ssdp is None: + return + k = device.key + if k in self._anticipatory_fetch_attempted: + return + sip = str(device.ip).strip() + if not sip or sip in {"0.0.0.0", "::"}: + return + + resolved = self._resolve_anticipatory_descriptor_for_mdns(device, sip) + if not resolved: + return + url_new, url_source = resolved + + self._anticipatory_fetch_attempted.add(k) + self._logger.debug( + "Anticipatory descriptor fetch scheduled ip=%s source=%s url=%s", + sip, + url_source, + url_new, + ) + + def worker() -> None: + try: + xml_fields, raw_xml = ssdp.fetch_descriptor_xml(url_new) + except Exception: + self._mdns_logger.warning("Anticipatory descriptor fetch failed for %s", url_new, exc_info=True) + return + if not xml_fields and not raw_xml: + return + + def apply_on_idle() -> None: + self._apply_prefetched_descriptor( + k, + url_new, + xml_fields or {}, + raw_xml, + url_source=url_source, + ) + + self._schedule_on_main_thread(apply_on_idle) + + threading.Thread(target=worker, name="NetNeighbor-anticipatory-xml", daemon=True).start() + + def _apply_prefetched_descriptor( + self, + device_key: str, + fetch_url: str, + xml_fields: dict, + raw_xml: str | None, + *, + url_source: AnticipatoryDescriptorSource, + ) -> None: + if device_key in self._anticipatory_reentrant: + return + existing = self._devices.get(device_key) + if existing is None or existing.source != "mdns": + return + self._anticipatory_reentrant.add(device_key) + try: + md = dict(existing.metadata) if isinstance(existing.metadata, dict) else {} + prev_xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} + merged_xf = dict(prev_xf) + for fk, fv in xml_fields.items(): + if fv is None: + continue + if isinstance(fv, str) and not fv.strip(): + continue + merged_xf[fk] = fv.strip() if isinstance(fv, str) else fv + md["xml_fields"] = merged_xf + if raw_xml: + md["xml"] = raw_xml + md["anticipatory_descriptor_url"] = fetch_url + md["anticipatory_descriptor_source"] = url_source + name = existing.name + fn = merged_xf.get("friendlyName") or merged_xf.get("displayName") + if not self._has_effective_name_override(existing): + if isinstance(fn, str) and fn.strip() and self._is_generic_discovery_name(name): + name = fn.strip() + url = existing.url + if not url: + pu = merged_xf.get("presentationURL") + if isinstance(pu, str) and pu.strip(): + url = pu.strip() + icon = existing.icon + if not icon: + iu = merged_xf.get("iconURL") + if isinstance(iu, str) and iu.strip(): + icon = iu.strip() + updated = Device( + name=name, + ip=existing.ip, + port=existing.port, + type=existing.type, + category=existing.category, + source=existing.source, + url=url, + metadata=md, + last_seen=existing.last_seen, + online=existing.online, + monitored=existing.monitored, + icon=icon, + ) + self._apply_field_mapping_rules(updated) + self._apply_type_override(updated) + self._apply_name_override(updated) + self._apply_location_override(updated) + self._apply_url_override(updated) + self._apply_device_commands(updated) + self._apply_custom_command_override(updated) + self._apply_monitored_override(updated) + self._devices[device_key] = updated + self._run_location_reapply_sweep() + self._notify() + finally: + self._anticipatory_reentrant.discard(device_key) + + def _stable_identity_available(self, device: Device) -> bool: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + return bool(self._extract_uid(metadata) or self._extract_mac(metadata)) + + def _pending_identity_key(self, device: Device) -> str: + return f"{(device.source or '').strip().lower()}:{str(device.ip).strip()}:{int(device.port)}" + + def _should_hold_for_stable_identity(self, device: Device) -> bool: + """Delay first appearance briefly until UID/MAC shows up, then release.""" + if device.source not in {"mdns", "ssdp"}: + return False + if not bool(device.online): + self._identity_pending.pop(self._pending_identity_key(device), None) + return False + if self._stable_identity_available(device): + pending_key = self._pending_identity_key(device) + if pending_key in self._identity_pending: + self._identity_pending.pop(pending_key, None) + self._device_event_logger(device.source).debug( + "identity_resolved ip=%s port=%s source=%s", + device.ip, + device.port, + device.source, + ) + return False + + now = datetime.now(timezone.utc) + pending_key = self._pending_identity_key(device) + first_seen, _prev = self._identity_pending.get(pending_key, (now, device)) + self._identity_pending[pending_key] = (first_seen, device) + if now - first_seen < timedelta(seconds=_IDENTITY_HOLD_SECONDS): + self._device_event_logger(device.source).debug( + "identity_pending ip=%s port=%s source=%s held_for_ms=%s", + device.ip, + device.port, + device.source, + int((now - first_seen).total_seconds() * 1000), + ) + return True + self._device_event_logger(device.source).debug( + "identity_pending_timeout ip=%s port=%s source=%s hold_s=%s", + device.ip, + device.port, + device.source, + _IDENTITY_HOLD_SECONDS, + ) + self._identity_pending.pop(pending_key, None) + return False + + def _emit_presence_hooks_if_transition(self, device: Device, prev_online: bool | None, now_online: bool) -> None: + # Skip first-seen already-offline rows (monitoring placeholders, etc.). + if now_online and prev_online is not True: + transition: PresenceTransitionKind = "online" + elif prev_online is True and not now_online: + transition = "offline" + else: + return + host_key = self._presence_dedupe_key(device) + if host_key: + if transition == "online": + if host_key in self._presence_announced_hosts: + return + self._presence_announced_hosts.add(host_key) + else: + self._presence_announced_hosts.discard(host_key) + if not self._presence_hooks: + return + for hook in tuple(self._presence_hooks): + try: + hook(device, transition) + except Exception: + self._logger.exception("Presence transition hook failed (event=%s)", transition) + + def set_type_overrides(self, overrides: dict[str, str]) -> None: + normalized: dict[str, str] = {} + for key, value in overrides.items(): + if not isinstance(key, str) or not isinstance(value, str): + continue + value_norm = value.strip().lower() + if value_norm: + normalized[key] = value_norm + self._type_overrides = normalized + + def get_type_overrides(self) -> dict[str, str]: + return dict(self._type_overrides) + + def set_name_overrides(self, overrides: dict[str, str]) -> None: + normalized: dict[str, str] = {} + for key, value in overrides.items(): + if not isinstance(key, str) or not isinstance(value, str): + continue + value_norm = value.strip() + if value_norm: + normalized[key] = value_norm + self._name_overrides = normalized + + def get_name_overrides(self) -> dict[str, str]: + return dict(self._name_overrides) + + def set_url_overrides(self, overrides: dict[str, str]) -> None: + normalized: dict[str, str] = {} + for key, value in overrides.items(): + if not isinstance(key, str) or not isinstance(value, str): + continue + value_norm = value.strip() + if value_norm: + normalized[key] = value_norm + self._url_overrides = normalized + + def get_url_overrides(self) -> dict[str, str]: + return dict(self._url_overrides) + + def set_device_commands_overrides(self, overrides: object) -> None: + """Bulk-load per-device commands from persisted preferences. + Accepts new list format or legacy dict format (auto-migrated to override mode).""" + normalized: dict[str, list[dict]] = {} + if not isinstance(overrides, dict): + self._device_commands = normalized + return + for key, raw in overrides.items(): + if not isinstance(key, str): + continue + # Legacy format: {scheme: {ip, port}} → convert to list with mode=override + if isinstance(raw, dict): + raw = [ + {"scheme": s, "ip": ep.get("ip", ""), "port": ep.get("port", 0), + "mode": "override", "label": ""} + for s, ep in raw.items() if isinstance(ep, dict) + ] + if not isinstance(raw, list): + continue + valid = _normalize_command_list(raw) + if valid: + normalized[key] = valid + self._device_commands = normalized + + def get_device_commands_overrides(self) -> dict[str, list[dict]]: + return {k: [dict(c) for c in cmds] for k, cmds in self._device_commands.items()} + + def set_custom_command_overrides(self, overrides: dict[str, str]) -> None: + """Bulk-load per-device custom command overrides from persisted preferences.""" + normalized: dict[str, str] = {} + if isinstance(overrides, dict): + for key, cmd in overrides.items(): + if isinstance(key, str) and isinstance(cmd, str) and cmd.strip(): + normalized[key] = cmd.strip() + self._custom_command_overrides = normalized + + def get_custom_command_overrides(self) -> dict[str, str]: + return dict(self._custom_command_overrides) + + def set_location_overrides(self, overrides: dict[str, str]) -> None: + normalized: dict[str, str] = {} + for key, value in overrides.items(): + if not isinstance(key, str) or not isinstance(value, str): + continue + value_norm = value.strip() + if value_norm: + normalized[key] = value_norm + self._location_overrides = normalized + changed = False + for device in list(self._devices.values()): + before = "" + metadata = device.metadata if isinstance(device.metadata, dict) else {} + value = metadata.get("user_location") + if isinstance(value, str): + before = value + self._apply_location_override(device) + metadata_after = device.metadata if isinstance(device.metadata, dict) else {} + after_raw = metadata_after.get("user_location") + after = after_raw if isinstance(after_raw, str) else "" + if before != after: + changed = True + if self._run_location_reapply_sweep(): + changed = True + if changed: + self._notify() + + def get_location_overrides(self) -> dict[str, str]: + return dict(self._location_overrides) + + def set_location_policy(self, allowed_locations: list[str], auto_add_discovered: bool) -> None: + """Discovered locations are applied only when listed here or when auto-add is on; + otherwise the device stays without location. User overrides are unaffected.""" + mapping: dict[str, str] = {} + for raw in allowed_locations or []: + if isinstance(raw, str) and raw.strip(): + mapping.setdefault(raw.strip().casefold(), raw.strip()) + self._allowed_locations = mapping + self._auto_add_discovered_locations = bool(auto_add_discovered) + # Re-evaluate every cached device against the new policy. + self.set_location_overrides(self.get_location_overrides()) + + def set_field_mapping_rules(self, rules: dict[str, dict[str, list[str]]]) -> None: + normalized: dict[str, dict[str, list[str]]] = {} + for key, value in rules.items(): + if not isinstance(key, str) or not isinstance(value, dict): + continue + per_target: dict[str, list[str]] = {} + for target in ("name", "location", "information"): + raw = value.get(target) + if not isinstance(raw, list): + continue + cleaned = [str(x).strip() for x in raw if isinstance(x, str) and str(x).strip()] + if cleaned: + per_target[target] = list(dict.fromkeys(cleaned)) + if per_target: + normalized[key] = per_target + self._field_mapping_rules = normalized + changed = False + for device in list(self._devices.values()): + before_name = device.name + before_info = "" + before_loc = "" + md = device.metadata if isinstance(device.metadata, dict) else {} + if isinstance(md.get("information"), str): + before_info = md.get("information", "") + if isinstance(md.get("user_location"), str): + before_loc = md.get("user_location", "") + self._apply_field_mapping_rules(device) + self._apply_name_override(device) + self._apply_location_override(device) + md_after = device.metadata if isinstance(device.metadata, dict) else {} + after_info = md_after.get("information") if isinstance(md_after.get("information"), str) else "" + after_loc = md_after.get("user_location") if isinstance(md_after.get("user_location"), str) else "" + if device.name != before_name or after_info != before_info or after_loc != before_loc: + changed = True + if changed: + self._notify() + + def get_field_mapping_rules(self) -> dict[str, dict[str, list[str]]]: + out: dict[str, dict[str, list[str]]] = {} + for key, value in self._field_mapping_rules.items(): + out[key] = {target: list(paths) for target, paths in value.items()} + return out + + def set_monitored_overrides(self, overrides: dict[str, bool]) -> None: + normalized: dict[str, bool] = {} + for key, value in overrides.items(): + if isinstance(key, str): + normalized[key] = bool(value) + self._monitored_overrides = normalized + + def get_monitored_overrides(self) -> dict[str, bool]: + return dict(self._monitored_overrides) + + def set_hidden_overrides(self, overrides: dict[str, bool], *, notify: bool = True) -> None: + normalized: dict[str, bool] = {} + for key, value in overrides.items(): + if isinstance(key, str): + normalized[key] = bool(value) + self._hidden_overrides = normalized + changed = False + for device in self._devices_snapshot(): + before = device.hidden + self._apply_hidden_override(device) + if device.hidden != before: + changed = True + if changed and notify: + self._notify() + + def get_hidden_overrides(self) -> dict[str, bool]: + return dict(self._hidden_overrides) + + def set_last_seen_overrides(self, overrides: dict[str, str]) -> None: + normalized: dict[str, str] = {} + for key, value in overrides.items(): + if isinstance(key, str) and isinstance(value, str) and value.strip(): + normalized[key] = value.strip() + self._last_seen_overrides = normalized + + def get_last_seen_overrides(self) -> dict[str, str]: + return dict(self._last_seen_overrides) + + def restore_monitored_snapshots(self, snapshots: list[dict]) -> None: + if not isinstance(snapshots, list): + return + changed = False + for raw in snapshots: + if not isinstance(raw, dict): + continue + source = str(raw.get("source", "unknown")).strip().lower() + ip = str(raw.get("ip", "")).strip() + port_raw = raw.get("port", 0) + try: + port = int(port_raw) + except (TypeError, ValueError): + continue + if not ip or port <= 0: + continue + metadata = raw.get("metadata") + if not isinstance(metadata, dict): + metadata = {} + device = Device( + name=str(raw.get("name", "Unknown")) or "Unknown", + ip=ip, + port=port, + type=str(raw.get("type", "unknown")) or "unknown", + category=str(raw.get("category", "Unknown Devices")) or "Unknown Devices", + source=source or "unknown", + url=raw.get("url") if isinstance(raw.get("url"), str) else None, + metadata=metadata, + online=False, + monitored=True, + icon=raw.get("icon") if isinstance(raw.get("icon"), str) else None, + ) + seen_text = raw.get("last_seen") + if isinstance(seen_text, str) and seen_text.strip(): + try: + device.last_seen = datetime.fromisoformat(seen_text.strip()) + except ValueError: + pass + self._apply_type_override(device) + self._apply_monitored_override(device) + if not device.monitored: + continue + existing = self._devices.get(device.key) + if existing is not None and existing.online: + continue + self._devices[device.key] = device + changed = True + if changed: + self._notify() + + def set_device_type_override(self, source: str, ip: str, port: int, device_type: str | None) -> None: + changed = False + for old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + if device_type is None or not str(device_type).strip() or str(device_type).strip().lower() == "auto": + self._type_overrides.pop(preferred_key, None) + self._type_overrides.pop(endpoint_key, None) + else: + self._type_overrides.pop(endpoint_key, None) + self._type_overrides[preferred_key] = str(device_type).strip().lower() + self._apply_type_override(existing) + new_key = existing.key + if new_key != old_key: + self._devices.pop(old_key, None) + self._devices[new_key] = existing + changed = True + if changed: + self._notify() + + def set_device_name_override(self, source: str, ip: str, port: int, device_name: str | None) -> None: + changed = False + for _old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_name_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + if device_name is None or not str(device_name).strip(): + self._name_overrides.pop(preferred_key, None) + self._name_overrides.pop(endpoint_key, None) + existing.name = self._default_name_for_device(existing) + else: + self._name_overrides.pop(endpoint_key, None) + self._name_overrides[preferred_key] = str(device_name).strip() + self._apply_name_override(existing) + changed = True + if changed: + self._notify() + + def set_device_location_override(self, source: str, ip: str, port: int, location: str | None) -> None: + changed = False + for _old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_name_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + if location is None or not str(location).strip(): + self._location_overrides.pop(preferred_key, None) + self._location_overrides.pop(endpoint_key, None) + else: + self._location_overrides.pop(endpoint_key, None) + self._location_overrides[preferred_key] = str(location).strip() + self._apply_location_override(existing) + changed = True + if changed: + self._notify() + + def set_device_url_override(self, source: str, ip: str, port: int, url: str | None) -> None: + changed = False + for _old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_name_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + if url is None or not str(url).strip(): + self._url_overrides.pop(preferred_key, None) + self._url_overrides.pop(endpoint_key, None) + else: + self._url_overrides.pop(endpoint_key, None) + self._url_overrides[preferred_key] = str(url).strip() + self._apply_url_override(existing) + changed = True + if changed: + self._notify() + + def set_device_commands( + self, source: str, ip: str, port: int, commands: list[dict], + ) -> None: + """Replace all per-device commands for a specific device.""" + changed = False + for _old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_name_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + self._device_commands.pop(endpoint_key, None) + valid = _normalize_command_list(commands) if isinstance(commands, list) else [] + if valid: + self._device_commands[preferred_key] = valid + else: + self._device_commands.pop(preferred_key, None) + self._apply_device_commands(existing) + changed = True + if changed: + self._notify() + + def set_device_custom_command(self, source: str, ip: str, port: int, cmd: str | None) -> None: + """Set or clear a per-device custom command override.""" + changed = False + for _old_key, existing in list(self._devices.items()): + if existing.source != source or existing.ip != ip or existing.port != port: + continue + preferred_key = self._make_name_override_key_for_device(existing) + endpoint_key = self._make_override_key(source, ip, port) + if cmd is None or not str(cmd).strip(): + self._custom_command_overrides.pop(preferred_key, None) + self._custom_command_overrides.pop(endpoint_key, None) + else: + self._custom_command_overrides.pop(endpoint_key, None) + self._custom_command_overrides[preferred_key] = str(cmd).strip() + self._apply_custom_command_override(existing) + changed = True + if changed: + self._notify() + + def set_device_field_mapping_rule(self, source: str, ip: str, port: int, target: str, field_path: str) -> None: + target_norm = str(target).strip().lower() + path_norm = str(field_path).strip() + if target_norm not in {"name", "location", "information"} or not path_norm: + return + changed = False + ip_norm = str(ip).strip() + for _old_key, existing in list(self._devices.items()): + if str(existing.ip).strip() != ip_norm: + continue + preferred_key = self._make_name_override_key_for_device(existing) + rules = self._field_mapping_rules.get(preferred_key) + if not isinstance(rules, dict): + rules = {} + bucket = rules.get(target_norm) + if not isinstance(bucket, list): + bucket = [] + if path_norm not in bucket: + bucket.append(path_norm) + rules[target_norm] = bucket + self._field_mapping_rules[preferred_key] = rules + # Apply even when the rule already exists: same-IP rows often share one key + # (SSDP + mDNS by UID), and the second row must be renamed too. + changed = True + self._apply_field_mapping_rules(existing) + self._apply_location_override(existing) + self._apply_name_override(existing) + if changed: + self._notify() + + def remove_device_field_mapping_rule( + self, source: str, ip: str, port: int, target: str, field_path: str | None = None + ) -> None: + target_norm = str(target).strip().lower() + if target_norm not in {"name", "location", "information"}: + return + field_norm = str(field_path).strip() if isinstance(field_path, str) else "" + changed = False + ip_norm = str(ip).strip() + for _old_key, existing in list(self._devices.items()): + if str(existing.ip).strip() != ip_norm: + continue + preferred_key = self._make_name_override_key_for_device(existing) + rules = self._field_mapping_rules.get(preferred_key) + if not isinstance(rules, dict): + continue + bucket = rules.get(target_norm) + if not isinstance(bucket, list) or not bucket: + continue + if field_norm: + new_bucket = [x for x in bucket if x != field_norm] + else: + new_bucket = [] + if new_bucket == bucket: + continue + if new_bucket: + rules[target_norm] = new_bucket + else: + rules.pop(target_norm, None) + if rules: + self._field_mapping_rules[preferred_key] = rules + else: + self._field_mapping_rules.pop(preferred_key, None) + changed = True + self._apply_field_mapping_rules(existing) + self._apply_location_override(existing) + self._apply_name_override(existing) + if changed: + self._notify() + + def get_device_field_mapping_rules(self, device: Device) -> dict[str, list[str]]: + out: dict[str, list[str]] = {} + ip_norm = str(device.ip).strip() + for row in self._devices.values(): + if str(row.ip).strip() != ip_norm: + continue + preferred_key = self._make_name_override_key_for_device(row) + value = self._field_mapping_rules.get(preferred_key) + if not isinstance(value, dict): + continue + for target, paths in value.items(): + if not isinstance(paths, list): + continue + bucket = out.get(target) + if not isinstance(bucket, list): + bucket = [] + for path in paths: + if isinstance(path, str) and path.strip() and path not in bucket: + bucket.append(path) + out[target] = bucket + return out + + def _merge_ssdp_metadata(self, old_meta: dict, new_meta: dict, old_name: str, new_name: str) -> dict: + old_meta = old_meta if isinstance(old_meta, dict) else {} + new_meta = new_meta if isinstance(new_meta, dict) else {} + merged = dict(old_meta) + merged.update(new_meta) + + old_xml_fields = old_meta.get("xml_fields") if isinstance(old_meta.get("xml_fields"), dict) else {} + new_xml_fields = new_meta.get("xml_fields") if isinstance(new_meta.get("xml_fields"), dict) else {} + old_rank = self._ssdp_profile_rank(old_xml_fields) + new_rank = self._ssdp_profile_rank(new_xml_fields) + preferred_xml_fields = old_xml_fields if old_rank >= new_rank else new_xml_fields + self._ssdp_logger.debug( + "SSDP profile rank old=%s new=%s selected=%s", + old_rank, + new_rank, + "old" if old_rank >= new_rank else "new", + ) + + merged_xml_fields = dict(old_xml_fields) + for key, value in new_xml_fields.items(): + if value is None: + continue + if isinstance(value, str): + value_norm = value.strip() + if not value_norm or value_norm.lower() == "unavailable": + continue + old_value = merged_xml_fields.get(key) + if not old_value: + merged_xml_fields[key] = value_norm + continue + # Keep richer data when two payloads disagree (e.g. Sonos speaker group vs full root description). + if len(value_norm) > len(str(old_value).strip()): + merged_xml_fields[key] = value_norm + else: + merged_xml_fields[key] = value + + # Strict preference for the richer/profile-ranked XML fields. + for strict_key in ("friendlyName", "deviceType", "iconURL", "icons_description"): + preferred_value = preferred_xml_fields.get(strict_key) + if isinstance(preferred_value, str) and preferred_value.strip(): + merged_xml_fields[strict_key] = preferred_value.strip() + + merged["xml_fields"] = merged_xml_fields + + # Track alternate names instead of overwriting main identity. + aliases = merged.get("alternate_names") + if not isinstance(aliases, list): + aliases = [] + for candidate in (old_name, new_name): + if not isinstance(candidate, str): + continue + value = candidate.strip() + if not value or value in aliases: + continue + aliases.append(value) + self._ssdp_logger.debug("SSDP alias tracked: %s", value) + merged["alternate_names"] = aliases + + # Keep last known information text when a partial payload does not provide it. + old_info = old_meta.get("information") + new_info = new_meta.get("information") + if isinstance(new_info, str) and new_info.strip(): + merged["information"] = new_info.strip() + elif isinstance(old_info, str) and old_info.strip(): + merged["information"] = old_info.strip() + + old_xml = old_meta.get("xml") + new_xml = new_meta.get("xml") + if isinstance(old_xml, str) and isinstance(new_xml, str): + if old_rank >= new_rank and len(old_xml.strip()) >= len(new_xml.strip()): + merged["xml"] = old_xml + self._ssdp_logger.debug("SSDP raw XML preserved from previous richer profile") + elif isinstance(old_xml, str) and not isinstance(new_xml, str): + merged["xml"] = old_xml + self._ssdp_logger.debug("SSDP raw XML preserved because new payload has no XML") + + merged["location"] = self._pick_better_ssdp_location( + old_meta.get("location"), + new_meta.get("location"), + old_rank, + new_rank, + ) + + return merged + + def _ssdp_location_quality_score(self, value: str) -> int: + s = (value or "").strip() + if not s: + return -1 + low = s.lower() + score = 0 + if low.startswith(("http://", "https://")): + score += 1 + if low.endswith(".xml"): + score += 1 + if any(x in low for x in ("device-desc.xml", "description.xml", "/ssdp/")): + score += 4 + if "/dd.xml" in low: + score -= 2 + try: + parsed = urlparse(s) + if parsed.port in {80, 443, 8008, 1400, 5000}: + score += 1 + except Exception: + pass + return score + + def _pick_better_ssdp_location(self, old_loc, new_loc, old_rank: int, new_rank: int) -> str | None: + old_s = old_loc.strip() if isinstance(old_loc, str) and old_loc.strip() else "" + new_s = new_loc.strip() if isinstance(new_loc, str) and new_loc.strip() else "" + if not old_s: + self._ssdp_logger.debug( + "SSDP XML location selected(new-only) old=%r new=%r old_rank=%s new_rank=%s", + old_s, + new_s, + old_rank, + new_rank, + ) + return new_s or None + if not new_s: + self._ssdp_logger.debug( + "SSDP XML location selected(old-only) old=%r new=%r old_rank=%s new_rank=%s", + old_s, + new_s, + old_rank, + new_rank, + ) + return old_s + old_q = self._ssdp_location_quality_score(old_s) + new_q = self._ssdp_location_quality_score(new_s) + # If one LOCATION looks clearly better, prefer it even if XML profile rank differs. + # This avoids sticky picks like random-port /dd.xml overriding DIAL device-desc.xml. + quality_gap = 3 + if new_q >= old_q + quality_gap: + self._ssdp_logger.debug( + "SSDP XML location selected(new-quality-gap) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", + old_s, + new_s, + old_rank, + new_rank, + old_q, + new_q, + ) + return new_s + if old_q >= new_q + quality_gap: + self._ssdp_logger.debug( + "SSDP XML location selected(old-quality-gap) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", + old_s, + new_s, + old_rank, + new_rank, + old_q, + new_q, + ) + return old_s + if new_rank > old_rank: + self._ssdp_logger.debug( + "SSDP XML location selected(new-better-rank) old=%r new=%r old_rank=%s new_rank=%s", + old_s, + new_s, + old_rank, + new_rank, + ) + return new_s + if old_rank > new_rank: + self._ssdp_logger.debug( + "SSDP XML location selected(old-better-rank) old=%r new=%r old_rank=%s new_rank=%s", + old_s, + new_s, + old_rank, + new_rank, + ) + return old_s + if new_q > old_q: + self._ssdp_logger.debug( + "SSDP XML location selected(new-better-quality) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", + old_s, + new_s, + old_rank, + new_rank, + old_q, + new_q, + ) + return new_s + # Keep previous location on tie for visual stability. + self._ssdp_logger.debug( + "SSDP XML location selected(old-stable) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", + old_s, + new_s, + old_rank, + new_rank, + old_q, + new_q, + ) + return old_s + + def _ssdp_profile_rank(self, xml_fields: dict) -> int: + if not isinstance(xml_fields, dict): + return 0 + device_type = str(xml_fields.get("deviceType", "")).lower() + score = 0 + if "schemas-upnp-org" in device_type: + score += 4 + if "smartspeaker-audio" in device_type: + score -= 1 + if isinstance(xml_fields.get("iconURL"), str) and xml_fields.get("iconURL", "").strip(): + score += 1 + if isinstance(xml_fields.get("manufacturer"), str) and xml_fields.get("manufacturer", "").strip(): + score += 1 + if isinstance(xml_fields.get("modelName"), str) and xml_fields.get("modelName", "").strip(): + score += 1 + # Penalise generic placeholder names where friendlyName == modelName. + # Manufacturers sometimes leave both fields identical (e.g. "Mediatek_MTXXXX"), + # which is less useful than a user-visible name from a co-hosted DIAL service. + friendly = str(xml_fields.get("friendlyName", "")).strip() + model = str(xml_fields.get("modelName", "")).strip() + if friendly and model and friendly.lower() == model.lower(): + score -= 3 + return score + + def _pick_ssdp_name(self, old_name: str, new_name: str, old_meta: dict, new_meta: dict) -> str: + old_name = old_name.strip() if isinstance(old_name, str) else "" + new_name = new_name.strip() if isinstance(new_name, str) else "" + if not old_name: + return new_name or "Unknown" + if not new_name: + return old_name + + if old_name.startswith(("SSDP Device ", "Router ", "Media Server ", "Printer ")) and not new_name.startswith( + ("SSDP Device ", "Router ", "Media Server ", "Printer ") + ): + return new_name + + old_fields = old_meta.get("xml_fields") if isinstance(old_meta, dict) and isinstance(old_meta.get("xml_fields"), dict) else {} + new_fields = new_meta.get("xml_fields") if isinstance(new_meta, dict) and isinstance(new_meta.get("xml_fields"), dict) else {} + if self._ssdp_profile_rank(new_fields) > self._ssdp_profile_rank(old_fields): + self._ssdp_logger.debug("SSDP name switched to newer profile name: %s", new_name) + return new_name + self._ssdp_logger.debug("SSDP name preserved from previous profile: %s", old_name) + return old_name + + def _find_existing_ssdp_by_endpoint(self, candidate: Device) -> tuple[str, Device] | tuple[None, None]: + candidate_mac = self._extract_mac(candidate.metadata) + for key, item in self._devices.items(): + if item.source != "ssdp": + continue + if item.ip != candidate.ip or item.port != candidate.port: + continue + existing_mac = self._extract_mac(item.metadata) + if candidate_mac and existing_mac and candidate_mac != existing_mac: + self._ssdp_logger.debug( + "SSDP endpoint match rejected due to MAC mismatch ip=%s port=%s old=%s new=%s", + candidate.ip, + candidate.port, + existing_mac, + candidate_mac, + ) + continue + if candidate_mac and not existing_mac: + self._ssdp_logger.debug( + "SSDP endpoint match accepted and upgraded with MAC ip=%s port=%s mac=%s", + candidate.ip, + candidate.port, + candidate_mac, + ) + if existing_mac and not candidate_mac: + self._ssdp_logger.debug( + "SSDP endpoint match accepted using existing MAC ip=%s port=%s mac=%s", + candidate.ip, + candidate.port, + existing_mac, + ) + return key, item + return key, item + return None, None + + def _find_existing_cross_protocol_by_identity(self, candidate: Device) -> tuple[str, Device] | tuple[None, None]: + """Find an existing row from another protocol for the same host identity.""" + candidate_host_key = self._make_override_key_for_device(candidate) + if not isinstance(candidate_host_key, str) or not candidate_host_key.startswith("host:"): + return None, None + for key, item in self._devices.items(): + if item.source == candidate.source: + continue + if self._make_override_key_for_device(item) != candidate_host_key: + continue + self._device_event_logger(candidate.source).debug( + "Cross-protocol dedup matched host=%s old=%s/%s:%s new=%s/%s:%s", + candidate_host_key, + item.source, + item.ip, + item.port, + candidate.source, + candidate.ip, + candidate.port, + ) + return key, item + return None, None + + def _cross_protocol_type_rank(self, device_type: str) -> int: + t = (device_type or "unknown").strip().lower() + return { + "unknown": 0, + "http": 12, + "https": 12, + "computer": 20, + "esp32": 22, + "router": 35, + "server": 37, + "rackserver": 37, + "desktop": 41, + "minipc": 41, + "allinone": 41, + "laptop": 41, + "smartphone": 41, + "nas": 38, + "mediaserver": 34, + "smartspeaker": 40, + "networkprinter": 55, + "multifunction_printer": 56, + "printer": 55, + "scanner": 52, + "smarttv": 41, + "smartdevice": 28, + "camera": 30, + "homeappliance": 26, + "cnc": 30, + "3dprinter": 32, + }.get(t, 8) + + def _is_generic_discovery_name(self, name: str) -> bool: + s = (name or "").strip().lower() + if not s: + return True + prefixes = ("ssdp device ", "mdns device ", "router ", "media server ", "printer ") + return any(s.startswith(prefix) for prefix in prefixes) + + def _protocol_merge_rank(self, source: str) -> int: + """Lower rank = higher precedence (earlier in ``discovery.json`` ``merge.protocol_order``).""" + s = (source or "").strip().lower() + order = self._protocol_merge_order + try: + return order.index(s) + except ValueError: + return len(order) + + def _choose_cross_protocol_display_name(self, existing: Device, incoming: Device) -> str: + """Prefer a non-generic name; if both are specific or both generic, prefer stronger protocol.""" + eg = self._is_generic_discovery_name(existing.name) + ig = self._is_generic_discovery_name(incoming.name) + if not eg and ig: + return existing.name + if eg and not ig: + return incoming.name + ir = self._protocol_merge_rank(incoming.source) + er = self._protocol_merge_rank(existing.source) + if ir < er: + return incoming.name + if er < ir: + return existing.name + return existing.name + + def _merge_cross_protocol_device(self, existing: Device, incoming: Device) -> Device: + """Merge SSDP/mDNS rows that represent the same host.""" + old_meta = existing.metadata if isinstance(existing.metadata, dict) else {} + new_meta = incoming.metadata if isinstance(incoming.metadata, dict) else {} + merged_meta = dict(old_meta) + # Keep per-protocol metadata snapshots to avoid losing diagnostics/details payloads. + proto_meta = merged_meta.get("protocol_metadata") if isinstance(merged_meta.get("protocol_metadata"), dict) else {} + proto_meta = dict(proto_meta) + proto_meta[str(existing.source)] = dict(old_meta) + proto_meta[str(incoming.source)] = dict(new_meta) + merged_meta["protocol_metadata"] = proto_meta + seen_sources = merged_meta.get("seen_sources") if isinstance(merged_meta.get("seen_sources"), list) else [] + merged_meta["seen_sources"] = sorted({str(x) for x in [*seen_sources, existing.source, incoming.source] if str(x).strip()}) + old_loc = old_meta.get("user_location") + new_loc = new_meta.get("user_location") + if isinstance(new_loc, str) and new_loc.strip(): + # Only overwrite user_location if there is no existing user preference. + if not (isinstance(old_loc, str) and old_loc.strip()): + merged_meta["user_location"] = new_loc.strip() + + old_rank = self._cross_protocol_type_rank(existing.type) + new_rank = self._cross_protocol_type_rank(incoming.type) + chosen_type = incoming.type if new_rank > old_rank else existing.type + chosen_category = category_for_device_type(chosen_type) + chosen_name = self._choose_cross_protocol_display_name(existing, incoming) + chosen_icon = existing.icon + if (not chosen_icon and incoming.icon) or new_rank > old_rank: + chosen_icon = incoming.icon or chosen_icon + chosen_url = existing.url or incoming.url + chosen_last_seen = existing.last_seen if existing.last_seen >= incoming.last_seen else incoming.last_seen + chosen_online = bool(existing.online or incoming.online) + + self._logger.debug( + "Cross-protocol merge kept=%s/%s:%s merged=%s/%s:%s type=%s->%s", + existing.source, + existing.ip, + existing.port, + incoming.source, + incoming.ip, + incoming.port, + existing.type, + chosen_type, + ) + + return Device( + name=chosen_name, + ip=existing.ip, + port=existing.port, + type=chosen_type, + category=chosen_category, + source=existing.source, + url=chosen_url, + metadata=merged_meta, + last_seen=chosen_last_seen, + online=chosen_online, + monitored=bool(existing.monitored), + icon=chosen_icon, + ) + + def _extract_mac(self, metadata: dict) -> str: + if not isinstance(metadata, dict): + return "" + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + mac = ( + xml_fields.get("mac") + or metadata.get("mac") + or metadata.get("mac_address") + or metadata.get("MAC") + or metadata.get("macAddress") + ) + if isinstance(mac, str) and mac.strip(): + return mac.strip().lower() + + def _mac_from_txt(txt: dict) -> str: + if not isinstance(txt, dict): + return "" + for key in ("mac", "hardware-address", "hwaddr", "device-mac", "machine"): + raw = txt.get(key) + if isinstance(raw, str) and raw.strip(): + return raw.strip().lower() + return "" + + top = _mac_from_txt(metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {}) + if top: + return top + services = metadata.get("services") + if isinstance(services, list): + for svc in services: + if not isinstance(svc, dict): + continue + got = _mac_from_txt(svc.get("txt") if isinstance(svc.get("txt"), dict) else {}) + if got: + return got + return "" + + def _apply_local_host_identity(self, device: Device) -> None: + """Classify the machine NetNeighbor runs on as a computer when no protocol can. + + Windows never answers WSD probes sent from the host itself and NetBIOS browsing + does not return the local machine either, so its only rows come from incidental + mDNS adverts (e.g. Spotify's ``_spotify-connect._tcp``) that carry no host + identity and would leave it in "Unknown Devices". Runs before + ``_apply_type_override`` so an explicit user type preference still wins. + """ + cur = (device.type or "unknown").strip().lower() + if cur not in {"", "unknown"}: + return + if not is_local_host_ip(str(device.ip).strip()): + return + device.type = "computer" + device.category = category_for_device_type("computer") + if isinstance(device.metadata, dict): + device.metadata["local_host"] = True + self._device_event_logger(device.source).debug( + "Local-host identity: ip=%s classified as computer (source=%s name=%s)", + device.ip, + device.source, + device.name, + ) + + def _apply_type_override(self, device: Device) -> None: + override_type = self._find_override_value(self._type_overrides, device) + if not override_type: + return + device.type = override_type + device.category = category_for_device_type(override_type) + + def _apply_name_override(self, device: Device) -> None: + """Rule 0: apply saved name prefs last among the early pipeline (overrides rule 1 and mDNS).""" + override_name = self._find_name_override_value(device) + if not override_name: + return + device.name = override_name + + def _apply_url_override(self, device: Device) -> None: + override_url = self._find_override_value(self._url_overrides, device) + if not isinstance(device.metadata, dict): + device.metadata = {} + if isinstance(override_url, str) and override_url.strip(): + device.metadata["url_override"] = override_url.strip() + else: + device.metadata.pop("url_override", None) + + def _apply_device_commands(self, device: Device) -> None: + cmds = self._find_override_value(self._device_commands, device) + if not isinstance(device.metadata, dict): + device.metadata = {} + valid = _normalize_command_list(cmds) if isinstance(cmds, list) else [] + if valid: + device.metadata["device_commands"] = valid + else: + device.metadata.pop("device_commands", None) + + def _apply_custom_command_override(self, device: Device) -> None: + cmd = self._find_override_value(self._custom_command_overrides, device) + if not isinstance(device.metadata, dict): + device.metadata = {} + if isinstance(cmd, str) and cmd.strip(): + device.metadata["custom_command"] = cmd.strip() + else: + device.metadata.pop("custom_command", None) + + def _clip_loc_log(self, value: str) -> str: + return value if len(value) <= 120 else value[:117] + "..." + + def _store_location_preference_for_device(self, device: Device, location: str) -> bool: + """Write identity-based location prefs (same key rules as set_device_location_override).""" + loc = str(location).strip() + if not loc or not is_plausible_room_location(loc): + return False + preferred_key = self._make_name_override_key_for_device(device) + endpoint_key = self._make_override_key(device.source, device.ip, device.port) + if self._location_overrides.get(preferred_key) == loc: + return False + self._location_overrides.pop(endpoint_key, None) + self._location_overrides[preferred_key] = loc + self._location_prefs_need_reapply = True + return True + + def _consume_location_prefs_need_reapply(self) -> bool: + if not self._location_prefs_need_reapply: + return False + self._location_prefs_need_reapply = False + return True + + def _run_location_reapply_sweep(self) -> bool: + """Re-apply location rules to all cached devices after prefs mutation; persist if needed.""" + any_round = False + rounds = 0 + while self._consume_location_prefs_need_reapply() and rounds < 8: + rounds += 1 + any_round = True + for existing in list(self._devices.values()): + self._apply_location_override(existing) + if any_round and self._location_prefs_dirty_callback is not None: + try: + self._location_prefs_dirty_callback() + except Exception: + self._logger.exception("location_prefs_dirty_callback failed") + return any_round + + def _apply_location_override(self, device: Device) -> None: + if not isinstance(device.metadata, dict): + device.metadata = {} + dev_log = self._device_event_logger(device.source) + cached_raw = self._find_location_override_value(device) + discovered_raw = self._default_location_for_device(device) + c_norm = cached_raw.strip() if isinstance(cached_raw, str) and cached_raw.strip() else "" + d_norm = discovered_raw.strip() if isinstance(discovered_raw, str) and discovered_raw.strip() else "" + + r_norm = self._resolved_field_rule_value(device, "location") + + chosen = "" + + if c_norm: + # User preference always wins over discovered location. + chosen = c_norm + dev_log.debug( + "Location: prefs cache ip=%s port=%s value=%r", + device.ip, + device.port, + self._clip_loc_log(chosen), + ) + elif r_norm: + # "Use as location" field rule (user choice) beats auto-discovered keys. + chosen = r_norm + dev_log.debug( + "Location: field rule ip=%s port=%s value=%r", + device.ip, + device.port, + self._clip_loc_log(chosen), + ) + elif d_norm and is_plausible_room_location(d_norm): + canonical = self._allowed_locations.get(d_norm.casefold()) + if canonical is not None: + d_norm = canonical + if canonical is not None or self._auto_add_discovered_locations: + self._store_location_preference_for_device(device, d_norm) + chosen = d_norm + dev_log.debug( + "Location: auto from discovery (persisted) ip=%s port=%s value=%r", + device.ip, + device.port, + self._clip_loc_log(chosen), + ) + else: + dev_log.debug( + "Location: discovered %r ignored (not in configured list, auto-add off) ip=%s port=%s", + self._clip_loc_log(d_norm), + device.ip, + device.port, + ) + else: + dev_log.debug( + "Location: empty ip=%s port=%s (no RoomName/xml_fields or TXT keys matched)", + device.ip, + device.port, + ) + + if chosen: + device.metadata["user_location"] = chosen + else: + device.metadata.pop("user_location", None) + + def _apply_field_mapping_rules(self, device: Device) -> None: + if not isinstance(device.metadata, dict): + device.metadata = {} + rules = self.get_device_field_mapping_rules(device) + if not rules: + return + for target, paths in rules.items(): + chosen = "" + for raw in paths: + value = self._mapped_value_for_field_path(device, raw) + if isinstance(value, str) and value.strip(): + chosen = value.strip() + break + if not chosen: + continue + if target == "name": + device.name = chosen + elif target == "location": + if is_plausible_room_location(chosen): + device.metadata["user_location"] = chosen + elif target == "information": + device.metadata["information"] = chosen + + def _mapped_value_for_field_path(self, device: Device, field_path: str) -> str: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + raw = str(field_path or "").strip() + if ":" not in raw: + return "" + prefix, rest = raw.split(":", 1) + key = rest.strip() + if not key: + return "" + if prefix == "txt": + def _txt_search(meta: dict) -> str: + txt = meta.get("txt") if isinstance(meta.get("txt"), dict) else {} + for rk, rv in txt.items(): + if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): + return rv + services = meta.get("services") if isinstance(meta.get("services"), list) else [] + for svc in services: + if not isinstance(svc, dict): + continue + st = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} + for rk, rv in st.items(): + if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): + return rv + return "" + found = _txt_search(metadata) + if found: + return found + # Fall back to sibling devices with the same IP (e.g. SSDP primary + mDNS TXT data) + ip_norm = str(device.ip).strip() + for sibling in self._devices.values(): + if sibling is device or str(sibling.ip).strip() != ip_norm: + continue + sib_meta = sibling.metadata if isinstance(sibling.metadata, dict) else {} + found = _txt_search(sib_meta) + if found: + return found + return "" + if prefix == "xml": + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + for rk, rv in xml_fields.items(): + if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): + return rv + return "" + if prefix == "meta": + for rk, rv in metadata.items(): + if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): + return rv + return "" + return "" + + def _apply_monitored_override(self, device: Device) -> None: + override_value = self._find_monitored_override_value(device) + if override_value is not None: + device.monitored = bool(override_value) + + def _apply_hidden_override(self, device: Device) -> None: + override_value = self._find_hidden_override_value(device) + if override_value is not None: + device.hidden = bool(override_value) + + def _find_override_value(self, store: dict, device: Device): + preferred_key = self._make_override_key_for_device(device) + if preferred_key in store: + return store[preferred_key] + endpoint_key = self._make_override_key(device.source, device.ip, device.port) + if endpoint_key in store: + return store[endpoint_key] + hit = self._prefs_entry_same_source_ipv4_any_port(store, device) + if hit is not None: + return hit + return self._prefs_entry_for_host_ip_fallback(store, device) + + def _find_name_override_value(self, device: Device) -> str | None: + preferred_key = self._make_name_override_key_for_device(device) + value = self._name_overrides.get(preferred_key) + if isinstance(value, str) and value.strip(): + return value.strip() + endpoint_key = self._make_override_key(device.source, device.ip, device.port) + value = self._name_overrides.get(endpoint_key) + if isinstance(value, str) and value.strip(): + return value.strip() + hit_ep = self._prefs_entry_same_source_ipv4_any_port(self._name_overrides, device) + if isinstance(hit_ep, str) and hit_ep.strip(): + return hit_ep.strip() + hit = self._prefs_entry_for_host_ip_fallback(self._name_overrides, device) + if isinstance(hit, str) and hit.strip(): + return hit.strip() + return None + + def _has_effective_name_override(self, device: Device, prior_row: Device | None = None) -> bool: + """Rule 0: user-renamed devices (prefs) beat SSDP cache, mDNS, and descriptor-derived names.""" + if self._find_name_override_value(device) is not None: + return True + if prior_row is not None and self._find_name_override_value(prior_row) is not None: + return True + # A "name" field-mapping rule (e.g. txt:fn) that resolves is a user naming choice too. + if self._resolved_field_rule_name(device): + return True + if prior_row is not None and self._resolved_field_rule_name(prior_row): + return True + return False + + def _resolved_field_rule_value(self, device: Device, target: str) -> str: + """Value of the first resolvable ``target`` field-mapping rule for ``device`` ("" if none).""" + rules = self.get_device_field_mapping_rules(device) + for raw in rules.get(target) or []: + value = self._mapped_value_for_field_path(device, raw) + if isinstance(value, str) and value.strip(): + if target == "location" and not is_plausible_room_location(value.strip()): + continue + return value.strip() + return "" + + def _resolved_field_rule_name(self, device: Device) -> str: + return self._resolved_field_rule_value(device, "name") + + def _reapply_field_rules_to_ip_siblings(self, device: Device) -> None: + """Re-resolve field-mapping rules (name/location/information) on other rows of the same IP. + + A rule like ``txt:fn`` set on an SSDP-primary bundle resolves from the mDNS sibling's + TXT; when that sibling (re)appears after the SSDP row, the SSDP row must pick it up. + Saved user names/locations (prefs) still win. + """ + ip_norm = str(device.ip).strip() + for row in list(self._devices.values()): + if row is device or str(row.ip).strip() != ip_norm: + continue + if not self.get_device_field_mapping_rules(row): + continue + self._apply_field_mapping_rules(row) + self._apply_location_override(row) + self._apply_name_override(row) + + def _find_location_override_value(self, device: Device) -> str | None: + preferred_key = self._make_name_override_key_for_device(device) + value = self._location_overrides.get(preferred_key) + if isinstance(value, str) and value.strip(): + return value.strip() + endpoint_key = self._make_override_key(device.source, device.ip, device.port) + value = self._location_overrides.get(endpoint_key) + if isinstance(value, str) and value.strip(): + return value.strip() + hit_ep = self._prefs_entry_same_source_ipv4_any_port(self._location_overrides, device) + if isinstance(hit_ep, str) and hit_ep.strip(): + return hit_ep.strip() + hit = self._prefs_entry_for_host_ip_fallback(self._location_overrides, device) + if isinstance(hit, str) and hit.strip(): + return hit.strip() + return None + + def _prefs_entry_for_host_ip_fallback(self, store: dict, device: Device): + """Prefs may use host:ip:… while identity later resolves to host:uid:… / host:mac:… (richer mDNS).""" + ip_only = str(device.ip).strip() + if not ip_only or ip_only == "0.0.0.0": + return None + host_ip_key = f"host:ip:{ip_only}" + if self._make_override_key_for_device(device) == host_ip_key: + return None + if host_ip_key in store: + return store[host_ip_key] + return None + + def _prefs_entry_same_source_ipv4_any_port(self, store: dict, device: Device): + """Match `mdns:192.168.1.10:8611` when aggregated row moves to `:631`, etc. (IPv4-only).""" + sip = str(device.ip).strip() + if sip in {"", "0.0.0.0"}: + return None + try: + if not isinstance(ipaddress.ip_address(sip), ipaddress.IPv4Address): + return None + except ValueError: + return None + prefix = f"{(device.source or '').strip().lower()}:{sip}:" + matches: list[str] = [] + for key in store: + if isinstance(key, str) and key.startswith(prefix): + tail = key[len(prefix) :] + if tail.isdigit(): + matches.append(key) + if not matches: + return None + + endpoint_exact = prefix + str(int(device.port)) + if endpoint_exact in store: + return store.get(endpoint_exact) + widest = max(matches, key=lambda k: int(k.rsplit(":", 1)[-1])) + return store.get(widest) + + def _supplement_missing_user_location(self, device: Device, prior_row: Device | None) -> None: + """Stabilise location when fresh payload lacks room info but cache already had one.""" + if device.source not in {"mdns", "ssdp"}: + return + if not isinstance(device.metadata, dict): + device.metadata = {} + cur = device.metadata.get("user_location") + if isinstance(cur, str) and cur.strip(): + return + sip = str(device.ip).strip() + if not sip or sip == "0.0.0.0": + return + if prior_row is not None and prior_row.source == device.source and prior_row.key == device.key: + dm = prior_row.metadata if isinstance(prior_row.metadata, dict) else {} + preserved = dm.get("user_location") + if isinstance(preserved, str) and preserved.strip(): + ps = preserved.strip() + if is_plausible_room_location(ps): + device.metadata["user_location"] = ps + self._device_event_logger(device.source).debug( + "Location: %s carry-over from prior row ip=%s value=%r", + device.source, + sip, + ps if len(ps) <= 120 else ps[:117] + "...", + ) + return + if device.source == "ssdp": + for row in self._devices.values(): + if row is prior_row: + continue + if row.source != "ssdp" or row.key == device.key: + continue + if str(row.ip).strip() != sip: + continue + dm = row.metadata if isinstance(row.metadata, dict) else {} + borrowed = dm.get("user_location") + if isinstance(borrowed, str) and borrowed.strip(): + bs = borrowed.strip() + if not is_plausible_room_location(bs): + continue + device.metadata["user_location"] = bs + self._ssdp_logger.debug( + "Location: SSDP borrowed same-ip ip=%s from key=%s value=%r", + sip, + row.key, + bs if len(bs) <= 120 else bs[:117] + "...", + ) + return + return + for row in self._devices.values(): + if row is prior_row: + continue + if row.source != "mdns" or row.key == device.key: + continue + if str(row.ip).strip() != sip: + continue + dm = row.metadata if isinstance(row.metadata, dict) else {} + borrowed = dm.get("user_location") + if isinstance(borrowed, str) and borrowed.strip(): + bs = borrowed.strip() + if not is_plausible_room_location(bs): + continue + device.metadata["user_location"] = bs + self._mdns_logger.debug( + "Location: mDNS borrowed same-ip ip=%s from key=%s value=%r", + sip, + row.key, + bs if len(bs) <= 120 else bs[:117] + "...", + ) + return + + def _make_override_key(self, source: str, ip: str, port: int) -> str: + return f"{source}:{ip}:{int(port)}" + + def _mac_for_device_identity(self, device: Device) -> str: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + raw = self._extract_mac(metadata) + normalized = normalize_mac_for_bundle_merge(raw) if raw else "" + if normalized: + return normalized + hit = lookup_mac_from_neighbor_cache(str(device.ip).strip()) + return normalize_mac_for_bundle_merge(hit) if hit else "" + + def _normalized_monitored_uid(self, device: Device) -> str: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + uid = self._extract_uid(metadata) + return normalize_monitored_uid(uid) if uid else "" + + def _monitored_name_for_identity(self, device: Device) -> str: + override = self._find_name_override_value(device) + if override: + return normalize_monitored_name(override) + return normalize_monitored_name(device.name or "") + + def _monitored_lookup_keys_for_device(self, device: Device) -> list[str]: + """Prefs aliases for this row: MAC → UID → name → IP (then legacy endpoint keys).""" + keys: list[str] = [] + seen: set[str] = set() + + def _add(key: str) -> None: + if key and key not in seen: + seen.add(key) + keys.append(key) + + mac = self._mac_for_device_identity(device) + if mac: + _add(f"host:mac:{mac}") + uid = self._normalized_monitored_uid(device) + if uid: + _add(f"host:uid:{uid}") + metadata = device.metadata if isinstance(device.metadata, dict) else {} + raw_uid = self._extract_uid(metadata) + if raw_uid: + _add(f"host:uid:{raw_uid.strip().lower()}") + name = self._monitored_name_for_identity(device) + if name: + _add(f"host:name:{name}") + ip = str(device.ip).strip() + if ip and ip != "0.0.0.0": + _add(f"host:ip:{ip}") + _add(self._make_override_key(device.source, device.ip, device.port)) + return keys + + def _canonical_monitored_keys(self, device: Device) -> list[str]: + """Persisted follow key preference: MAC, UUID, name, IP (no endpoint/port keys).""" + out: list[str] = [] + mac = self._mac_for_device_identity(device) + if mac: + out.append(f"host:mac:{mac}") + uid = self._normalized_monitored_uid(device) + if uid: + out.append(f"host:uid:{uid}") + name = self._monitored_name_for_identity(device) + if name: + out.append(f"host:name:{name}") + ip = str(device.ip).strip() + if ip and ip != "0.0.0.0": + out.append(f"host:ip:{ip}") + return out + + def _canonical_monitored_key(self, device: Device) -> str: + keys = self._canonical_monitored_keys(device) + if keys: + return keys[0] + return self._make_override_key(device.source, device.ip, device.port) + + def _presence_dedupe_key(self, device: Device) -> str | None: + return self._canonical_monitored_key(device) + + def _find_monitored_override_value(self, device: Device) -> bool | None: + return self._find_host_flag_override_value(self._monitored_overrides, device) + + def _find_hidden_override_value(self, device: Device) -> bool | None: + return self._find_host_flag_override_value(self._hidden_overrides, device) + + def _find_host_flag_override_value(self, store: dict[str, bool], device: Device) -> bool | None: + for key in self._monitored_lookup_keys_for_device(device): + if key in store: + return store[key] + legacy = self._find_override_value(store, device) + if legacy is not None: + return bool(legacy) + return None + + def _device_matches_monitored_key(self, device: Device, host_key: str) -> bool: + return host_key in self._monitored_lookup_keys_for_device(device) + + def _device_matches_hidden_key(self, device: Device, host_key: str) -> bool: + return host_key in self._monitored_lookup_keys_for_device(device) + + def bundle_is_hidden(self, ip: str, port: int) -> bool: + anchor = self._anchor_device_for_endpoint(ip, port) + if anchor is not None: + return self._find_hidden_override_value(anchor) is True + host_key = f"host:ip:{str(ip).strip()}" + return bool(self._hidden_overrides.get(host_key)) + + def canonical_host_identity_key(self, ip: str, port: int) -> str: + anchor = self._anchor_device_for_endpoint(ip, port) + if anchor is not None: + return self._canonical_monitored_key(anchor) + sip = str(ip).strip() + return f"host:ip:{sip}" if sip and sip != "0.0.0.0" else "" + + def _anchor_device_for_endpoint(self, ip: str, port: int) -> Device | None: + sip = str(ip).strip() + if not sip or sip == "0.0.0.0": + return None + exact: list[Device] = [] + same_ip: list[Device] = [] + for device in self._devices_snapshot(): + if str(device.ip).strip() != sip: + continue + same_ip.append(device) + if int(device.port) == int(port): + exact.append(device) + if exact: + for preferred in ("ssdp", "mdns", "wsd", "wsdd", "nmb"): + for device in exact: + if (device.source or "").strip().lower() == preferred: + return device + return exact[0] + if same_ip: + for preferred in ("ssdp", "mdns", "wsd", "wsdd", "nmb"): + for device in same_ip: + if (device.source or "").strip().lower() == preferred: + return device + return same_ip[0] + return None + + def _make_override_key_for_device(self, device: Device) -> str: + uid = self._extract_uid(device.metadata) + if uid: + return f"host:uid:{uid}" + mac = self._extract_mac(device.metadata) + if mac: + return f"host:mac:{mac}" + ip = str(device.ip).strip() + if ip and ip != "0.0.0.0": + return f"host:ip:{ip}" + return self._make_override_key(device.source, device.ip, device.port) + + def _make_name_override_key_for_device(self, device: Device) -> str: + return self._make_override_key_for_device(device) + + def _extract_uid(self, metadata: dict) -> str: + if not isinstance(metadata, dict): + return "" + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} + usn = metadata.get("usn") + if isinstance(usn, str) and usn.strip(): + return upnp_identity_from_usn(usn) + wsd_epr = metadata.get("wsd_epr") + if isinstance(wsd_epr, str) and wsd_epr.strip(): + u = uuid_urn_if_present(wsd_epr) + if u: + return u + wsdd_uri = metadata.get("wsdd_uri") + if isinstance(wsdd_uri, str) and wsdd_uri.strip(): + u = uuid_urn_if_present(wsdd_uri) + if u: + return u + udn_raw = xml_fields.get("UDN") + if isinstance(udn_raw, str) and udn_raw.strip(): + hit = upnp_identity_from_udn(udn_raw) + if hit: + return hit + candidates = [ + xml_fields.get("UDN"), + metadata.get("udn"), + txt_fields.get("uuid"), + txt_fields.get("udn"), + txt_fields.get("id"), + txt_fields.get("deviceid"), + txt_fields.get("device_id"), + txt_fields.get("serial"), + txt_fields.get("serialnumber"), + ] + for value in candidates: + if isinstance(value, str) and value.strip(): + return value.strip().lower() + return "" + + def _default_name_for_device(self, device: Device) -> str: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} + ip = str(device.ip).strip() or "0.0.0.0" + + for key in ("friendlyName", "displayName"): + value = xml_fields.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + + if device.source == "mdns": + for key in ("name", "fn", "friendlyname", "friendly_name", "device"): + value = txt_fields.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + server_raw = metadata.get("server") + if isinstance(server_raw, str) and server_raw.strip(): + normalized = server_raw.strip().removesuffix(".local.").removesuffix(".local").strip(".") + if normalized: + base = normalized.replace("-", " ") + prod = "" + if isinstance(txt_fields, dict): + for tk, tv in txt_fields.items(): + if isinstance(tk, str) and tk.lower() == "product" and isinstance(tv, str) and tv.strip(): + prod = tv.strip() + break + if prod: + return f"{base} ({prod})" + return base + for key in ("model", "mdl", "md", "product"): + value = txt_fields.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + hostname = metadata.get("hostname") + if isinstance(hostname, str) and hostname.strip(): + normalized = hostname.strip().removesuffix(".local.").removesuffix(".local").strip(".") + if normalized: + return normalized.replace("-", " ") + return f"mDNS Device {ip}" + + if device.source == "ssdp": + server = str(metadata.get("server", "")) + st = str(metadata.get("st", "")) + server_low = server.lower() + st_low = st.lower() + if "router" in server_low or "wan" in st_low: + return f"Router {ip}" + if "mediaserver" in st_low or "dlna" in server_low: + return f"Media Server {ip}" + if "printer" in st_low: + return f"Printer {ip}" + return f"SSDP Device {ip}" + + return str(device.name).strip() or "Unknown" + + def _default_location_for_device(self, device: Device) -> str: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} + + # Sonos commonly exposes a room label in SSDP XML fields. + for value in (xml_fields.get("RoomName"), xml_fields.get("roomName"), metadata.get("RoomName"), metadata.get("roomName")): + if isinstance(value, str) and value.strip(): + s = value.strip() + if is_plausible_room_location(s): + return s + + def txt_by_key_ci(txt: dict, *wanted_lower: str) -> str: + index: dict[str, str] = {} + if isinstance(txt, dict): + for rk, rv in txt.items(): + if isinstance(rk, str) and isinstance(rv, str): + index[rk.lower()] = rv + for wl in wanted_lower: + cand = index.get(wl.lower()) + if isinstance(cand, str) and cand.strip(): + s = cand.strip() + if is_plausible_room_location(s): + return s + return "" + + loc = txt_by_key_ci( + txt_fields, + "roomname", + "room_name", + "room", + "location", + "locationname", + "location_name", + "zonename", + "zone_name", + "zone", + ) + if loc: + return loc + services = metadata.get("services") if isinstance(metadata.get("services"), list) else [] + for svc in services: + if not isinstance(svc, dict): + continue + st = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} + loc = txt_by_key_ci(st, "roomname", "room_name", "room", "location", "locationname", "zonename", "zone") + if loc: + return loc + return "" + + def set_bundle_monitored(self, ip: str, port: int, monitored: bool) -> None: + """Follow/unfollow a UI bundle (persisted by MAC, else UPnP UID, else IP).""" + anchor = self._anchor_device_for_endpoint(ip, port) + host_key = self._canonical_monitored_key(anchor) if anchor is not None else f"host:ip:{ip}" + if monitored: + self._monitored_overrides[host_key] = True + else: + keys_to_drop: set[str] = {host_key} + for device in self._devices_snapshot(): + if anchor is not None: + if not self._device_matches_monitored_key(device, host_key): + continue + elif str(device.ip).strip() != str(ip).strip(): + continue + keys_to_drop.update(self._monitored_lookup_keys_for_device(device)) + for key in keys_to_drop: + self._monitored_overrides.pop(key, None) + changed = False + for device in self._devices_snapshot(): + if anchor is not None: + if not self._device_matches_monitored_key(device, host_key): + continue + elif str(device.ip).strip() != str(ip).strip(): + continue + if device.monitored != monitored: + device.monitored = monitored + changed = True + if changed: + self._notify() + + def set_host_monitored(self, ip: str, monitored: bool) -> None: + """Backward-compatible wrapper (uses first row at ``ip`` for identity).""" + anchor = self._anchor_device_for_endpoint(ip, 0) + port = int(anchor.port) if anchor is not None else 0 + self.set_bundle_monitored(ip, port, monitored) + + def set_device_monitored(self, device_key: str, monitored: bool) -> None: + device = self._devices.get(device_key) + if device is None: + return + self.set_bundle_monitored(str(device.ip), int(device.port), monitored) + + def purge_bundle(self, ip: str, port: int) -> None: + """Completely remove a bundle from in-memory state (devices + all overrides).""" + sip = str(ip).strip() + if not sip or sip == "0.0.0.0": + return + # Collect all devices that share this IP (any source/port — they form the bundle). + to_remove: list[Device] = [ + d for d in self._devices_snapshot() + if str(d.ip).strip() == sip + ] + all_override_keys: set[str] = {f"host:ip:{sip}"} + for device in to_remove: + all_override_keys.update(self._monitored_lookup_keys_for_device(device)) + all_override_keys.add(self._make_override_key_for_device(device)) + override_stores: list[dict] = [ + self._type_overrides, + self._name_overrides, + self._location_overrides, + self._url_overrides, + self._monitored_overrides, + self._hidden_overrides, + self._last_seen_overrides, + self._device_commands, + self._custom_command_overrides, + self._field_mapping_rules, + ] + for store in override_stores: + for key in all_override_keys: + store.pop(key, None) + remove_ids = {id(d) for d in to_remove} + for store_key, d in list(self._devices.items()): + # Pop by storage key (not d.key): a merged/re-keyed row can compute a + # different key and silently survive a pop(d.key), leaving a ghost. + if id(d) in remove_ids: + self._devices.pop(store_key, None) + # Clear in-memory protocol caches for this IP. + self._nmb_name_cache.pop(sip, None) + wsd_keys_to_drop = [k for k, v in self._wsd_device_cache.items() + if isinstance(v, dict) and str(v.get("ip", "") or "").strip() == sip] + for k in wsd_keys_to_drop: + self._wsd_device_cache.pop(k, None) + # Purge SSDP profile cache and XML descriptor cache (memory + disk) for this IP. + if self._ssdp_discovery is not None: + try: + self._ssdp_discovery.purge_ip_from_profile_cache(sip) + self._ssdp_discovery.purge_ip_from_xml_cache(sip) + except Exception: + self._logger.warning("SSDP cache purge failed for %s", sip, exc_info=True) + with self._ssdp_profile_cache_lock: + self._ssdp_profile_cache_by_ip.pop(sip, None) + self._ssdp_profile_cache_emit_rows = [ + (row_ip, row) for row_ip, row in self._ssdp_profile_cache_emit_rows + if str(row_ip).strip() != sip + ] + if to_remove: + self._notify() + + def set_bundle_hidden(self, ip: str, port: int, hidden: bool, *, notify: bool = True) -> None: + """Hide/show a UI bundle (same identity keys as follow/monitor).""" + anchor = self._anchor_device_for_endpoint(ip, port) + host_key = self._canonical_monitored_key(anchor) if anchor is not None else f"host:ip:{ip}" + if hidden: + self._hidden_overrides[host_key] = True + else: + keys_to_drop: set[str] = {host_key} + for device in self._devices_snapshot(): + if anchor is not None: + if not self._device_matches_hidden_key(device, host_key): + continue + elif str(device.ip).strip() != str(ip).strip(): + continue + keys_to_drop.update(self._monitored_lookup_keys_for_device(device)) + for key in keys_to_drop: + self._hidden_overrides.pop(key, None) + changed = False + for device in self._devices_snapshot(): + if anchor is not None: + if not self._device_matches_hidden_key(device, host_key): + continue + elif str(device.ip).strip() != str(ip).strip(): + continue + if device.hidden != hidden: + device.hidden = hidden + changed = True + if changed and notify: + self._notify() + + def _notify(self) -> None: + if not self._listeners: + return + with self._notify_debounce_lock: + if self._notify_debounce_timer is not None: + self._notify_debounce_timer.cancel() + self._notify_debounce_timer = None + self._notify_debounce_timer = threading.Timer( + _NOTIFY_DEBOUNCE_SECONDS, + self._notify_emit_debounced, + ) + self._notify_debounce_timer.daemon = True + self._notify_debounce_timer.start() + + def _notify_emit_debounced(self) -> None: + if self._stopped: + return + with self._notify_debounce_lock: + self._notify_debounce_timer = None + snapshot = self.devices + self._logger.debug("Publishing %d devices to %d listeners", len(snapshot), len(self._listeners)) + for listener in self._listeners: + listener(snapshot) + + def _on_protocol_event(self, event_type: str, payload: dict) -> None: + if event_type != "device": + self._logger.debug("Ignoring protocol event_type=%s", event_type) + return + + device = Device( + name=payload.get("name", "Unknown"), + ip=payload.get("ip", "0.0.0.0"), + port=int(payload.get("port", 0)), + type=payload.get("type", "unknown"), + category=payload.get("category", "Unknown Devices"), + source=payload.get("source", "unknown"), + url=payload.get("url"), + metadata=payload.get("metadata", {}), + online=bool(payload.get("online", True)), + icon=payload.get("icon"), + ) + self.add_or_update_device(device) + + def _load_demo_devices(self) -> None: + demo_devices = [ + Device( + name="ESP3D Printer Node", + ip="192.168.1.42", + port=80, + type="esp32", + category="ESP3D Devices", + source="mdns", + url="http://192.168.1.42:80/", + metadata={ + "hostname": "esp3d-printer.local.", + "server": "esp3d-printer.local.", + "interface": "wlan0", + "priority": 0, + "weight": 0, + "ttl": 120, + "services": [ + { + "service": "_esp3d._tcp.local.", + "port": 80, + "hostname": "esp3d-printer.local.", + "server": "esp3d-printer.local.", + }, + { + "service": "_arduino._tcp.local.", + "port": 81, + "hostname": "esp3d-printer.local.", + "server": "esp3d-printer.local.", + }, + ], + "txt": { + "board": "ESP32", + "fw": "ESP3D 3.0.2", + "path": "/", + "auth": "false", + }, + }, + online=True, + icon="esp32.png", + ), + Device( + name="Salon Media Server", + ip="192.168.1.15", + port=8200, + type="mediaserver", + category="Media Servers", + source="ssdp", + url="http://192.168.1.15:8200/", + metadata={ + "st": "urn:schemas-upnp-org:device:MediaServer:1", + "nt": "urn:schemas-upnp-org:device:MediaServer:1", + "usn": "uuid:media-server-01::urn:schemas-upnp-org:device:MediaServer:1", + "location": "http://192.168.1.15:8200/rootDesc.xml", + "server": "Linux/6.8 UPnP/1.1 ReadyMedia/1.3.2", + "cache_control": "max-age=1800", + "headers": { + "HOST": "239.255.255.250:1900", + "CACHE-CONTROL": "max-age=1800", + "LOCATION": "http://192.168.1.15:8200/rootDesc.xml", + "NT": "urn:schemas-upnp-org:device:MediaServer:1", + "NTS": "ssdp:alive", + "SERVER": "Linux/6.8 UPnP/1.1 ReadyMedia/1.3.2", + "USN": "uuid:media-server-01::urn:schemas-upnp-org:device:MediaServer:1", + }, + "xml_fields": { + "friendlyName": "Salon Media Server", + "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", + "manufacturer": "ReadyMedia", + "manufacturerURL": "https://www.readymedia.org/", + "modelName": "MiniDLNA", + "modelURL": "https://www.readymedia.org/docs/", + "serialNumber": "RM-001-ABCD", + "UDN": "uuid:media-server-01", + "presentationURL": "http://192.168.1.15:8200/", + "services_description": "urn:schemas-upnp-org:service:ContentDirectory:1, urn:schemas-upnp-org:service:ConnectionManager:1", + "icons_description": "mimetype=image/png;width=48;height=48;url=/icons/icon48.png", + }, + "xml": """ + + 10 + http://192.168.1.15:8200/ + + urn:schemas-upnp-org:device:MediaServer:1 + Salon Media Server + ReadyMedia + MiniDLNA + uuid:media-server-01 + +""", + }, + online=True, + icon="mediaserver.png", + ), + Device( + name="Box Internet", + ip="192.168.1.1", + port=80, + type="router", + category="Routers & Gateways", + source="ssdp", + url="http://192.168.1.1:80/", + metadata={ + "st": "urn:schemas-upnp-org:device:WANDevice:1", + "nt": "urn:schemas-upnp-org:device:WANDevice:1", + "usn": "uuid:router-01::urn:schemas-upnp-org:device:WANDevice:1", + "location": "http://192.168.1.1:80/igd.xml", + "server": "Linux/5.15 UPnP/1.0 RouterOS/7.10", + "cache_control": "max-age=1200", + "headers": { + "HOST": "239.255.255.250:1900", + "CACHE-CONTROL": "max-age=1200", + "LOCATION": "http://192.168.1.1:80/igd.xml", + "NT": "urn:schemas-upnp-org:device:WANDevice:1", + "NTS": "ssdp:alive", + "SERVER": "Linux/5.15 UPnP/1.0 RouterOS/7.10", + "USN": "uuid:router-01::urn:schemas-upnp-org:device:WANDevice:1", + }, + "xml_fields": { + "friendlyName": "Box Internet", + "deviceType": "urn:schemas-upnp-org:device:WANDevice:1", + "manufacturer": "ISP Vendor", + "manufacturerURL": "unavailable", + "modelName": "Gateway X1", + "modelURL": "unavailable", + "serialNumber": "GWX1-7788", + "UDN": "uuid:router-01", + "presentationURL": "http://192.168.1.1/", + "services_description": "urn:schemas-upnp-org:service:WANIPConnection:1", + "icons_description": "unavailable", + }, + "xml": """ + + 10 + + urn:schemas-upnp-org:device:WANDevice:1 + Box Internet + ISP Vendor + Gateway X1 + uuid:router-01 + +""", + }, + online=True, + icon="router.png", + ), + Device( + name="NAS Atelier", + ip="192.168.1.20", + port=2049, + type="nas", + category="NAS / File Servers", + source="mdns", + url=None, + metadata={ + "hostname": "nas-atelier.local.", + "server": "nas-atelier.local.", + "interface": "eth0", + "priority": 0, + "weight": 0, + "ttl": 4500, + "services": [ + { + "service": "_nfs._tcp.local.", + "port": 2049, + "hostname": "nas-atelier.local.", + "server": "nas-atelier.local.", + }, + { + "service": "_mountd._tcp.local.", + "port": 32768, + "hostname": "nas-atelier.local.", + "server": "nas-atelier.local.", + }, + ], + "txt": { + "model": "DS224+", + "vendor": "Synology", + "path": "/volume1", + }, + }, + online=False, + icon="nas.png", + ), + ] + for device in demo_devices: + self._devices[device.key] = device + self._notify() diff --git a/app/discovery/mdns.py b/app/discovery/mdns.py new file mode 100644 index 00000000..f83bea56 --- /dev/null +++ b/app/discovery/mdns.py @@ -0,0 +1,1259 @@ +# File mdns.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""mDNS discovery using zeroconf service browsing.""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +import socket +import threading +import time + +from discovery.base import BaseDiscovery +from utils.discovery_config import category_for_device_type +from utils.local_host import address_preference_rank, choose_best_address +from utils.double_click_open import mdns_http_path +from utils.mdns_rules import cached_mdns_rules, evaluate_type_rules +from utils.scheduling import ScheduleMainFn +from utils.user_config_overlay import USER_DEVICE_TYPES_JSON, merge_device_types_trees, optional_user_json + +ServiceBrowser = None +ServiceListener = object +Zeroconf = None +ZeroconfServiceTypes = None + +_ENUMERATION_TIMEOUT_S = 2.5 +_ENUMERATION_REFRESH_INTERVAL_S = 240 +# How long to retain a per-service record after remove_service() when the host +# is still alive via other services. In practice, genuine mid-session service +# removal (NAS disabling FTP, etc.) is extremely rare; almost all remove_service +# callbacks while a host is online are TTL re-announcement jitter or transient +# network hiccups. A refresh() restarts browsers and actively re-queries, so +# stale records that truly disappeared will be cleaned up on the next user- +# initiated reload even if this timer hasn't fired. Set long enough to survive +# the worst-case zeroconf re-query window (~4 × re-query intervals ≈ 2-3 min). +_SERVICE_REMOVE_GRACE_S = 120 +# After a forced refresh the Zeroconf cache is cleared and fresh PTR queries go +# out. Devices that are still online re-announce quickly; those that don't +# re-announce within this window are considered offline. +_REFRESH_REMOVE_GRACE_S = 15 +# Periodically force a full Zeroconf reopen so fresh PTR queries go out for every +# browsed type — exactly what a user "reload" does. A *lightweight* browser +# restart on the same Zeroconf instance is not enough: while records linger in +# the cache, recreating a ServiceBrowser only replays them from cache (no real +# network confirmation), and once they expire (services slowly vanishing +# overnight) the reused socket no longer recovers them — a sleeping printer that +# stopped re-announcing, or a degraded mDNS multicast socket, only responds to a +# query carrying NO known answers, which a fresh Zeroconf instance guarantees. +# So this periodic maintenance must reopen Zeroconf (clear cache + new sockets), +# not just restart browsers. Kept infrequent on purpose. +_BROWSER_REFRESH_INTERVAL_S = 600 +# Legacy-unicast fallback (RFC 6762 §6.7): retry/negative-cache windows for responders +# that ignore standard multicast queries (see _legacy_unicast_service_info). +_LEGACY_RESOLVE_RETRY_S = 60.0 +_LEGACY_UNICAST_TIMEOUT_S = 1.5 +# How long a host's last known routable (rank-0) address outweighs a worse-ranked one. +# zeroconf resolutions occasionally surface only a subset of a multi-homed host's A records +# (e.g. just the APIPA 169.254.x entry); without stickiness the aggregate endpoint flaps, +# each flap emitting an offline for the previous endpoint and churning the device row. +_STICKY_HOST_IP_TTL_S = 600.0 + + +_TYPE_MAP_PATH = Path(__file__).resolve().parent.parent / "config" / "device_types.json" +_ZEROCONF_LIBS_LOADED = False + + +def _ensure_zeroconf_libs() -> None: + global ServiceBrowser, Zeroconf, ZeroconfServiceTypes, _ZEROCONF_LIBS_LOADED + if _ZEROCONF_LIBS_LOADED: + return + _ZEROCONF_LIBS_LOADED = True + try: + from zeroconf import ServiceBrowser as _SB, Zeroconf as _Z + ServiceBrowser = _SB + Zeroconf = _Z + except Exception: + return + try: + from zeroconf import ZeroconfServiceTypes as _ZST + ZeroconfServiceTypes = _ZST + except Exception: + pass + + +class _MDNSListener(ServiceListener): + def __init__(self, discovery: "MDNSDiscovery") -> None: + self._discovery = discovery + + def add_service(self, zc, service_type: str, name: str) -> None: + try: + self._discovery._on_service_change(zc, service_type, name, online=True) + except Exception: + self._discovery._logger.debug("Exception in add_service", exc_info=True) + + def update_service(self, zc, service_type: str, name: str) -> None: + try: + self._discovery._on_service_change(zc, service_type, name, online=True) + except Exception: + self._discovery._logger.debug("Exception in update_service", exc_info=True) + + def remove_service(self, _zc, service_type: str, name: str) -> None: + try: + self._discovery._on_service_remove(service_type, name) + except Exception: + self._discovery._logger.debug("Exception in remove_service", exc_info=True) + + +class MDNSDiscovery(BaseDiscovery): + def __init__( + self, + rules_enabled: bool = True, + *, + enumeration_timeout_seconds: float | None = None, + enumeration_interval_seconds: int | None = None, + service_info_timeout_ms: int | None = None, + schedule_on_main_thread: ScheduleMainFn | None = None, + ) -> None: + super().__init__(source="mdns") + self._logger = logging.getLogger(__name__) + self._rules_enabled = bool(rules_enabled) + self._enumeration_timeout_s = ( + float(enumeration_timeout_seconds) + if enumeration_timeout_seconds is not None + else _ENUMERATION_TIMEOUT_S + ) + self._enumeration_interval_s = ( + int(enumeration_interval_seconds) + if enumeration_interval_seconds is not None + else _ENUMERATION_REFRESH_INTERVAL_S + ) + self._service_info_timeout_ms = ( + int(service_info_timeout_ms) if service_info_timeout_ms is not None else 2500 + ) + self._mdns_rules = cached_mdns_rules() if self._rules_enabled else {"type_rules": [], "summary_fields": []} + self._running = False + self._zeroconf = None + self._browsers: list[ServiceBrowser] = [] + self._browsers_started: set[str] = set() + self._listener = _MDNSListener(self) + self._seen_by_service: dict[tuple[str, str], dict] = {} + self._txt_logged: dict[tuple[str, str], tuple[tuple[str, str], ...]] = {} + self._service_host_keys: dict[tuple[str, str], str] = {} + self._host_last_endpoint: dict[str, tuple[str, int]] = {} + self._host_sticky_ip: dict[str, tuple[str, float]] = {} + self._legacy_resolve_cache: dict[tuple[str, str], tuple[float, object | None]] = {} + self._type_map = self._load_mdns_type_map() + self._schedule_main: ScheduleMainFn = ( + schedule_on_main_thread if schedule_on_main_thread is not None else (lambda fn: fn()) + ) + self._enumeration_timer: threading.Timer | None = None + self._enumeration_busy = False + self._browser_refresh_timer: threading.Timer | None = None + self._browser_refresh_interval_s = _BROWSER_REFRESH_INTERVAL_S + self._pending_remove_timers: dict[tuple[str, str], threading.Timer] = {} + self._last_recovery_time = 0.0 + + def start(self) -> None: + if self._running: + return + self._running = True + _ensure_zeroconf_libs() + if Zeroconf is None or ServiceBrowser is None: + self._logger.warning("mDNS discovery unavailable: zeroconf not installed") + return + try: + self._zeroconf = Zeroconf() + except Exception: + self._logger.exception("Failed to initialize zeroconf") + self._running = False + return + + self._browsers_started.clear() + for service_type in self._service_types_to_browse_from_config(): + self._ensure_browser(service_type) + self._kick_service_type_enumeration() + self._schedule_enumeration_timer() + self._schedule_browser_refresh_timer() + if not self._browsers: + self._logger.warning("No mDNS service browser started") + + def stop(self) -> None: + if not self._running: + return + self._running = False + self._enumeration_busy = False + if self._enumeration_timer is not None: + try: + self._enumeration_timer.cancel() + except Exception: + pass + self._enumeration_timer = None + if self._browser_refresh_timer is not None: + try: + self._browser_refresh_timer.cancel() + except Exception: + pass + self._browser_refresh_timer = None + for key in list(self._pending_remove_timers): + self._cancel_grace_remove(key) + self._seen_by_service.clear() + self._host_last_endpoint.clear() + self._host_sticky_ip.clear() + self._legacy_resolve_cache.clear() + self._browsers.clear() + self._browsers_started.clear() + zc = self._zeroconf + self._zeroconf = None + if zc is not None: + try: + zc.close() + except Exception: + self._logger.debug("Error while closing zeroconf", exc_info=True) + + def refresh(self) -> None: + if not self._running or self._zeroconf is None: + return + # Reschedule pending grace-removes with short timeout instead of cancelling. + # Devices that re-announce during the refresh will cancel their timer; devices + # that don't re-announce within _REFRESH_REMOVE_GRACE_S are considered offline. + for key in list(self._pending_remove_timers): + host_key = self._service_host_keys.get(key, "") + self._schedule_grace_remove(key, host_key, delay=float(_REFRESH_REMOVE_GRACE_S)) + # Cancel running browsers. + for browser in self._browsers: + try: + if hasattr(browser, "cancel"): + browser.cancel() + except Exception: + pass + self._browsers.clear() + # Close and reopen the Zeroconf instance to clear its internal DNS cache. + # This ensures the subsequent PTR queries go out without "known answer" + # suppression headers (RFC 6762 §7.1), so devices that stopped announcing + # (e.g. a NAS whose TTL expired) will respond and re-populate the device list. + old_zc = self._zeroconf + self._zeroconf = None + if old_zc is not None: + try: + old_zc.close() + except Exception: + self._logger.debug("mDNS refresh: error closing zeroconf", exc_info=True) + try: + self._zeroconf = Zeroconf() + except Exception: + self._logger.exception("mDNS refresh: failed to reopen zeroconf") + return + self._logger.debug("mDNS refresh: zeroconf cache cleared, sending fresh PTR queries") + types_to_rebrowse = list(self._browsers_started) + self._browsers_started.clear() + for service_type in types_to_rebrowse: + self._ensure_browser(service_type) + self._kick_service_type_enumeration() + + def _service_types_to_browse_from_config(self) -> list[str]: + known_types = sorted(self._type_map.keys()) if self._type_map else [] + if not known_types: + known_types = ["_http._tcp"] + return [self._normalize_service_type(service) for service in known_types] + + def _ensure_browser(self, service_type: str) -> None: + if not self._running or self._zeroconf is None or ServiceBrowser is None: + return + normalized = self._normalize_service_type(service_type) + if normalized in self._browsers_started: + return + try: + browser = ServiceBrowser(self._zeroconf, normalized, self._listener) + self._browsers.append(browser) + self._browsers_started.add(normalized) + self._logger.debug("mDNS browser started for %s", normalized) + except Exception: + self._logger.exception("Failed to start mDNS browser for %s", normalized) + + def _enqueue_browsers_for_types(self, service_types: list[str]) -> None: + """Register browsers on the UI main thread via ``schedule_on_main_thread`` when provided.""" + + def apply_pending() -> None: + if not self._running or self._zeroconf is None: + return + for service_type in service_types: + self._ensure_browser(service_type) + + self._schedule_main(apply_pending) + + def _kick_service_type_enumeration(self) -> None: + """DNS-SD: discover which service types are advertised on the LAN (beyond config file).""" + + if ZeroconfServiceTypes is None or not self._running: + return + if self._enumeration_busy: + self._logger.debug("mDNS enumeration skipped (already in progress)") + return + + self._enumeration_busy = True + + def worker() -> None: + try: + try: + found = ZeroconfServiceTypes.find(zc=None, timeout=self._enumeration_timeout_s) + except Exception: + self._logger.exception("mDNS service type enumeration failed") + return + + additions: list[str] = [] + seen: set[str] = set() + for raw in found: + if not isinstance(raw, str) or not raw.strip(): + continue + normalized = self._normalize_service_type(raw) + if normalized in seen: + continue + meta = "_services._dns-sd._udp" in normalized + # Avoid browsing the enumerator itself as a generic service catalogue. + if meta: + continue + seen.add(normalized) + additions.append(normalized) + + self._enqueue_browsers_for_types(additions) + self._logger.info("mDNS enumeration found %d service type(s)", len(additions)) + finally: + self._enumeration_busy = False + + threading.Thread(target=worker, name="NetNeighbor-mdns-enumerate", daemon=True).start() + + def _schedule_enumeration_timer(self) -> None: + if self._enumeration_timer is not None: + return + + def on_timer_fire() -> None: + self._enumeration_timer = None + if not self._running or self._zeroconf is None: + return + + def kick() -> None: + self._kick_service_type_enumeration() + + self._schedule_main(kick) + if self._running: + self._schedule_enumeration_timer() + + timer = threading.Timer(float(self._enumeration_interval_s), on_timer_fire) + timer.daemon = True + self._enumeration_timer = timer + timer.start() + + def _schedule_browser_refresh_timer(self) -> None: + """Periodically re-query all browsed types to recover silently evicted records.""" + if self._browser_refresh_timer is not None: + return + + def on_timer_fire() -> None: + self._browser_refresh_timer = None + if not self._running or self._zeroconf is None: + return + + def do_refresh() -> None: + if not self._running or self._zeroconf is None: + return + self._logger.debug( + "mDNS periodic browser refresh: reopening zeroconf, re-querying %d type(s)", + len(self._browsers_started), + ) + # Full reopen (same as a user reload): clears the cache and sends + # fresh PTR queries with no known-answer suppression, so records + # that silently went stale overnight are actually recovered. + self.refresh() + + self._schedule_main(do_refresh) + if self._running: + self._schedule_browser_refresh_timer() + + timer = threading.Timer(float(self._browser_refresh_interval_s), on_timer_fire) + timer.daemon = True + self._browser_refresh_timer = timer + timer.start() + + def _normalize_service_type(self, service: str) -> str: + value = (service or "").strip().lower() + if not value: + return "_http._tcp.local." + if value.endswith(".local."): + return value + if value.endswith(".local"): + return f"{value}." + return f"{value}.local." + + def _load_mdns_type_map(self) -> dict[str, dict]: + try: + parsed = json.loads(_TYPE_MAP_PATH.read_text(encoding="utf-8")) + if isinstance(parsed, dict): + overlay = optional_user_json(USER_DEVICE_TYPES_JSON) + if overlay is not None: + parsed = merge_device_types_trees(parsed, overlay) + self._logger.info("Merged device_types.json with user overlay %s", USER_DEVICE_TYPES_JSON) + mdns_map = parsed.get("mdns") if isinstance(parsed, dict) else {} + if isinstance(mdns_map, dict): + normalized: dict[str, dict] = {} + for key, value in mdns_map.items(): + if isinstance(key, str) and isinstance(value, dict): + normalized[key.strip().lower()] = value + return normalized + except (OSError, json.JSONDecodeError): + self._logger.exception("Failed to load mDNS type map from %s", _TYPE_MAP_PATH) + return {} + + def _log_txt_if_changed(self, key: tuple[str, str], payload: dict) -> None: + """INFO trace of a service's TXT records (original key spelling), only when they change. + + Services re-announce often; logging every resolution would flood the log. + """ + if not self._logger.isEnabledFor(logging.INFO): + return + metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} + services = metadata.get("services") if isinstance(metadata.get("services"), list) else [] + svc = services[0] if services and isinstance(services[0], dict) else {} + records = svc.get("txt_records") if isinstance(svc.get("txt_records"), list) else [] + snapshot = tuple((str(k), str(v)) for k, v in records) + if self._txt_logged.get(key) == snapshot: + return + self._txt_logged[key] = snapshot + rendered = "; ".join(f"{k}={v}" if v else k for k, v in snapshot) or "(none)" + self._logger.info( + "mDNS TXT %s ip=%s port=%s: %s", + key[1], + payload.get("ip"), + payload.get("port"), + rendered, + ) + + def _on_service_change(self, zc, service_type: str, name: str, online: bool) -> None: + if not self._running: + return + # Service is re-announcing — cancel any pending grace-remove immediately so + # the UI never sees the record disappear if re-announcement arrives in time. + self._cancel_grace_remove((service_type, name)) + try: + info = zc.get_service_info(service_type, name, timeout=self._service_info_timeout_ms) + except OSError as exc: + self._logger.warning("mDNS lookup OS error for %s %s: %s", service_type, name, exc) + self._schedule_recovery() + return + except Exception: + self._logger.debug("mDNS lookup failed for %s %s", service_type, name, exc_info=True) + return + if info is None: + info = self._legacy_unicast_service_info(service_type, name) + if info is None: + self._logger.debug("mDNS service info unavailable for %s %s", service_type, name) + return + try: + payload = self._build_payload(service_type, name, info, online=online) + except Exception: + self._logger.debug("mDNS payload build failed for %s %s", service_type, name, exc_info=True) + return + key = (service_type, name) + self._seen_by_service[key] = payload + self._log_txt_if_changed(key, payload) + host_key = self._host_key_for_payload(payload, service_type, name) + self._service_host_keys[key] = host_key + try: + aggregate = self._aggregate_payload_for_host(host_key, online=True) + except Exception: + self._logger.debug("mDNS aggregate failed for %s %s", service_type, name, exc_info=True) + return + previous_endpoint = self._host_last_endpoint.get(host_key) + current_endpoint = (str(aggregate.get("ip", "0.0.0.0")), int(aggregate.get("port", 0) or 0)) + if previous_endpoint and previous_endpoint != current_endpoint: + stale_payload = dict(aggregate) + stale_payload["ip"] = previous_endpoint[0] + stale_payload["port"] = previous_endpoint[1] + stale_payload["online"] = False + self._emit("device", stale_payload) + self._host_last_endpoint[host_key] = current_endpoint + self._emit("device", aggregate) + + def _on_service_remove(self, service_type: str, name: str) -> None: + if not self._running: + return + key = (service_type, name) + host_key = self._service_host_keys.get(key, "") + if host_key: + # Check if host is still alive via other services (excluding this key). + still_alive = any( + v == host_key for k, v in self._service_host_keys.items() if k != key + ) + if still_alive: + # Host is still up — delay the removal to absorb TTL re-announcement + # jitter. If add_service fires within the grace window the timer is + # cancelled and the UI never sees the record disappear. + self._schedule_grace_remove(key, host_key) + return + # Host going fully offline (or no known host) — apply immediately. + self._cancel_grace_remove(key) + self._apply_remove(key) + + def _schedule_grace_remove(self, key: tuple[str, str], _host_key: str, delay: float | None = None) -> None: + grace_s = delay if delay is not None else float(_SERVICE_REMOVE_GRACE_S) + self._cancel_grace_remove(key) + + def apply_remove() -> None: + self._pending_remove_timers.pop(key, None) + if not self._running: + return + self._apply_remove(key) + + def _fire() -> None: + self._schedule_main(apply_remove) + + timer = threading.Timer(grace_s, _fire) + timer.daemon = True + self._pending_remove_timers[key] = timer + timer.start() + self._logger.debug( + "mDNS grace remove scheduled for %s %s (host still alive, %.0fs delay)", + key[0], key[1], grace_s, + ) + + def _cancel_grace_remove(self, key: tuple[str, str]) -> None: + timer = self._pending_remove_timers.pop(key, None) + if timer is not None: + try: + timer.cancel() + except Exception: + pass + + def _schedule_recovery(self) -> None: + """Rate-limited zeroconf refresh to recover from internal socket errors.""" + import time + now = time.monotonic() + if now - self._last_recovery_time < 30.0: + return + self._last_recovery_time = now + + def _recover() -> None: + if not self._running: + return + self._logger.info("mDNS recovery: refreshing zeroconf after socket error") + try: + self.refresh() + except Exception: + self._logger.debug("mDNS recovery refresh failed", exc_info=True) + + self._schedule_main(_recover) + + def _apply_remove(self, key: tuple[str, str]) -> None: + """Commit a service removal after the optional grace delay has elapsed.""" + self._seen_by_service.pop(key, None) + host_key = self._service_host_keys.pop(key, "") + if host_key: + still_online = any(value == host_key for value in self._service_host_keys.values()) + if still_online: + self._emit("device", self._aggregate_payload_for_host(host_key, online=True)) + return + self._host_last_endpoint.pop(host_key, None) + payload = self._aggregate_payload_for_host(host_key, online=False) + self._host_sticky_ip.pop(host_key, None) + self._emit("device", payload) + return + service_type, name = key + payload = self._build_fallback_remove_payload(service_type, name) + self._emit("device", payload) + + def _legacy_unicast_service_info(self, service_type: str, name: str): + """RFC 6762 §6.7 legacy-unicast fallback for responders that ignore multicast queries. + + Some embedded mDNS responders (case study: LUC-NAS — see docs/reference/MDNS.md) + announce PTRs but never answer standard QM/QU multicast queries, so + ``get_service_info()`` always returns ``None``. They DO answer one-shot queries + sent from an ephemeral port with a unicast reply (recognisable by TTL ≤ 10). + Resolve the instance label via the OS resolver (Windows resolves ``.local`` + natively, Linux via nss-mdns), then query the host directly for SRV/TXT. + """ + key = (service_type, name) + cached = self._legacy_resolve_cache.get(key) + now = time.monotonic() + if cached is not None and now - cached[0] <= _LEGACY_RESOLVE_RETRY_S: + return cached[1] + info = None + try: + info = self._legacy_unicast_query(service_type, name) + except Exception: + self._logger.debug("mDNS legacy-unicast resolve failed for %s", name, exc_info=True) + self._legacy_resolve_cache[key] = (now, info) + return info + + def _legacy_unicast_query(self, service_type: str, name: str): + import re + import types + + label = name.split("._", 1)[0].strip() + # Only plausible single-label hostnames — instance labels with spaces or + # punctuation ("Sonos Play:1", …) would just stall in the OS resolver. + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9\-_]{0,62}", label): + return None + host = f"{label}.local" + try: + resolved = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP) + except OSError: + return None + ip = choose_best_address([str(r[4][0]).split("%", 1)[0] for r in resolved]) + if not ip or ":" in ip: + return None + import ipaddress + + # DNS-suffix search or ISP NXDOMAIN redirection can hand back a public IP for an + # unknown name — a LAN neighbour is private by definition. + if not ipaddress.ip_address(ip).is_private: + return None + + srv_port = 0 + srv_server = "" + txt_bytes = b"" + try: + from zeroconf import DNSIncoming, DNSOutgoing, DNSQuestion + from zeroconf.const import _CLASS_IN, _FLAGS_QR_QUERY, _TYPE_ANY + + out = DNSOutgoing(_FLAGS_QR_QUERY) + out.add_question(DNSQuestion(name, _TYPE_ANY, _CLASS_IN)) + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + sock.settimeout(_LEGACY_UNICAST_TIMEOUT_S) + for packet in out.packets(): + sock.sendto(packet, (ip, 5353)) + deadline = time.monotonic() + _LEGACY_UNICAST_TIMEOUT_S + while time.monotonic() < deadline and not srv_port: + data, addr = sock.recvfrom(65535) + if addr[0] != ip: + continue + for record in DNSIncoming(data).answers(): + if getattr(record, "name", "").lower() != name.lower(): + continue + port = getattr(record, "port", None) + if port: + srv_port = int(port) + srv_server = str(getattr(record, "server", "") or "") + text = getattr(record, "text", None) + if isinstance(text, (bytes, bytearray)): + txt_bytes = bytes(text) + finally: + sock.close() + except OSError: + pass + except Exception: + self._logger.debug("mDNS legacy-unicast query failed for %s", name, exc_info=True) + + if not srv_port: + mapping = self._type_map.get(self._service_key(service_type), {}) + srv_port = int(mapping.get("default_port", 0) or 0) + self._logger.info( + "mDNS legacy-unicast resolved %s via %s (ip=%s port=%s)", + name, + host, + ip, + srv_port, + ) + return types.SimpleNamespace( + parsed_addresses=lambda: [ip], + addresses=None, + port=srv_port, + name=name, + server=srv_server or f"{host}.", + priority=0, + weight=0, + host_ttl=120, + other_ttl=120, + text=txt_bytes, + properties=None, + ) + + def _build_payload(self, service_type: str, name: str, info, online: bool) -> dict: + service_key = self._service_key(service_type) + mapping = self._type_map.get(service_key, {}) + addresses = self._extract_addresses(info) + # Multi-homed hosts advertise every interface (LAN + virtual switches + APIPA) and + # zeroconf's ordering is unstable — rank instead of trusting addresses[0]. + ip = choose_best_address(addresses) or "0.0.0.0" + port = int(getattr(info, "port", 0) or 0) + hostname = getattr(info, "name", "") or name + server = getattr(info, "server", "") + priority = int(getattr(info, "priority", 0) or 0) + weight = int(getattr(info, "weight", 0) or 0) + txt, txt_records = self._txt_from_service_info(info) + instance_label = name.split("._", 1)[0].strip() if name else "" + + display_name = self._infer_display_name(name, txt, self._to_text(server)) + type_name = str(mapping.get("type", "unknown")).strip().lower() or "unknown" + type_name = self._infer_type_from_context( + type_name, service_key, display_name, txt, srv_target=self._to_text(server) + ) + category = category_for_device_type( + type_name, + str(mapping.get("category", _("Unknown Devices"))) or _("Unknown Devices"), + ) + icon = mapping.get("icon") + if not isinstance(icon, str): + icon = self._icon_for_type(type_name) + + service_normalized = self._normalize_service_type(service_type) + metadata = { + "service": service_normalized, + "hostname": hostname, + "server": server, + "priority": priority, + "weight": weight, + "ttl": int(getattr(info, "host_ttl", 0) or getattr(info, "other_ttl", 0) or 0), + "services": [ + { + "service": service_normalized, + "port": port, + "hostname": hostname, + "server": server, + "instance": instance_label, + "txt": txt, + "txt_records": txt_records, + } + ], + "txt": txt, + } + return { + "name": display_name, + "ip": ip, + "port": port, + "type": type_name, + "category": category, + "source": "mdns", + "url": None, + "metadata": metadata, + "online": bool(online), + "icon": icon, + } + + def _build_fallback_remove_payload(self, service_type: str, name: str) -> dict: + service_key = self._service_key(service_type) + mapping = self._type_map.get(service_key, {}) + type_name = str(mapping.get("type", "unknown")).strip().lower() or "unknown" + type_name = self._infer_type_from_context(type_name, service_key, self._infer_display_name(name, {}), {}) + category = category_for_device_type( + type_name, + str(mapping.get("category", _("Unknown Devices"))) or _("Unknown Devices"), + ) + icon = mapping.get("icon") + if not isinstance(icon, str): + icon = self._icon_for_type(type_name) + return { + "name": self._infer_display_name(name, {}), + "ip": "0.0.0.0", + "port": int(mapping.get("default_port", 0) or 0), + "type": type_name, + "category": category, + "source": "mdns", + "url": None, + "metadata": {"service": self._normalize_service_type(service_type), "txt": {}, "services": []}, + "online": False, + "icon": icon, + } + + def _service_key(self, service_type: str) -> str: + value = self._normalize_service_type(service_type) + if value.endswith(".local."): + value = value[: -len(".local.")] + return value + + def _infer_type_from_service(self, service_key: str) -> str: + if "_esp3d._tcp" in service_key or "_arduino._tcp" in service_key: + return "esp32" + if "_smb._tcp" in service_key: + return "computer" + if "_printer._tcp" in service_key or "_ipp._tcp" in service_key or "_ipps._tcp" in service_key: + return "networkprinter" + if "_airplay._tcp" in service_key or "_raop._tcp" in service_key or "_companion-link._tcp" in service_key: + return "smartspeaker" + if "_ftp._tcp" in service_key or "_afpovertcp._tcp" in service_key or "_webdav._tcp" in service_key: + # NAS heuristic refines Synology/QNAP in TXT / name. + return "computer" + if "_scanner" in service_key or "_uscan" in service_key or "_uscans." in service_key: + return "scanner" + if "_http._tcp" in service_key or "_https._tcp" in service_key: + return "http" + return "unknown" + + def _infer_type_from_context( + self, + mapped_type: str, + service_key: str, + display_name: str, + txt: dict[str, str], + merged_services_line: str = "", + srv_target: str = "", + ) -> str: + base = mapped_type if mapped_type and mapped_type != "unknown" else self._infer_type_from_service(service_key) + # Collapse printer variants into one device type class. + if base == "printer": + base = "networkprinter" + + haystack_parts = [service_key, display_name, merged_services_line] + # SRV target as "target=" so rules can match the host name precisely + # (e.g. "target=android_" for Android phones) without loose name matches. + target = (srv_target or "").strip().rstrip(".") + if target: + haystack_parts.append(f"target={target}") + haystack_parts.extend([f"{k}={v}" for k, v in txt.items()]) + haystack = " ".join([part.lower() for part in haystack_parts if isinstance(part, str)]) + + # All type heuristics live in config/mdns_rules.json (type_rules); see _DEFAULT_RULES + # in utils/mdns_rules.py for the bundled baseline. No hardcoded classification here. + if not self._rules_enabled: + return base + return evaluate_type_rules(haystack, base, self._mdns_rules) + + def _aggregate_type_rank(self, device_type: str) -> int: + """Higher = stronger signal for host-level aggregate type (icon + category). + + Kept in sync with DiscoveryManager._cross_protocol_type_rank. ``esp32`` is a low-confidence + fallback ("ESP3D board, machine unknown"): any concrete machine type (cnc, 3dprinter, …) + must outrank it so a controller that reveals its machine via TXT is classified accordingly. + """ + t = (device_type or "unknown").strip().lower() + return { + "unknown": 0, + "http": 12, + "https": 12, + "computer": 20, + "esp32": 22, + "homeappliance": 26, + "smartdevice": 28, + "camera": 30, + "cnc": 30, + "3dprinter": 32, + "mediaserver": 34, + "router": 35, + "smarttv": 41, + "server": 37, + "rackserver": 37, + "nas": 38, + "smartspeaker": 40, + # Explicit form factor from TXT model= (e.g. a Mac's _device-info): beats the + # smartspeaker guess a Mac's own _airplay/_raop receiver would otherwise give. + "desktop": 41, + "minipc": 41, + "allinone": 41, + "laptop": 41, + "smartphone": 41, + "scanner": 52, + "networkprinter": 55, + "printer": 55, + "multifunction_printer": 56, + }.get(t, 8) + + def _best_aggregate_mdns_type(self, seed: str, merged_services: list) -> str: + best = (seed or "unknown").strip().lower() + best_r = self._aggregate_type_rank(best) + for svc in merged_services: + if not isinstance(svc, dict): + continue + svc_key = str(svc.get("service", "")).lower() + cand = self._infer_type_from_service(svc_key) + cr = self._aggregate_type_rank(cand) + if cr > best_r: + best = cand + best_r = cr + return best + + def _merged_services_imply_multifunction_printer(self, merged_services: list) -> bool: + """Printer-class DNS-SD plus scanner / eSCL on the same host → multifunction.""" + parts: list[str] = [] + for svc in merged_services: + if not isinstance(svc, dict): + continue + parts.append(str(svc.get("service", "")).lower()) + line = " ".join(parts) + printer = any( + x in line + for x in ("_ipp._tcp", "_ipps._tcp", "_printer._tcp", "_pdl-datastream._tcp") + ) + scanner = any( + tok in line + for tok in ( + "_uscan._tcp", + "_uscans._tcp", + "_scanner._tcp", + "_scan._tcp", + "_escl._tcp", + ) + ) or ("scanner" in line and "._tcp" in line) + return bool(printer and scanner) + + def _dns_target_label_from_server(self, server: str) -> str: + """SRV / PTR target host (often ``thing.local``) without ``.local`` — good NAS / printer labels.""" + s = self._to_text(server).strip().strip(".") + if not s: + return "" + low = s.lower() + if low.endswith(".local"): + s = s[:-6].strip(".") + elif low.endswith(".local."): + s = s[:-7].strip(".") + return s.replace("-", " ").strip() if s else "" + + def _txt_product_value(self, txt: dict[str, str]) -> str: + """Non-empty ``product`` TXT field if present (case-insensitive key).""" + if not isinstance(txt, dict): + return "" + for raw_k, raw_v in txt.items(): + if not isinstance(raw_k, str) or raw_k.lower() != "product": + continue + if isinstance(raw_v, str) and raw_v.strip(): + return raw_v.strip() + return "" + + def _infer_display_name(self, service_instance: str, txt: dict[str, str], server: str = "") -> str: + # Order: friendly TXT first; Google Cast uses ``fn``. DNS target (without .local) before hardware + # ``model`` so NAS / printers show hostname when TXT advertises a bare model string. + for key in ("name", "fn", "friendlyname", "friendly_name", "device"): + value = txt.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + dns_label = self._dns_target_label_from_server(server) + if dns_label: + prod = self._txt_product_value(txt) + if prod: + return f"{dns_label} ({prod})" + return dns_label + for key in ("model", "mdl", "md", "product"): + value = txt.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + label = service_instance.split("._", 1)[0].strip() + return label or "mDNS Device" + + def _extract_addresses(self, info) -> list[str]: + addresses: list[str] = [] + parsed_addresses = getattr(info, "parsed_addresses", None) + if callable(parsed_addresses): + try: + values = parsed_addresses() + if isinstance(values, list): + addresses.extend([str(v) for v in values if v]) + except Exception: + pass + raw_addrs = getattr(info, "addresses", None) + if isinstance(raw_addrs, list): + for raw in raw_addrs: + if not isinstance(raw, (bytes, bytearray)): + continue + try: + if len(raw) == 4: + addresses.append(socket.inet_ntop(socket.AF_INET, raw)) + elif len(raw) == 16: + addresses.append(socket.inet_ntop(socket.AF_INET6, raw)) + except OSError: + continue + unique: list[str] = [] + for value in addresses: + if value not in unique: + unique.append(value) + return unique + + def _unpack_txt_bytes(self, text: bytes) -> list[tuple[str, str]]: + """Parse concatenated RFC 6763 TXT blobs; preserves order and duplicate keys. + + zeroconf's internal unpack keeps only the first occurrence per key — some devices expose + multiple strings or duplicated keys across the TXT compound. + """ + if not text: + return [] + pairs: list[tuple[str, str]] = [] + index = 0 + end = len(text) + while index < end: + length = text[index] + index += 1 + if length == 0: + continue + segment = text[index : index + length] + index += length + split = segment.split(b"=", 1) + key = self._to_text(split[0]).strip() + if not key and len(split) < 2: + continue + value = self._to_text(split[1]).strip() if len(split) > 1 else "" + pairs.append((key, value)) + return pairs + + def _txt_from_service_info(self, info) -> tuple[dict[str, str], list[tuple[str, str]]]: + """TXT as dict (last wins duplicate keys for heuristics) + ordered record list.""" + + pairs: list[tuple[str, str]] = [] + raw_text = getattr(info, "text", None) + if isinstance(raw_text, (bytes, bytearray)) and len(raw_text) > 0: + pairs = self._unpack_txt_bytes(bytes(raw_text)) + if not pairs: + props = getattr(info, "properties", None) + if isinstance(props, dict): + for raw_key, raw_value in props.items(): + key = self._to_text(raw_key).strip() + if not key: + continue + val = "" if raw_value is None else self._to_text(raw_value).strip() + pairs.append((key, val)) + # RFC 6763 §6.4: TXT keys are case-insensitive (printers send "UUID=", others "uuid="). + # The lookup dict is lower-cased so every reader can use plain lower-case keys; the + # ordered record list keeps the original spelling for the details view. + merged: dict[str, str] = {} + for key, val in pairs: + if key: + merged[key.lower()] = val + return merged, pairs + + def _decode_properties(self, props) -> dict[str, str]: + if not isinstance(props, dict): + return {} + decoded: dict[str, str] = {} + for raw_key, raw_value in props.items(): + key = self._to_text(raw_key).strip() + if not key: + continue + decoded[key] = self._to_text(raw_value).strip() + return decoded + + def _to_text(self, value) -> str: + if isinstance(value, bytes): + return value.decode("utf-8", errors="replace") + return str(value) + + def _sticky_host_ip(self, host_key: str, ip: str) -> str: + """Never downgrade a host to a worse-ranked address while a recent routable one is known. + + A resolution that momentarily surfaces only the APIPA/virtual-switch A record of a + multi-homed host must not move the aggregate endpoint: the flap would retire the + LAN endpoint (offline) and churn the device row. A genuinely new routable address + (e.g. DHCP renewal) still replaces the remembered one immediately. + """ + now = time.monotonic() + rank = address_preference_rank(ip) + if rank == 0: + self._host_sticky_ip[host_key] = (ip, now) + return ip + remembered = self._host_sticky_ip.get(host_key) + if remembered is not None: + sticky_ip, seen_at = remembered + if now - seen_at <= _STICKY_HOST_IP_TTL_S and address_preference_rank(sticky_ip) < rank: + self._logger.debug( + "mDNS sticky ip: host=%s keeping %s over %s", host_key, sticky_ip, ip + ) + return sticky_ip + self._host_sticky_ip.pop(host_key, None) + return ip + + def _host_key_for_payload(self, payload: dict, service_type: str, name: str) -> str: + metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} + # The SRV target ("server", e.g. "DESKTOP-LUCTW.local.") is unique per machine — key + # hosts by it so a multi-homed host stays ONE aggregate even when successive + # resolutions surface different interface addresses. Keying by IP (previous + # behaviour) split such a host into one row per interface, and the stale-endpoint + # retirement in _on_service_change never fired. + server = metadata.get("server") + if isinstance(server, str) and server.strip(): + return server.strip().lower().rstrip(".") + ip = str(payload.get("ip", "")).strip() + if ip and ip != "0.0.0.0": + return ip + value = metadata.get("hostname") + if isinstance(value, str) and value.strip(): + return value.strip().lower() + return f"{self._normalize_service_type(service_type)}::{name.strip().lower()}" + + def _aggregate_payload_for_host(self, host_key: str, online: bool) -> dict: + entries: list[dict] = [] + for key, value in self._seen_by_service.items(): + if self._service_host_keys.get(key) == host_key: + entries.append(value) + if not entries: + return { + "name": "mDNS Device", + "ip": "0.0.0.0", + "port": 0, + "type": "unknown", + "category": _("Unknown Devices"), + "source": "mdns", + "url": None, + "metadata": {"service": "_mdns._udp.local.", "txt": {}, "services": []}, + "online": bool(online), + "icon": self._icon_for_type("unknown"), + } + + def _score(entry: dict) -> tuple[int, int]: + metadata = entry.get("metadata") if isinstance(entry.get("metadata"), dict) else {} + service_text = str(metadata.get("service", "")).lower() + # Prefer print-related rows over bare _http so aggregate type/icon stay printer-like + # (avoids http → GTK "browser" flash before IPP TXT / device icon URL arrives). + if any( + x in service_text + for x in ("_ipp._tcp", "_ipps._tcp", "_printer._tcp", "_pdl-datastream._tcp") + ): + return (0, 0) + # Prefer playback / casting rows over bare _http (room TXT + artwork URLs). + if any( + x in service_text + for x in ( + "_airplay._tcp", + "_raop._tcp", + "_companion-link._tcp", + "_sonos._tcp", + "_spotify-connect._tcp", + "_googlecast._tcp", + ) + ): + return (1, 0) + if "_http._tcp" in service_text or "_https._tcp" in service_text: + return (2, 0) + if "_esp3d._tcp" in service_text: + return (3, 0) + return (4, int(entry.get("port", 0) or 0)) + + representative = sorted(entries, key=_score)[0] + rep_metadata = representative.get("metadata") if isinstance(representative.get("metadata"), dict) else {} + merged_services: list[dict] = [] + combined_txt: dict[str, str] = {} + for entry in entries: + metadata = entry.get("metadata") if isinstance(entry.get("metadata"), dict) else {} + entry_txt = metadata.get("txt") + if isinstance(entry_txt, dict): + combined_txt.update(entry_txt) + services_list = metadata.get("services") if isinstance(metadata.get("services"), list) else [] + for service in services_list: + if not isinstance(service, dict): + continue + normalized_service = str(service.get("service", "")).strip() + normalized_port = int(service.get("port", 0) or 0) + inst_norm = str(service.get("instance", "")).strip() + duplicate = any( + str(existing.get("service", "")).strip() == normalized_service + and int(existing.get("port", 0) or 0) == normalized_port + and str(existing.get("instance", "")).strip() == inst_norm + for existing in merged_services + ) + if not duplicate: + merged_services.append(dict(service)) + + http_port = None + http_path = "/" + for service in merged_services: + service_name = str(service.get("service", "")).lower() + if "_http._tcp" in service_name: + candidate = int(service.get("port", 0) or 0) + if candidate > 0: + http_port = candidate + # DNS-SD convention: the web UI path is in TXT "path=" (default "/"). + http_path = mdns_http_path(service.get("txt")) + break + + # Services of one host may have resolved to different interfaces (multi-homed + # hosts, or payloads cached before an address change) — rank across all rows so + # the aggregate endpoint stays on the routable LAN address. + ip = choose_best_address([str(e.get("ip", "")) for e in entries]) or str( + representative.get("ip", "0.0.0.0") + ) + ip = self._sticky_host_ip(host_key, ip) + url = None + if http_port and ip and ip != "0.0.0.0": + url = f"http://{ip}:{http_port}{http_path}" + + merged_metadata = dict(rep_metadata) + merged_metadata["services"] = merged_services + if combined_txt: + merged_metadata["txt"] = combined_txt + + seed_type = str(representative.get("type", "unknown")).strip().lower() + services_line_for_infer = " ".join( + str(s.get("service", "")).lower() for s in merged_services if isinstance(s, dict) + ) + agg_type = self._infer_type_from_context( + seed_type, + str(rep_metadata.get("service", "")).lower(), + str(representative.get("name", "mDNS Device")), + combined_txt, + services_line_for_infer, + srv_target=self._to_text(rep_metadata.get("server", "")), + ) + agg_type = self._best_aggregate_mdns_type(agg_type, merged_services) + if self._merged_services_imply_multifunction_printer(merged_services): + agg_type = "multifunction_printer" + icon_out = representative.get("icon") + if not isinstance(icon_out, str) or not icon_out.strip(): + icon_out = self._icon_for_type(agg_type) + elif self._aggregate_type_rank(agg_type) > self._aggregate_type_rank(seed_type): + icon_out = self._icon_for_type(agg_type) + category = category_for_device_type(agg_type, representative.get("category", _("Unknown Devices"))) + + rep_svc = str(rep_metadata.get("service", "")) + self._logger.debug( + "mDNS aggregate host=%s ip=%s rows=%d rep_service=%r rep_port=%s seed_type=%s agg_type=%s icon=%s " + "merged_txt_keys=%d merged_services=%d", + host_key, + ip, + len(entries), + rep_svc, + representative.get("port"), + seed_type, + agg_type, + icon_out, + len(combined_txt), + len(merged_services), + ) + + return { + "name": representative.get("name", "mDNS Device"), + "ip": ip, + "port": int(representative.get("port", 0) or 0), + "type": agg_type, + "category": category, + "source": "mdns", + "url": url, + "metadata": merged_metadata, + "online": bool(online), + "icon": icon_out, + } + + def _build_url(self, mapping: dict, ip: str, port: int) -> str | None: + info_url = mapping.get("info_url") + if not isinstance(info_url, str) or not info_url.strip(): + return None + try: + return info_url.format(ip=ip, port=port) + except Exception: + return None + + def _icon_for_type(self, device_type: str) -> str | None: + return { + "router": "router.png", + "mediaserver": "mediaserver.png", + "scanner": "printer.png", + "printer": "printer.png", + "networkprinter": "printer.png", + "multifunction_printer": "printer.png", + "smartspeaker": "smartspeaker.png", + "smarttv": "smarttv.png", + "smartdevice": "smartdevice.png", + "camera": "camera.png", + "homeappliance": "homeappliance.png", + "cnc": "cnc.png", + "3dprinter": "3dprinter.png", + "nas": "nas.png", + "server": "server.png", + "rackserver": "server.png", + "desktop": "computer.png", + "minipc": "computer.png", + "allinone": "computer.png", + "laptop": "computer.png", + "smartphone": "smartdevice.png", + "computer": "computer.png", + "esp32": "esp32.png", + "http": "http.png", + "unknown": "unknown.png", + }.get(device_type) diff --git a/app/discovery/netbios.py b/app/discovery/netbios.py new file mode 100644 index 00000000..1274b57c --- /dev/null +++ b/app/discovery/netbios.py @@ -0,0 +1,497 @@ +# File netbios.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""NetBIOS LAN discovery via Samba ``nmblookup`` (NMB broadcast / name query).""" + +from __future__ import annotations + +import concurrent.futures +import ipaddress +import logging +import re +import shutil +import subprocess +import sys +import threading +from collections import OrderedDict, defaultdict +from collections.abc import Sequence + +from discovery.base import BaseDiscovery + +_DEFAULT_INTERVAL_S = 180.0 +_DEFAULT_TIMEOUT_S = 15.0 + + +def _subprocess_no_window_kwargs() -> dict[str, object]: + """Avoid flashing console windows when ``nmblookup`` runs on Windows.""" + if sys.platform != "win32": + return {} + out: dict[str, object] = {} + flag = getattr(subprocess, "CREATE_NO_WINDOW", 0) + if flag: + out["creationflags"] = flag + # Some CUI builds still create a brief host window; STARTUPINFO reinforces hide. + if hasattr(subprocess, "STARTUPINFO"): + si = subprocess.STARTUPINFO() + si.dwFlags |= subprocess.STARTF_USESHOWWINDOW + si.wShowWindow = subprocess.SW_HIDE + out["startupinfo"] = si + return out + + +_NMB_SUBPROCESS_KW = _subprocess_no_window_kwargs() + +# ``Looking up status of 192.168.1.10`` / IPv6 +_STATUS_OF_RE = re.compile(r"^Looking up status of\s+(\S+)\s*$", re.IGNORECASE) +# `` DS415PLUS <00> - B `` +_STATUS_NAME_RE = re.compile(r"^\s+(\S+)\s+<([0-9a-fA-F]{2})>\s*-") +# nbtstat -A output: `` MYPC <00> UNIQUE Registered`` +_NBTSTAT_NAME_RE = re.compile( + r"^\s+(\S+)\s+<([0-9a-fA-F]{2})>\s+(?:UNIQUE|GROUP)\b", + re.IGNORECASE, +) + + +def _parse_ip_name_suffix(rest: str) -> tuple[str, str] | None: + """Parse ``HOSTNAME<00>`` tail after first column.""" + m = re.match(r"^(.+)<([0-9a-fA-F]{2})>\s*$", rest.strip()) + if not m: + return None + return m.group(1).strip(), m.group(2).lower() + + +def _parse_flat_ip_line(line: str) -> tuple[str, str, str] | None: + """Parse ``192.168.1.10 HOST<00>`` or IPv6 equivalent.""" + line = line.strip() + if not line or line.lower().startswith("querying"): + return None + parts = line.split(None, 1) + if len(parts) != 2: + return None + ip_s, rest = parts[0], parts[1].strip() + try: + addr = ipaddress.ip_address(ip_s) + except ValueError: + return None + parsed = _parse_ip_name_suffix(rest) + if not parsed: + return None + name, suf = parsed + return str(addr), name, suf + + +def _ip_rank(ip_s: str) -> tuple[int, int]: + """Sort key: lower = better. Prefer LAN IPv4 over IPv6 (esp. link-local).""" + try: + a = ipaddress.ip_address(ip_s) + except ValueError: + return (99, 99) + if isinstance(a, ipaddress.IPv4Address): + if a.is_loopback: + return (5, 0) + if a.is_private or a.is_link_local: + return (0, 0) + return (1, 0) + if isinstance(a, ipaddress.IPv6Address): + if a.is_loopback: + return (6, 0) + if a.is_link_local: + return (4, 0) + if a.is_private: + return (3, 0) + return (2, 0) + return (99, 99) + + +def _is_placeholder_netbios_name(name: str) -> bool: + n = (name or "").strip() + return n in {"*", "?"} + + +def _parse_nbtstat_output(text: str, queried_ip: str) -> list[tuple[str, str, str]]: + """Parse ``nbtstat -A `` output → ``(ip, name, suffix_hex)`` rows. + + The "Node IpAddress" header is our local interface IP, not the target — + use ``queried_ip`` as the canonical IP for all parsed names. + """ + try: + ip = str(ipaddress.ip_address(queried_ip.strip())) + except ValueError: + ip = queried_ip.strip() + rows: list[tuple[str, str, str]] = [] + for raw in (text or "").splitlines(): + m = _NBTSTAT_NAME_RE.match(raw) + if m: + rows.append((ip, m.group(1).strip(), m.group(2).lower())) + return rows + + +def _parse_nmblookup_output(text: str) -> list[tuple[str, str, str]]: + """Return rows ``(ip, netbios_name, suffix_hex)`` from ``nmblookup`` stdout/stderr.""" + rows: list[tuple[str, str, str]] = [] + current_status_ip: str | None = None + for raw in (text or "").splitlines(): + line = raw.rstrip() + if not line.strip(): + continue + if line.lower().lstrip().startswith("querying"): + continue + + m_hdr = _STATUS_OF_RE.match(line.strip()) + if m_hdr: + ip_raw = m_hdr.group(1).strip() + if ip_raw.startswith("[") and "]" in ip_raw: + ip_raw = ip_raw.split("[", 1)[1].split("]", 1)[0].strip() + try: + current_status_ip = str(ipaddress.ip_address(ip_raw)) + except ValueError: + current_status_ip = None + continue + + m_stat = _STATUS_NAME_RE.match(line) + if m_stat and current_status_ip: + name, suf = m_stat.group(1), m_stat.group(2).lower() + rows.append((current_status_ip, name, suf)) + continue + + flat = _parse_flat_ip_line(line) + if flat: + rows.append(flat) + continue + + return rows + + +def _noise_netbios_name(name: str, suffix: str) -> bool: + bu = name.strip().upper() + su = (suffix or "").strip().lower() + # Group/workgroup registrations — not a machine unique name (do not hide whole IP if only `<20>` etc. remains). + if bu == "WORKGROUP" and su in ("00", "1e", "1d"): + return True + if "__MSBROWSE__" in bu: + return True + if bu.startswith("__MSBROWSE__"): + return True + if bu == "MSBROWSE": + return True + return False + + +def _pick_netbios_display_name(candidates: Sequence[tuple[str, str]]) -> str | None: + """Pick host-style NetBIOS label for one IP; skip workgroup / wildcard.""" + filtered: list[tuple[str, str]] = [] + for base, suf in candidates: + if _noise_netbios_name(base, suf): + continue + if _is_placeholder_netbios_name(base): + continue + filtered.append((base.strip(), suf)) + if not filtered: + return None + for base, suf in filtered: + if suf == "00": + return base + for base, suf in filtered: + if suf == "20": + return base + return filtered[0][0] + + +def _merge_row_sort_key(r: tuple[str, str, str]) -> tuple[tuple[int, int], int]: + ip_s = r[0] + try: + a = ipaddress.ip_address(ip_s) + v6 = 1 if isinstance(a, ipaddress.IPv6Address) else 0 + except ValueError: + v6 = 9 + return (_ip_rank(ip_s), v6) + + +def _merge_rows_prefer_ipv4(rows: list[tuple[str, str, str]]) -> list[tuple[str, str, str]]: + """One row per distinct NetBIOS name; prefer IPv4 / routable over link-local IPv6.""" + by_ip: dict[str, list[tuple[str, str]]] = defaultdict(list) + for ip_s, name, suf in rows: + by_ip[ip_s].append((name, suf)) + + per_name: dict[str, list[tuple[str, str, str]]] = defaultdict(list) + for ip_s, cands in by_ip.items(): + display = _pick_netbios_display_name(cands) + if not display or _is_placeholder_netbios_name(display): + continue + suf_pick = "" + for nb, suf in cands: + if nb.strip() == display.strip(): + suf_pick = suf + break + per_name[display.strip().lower()].append((ip_s, display, suf_pick)) + + merged: list[tuple[str, str, str]] = [] + for _k, group in per_name.items(): + merged.append(min(group, key=_merge_row_sort_key)) + return merged + + +class NetbiosDiscovery(BaseDiscovery): + """Periodic ``nmblookup`` sweep; emits ``computer`` rows when hosts respond on NMB.""" + + def __init__( + self, + *, + interval_seconds: float | None = None, + timeout_seconds: float | None = None, + argv: list[str] | None = None, + directed_ips: list[str] | None = None, + ) -> None: + super().__init__(source="nmb") + self._logger = logging.getLogger(__name__) + self._interval_s = ( + float(interval_seconds) if interval_seconds is not None else _DEFAULT_INTERVAL_S + ) + self._timeout_s = ( + float(timeout_seconds) if timeout_seconds is not None else _DEFAULT_TIMEOUT_S + ) + self._interval_s = max(60.0, min(3600.0, self._interval_s)) + self._timeout_s = max(5.0, min(120.0, self._timeout_s)) + # ``-S`` adds node status so we get real names (plain ``*`` only yields ``*<00>`` per IP). + self._argv_rest: list[str] = list(argv) if argv else ["-S", "*"] + self._directed_ips: list[str] = [] + for raw in directed_ips or []: + if not isinstance(raw, str) or not raw.strip(): + continue + try: + self._directed_ips.append(str(ipaddress.ip_address(raw.strip()))) + except ValueError: + self._logger.debug("NetBIOS directed_ips skip invalid IP: %r", raw) + self._nmblookup = shutil.which("nmblookup") + self._nbtstat: str | None = shutil.which("nbtstat") if sys.platform == "win32" else None + self._running = False + self._stop_event = threading.Event() + self._wake_event = threading.Event() + self._probe_thread: threading.Thread | None = None + self._missing_logged = False + self._extra_directed_lock = threading.Lock() + # IPs to probe with ``nmblookup -A`` (e.g. suggested when WSD only has a synthetic label). + self._extra_directed: OrderedDict[str, None] = OrderedDict() + self._max_extra_directed = 64 + # TTL tracking: emit offline for hosts absent ≥ _nmb_grace_sweeps consecutive sweeps. + self._nmb_known: dict[str, dict] = {} # ip → last emitted payload + self._nmb_miss_counts: dict[str, int] = {} # ip → consecutive missed sweeps + self._nmb_grace_sweeps: int = 2 + + def suggest_directed_ip(self, ip_s: str) -> None: + """Queue ``nmblookup -A`` / ``nbtstat -A`` for this IP on the next probe.""" + if not self._running or (not self._nmblookup and not self._nbtstat): + return + try: + normalized = str(ipaddress.ip_address((ip_s or "").strip())) + except ValueError: + return + with self._extra_directed_lock: + self._extra_directed.pop(normalized, None) + self._extra_directed[normalized] = None + while len(self._extra_directed) > self._max_extra_directed: + self._extra_directed.popitem(last=False) + self._logger.debug("NetBIOS: extra directed probe queued for %s", normalized) + self.refresh() + + def remove_directed_ip(self, ip_s: str) -> None: + """Remove an IP from the extra directed probe queue (e.g. device went offline).""" + try: + normalized = str(ipaddress.ip_address((ip_s or "").strip())) + except ValueError: + return + with self._extra_directed_lock: + self._extra_directed.pop(normalized, None) + self._logger.debug("NetBIOS: removed directed probe for %s", normalized) + + def start(self) -> None: + if self._running: + return + if not self._nmblookup and not self._nbtstat: + if not self._missing_logged: + self._logger.warning( + "NetBIOS discovery unavailable: nmblookup not in PATH " + "(install samba-common-bin or samba-common; ensure nmbd can answer on the LAN)" + ) + self._missing_logged = True + return + self._running = True + self._stop_event.clear() + self._wake_event.clear() + self._probe_thread = threading.Thread(target=self._probe_loop, name="nmb-probe", daemon=True) + self._probe_thread.start() + self._logger.info( + "NetBIOS discovery started (interval=%.1fs timeout=%.1fs argv=%s)", + self._interval_s, + self._timeout_s, + self._argv_rest, + ) + + def stop(self) -> None: + if not self._running: + return + self._running = False + self._stop_event.set() + self._wake_event.set() + if self._probe_thread is not None: + self._probe_thread.join(timeout=2.0) + self._probe_thread = None + self._nmb_known.clear() + self._nmb_miss_counts.clear() + self._logger.info("NetBIOS discovery stopped") + + def refresh(self) -> None: + if not self._running: + return + self._wake_event.set() + + def _probe_loop(self) -> None: + while self._running: + self._run_once() + if self._stop_event.is_set(): + break + if self._wake_event.wait(timeout=self._interval_s): + self._wake_event.clear() + + def _run_once(self) -> None: + if not self._nmblookup and not self._nbtstat: + return + rows: list[tuple[str, str, str]] = [] + sweep_rc: int | None = None + + # Broadcast sweep: nmblookup only (nbtstat has no broadcast mode). + if self._nmblookup: + cmd = [self._nmblookup, *self._argv_rest] + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=float(self._timeout_s), + check=False, + **_NMB_SUBPROCESS_KW, + ) + sweep_rc = proc.returncode + except subprocess.TimeoutExpired: + self._logger.debug("nmblookup timed out after %.1fs", self._timeout_s) + return + except OSError: + self._logger.debug("nmblookup failed to run", exc_info=True) + return + out = (proc.stdout or "") + "\n" + (proc.stderr or "") + rows = _parse_nmblookup_output(out) + + with self._extra_directed_lock: + extra_directed = list(self._extra_directed.keys()) + directed_chain = list(dict.fromkeys([*self._directed_ips, *sorted(extra_directed)])) + + def _probe_one(dip: str) -> list[tuple[str, str, str]]: + if self._nmblookup: + try: + proc_d = subprocess.run( + [self._nmblookup, "-A", dip], + capture_output=True, + text=True, + timeout=float(self._timeout_s), + check=False, + **_NMB_SUBPROCESS_KW, + ) + return _parse_nmblookup_output((proc_d.stdout or "") + "\n" + (proc_d.stderr or "")) + except subprocess.TimeoutExpired: + self._logger.debug("nmblookup -A %s timed out after %.1fs", dip, self._timeout_s) + except OSError: + self._logger.debug("nmblookup -A %s failed", dip, exc_info=True) + elif self._nbtstat: + try: + proc_d = subprocess.run( + [self._nbtstat, "-A", dip], + capture_output=True, + text=True, + timeout=float(self._timeout_s), + check=False, + **_NMB_SUBPROCESS_KW, + ) + result = _parse_nbtstat_output((proc_d.stdout or "") + "\n" + (proc_d.stderr or ""), dip) + if result: + return result + except subprocess.TimeoutExpired: + self._logger.debug("nbtstat -A %s timed out after %.1fs — trying DNS reverse lookup", dip, self._timeout_s) + except OSError: + self._logger.debug("nbtstat -A %s failed", dip, exc_info=True) + # Fallback: DNS reverse lookup (covers DNS-registered hosts when UDP 137 is firewalled). + try: + import socket as _socket + fqdn, _, _ = _socket.gethostbyaddr(dip) + short = fqdn.split(".")[0].strip().upper() + if short: + self._logger.debug("DNS reverse fallback for %s → %s", dip, short) + return [(dip, short, "00")] + except Exception: + pass + return [] + + if directed_chain: + workers = min(8, len(directed_chain)) + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: + for partial_rows in pool.map(_probe_one, directed_chain): + rows.extend(partial_rows) + merged = _merge_rows_prefer_ipv4(rows) + if not merged: + if sweep_rc is not None: + self._logger.debug( + "NetBIOS: no hosts parsed (nmblookup exit=%s; try ``nmblookup -S '*'`` / LAN NMB)", + sweep_rc, + ) + if self._directed_ips: + self._logger.warning( + "NetBIOS: directed_ips=%s returned no usable names — check ``nmblookup -A `` from this host", + self._directed_ips, + ) + + # Build payloads for hosts found in this sweep. + current_payloads: dict[str, dict] = {} + for ip_s, name, suffix_primary in merged: + current_payloads[ip_s] = { + "name": name, + "ip": ip_s, + "port": 445, + "type": "computer", + "category": _("Computers"), + "source": self.source, + "url": None, + "metadata": { + "nmb_name": name, + "nmb_suffix": suffix_primary, + "nmb_argv": list(self._argv_rest), + }, + "online": True, + "icon": None, + } + + # TTL: emit offline for previously-known hosts absent from this sweep for ≥ grace sweeps. + for ip in list(self._nmb_known): + if ip not in current_payloads: + miss = self._nmb_miss_counts.get(ip, 0) + 1 + self._nmb_miss_counts[ip] = miss + if miss >= self._nmb_grace_sweeps: + offline_payload = dict(self._nmb_known[ip]) + offline_payload["online"] = False + self._emit("device", offline_payload) + self._logger.info( + "NetBIOS: ip=%s offline after %d missed sweep(s)", ip, miss + ) + del self._nmb_known[ip] + self._nmb_miss_counts.pop(ip, None) + else: + self._nmb_miss_counts.pop(ip, None) + + if current_payloads: + self._logger.info("NetBIOS: publishing %d host row(s)", len(current_payloads)) + self._logger.debug( + "NetBIOS host rows (ip=name): %s", + ", ".join(f"{ip}={p['name']}" for ip, p in current_payloads.items()), + ) + for ip_s, payload in current_payloads.items(): + self._nmb_known[ip_s] = payload + self._emit("device", payload) diff --git a/app/discovery/ssdp.py b/app/discovery/ssdp.py new file mode 100644 index 00000000..c7b9dd7a --- /dev/null +++ b/app/discovery/ssdp.py @@ -0,0 +1,1598 @@ +# File ssdp.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Minimal live SSDP discovery (M-SEARCH + response parsing).""" + +from __future__ import annotations + +import concurrent.futures +from datetime import datetime, timedelta, timezone +import ipaddress +import json +import logging +from pathlib import Path +import queue +import re +import select +import socket +import struct +import sys +import threading +import time +from urllib.error import URLError +from urllib.parse import urljoin, urlparse +from urllib.request import urlopen +import xml.etree.ElementTree as ET +from collections.abc import Callable + +from discovery.base import BaseDiscovery +from utils.discovery_cache import load_discovery_cache, save_discovery_cache +from utils.discovery_config import category_for_device_type +from utils.local_host import VIRTUAL_HOST_SUBNETS +from utils.user_config_overlay import merge_ssdp_rules_overlays + +_SSDP_ADDR = ("239.255.255.250", 1900) +# Multicast M-SEARCH targets; unicast directed searches use the same ST list. +_SSDP_SEARCH_ST: tuple[str, ...] = ( + "ssdp:all", + "upnp:rootdevice", + "urn:dial-multiscreen-org:service:dial:1", + "urn:schemas-upnp-org:device:MediaRenderer:1", + "urn:schemas-upnp-org:device:MediaServer:1", + "urn:schemas-upnp-org:device:MediaPlayer:1", +) +_DEFAULT_TIMEOUT_SECONDS = 180 +_REFRESH_INTERVAL_SECONDS = 60 +_MAX_TIMEOUT_SECONDS = 3600 +_MAX_AGE_RE = re.compile(r"max-age\s*=\s*(\d+)", re.IGNORECASE) +_RULES_PATH = Path(__file__).resolve().parent.parent / "config" / "ssdp_rules.json" +_RX_FRAME_DELIMITER = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" +_TX_FRAME_DELIMITER = "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" +_XML_CACHE_MEMORY_TTL_SECONDS = 60 +_XML_CACHE_DISK_TTL_SECONDS = 1800 +_PROFILE_CACHE_DISK_TTL_SECONDS = 86400 +_CACHE_FLUSH_INTERVAL_SECONDS = 3.0 +# Recv thread only enqueues; HTTP/XML runs on workers so M-SEARCH bursts are not dropped. +# Windows tends toward slower LAN HTTP and larger SSDP bursts per device (many ST values), so +# use more workers and a deeper queue than POSIX — same code path, OS-tuned defaults. +_RX_QUEUE_MAXSIZE = 4096 if sys.platform == "win32" else 2048 +_RX_WORKER_COUNT = 4 if sys.platform == "win32" else 2 +# Drop near-duplicate SSDP replies (same USN + LOCATION) from the same host within this window. +# One device often answers each M-SEARCH for several ST targets; dedup avoids serial XML fetches. +_RX_DEDUP_WINDOW_S = 0.65 +_RX_DEDUP_PRUNE_AGE_S = 5.0 +_RX_DEDUP_MAX_KEYS = 2000 + + +def _resolve_ssdp_device_ip(parsed_hostname: str | None, packet_source_ip: str) -> str: + """Use numeric IP from LOCATION when present; else the SSDP packet source (not DNS names).""" + fb = str(packet_source_ip).strip() + if not parsed_hostname or not str(parsed_hostname).strip(): + return fb if fb else "0.0.0.0" + host = str(parsed_hostname).strip() + inner = host[1:-1] if host.startswith("[") and host.endswith("]") else host + try: + addr = ipaddress.ip_address(inner) + return addr.compressed + except ValueError: + pass + if fb and fb not in {"0.0.0.0", "::"}: + return fb + return host + + +# Exclude host-only / hypervisor switches from SSDP multicast join & send — they are not the LAN +# where UPnP devices live, and on Windows they can starve or mis-order stack behavior vs. real NICs. +_SSDP_MULTICAST_SKIP_SUBNETS = VIRTUAL_HOST_SUBNETS + + +def _local_ipv4_multicast_ifaces() -> list[str]: + """Local IPv4 addresses for SSDP multicast join and per-interface M-SEARCH (multi-homed hosts). + + On Windows, a single INADDR_ANY membership plus default multicast route often leaves LAN + traffic on a virtual adapter (Hyper-V/WSL); explicit joins and ``IP_MULTICAST_IF`` steer + discovery toward the real subnet. + + Virtual host-only subnets (VirtualBox, Hyper-V internal, etc.) are skipped so M-SEARCH + multicast is not pinned to adapters that do not reach household UPnP devices. + """ + preferred: str | None = None + found: set[str] = set() + try: + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.connect(("203.0.113.1", 9)) + ip = probe.getsockname()[0] + if ip: + preferred = ip + found.add(ip) + finally: + probe.close() + except OSError: + pass + try: + for res in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET, socket.SOCK_DGRAM): + ip = res[4][0] + if ip: + found.add(ip) + except OSError: + pass + out: list[str] = [] + for ip in sorted(found): + try: + a = ipaddress.ip_address(ip) + except ValueError: + continue + if not isinstance(a, ipaddress.IPv4Address) or a.is_loopback: + continue + if a.is_multicast or a.is_unspecified: + continue + if a.is_link_local: + continue # SSDP discovery targets routed LAN; skip 169.254 noise + out.append(a.compressed) + + def _in_skip_net(ip_s: str) -> bool: + try: + addr = ipaddress.ip_address(ip_s) + except ValueError: + return True + return any(addr in net for net in _SSDP_MULTICAST_SKIP_SUBNETS) + + filtered = [x for x in out if not _in_skip_net(x)] + if not filtered: + filtered = list(out) + + if preferred and preferred in filtered: + rest = sorted(x for x in filtered if x != preferred) + return [preferred, *rest] + return sorted(filtered) + + +def _descriptor_xml_host_key(location: str) -> str: + """Host:port part of SSDP descriptor URLs for throttle/coalesce bucketing. + + Including the port prevents cross-port XML substitution: a device that serves + genuinely different descriptors on different ports (e.g. DIAL on :8008 and + tvdevice on :56790) must not have its XML coalesced — they hold different + friendlyName values and merging them produces wrong device names. + """ + p = urlparse((location or "").strip()) + raw = (p.hostname or "").strip() + if not raw: + return "" + inner = raw[1:-1] if raw.startswith("[") and raw.endswith("]") else raw + try: + addr = ipaddress.ip_address(inner) + host = addr.compressed + except ValueError: + host = raw.lower() + port = p.port + if port: + return f"{host}:{port}" + return host + + +def _sonos_device_description_alternate_url(location: str | None) -> str | None: + """Map Sonos ``group_description.xml`` LOCATION to sibling ``device_description.xml``. + + Group XML is small and often lacks ``roomName`` / icon list; the device descriptor has them. + Without a follow-up fetch, the UI waits for a later NOTIFY or refresh — often tens of seconds. + """ + if not location: + return None + s = location.strip() + lower = s.lower() + needle = "group_description.xml" + pos = lower.find(needle) + if pos < 0: + return None + return f"{s[:pos]}device_description.xml{s[pos + len(needle) :]}" + + +class SSDPDiscovery(BaseDiscovery): + def __init__( + self, + rules_enabled: bool = True, + query_interval_seconds: int | None = None, + mx_seconds: int | None = None, + descriptor_http_min_interval_seconds: float | None = None, + msearch_directed_ips: list[str] | None = None, + ephemeral_msearch_probe_ips: Callable[[], list[str]] | None = None, + ) -> None: + super().__init__(source="ssdp") + self._logger = logging.getLogger(__name__) + self._rules_enabled = bool(rules_enabled) + self._refresh_interval_seconds = ( + int(query_interval_seconds) if query_interval_seconds is not None else _REFRESH_INTERVAL_SECONDS + ) + mx = int(mx_seconds) if mx_seconds is not None else 5 + self._mx_seconds = max(5, min(6, mx)) + if descriptor_http_min_interval_seconds is None: + self._descriptor_http_min_interval = 5.0 + else: + self._descriptor_http_min_interval = max(0.0, float(descriptor_http_min_interval_seconds)) + self._last_descriptor_http_mono: dict[str, float] = {} + # (USN, ignored LOCATION) pairs already traced by _best_profile_for_headers (DEBUG). + self._profile_ignore_logged: set[str] = set() + self._xml_fetch_gates: dict[str, threading.Lock] = {} + self._xml_fetch_gates_lock = threading.Lock() + self._rules = self._load_rules() + self._running = False + self._send_socket: socket.socket | None = None + self._recv_socket: socket.socket | None = None + self._listen_thread: threading.Thread | None = None + self._rx_queue: queue.Queue[tuple[str, str]] = queue.Queue(maxsize=_RX_QUEUE_MAXSIZE) + self._rx_worker_threads: list[threading.Thread] = [] + self._gc_thread: threading.Thread | None = None + self._refresh_thread: threading.Thread | None = None + self._lock = threading.Lock() + self._seen_devices: dict[str, tuple[datetime, int, dict]] = {} + self._xml_cache: dict[str, tuple[datetime, dict, str | None]] = {} + self._xml_disk_cache: dict[str, tuple[datetime, dict, str | None]] = self._load_persistent_xml_cache() + self._profile_disk_cache: dict[str, tuple[datetime, dict]] = self._load_persistent_profile_cache() + self._cache_dirty = False + self._last_cache_flush_monotonic = 0.0 + self._stop_event = threading.Event() + self._msearch_directed_ips: list[str] = [] + if msearch_directed_ips: + for raw in msearch_directed_ips: + if not isinstance(raw, str) or not raw.strip(): + continue + try: + addr = ipaddress.ip_address(raw.strip()) + except ValueError: + continue + if isinstance(addr, ipaddress.IPv4Address): + self._msearch_directed_ips.append(addr.compressed) + self._ephemeral_probe_resolver = ephemeral_msearch_probe_ips + self._multicast_if_ipv4s: list[str] = [] + self._rx_dedup: dict[str, float] = {} + self._rx_dedup_lock = threading.Lock() + # Separate thread pool for XML/HTTP enrichment so rx workers are never blocked. + _xml_workers = 6 if sys.platform == "win32" else 3 + self._xml_enrich_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=_xml_workers, thread_name_prefix="ssdp-xml" + ) + + def _should_skip_recent_duplicate_ssdp(self, headers: dict[str, str], src_ip: str) -> bool: + loc = (headers.get("LOCATION") or "").strip() + usn = (headers.get("USN") or "").strip() + if not loc or not usn: + return False + key = f"{src_ip}\0{usn}\0{loc}" + now = time.monotonic() + with self._rx_dedup_lock: + if len(self._rx_dedup) > _RX_DEDUP_MAX_KEYS: + cutoff = now - _RX_DEDUP_PRUNE_AGE_S + self._rx_dedup = {k: v for k, v in self._rx_dedup.items() if v >= cutoff} + last = self._rx_dedup.get(key) + if last is not None and (now - last) < _RX_DEDUP_WINDOW_S: + return True + self._rx_dedup[key] = now + return False + + def _directed_msearch_targets(self) -> list[str]: + configured = set(self._msearch_directed_ips) + extra: set[str] = set() + if self._ephemeral_probe_resolver is not None: + try: + for raw in self._ephemeral_probe_resolver(): + if not isinstance(raw, str) or not raw.strip(): + continue + try: + addr = ipaddress.ip_address(raw.strip()) + except ValueError: + continue + if isinstance(addr, ipaddress.IPv4Address) and not addr.is_loopback: + extra.add(addr.compressed) + except Exception: + self._logger.debug("ephemeral SSDP M-SEARCH target resolver failed", exc_info=True) + return sorted(configured | extra) + + def start(self) -> None: + if self._running: + return + self._running = True + self._stop_event.clear() + # Detect interfaces once so both sockets use the same list. + if_addrs = _local_ipv4_multicast_ifaces() + self._multicast_if_ipv4s = list(if_addrs) + if self._multicast_if_ipv4s: + self._logger.info( + "SSDP multicast will pin to IPv4 interface(s): %s", + ", ".join(self._multicast_if_ipv4s), + ) + else: + self._logger.info("SSDP multicast: no usable local IPv4 list; using OS default interface only") + # Dual socket architecture: + # _send_socket — ephemeral port; sends M-SEARCH and receives unicast responses. + # On Windows, port 1900 responses go to the Windows SSDP service; an ephemeral + # source port means M-SEARCH replies come back to US, not to that service. + # _recv_socket — port 1900; receives multicast NOTIFY announcements. + self._send_socket = self._create_send_socket(if_addrs) + self._recv_socket = self._create_recv_socket(if_addrs) + self._logger.info("SSDP discovery started") + self._listen_thread = threading.Thread(target=self._listen_loop, name="ssdp-listener", daemon=True) + self._listen_thread.start() + self._rx_worker_threads = [] + for i in range(_RX_WORKER_COUNT): + wt = threading.Thread(target=self._rx_worker_loop, name=f"ssdp-rx-worker-{i}", daemon=True) + self._rx_worker_threads.append(wt) + wt.start() + self._gc_thread = threading.Thread(target=self._gc_loop, name="ssdp-gc", daemon=True) + self._gc_thread.start() + self._refresh_thread = threading.Thread(target=self._refresh_loop, name="ssdp-refresh", daemon=True) + self._refresh_thread.start() + self.refresh() + + def stop(self) -> None: + if not self._running: + return + self._running = False + self._stop_event.set() + for attr in ("_send_socket", "_recv_socket"): + sock = getattr(self, attr, None) + setattr(self, attr, None) + if sock is not None: + try: + sock.close() + except OSError: + pass + if self._listen_thread is not None: + self._listen_thread.join(timeout=0.25) + for wt in self._rx_worker_threads: + wt.join(timeout=1.5) + self._rx_worker_threads.clear() + if self._gc_thread is not None: + self._gc_thread.join(timeout=0.25) + if self._refresh_thread is not None: + self._refresh_thread.join(timeout=0.25) + self._xml_enrich_executor.shutdown(wait=False, cancel_futures=True) + self._flush_persistent_caches_if_due(force=True) + self._logger.info("SSDP discovery stopped") + + def refresh(self) -> None: + if not self._running: + return + sock = self._send_socket + if sock is None: + return + search_targets = _SSDP_SEARCH_ST + mcast_ifs = self._multicast_if_ipv4s + mcast_round_robin = mcast_ifs if mcast_ifs else [None] + for st in search_targets: + payload = ( + "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + f"MX: {self._mx_seconds}\r\n" + f"ST: {st}\r\n" + "\r\n" + ).encode("utf-8") + payload_text = payload.decode("utf-8", errors="ignore") + for if_ip in mcast_round_robin: + if if_ip is not None: + try: + sock.setsockopt( + socket.IPPROTO_IP, + socket.IP_MULTICAST_IF, + socket.inet_aton(if_ip), + ) + except OSError: + self._logger.debug("IP_MULTICAST_IF failed for %s", if_ip, exc_info=True) + continue + try: + sock.sendto(payload, _SSDP_ADDR) + self._logger.debug( + "SSDP TX %s:%s if=%s\n%s\n%s\n%s", + _SSDP_ADDR[0], + _SSDP_ADDR[1], + if_ip or "default", + _TX_FRAME_DELIMITER, + payload_text, + _TX_FRAME_DELIMITER, + ) + except OSError: + self._logger.exception("Failed to send SSDP M-SEARCH for ST=%s (if=%s)", st, if_ip) + for dip in self._directed_msearch_targets(): + host_line = f"{dip}:1900" + for st in search_targets: + payload = ( + "M-SEARCH * HTTP/1.1\r\n" + f"HOST: {host_line}\r\n" + "MAN: \"ssdp:discover\"\r\n" + f"MX: {self._mx_seconds}\r\n" + f"ST: {st}\r\n" + "\r\n" + ).encode("utf-8") + try: + sock.sendto(payload, (dip, 1900)) + self._logger.debug( + "SSDP directed TX to %s ST=%s\n%s\n%s\n%s", + host_line, + st, + _TX_FRAME_DELIMITER, + payload.decode("utf-8", errors="ignore"), + _TX_FRAME_DELIMITER, + ) + except OSError: + self._logger.exception( + "Failed to send directed SSDP M-SEARCH to %s ST=%s", + host_line, + st, + ) + + def _create_send_socket(self, if_addrs: list[str]) -> socket.socket: + """Ephemeral-port socket for M-SEARCH sending and unicast response receiving. + + Because it is not bound to port 1900, M-SEARCH replies (unicast UDP back to the + sender's source port) arrive here instead of being intercepted by the Windows SSDP + service, which wins the port-1900 delivery race on shared sockets. + """ + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.settimeout(0.2) + try: + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, struct.pack("B", 4)) + except OSError: + try: + sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4) + except OSError: + self._logger.debug("Could not set IP_MULTICAST_TTL on send socket", exc_info=True) + sock.bind(("", 0)) + port = sock.getsockname()[1] + self._logger.info( + "SSDP send socket bound to ephemeral port %d (unicast M-SEARCH responses will arrive here)", + port, + ) + return sock + + def _create_recv_socket(self, if_addrs: list[str]) -> socket.socket: + """Port-1900 socket for multicast NOTIFY announcements. + + Bound to port 1900 with SO_REUSEADDR so it shares the port with the Windows SSDP + service. It receives multicast NOTIFY traffic (devices advertising themselves + spontaneously) but NOT the unicast M-SEARCH replies — those go to ``_send_socket``. + """ + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + # SO_REUSEPORT is not defined on Windows; optional on POSIX. + if sys.platform != "win32" and hasattr(socket, "SO_REUSEPORT"): + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + except OSError: + pass + sock.settimeout(0.2) + # Large receive buffer to absorb multicast NOTIFY bursts. + _rcvbuf = 512 * 1024 if sys.platform == "win32" else 256 * 1024 + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, _rcvbuf) + except OSError: + pass + try: + sock.bind(("", 1900)) + self._logger.info("SSDP recv socket bound to 0.0.0.0:1900 (multicast NOTIFY receive)") + except OSError as exc: + _bound_mcast = False + if sys.platform == "win32": + # Fallback: bind to the multicast group address itself — still receives NOTIFY. + try: + sock.bind((_SSDP_ADDR[0], 1900)) + _bound_mcast = True + self._logger.info( + "SSDP recv socket bound to %s:1900 (Windows port-sharing fallback; NOTIFY receive only)", + _SSDP_ADDR[0], + ) + except OSError: + pass + if not _bound_mcast: + self._logger.warning( + "SSDP recv socket could not bind UDP port 1900 (%s). " + "Multicast NOTIFY may be missed. " + "Unicast M-SEARCH responses will still arrive on the send socket.", + exc, + ) + sock.bind(("", 0)) + mcast_bin = socket.inet_aton(_SSDP_ADDR[0]) + joined_any = False + for if_ip in if_addrs: + try: + sock.setsockopt( + socket.IPPROTO_IP, + socket.IP_ADD_MEMBERSHIP, + mcast_bin + socket.inet_aton(if_ip), + ) + joined_any = True + except OSError: + self._logger.debug("IP_ADD_MEMBERSHIP failed for %s on recv socket", if_ip, exc_info=True) + if not joined_any: + try: + sock.setsockopt( + socket.IPPROTO_IP, + socket.IP_ADD_MEMBERSHIP, + mcast_bin + socket.inet_aton("0.0.0.0"), + ) + except OSError: + self._logger.debug("Unable to join SSDP multicast group (INADDR_ANY) on recv socket", exc_info=True) + return sock + + def _listen_loop(self) -> None: + while self._running: + send_sock = self._send_socket + recv_sock = self._recv_socket + readable_pool = [s for s in (send_sock, recv_sock) if s is not None] + if not readable_pool: + break + try: + ready, _, _ = select.select(readable_pool, [], [], 0.2) + except OSError: + break + for sock in ready: + try: + data, addr = sock.recvfrom(65535) + except OSError: + continue + raw = data.decode("utf-8", errors="ignore") + try: + self._rx_queue.put_nowait((raw, addr[0])) + except queue.Full: + self._logger.warning( + "SSDP RX queue full (%d); dropping packet from %s — workers cannot keep up", + _RX_QUEUE_MAXSIZE, + addr[0], + ) + + def _rx_worker_loop(self) -> None: + while self._running: + try: + payload, src_ip = self._rx_queue.get(timeout=0.3) + except queue.Empty: + continue + # Accept both HTTP/1.1 and HTTP/1.0 — some devices (older TVs, embedded firmware) use 1.0. + # Case-insensitive match on the first token — some devices send lowercase. + first = payload[:20].upper() + is_reply = first.startswith("HTTP/1.1 200") or first.startswith("HTTP/1.0 200") + is_notify = first.startswith("NOTIFY * HTTP/1") + if not (is_reply or is_notify): + self._logger.debug( + "SSDP RX ignored (unrecognized type) from %s: %.80s", + src_ip, + payload[:80].replace("\r\n", " | "), + ) + continue + self._logger.debug( + "SSDP RX from %s\n%s\n%s\n%s", + src_ip, + _RX_FRAME_DELIMITER, + payload, + _RX_FRAME_DELIMITER, + ) + headers = self._parse_headers(payload) + if not headers: + continue + # One compact line per received frame (all descriptors a device advertises, + # even those later deduplicated or whose XML is never fetched). + self._logger.debug( + "SSDP RX headers from %s kind=%s LOCATION=%s ST=%s USN=%s SERVER=%s", + src_ip, + ("NOTIFY " + headers.get("NTS", "")).strip() if is_notify else "M-SEARCH-RESPONSE", + headers.get("LOCATION", ""), + headers.get("ST") or headers.get("NT") or "", + headers.get("USN", ""), + headers.get("SERVER", ""), + ) + if is_notify: + nts = headers.get("NTS", "").lower() + if nts == "ssdp:byebye": + offline_payload = self._build_notify_offline_payload(headers, src_ip) + self._logger.info( + "SSDP NOTIFY byebye: %s %s:%s", + offline_payload.get("name"), + offline_payload.get("ip"), + offline_payload.get("port"), + ) + self._emit("device", offline_payload) + continue + if nts and nts != "ssdp:alive": + continue + if self._should_skip_recent_duplicate_ssdp(headers, src_ip): + continue + # Emit immediately from headers (no HTTP round-trip) so the device appears fast. + device_payload = self._build_device_payload(headers, src_ip, fetch_xml=False) + self._logger.debug( + "SSDP response from %s -> %s %s:%s (fast emit, XML pending)", + src_ip, + device_payload.get("name"), + device_payload.get("ip"), + device_payload.get("port"), + ) + device_key = self._device_key(device_payload) + now = datetime.now(timezone.utc) + timeout_seconds = self._timeout_seconds_for_payload(device_payload) + with self._lock: + self._seen_devices[device_key] = (now, timeout_seconds, device_payload) + self._emit("device", device_payload) + # Offload XML/HTTP fetch to the enrichment pool so rx workers stay free. + if headers.get("LOCATION"): + self._xml_enrich_executor.submit(self._xml_enrich_task, headers, src_ip) + + def _xml_enrich_task(self, headers: dict[str, str], src_ip: str) -> None: + """Fetch XML descriptor and re-emit the device with enriched data.""" + try: + enriched = self._build_device_payload(headers, src_ip, fetch_xml=True) + device_key = self._device_key(enriched) + now = datetime.now(timezone.utc) + timeout_seconds = self._timeout_seconds_for_payload(enriched) + with self._lock: + self._seen_devices[device_key] = (now, timeout_seconds, enriched) + self._emit("device", enriched) + self._logger.debug( + "SSDP XML enriched %s -> %s %s:%s", + src_ip, + enriched.get("name"), + enriched.get("ip"), + enriched.get("port"), + ) + except Exception: + self._logger.warning("SSDP XML enrichment failed for %s", src_ip, exc_info=True) + + def _refresh_loop(self) -> None: + while self._running: + if self._stop_event.wait(timeout=self._refresh_interval_seconds): + break + if not self._running: + break + self._logger.debug("Periodic SSDP refresh tick") + self._flush_persistent_caches_if_due() + self.refresh() + + def _gc_loop(self) -> None: + while self._running: + now = datetime.now(timezone.utc) + expired: list[dict] = [] + with self._lock: + for key, (seen, timeout_seconds, payload) in self._seen_devices.items(): + if (now - seen) > timedelta(seconds=timeout_seconds): + expired.append(payload) + for payload in expired: + key = self._device_key(payload) + self._seen_devices.pop(key, None) + for payload in expired: + offline_payload = dict(payload) + offline_payload["online"] = False + self._logger.debug( + "SSDP timeout -> offline %s %s:%s", + offline_payload.get("name"), + offline_payload.get("ip"), + offline_payload.get("port"), + ) + self._emit("device", offline_payload) + # Lightweight periodic scan. + if self._stop_event.wait(timeout=2.0): + break + + def _parse_headers(self, response: str) -> dict[str, str]: + # splitlines(): some embedded firmwares end SSDP lines with a bare "\n"; splitting on + # "\r\n" only yielded no headers and the packet was silently dropped. + lines = response.splitlines() + headers: dict[str, str] = {} + for line in lines[1:]: + if not line or ":" not in line: + continue + key, value = line.split(":", 1) + headers[key.strip().upper()] = value.strip() + return headers + + def _build_device_payload(self, headers: dict[str, str], fallback_ip: str, *, fetch_xml: bool = True) -> dict: + location = headers.get("LOCATION") + parsed = urlparse(location) if location else None + ip = _resolve_ssdp_device_ip(parsed.hostname if parsed else None, fallback_ip) + port = parsed.port if parsed and parsed.port is not None else 80 + st = headers.get("ST") or headers.get("NT") or "ssdp:all" + nt = headers.get("NT") + server = headers.get("SERVER", "") + usn = headers.get("USN", "") + profile_key = self._profile_key_from_headers(headers, ip) + profile = self._best_profile_for_headers(headers, ip) + name = self._infer_name(server=server, st=st, ip=ip) + device_type = self._infer_type(st, usn=usn, server=server, model_name=None, manufacturer=None) + if profile is not None: + _seen_at, prof = profile + prof_name = prof.get("name") + prof_type = prof.get("type") + if isinstance(prof_name, str) and prof_name.strip(): + name = prof_name.strip() + if isinstance(prof_type, str) and prof_type.strip(): + device_type = prof_type.strip() + if fetch_xml: + xml_fields, raw_xml = self._fetch_and_parse_xml(location) + dev_loc = _sonos_device_description_alternate_url(location) + if dev_loc and dev_loc != (location or "").strip(): + xf_dev, raw_dev = self._fetch_and_parse_xml( + dev_loc, + bypass_descriptor_min_interval=True, + ) + if xf_dev: + for key in ( + "friendlyName", + "displayName", + "roomName", + "modelName", + "manufacturer", + "manufacturerURL", + "modelURL", + "serialNumber", + "deviceType", + "UDN", + "mac", + "modelType", + "presentationURL", + "iconURL", + "icons_description", + "services_description", + "services_records", + ): + val = xf_dev.get(key) + if val: + xml_fields[key] = val + if raw_dev: + raw_xml = raw_dev + else: + xml_fields, raw_xml = {}, None + if not xml_fields and profile is not None: + _seen_at, prof = profile + prof_xml = prof.get("xml_fields") + prof_raw = prof.get("raw_xml") + if isinstance(prof_xml, dict): + xml_fields = dict(prof_xml) + if not raw_xml and isinstance(prof_raw, str) and prof_raw.strip(): + raw_xml = prof_raw + if xml_fields.get("friendlyName"): + name = xml_fields["friendlyName"] + elif xml_fields.get("displayName"): + name = xml_fields["displayName"] + type_seed = xml_fields.get("deviceType") or st + device_type = self._infer_type( + type_seed, + usn=usn, + server=server, + model_name=xml_fields.get("modelName"), + manufacturer=xml_fields.get("manufacturer"), + model_type=xml_fields.get("modelType"), + ) + info_text = self._build_information_text(xml_fields) + if info_text: + self._logger.debug("SSDP info extracted for %s:%s -> %s", ip, port, info_text) + if self._rules_enabled: + rule_name = self._apply_name_rules(xml_fields) + if rule_name: + name = rule_name + rule_type = self._apply_type_rules(headers=headers, xml_fields=xml_fields) + if rule_type: + device_type = rule_type + presentation_url = xml_fields.get("presentationURL") + services_description = self._build_services_description(xml_fields) + payload = { + "name": name, + "ip": ip, + "port": port, + "type": device_type, + "category": category_for_device_type(device_type), + "source": "ssdp", + # Only use a real presentation URL from SSDP XML. + "url": presentation_url if isinstance(presentation_url, str) and presentation_url.strip() else None, + "metadata": { + "location": location, + "st": st, + "nt": nt, + "usn": usn, + "server": server, + "mac_address": xml_fields.get("mac"), + "information": info_text, + "cache_control": headers.get("CACHE-CONTROL"), + "headers": headers, + "xml_fields": { + "friendlyName": xml_fields.get("friendlyName"), + "deviceType": xml_fields.get("deviceType"), + "manufacturer": xml_fields.get("manufacturer"), + "manufacturerURL": xml_fields.get("manufacturerURL"), + "modelName": xml_fields.get("modelName"), + "modelType": xml_fields.get("modelType"), + "displayName": xml_fields.get("displayName"), + "roomName": xml_fields.get("roomName"), + "modelURL": xml_fields.get("modelURL"), + "serialNumber": xml_fields.get("serialNumber"), + "mac": xml_fields.get("mac"), + "UDN": xml_fields.get("UDN"), + "presentationURL": xml_fields.get("presentationURL"), + "iconURL": xml_fields.get("iconURL"), + "icons_description": xml_fields.get("icons_description", "unavailable"), + "services_description": services_description or "unavailable", + "services_records": xml_fields.get("services_records"), + }, + "xml": raw_xml, + }, + "online": True, + } + # Only persist profile when we have real XML data to avoid overwriting rich cache with stubs. + if fetch_xml: + self._persist_profile_cache_entries(headers, ip, payload) + self._logger.info( + "SSDP device detected: %s %s:%s type=%s category=%s st=%s nt=%s (xml=%s)", + payload["name"], + payload["ip"], + payload["port"], + payload["type"], + payload["category"], + st, + nt, + fetch_xml, + ) + return payload + + def _build_notify_offline_payload(self, headers: dict[str, str], fallback_ip: str) -> dict: + st = headers.get("NT") or headers.get("ST") or "ssdp:all" + usn = headers.get("USN", "") + server = headers.get("SERVER", "") + location = headers.get("LOCATION") + parsed = urlparse(location) if location else None + ip = _resolve_ssdp_device_ip(parsed.hostname if parsed else None, fallback_ip) + port = parsed.port if parsed and parsed.port is not None else 80 + seen_payload = self._find_seen_payload_for_byebye(ip, usn) + if seen_payload is not None: + offline_payload = dict(seen_payload) + offline_payload["online"] = False + return offline_payload + device_type = self._infer_type(st, usn=usn, server=server) + return { + "name": self._infer_name(server=server, st=st, ip=fallback_ip), + "ip": ip, + "port": port, + "type": device_type, + "category": category_for_device_type(device_type), + "source": "ssdp", + "url": None, + "metadata": { + "location": location, + "st": st, + "nt": headers.get("NT"), + "usn": usn, + "server": server, + "headers": headers, + }, + "online": False, + } + + def _find_seen_payload_for_byebye(self, ip: str, usn: str) -> dict | None: + base_usn = usn.split("::", 1)[0].strip().lower() + with self._lock: + for _key, (_seen, _timeout_seconds, payload) in self._seen_devices.items(): + payload_ip = str(payload.get("ip", "")) + if payload_ip != ip: + continue + payload_usn = str(payload.get("metadata", {}).get("usn", "")).strip().lower() + payload_base_usn = payload_usn.split("::", 1)[0] + if base_usn and (payload_usn == usn.lower() or payload_base_usn == base_usn): + return dict(payload) + return None + + def _timeout_seconds_for_payload(self, payload: dict) -> int: + metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} + cache_control = metadata.get("cache_control") + max_age = None + if isinstance(cache_control, str): + # UDA allows whitespace around '=' (Sonos sends "max-age = 1800"); missing it fell + # back to the 180 s default, so a few skipped M-SEARCH replies took the device offline. + match = _MAX_AGE_RE.search(cache_control) + if match: + max_age = int(match.group(1)) + if max_age is None or max_age <= 0: + return _DEFAULT_TIMEOUT_SECONDS + timeout = max_age * 2 + return max(_DEFAULT_TIMEOUT_SECONDS, min(timeout, _MAX_TIMEOUT_SECONDS)) + + def _infer_name(self, server: str, st: str, ip: str) -> str: + if "router" in server.lower() or "wan" in st.lower(): + return f"Router {ip}" + if "mediaserver" in st.lower() or "dlna" in server.lower(): + return f"Media Server {ip}" + if "printer" in st.lower(): + return f"Printer {ip}" + return f"SSDP Device {ip}" + + def _infer_type( + self, + st: str, + usn: str = "", + server: str = "", + model_name: str | None = None, + manufacturer: str | None = None, + model_type: str | None = None, + ) -> str: + # Base classification from config/ssdp_rules.json "base_type_rules" (coarse fallbacks + # formerly hardcoded in this method). Evaluated against a NARROW haystack on purpose: + # free-form names are excluded so loose tokens like "wan" don't false-positive on a + # device named e.g. "Rowan's iPhone". Curated "type_rules" refine this in _apply_type_rules. + combined = " ".join( + [ + st.lower(), + usn.lower(), + server.lower(), + (model_name or "").lower(), + (manufacturer or "").lower(), + ] + ) + matched = self._match_type_rules( + self._rules.get("base_type_rules"), combined, {"modelType": model_type or ""} + ) + return matched or "unknown" + + def _device_key(self, payload: dict) -> str: + metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + + usn = metadata.get("usn") + if isinstance(usn, str) and usn.strip(): + usn_base = usn.strip().lower().split("::", 1)[0] + if usn_base: + return f"ssdp:usn:{usn_base}" + + udn = xml_fields.get("UDN") or metadata.get("udn") + if isinstance(udn, str) and udn.strip(): + return f"ssdp:udn:{udn.strip().lower()}" + + mac = ( + xml_fields.get("mac") + or metadata.get("mac") + or metadata.get("mac_address") + or metadata.get("MAC") + or metadata.get("macAddress") + ) + if isinstance(mac, str) and mac.strip(): + return f"ssdp:mac:{mac.strip().lower()}" + + ip = str(payload.get("ip", "0.0.0.0")) + port = int(payload.get("port", 0)) + return f"ssdp:endpoint:{ip}:{port}" + + def _profile_key_from_headers(self, headers: dict[str, str], fallback_ip: str) -> str: + usn = headers.get("USN", "") + if isinstance(usn, str) and usn.strip(): + usn_base = usn.strip().lower().split("::", 1)[0] + if usn_base: + return f"ssdp:usn:{usn_base}" + location = headers.get("LOCATION") + parsed = urlparse(location) if location else None + ip = parsed.hostname if parsed and parsed.hostname else fallback_ip + return f"ssdp:host:{str(ip).strip().lower()}" + + def _profile_candidate_keys(self, headers: dict[str, str], fallback_ip: str) -> list[str]: + keys: list[str] = [] + seen: set[str] = set() + + def add(key: str) -> None: + k = str(key).strip().lower() + if not k or k in seen: + return + seen.add(k) + keys.append(k) + + usn = headers.get("USN", "") + if isinstance(usn, str) and usn.strip(): + usn_full = usn.strip().lower() + add(f"ssdp:usn:{usn_full}") + add(f"ssdp:usn:{usn_full.split('::', 1)[0]}") + + location = headers.get("LOCATION") + parsed = urlparse(location) if location else None + ip = parsed.hostname if parsed and parsed.hostname else fallback_ip + ip_s = str(ip).strip().lower() + if ip_s: + add(f"ssdp:host:{ip_s}") + return keys + + def _best_profile_for_headers(self, headers: dict[str, str], fallback_ip: str) -> tuple[datetime, dict] | None: + # A USN-specific profile always beats the per-host one: one host can serve several + # descriptors (e.g. Sharp DIAL :8008 + MediaTek tvdevice :56790). The host key holds + # whichever was announced last, so "freshest wins" would leak the other descriptor's + # name / xml_fields onto this USN. + best: tuple[datetime, dict] | None = None + host_fallback: tuple[datetime, dict] | None = None + for key in self._profile_candidate_keys(headers, fallback_ip): + cached = self._profile_disk_cache.get(key) + if cached is None: + continue + if key.startswith("ssdp:host:"): + if host_fallback is None or cached[0] > host_fallback[0]: + host_fallback = cached + continue + if best is None or cached[0] > best[0]: + best = cached + if best is not None and host_fallback is not None and self._logger.isEnabledFor(logging.DEBUG): + kept_loc = str(best[1].get("ssdp_location") or "") + ignored_loc = str(host_fallback[1].get("ssdp_location") or "") + if kept_loc != ignored_loc: + note_key = f"{headers.get('USN', '')}\0{ignored_loc}" + if note_key not in self._profile_ignore_logged: + self._profile_ignore_logged.add(note_key) + self._logger.debug( + "SSDP profile cache: per-host entry ignored for USN=%s (kept %s name=%r, ignored %s name=%r)", + headers.get("USN", ""), + kept_loc, + best[1].get("name"), + ignored_loc, + host_fallback[1].get("name"), + ) + return best if best is not None else host_fallback + + def fetch_descriptor_xml(self, location_url: str | None) -> tuple[dict, str | None]: + """Fetch and parse UPnP device descriptor XML (same caches as live SSDP LOCATION handling).""" + return self._fetch_and_parse_xml(location_url) + + def _cached_xml_for_same_host(self, host_key: str, now: datetime) -> tuple[dict, str | None] | None: + """Return freshest valid cache entry for any LOCATION whose host matches ``host_key``.""" + if not host_key: + return None + best: tuple[datetime, dict, str | None] | None = None + for loc_key, tup in self._xml_cache.items(): + if _descriptor_xml_host_key(loc_key) != host_key: + continue + seen_at, fields, raw = tup + if (now - seen_at) >= timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): + continue + if best is None or seen_at > best[0]: + best = (seen_at, dict(fields), raw) + if best is not None: + return best[1], best[2] + for loc_key, tup in self._xml_disk_cache.items(): + if _descriptor_xml_host_key(loc_key) != host_key: + continue + seen_at, fields, raw = tup + if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): + return dict(fields), raw + return None + + def _fetch_and_parse_xml( + self, + location: str | None, + *, + bypass_descriptor_min_interval: bool = False, + ) -> tuple[dict, str | None]: + if not location: + return {}, None + now = datetime.now(timezone.utc) + memory_cached = self._xml_cache.get(location) + if memory_cached is not None: + seen_at, cached_fields, cached_raw = memory_cached + if (now - seen_at) < timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): + return dict(cached_fields), cached_raw + + disk_cached = self._xml_disk_cache.get(location) + if disk_cached is not None: + seen_at, cached_fields, cached_raw = disk_cached + if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): + self._xml_cache[location] = (now, dict(cached_fields), cached_raw) + self._logger.debug("SSDP XML cache hit (disk) for %s", location) + return dict(cached_fields), cached_raw + + host_key = _descriptor_xml_host_key(location) + with self._xml_fetch_gates_lock: + if host_key not in self._xml_fetch_gates: + self._xml_fetch_gates[host_key] = threading.Lock() + host_gate = self._xml_fetch_gates[host_key] + with host_gate: + now = datetime.now(timezone.utc) + mem2 = self._xml_cache.get(location) + if mem2 is not None: + seen_at, cached_fields, cached_raw = mem2 + if (now - seen_at) < timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): + return dict(cached_fields), cached_raw + disk2 = self._xml_disk_cache.get(location) + if disk2 is not None: + seen_at, cached_fields, cached_raw = disk2 + if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): + self._xml_cache[location] = (now, dict(cached_fields), cached_raw) + return dict(cached_fields), cached_raw + + mono = time.monotonic() + if ( + not bypass_descriptor_min_interval + and self._descriptor_http_min_interval > 0 + and host_key + ): + last_http = self._last_descriptor_http_mono.get(host_key) + if last_http is not None and (mono - last_http) < self._descriptor_http_min_interval: + alt = self._cached_xml_for_same_host(host_key, now) + if alt is not None: + fields_a, raw_a = alt + self._xml_cache[location] = (now, dict(fields_a), raw_a) + self._logger.debug( + "SSDP descriptor coalesced (min-interval) for %s host=%s", + location, + host_key, + ) + return dict(fields_a), raw_a + self._logger.debug( + "SSDP descriptor HTTP skipped (min-interval %.1fs, no cache for host %s) %s", + self._descriptor_http_min_interval, + host_key, + location, + ) + return {}, None + + try: + with urlopen(location, timeout=1.5) as response: + raw_xml = response.read().decode("utf-8", errors="ignore") + self._logger.debug("SSDP XML fetched from %s\n%s", location, raw_xml) + except (URLError, OSError, TimeoutError): + self._logger.debug("Failed to fetch SSDP XML at %s", location, exc_info=True) + mem_f = self._xml_cache.get(location) + if mem_f is not None: + _seen_at, cached_fields, cached_raw = mem_f + return dict(cached_fields), cached_raw + disk_f = self._xml_disk_cache.get(location) + if disk_f is not None: + _seen_at, cached_fields, cached_raw = disk_f + return dict(cached_fields), cached_raw + return {}, None + + fields: dict = {} + try: + root = ET.fromstring(raw_xml) + device_elem = self._find_first(root, "device") + if device_elem is not None: + fields["friendlyName"] = self._find_text(device_elem, "friendlyName") + fields["deviceType"] = self._find_text(device_elem, "deviceType") + fields["manufacturer"] = self._find_text(device_elem, "manufacturer") + fields["manufacturerURL"] = self._find_text(device_elem, "manufacturerURL") + fields["modelName"] = self._find_text(device_elem, "modelName") + fields["modelType"] = self._find_text(device_elem, "modelType") + fields["displayName"] = self._find_text(device_elem, "displayName") + fields["roomName"] = self._find_text(device_elem, "roomName") + fields["modelURL"] = self._find_text(device_elem, "modelURL") + fields["serialNumber"] = self._find_text(device_elem, "serialNumber") + fields["mac"] = self._find_text(device_elem, "MACAddress") or self._find_text(device_elem, "mac") + fields["UDN"] = self._find_text(device_elem, "UDN") + fields["presentationURL"] = self._find_text(device_elem, "presentationURL") + fields["icons_description"] = self._build_icons_description(device_elem) + fields["services_description"] = self._build_services_description_from_device(device_elem) + fields["services_records"] = self._build_services_records(device_elem, location) + fields["iconURL"] = self._build_preferred_icon_url(device_elem, location) + except ET.ParseError: + self._logger.debug("Invalid SSDP XML received from %s", location, exc_info=True) + if host_key: + self._last_descriptor_http_mono[host_key] = time.monotonic() + return {}, raw_xml + normalized = {k: v for k, v in fields.items() if v} + self._xml_cache[location] = (now, normalized, raw_xml) + self._xml_disk_cache[location] = (now, dict(normalized), raw_xml) + if host_key: + self._last_descriptor_http_mono[host_key] = time.monotonic() + self._mark_cache_dirty() + return dict(normalized), raw_xml + + def _load_persistent_xml_cache(self) -> dict[str, tuple[datetime, dict, str | None]]: + out: dict[str, tuple[datetime, dict, str | None]] = {} + cache_data = load_discovery_cache() + raw = cache_data.get("ssdp_xml_cache") + if not isinstance(raw, dict): + return out + entries = raw.get("entries") + if not isinstance(entries, dict): + return out + now = datetime.now(timezone.utc) + for location, row in entries.items(): + if not isinstance(location, str) or not location.strip() or not isinstance(row, dict): + continue + ts_text = row.get("updated_at") + if not isinstance(ts_text, str) or not ts_text.strip(): + continue + try: + seen_at = datetime.fromisoformat(ts_text) + except ValueError: + continue + if seen_at.tzinfo is None: + seen_at = seen_at.replace(tzinfo=timezone.utc) + if (now - seen_at) >= timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): + continue + xml_fields = row.get("xml_fields") + if not isinstance(xml_fields, dict): + xml_fields = {} + raw_xml = row.get("raw_xml") + if not isinstance(raw_xml, str) or not raw_xml.strip(): + raw_xml = None + out[location.strip()] = (seen_at, dict(xml_fields), raw_xml) + return out + + def _build_persistent_xml_cache_entries(self) -> dict[str, dict]: + entries: dict[str, dict] = {} + now = datetime.now(timezone.utc) + for location, cached in self._xml_disk_cache.items(): + if not isinstance(location, str) or not location.strip(): + continue + seen_at, xml_fields, raw_xml = cached + if (now - seen_at) >= timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): + continue + entries[location] = { + "updated_at": seen_at.isoformat(), + "xml_fields": dict(xml_fields) if isinstance(xml_fields, dict) else {}, + "raw_xml": raw_xml if isinstance(raw_xml, str) else None, + } + return entries + + def _load_persistent_profile_cache(self) -> dict[str, tuple[datetime, dict]]: + out: dict[str, tuple[datetime, dict]] = {} + cache_data = load_discovery_cache() + raw = cache_data.get("ssdp_profile_cache") + if not isinstance(raw, dict): + return out + entries = raw.get("entries") + if not isinstance(entries, dict): + return out + now = datetime.now(timezone.utc) + for key, row in entries.items(): + if not isinstance(key, str) or not key.strip() or not isinstance(row, dict): + continue + ts_text = row.get("updated_at") + if not isinstance(ts_text, str) or not ts_text.strip(): + continue + try: + seen_at = datetime.fromisoformat(ts_text) + except ValueError: + continue + if seen_at.tzinfo is None: + seen_at = seen_at.replace(tzinfo=timezone.utc) + if (now - seen_at) >= timedelta(seconds=_PROFILE_CACHE_DISK_TTL_SECONDS): + continue + out[key.strip()] = (seen_at, dict(row)) + return out + + def purge_ip_from_profile_cache(self, ip: str) -> None: + """Remove all profile-cache entries whose URLs resolve to *ip*.""" + sip = str(ip).strip() + if not sip: + return + removed = 0 + for key in list(self._profile_disk_cache.keys()): + cached = self._profile_disk_cache.get(key) + if not isinstance(cached, tuple) or len(cached) < 2: + continue + row = cached[1] + if not isinstance(row, dict): + continue + urls: list[str] = [] + loc = row.get("ssdp_location") + if isinstance(loc, str) and loc.strip(): + urls.append(loc.strip()) + url = row.get("url") + if isinstance(url, str) and url.strip(): + urls.append(url.strip()) + xf = row.get("xml_fields") + if isinstance(xf, dict): + pres = xf.get("presentationURL") + if isinstance(pres, str) and pres.strip(): + urls.append(pres.strip()) + matched = False + for u in urls: + try: + host = urlparse(u).hostname + except ValueError: + continue + if host and str(host).strip() == sip: + matched = True + break + if matched: + self._profile_disk_cache.pop(key, None) + removed += 1 + if removed: + self._logger.debug("SSDP profile cache purged %d entries for %s", removed, sip) + self._flush_persistent_caches_if_due(force=True) + + def purge_ip_from_xml_cache(self, ip: str) -> None: + """Remove all XML cache entries (memory + disk) whose descriptor URL resolves to *ip*.""" + sip = str(ip).strip() + if not sip: + return + removed = 0 + for cache in (self._xml_cache, self._xml_disk_cache): + for location in list(cache.keys()): + try: + host = urlparse(location).hostname + except ValueError: + continue + if host and str(host).strip() == sip: + cache.pop(location, None) + removed += 1 + # Reset the descriptor-fetch throttle for this host. Otherwise, after the cached XML is + # purged (e.g. user "Clear device"), a rediscovery within the min-interval window would be + # HTTP-skipped with no cache to fall back on, leaving the device stuck as a generic + # "SSDP Device" (no XML, no icon) until the throttle naturally expires or the app restarts. + for host_key in list(self._last_descriptor_http_mono.keys()): + if host_key == sip or host_key.startswith(f"{sip}:"): + self._last_descriptor_http_mono.pop(host_key, None) + if removed: + self._logger.debug("SSDP XML cache purged %d entries for %s", removed, sip) + self._flush_persistent_caches_if_due(force=True) + + def _build_persistent_profile_cache_entries(self) -> dict[str, dict]: + entries: dict[str, dict] = {} + now = datetime.now(timezone.utc) + for key, cached in self._profile_disk_cache.items(): + if not isinstance(key, str) or not key.strip(): + continue + seen_at, row = cached + if (now - seen_at) >= timedelta(seconds=_PROFILE_CACHE_DISK_TTL_SECONDS): + continue + payload = dict(row) + payload["updated_at"] = seen_at.isoformat() + entries[key] = payload + return entries + + def _persist_profile_cache_entry(self, profile_key: str, payload: dict) -> None: + if not isinstance(profile_key, str) or not profile_key.strip() or not isinstance(payload, dict): + return + metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} + xml_fields = metadata.get("xml_fields") if isinstance(metadata, dict) else {} + if not isinstance(xml_fields, dict): + xml_fields = {} + now = datetime.now(timezone.utc) + ssdp_loc = metadata.get("location") if isinstance(metadata.get("location"), str) else "" + row = { + "name": payload.get("name"), + "type": payload.get("type"), + "category": payload.get("category"), + "url": payload.get("url"), + "xml_fields": dict(xml_fields), + "raw_xml": metadata.get("xml") if isinstance(metadata, dict) else None, + "ssdp_location": ssdp_loc.strip() if ssdp_loc.strip() else None, + } + usn_persist = metadata.get("usn") if isinstance(metadata.get("usn"), str) else "" + if usn_persist.strip(): + row["usn"] = usn_persist.strip() + self._profile_disk_cache[profile_key.strip()] = (now, row) + self._mark_cache_dirty() + + def _persist_profile_cache_entries(self, headers: dict[str, str], fallback_ip: str, payload: dict) -> None: + for key in self._profile_candidate_keys(headers, fallback_ip): + self._persist_profile_cache_entry(key, payload) + + def _mark_cache_dirty(self) -> None: + self._cache_dirty = True + self._flush_persistent_caches_if_due() + + def _flush_persistent_caches_if_due(self, force: bool = False) -> None: + if not self._cache_dirty and not force: + return + now_mono = time.monotonic() + if not force and self._last_cache_flush_monotonic > 0: + if (now_mono - self._last_cache_flush_monotonic) < _CACHE_FLUSH_INTERVAL_SECONDS: + return + + xml_entries = self._build_persistent_xml_cache_entries() + profile_entries = self._build_persistent_profile_cache_entries() + save_discovery_cache( + { + "ssdp_xml_cache": {"version": 1, "entries": xml_entries}, + "ssdp_profile_cache": {"version": 1, "entries": profile_entries}, + } + ) + + self._xml_disk_cache = { + loc: (datetime.fromisoformat(row["updated_at"]), row["xml_fields"], row.get("raw_xml")) + for loc, row in xml_entries.items() + } + self._profile_disk_cache = { + key: (datetime.fromisoformat(row["updated_at"]), dict(row)) + for key, row in profile_entries.items() + } + self._cache_dirty = False + self._last_cache_flush_monotonic = now_mono + + def _build_services_description(self, xml_fields: dict[str, str]) -> str: + return xml_fields.get("services_description", "") + + def _build_services_description_from_device(self, device_elem: ET.Element) -> str: + services: list[str] = [] + for elem in device_elem.iter(): + if elem.tag.rsplit("}", 1)[-1] == "serviceType": + value = (elem.text or "").strip() + if value: + services.append(value) + return ", ".join(services) + + def _build_services_records(self, device_elem: ET.Element, location: str | None) -> list[dict[str, str]]: + parsed_location = urlparse(location or "") + target_default = parsed_location.hostname or "" + port_default = str(parsed_location.port) if parsed_location.port is not None else "" + records: list[dict[str, str]] = [] + for service_elem in self._find_elements(device_elem, "service"): + service_type = self._find_text(service_elem, "serviceType") + if not service_type: + continue + control_url = self._find_text(service_elem, "controlURL") + parsed_control = urlparse(urljoin(location or "", control_url)) if control_url else None + target = target_default + port = port_default + if parsed_control is not None: + if parsed_control.hostname: + target = parsed_control.hostname + if parsed_control.port is not None: + port = str(parsed_control.port) + records.append( + { + "service": service_type, + "target": target or "unavailable", + "port": port or "unavailable", + } + ) + return records + + def _build_icons_description(self, device_elem: ET.Element) -> str: + items: list[str] = [] + current: dict[str, str] = {} + for elem in device_elem.iter(): + local = elem.tag.rsplit("}", 1)[-1] + if local in {"mimetype", "width", "height", "url"}: + current[local] = (elem.text or "").strip() + if local == "icon": + if current: + items.append( + f"mimetype={current.get('mimetype', '')};" + f"width={current.get('width', '')};" + f"height={current.get('height', '')};" + f"url={current.get('url', '')}" + ) + current = {} + return ", ".join([item for item in items if item.strip(";,")]) + + def _build_preferred_icon_url(self, device_elem: ET.Element, location: str | None) -> str: + base_url = location or "" + best_url = "" + best_area = -1 + for icon_elem in self._find_elements(device_elem, "icon"): + icon_url = self._find_text(icon_elem, "url") + if not icon_url: + continue + width_txt = self._find_text(icon_elem, "width") + height_txt = self._find_text(icon_elem, "height") + try: + area = int(width_txt or "0") * int(height_txt or "0") + except ValueError: + area = 0 + if area >= best_area: + best_area = area + best_url = urljoin(base_url, icon_url) + return best_url + + def _find_first(self, root: ET.Element, local_name: str) -> ET.Element | None: + for elem in root.iter(): + if elem.tag.rsplit("}", 1)[-1] == local_name: + return elem + return None + + def _find_elements(self, root: ET.Element, local_name: str) -> list[ET.Element]: + return [elem for elem in root.iter() if elem.tag.rsplit("}", 1)[-1] == local_name] + + def _find_text(self, root: ET.Element, local_name: str) -> str: + for elem in root.iter(): + if elem.tag.rsplit("}", 1)[-1] == local_name: + return (elem.text or "").strip() + return "" + + def _load_rules(self) -> dict: + # The bundled config/ssdp_rules.json is the single source of truth. This empty skeleton is + # only a graceful degraded fallback if that file is missing/corrupt — startup runs + # utils.config_integrity, which shows a "corrupted installation" dialog in that case. + empty_rules: dict = { + "name_rules": {}, + "information_rules": {}, + "type_rules": [], + "base_type_rules": [], + } + try: + parsed = json.loads(_RULES_PATH.read_text(encoding="utf-8")) + if not isinstance(parsed, dict): + self._logger.warning("SSDP rules %s is not a JSON object — degraded (no rules)", _RULES_PATH) + return merge_ssdp_rules_overlays(empty_rules) + self._logger.info("Loaded SSDP rules from %s", _RULES_PATH) + return merge_ssdp_rules_overlays(parsed) + except FileNotFoundError: + self._logger.warning("SSDP rules file missing at %s — degraded (no rules)", _RULES_PATH) + return merge_ssdp_rules_overlays(empty_rules) + except (OSError, json.JSONDecodeError): + self._logger.warning("Invalid SSDP rules file %s — degraded (no rules)", _RULES_PATH, exc_info=True) + return merge_ssdp_rules_overlays(empty_rules) + + def _apply_name_rules(self, xml_fields: dict[str, str]) -> str: + rules = self._rules.get("name_rules", {}) + if not isinstance(rules, dict): + return "" + fallback_fields = rules.get("fallback_fields", []) + if not isinstance(fallback_fields, list): + fallback_fields = [] + friendly = str(xml_fields.get("friendlyName", "")).strip() + display = str(xml_fields.get("displayName", "")).strip() + if rules.get("prefer_display_name_when_no_friendly_name") and (not friendly) and display: + return display + for field in fallback_fields: + value = xml_fields.get(str(field)) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + def _build_information_text(self, xml_fields: dict[str, str]) -> str: + if not self._rules_enabled: + return "" + rules = self._rules.get("information_rules", {}) + if not isinstance(rules, dict): + return "" + fields = rules.get("concat_fields", []) + if not isinstance(fields, list): + fields = [] + separator = str(rules.get("separator", " / ")) + values: list[str] = [] + for field in fields: + value = xml_fields.get(str(field)) + if isinstance(value, str) and value.strip(): + value_norm = value.strip() + if value_norm not in values: + values.append(value_norm) + return separator.join(values) + + def _match_type_rules(self, rule_list: object, haystack: str, fields: dict[str, str]) -> str: + """Evaluate a rule list (first match wins) against a lowercased haystack. + + Each rule may declare ``contains_any`` (substring search in ``haystack``) and/or + ``equals_field`` (``{fieldName: [values]}``, exact case-insensitive match against + ``fields``). A rule matches if either condition holds. Returns the matched type + (lowercased) or ``""``. + """ + if not isinstance(rule_list, list): + return "" + norm_fields = { + str(k).strip().lower(): str(v).strip().lower() + for k, v in fields.items() + if isinstance(v, str) + } + for rule in rule_list: + if not isinstance(rule, dict): + continue + target_type = rule.get("type") + if not isinstance(target_type, str) or not target_type.strip(): + continue + equals_field = rule.get("equals_field") + if isinstance(equals_field, dict): + for fname, allowed in equals_field.items(): + if not isinstance(allowed, list): + continue + fval = norm_fields.get(str(fname).strip().lower(), "") + if fval and any(fval == str(a).strip().lower() for a in allowed): + return target_type.strip().lower() + contains_any = rule.get("contains_any", []) + if isinstance(contains_any, list): + for token in contains_any: + token_norm = str(token).strip().lower() + if token_norm and token_norm in haystack: + return target_type.strip().lower() + return "" + + def _apply_type_rules(self, headers: dict[str, str], xml_fields: dict[str, str]) -> str: + searchable_parts = [ + str(headers.get("ST", "")), + str(headers.get("NT", "")), + str(headers.get("USN", "")), + str(headers.get("SERVER", "")), + str(xml_fields.get("deviceType", "")), + str(xml_fields.get("manufacturer", "")), + str(xml_fields.get("modelName", "")), + str(xml_fields.get("modelType", "")), + str(xml_fields.get("modelNumber", "")), + str(xml_fields.get("friendlyName", "")), + str(xml_fields.get("displayName", "")), + str(xml_fields.get("roomName", "")), + ] + haystack = " ".join(searchable_parts).lower() + return self._match_type_rules( + self._rules.get("type_rules"), haystack, {"modelType": xml_fields.get("modelType", "")} + ) diff --git a/discovery/wsd.py b/app/discovery/wsd.py similarity index 81% rename from discovery/wsd.py rename to app/discovery/wsd.py index 57d61871..5dd39b0f 100644 --- a/discovery/wsd.py +++ b/app/discovery/wsd.py @@ -1,5 +1,5 @@ -# File wsd.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File wsd.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """WS-Discovery (WSD) — multicast SOAP/UDP discovery for Windows and compatible hosts.""" @@ -15,28 +15,34 @@ from urllib.parse import urlparse from discovery.base import BaseDiscovery +from utils.discovery_config import category_for_device_type +from utils.wsd_rules import cached_wsd_rules, infer_type_from_qnames -try: - from wsdiscovery import QName -except ImportError: # pragma: no cover - optional dependency - QName = None # type: ignore[misc, assignment] - -try: - from wsdiscovery.discovery import ThreadedWSDiscovery as _ThreadedWSDiscovery -except ImportError: # pragma: no cover - optional dependency - _ThreadedWSDiscovery = None +QName = None # type: ignore[misc, assignment] +_ThreadedWSDiscovery = None _DEFAULT_INTERVAL_S = 90.0 _DEFAULT_TIMEOUT_S = 8.0 # Remember last LAN IPv4 per WSD EPR when a later probe only lists link-local IPv6 (common on Wi‑Fi mini PCs). _STICKY_LAN_IPV4_TTL_S = 3600.0 -# DPWS "Device" — many Windows and embedded hosts match this type in Probe. -_DPWS_DEVICE_TYPE: object | None -if QName is not None: - _DPWS_DEVICE_TYPE = QName("http://schemas.xmlsoap.org/ws/2006/02/devprof", "Device") -else: - _DPWS_DEVICE_TYPE = None +_DPWS_DEVICE_TYPE: object | None = None +_WSD_LIBS_LOADED = False + + +def _ensure_wsd_libs() -> None: + global QName, _ThreadedWSDiscovery, _DPWS_DEVICE_TYPE, _WSD_LIBS_LOADED + if _WSD_LIBS_LOADED: + return + _WSD_LIBS_LOADED = True + try: + from wsdiscovery import QName as _QName + from wsdiscovery.discovery import ThreadedWSDiscovery as _T + QName = _QName + _ThreadedWSDiscovery = _T + _DPWS_DEVICE_TYPE = _QName("http://schemas.xmlsoap.org/ws/2006/02/devprof", "Device") + except ImportError: + pass # soap.udp://[fe80::1]:3702/ or soap.udp://192.168.1.1:3702/… _SOAP_UDP_RE = re.compile( @@ -93,90 +99,9 @@ def is_synthetic_wsd_display_name(name: str) -> bool: return False -def _category_for_wsd_type(device_type: str) -> str: - return { - "router": _("Routers & Gateways"), - "mediaserver": _("Media Servers"), - "printer": _("Printers"), - "networkprinter": _("Printers"), - "multifunction_printer": _("Printers"), - "smartspeaker": _("Smart Speakers"), - "smarttv": _("Smart TVs"), - "smartdevice": _("Smart Devices"), - "camera": _("Cameras"), - "homeappliance": _("Home Appliances"), - "cnc": _("CNC Machines"), - "3dprinter": _("3D Printers"), - "nas": _("NAS / File Servers"), - "computer": _("Computers"), - "esp32": _("ESP3D Devices"), - "unknown": _("Unknown Devices"), - }.get(device_type, _("Unknown Devices")) - - -def _qname_suggests_computer(t) -> bool: - """DPWS ``Device`` / devprof — Windows PCs often include this alongside print stack types.""" - if _DPWS_DEVICE_TYPE is not None: - try: - if t == _DPWS_DEVICE_TYPE: - return True - except Exception: - pass - try: - ns = (t.getNamespace() or "").lower() - local = (t.getLocalname() or "").lower() - except Exception: - return False - if local == "device" and "devprof" in ns: - return True - # Host / workstation hints (avoid treating mixed printer+host ads as printer-only). - if local in {"computer", "computerdevice"}: - return True - return False - - -def _qname_suggests_printer(t) -> bool: - """Strong printer/MFP QName signals — same rules as before, but evaluated per-type for aggregation.""" - try: - ns = (t.getNamespace() or "").lower() - local = (t.getLocalname() or "").lower() - except Exception: - return False - if local in {"printdevice", "printer"}: - return True - if local.endswith("printdevice") or local.endswith("printer"): - return True - if "printdevice" in ns: - return True - if "/wdp/" in ns and local and any( - x in local for x in ("print", "printer", "printdevice", "fax") - ): - return True - if "microsoft.com/windows" in ns and local and any( - x in local for x in ("printdevice", "printer", "fax") - ): - return True - if local in {"scanner", "fax", "faxdevice"} or local.endswith("scannerdevice"): - return True - return False - - -def _infer_type_from_qnames(types) -> str: - """Classify service type. Windows often lists print QNames and DPWS ``Device`` together — prefer PC.""" - if not types: - return "computer" - any_pc = False - any_printer = False - for t in types: - if _qname_suggests_computer(t): - any_pc = True - if _qname_suggests_printer(t): - any_printer = True - if any_pc: - return "computer" - if any_printer: - return "networkprinter" - return "computer" +# Type classification from service QNames lives in config/wsd_rules.json, evaluated by +# utils.wsd_rules.infer_type_from_qnames (Windows lists print QNames alongside a DPWS +# Device QName, so "computer" wins over "networkprinter" via the rules' precedence order). def _reverse_dns_short_name(ip_s: str) -> str | None: @@ -464,10 +389,16 @@ def __init__( self._wake_event = threading.Event() self._probe_thread: threading.Thread | None = None self._engine: object | None = None + # TTL tracking: emit offline for hosts absent ≥ _wsd_grace_sweeps consecutive sweeps. + self._wsd_known_eprs: dict[str, dict] = {} # epr/key → last payload + self._wsd_miss_counts: dict[str, int] = {} # epr/key → consecutive missed sweeps + self._wsd_grace_sweeps: int = 2 + self._wsd_rules = cached_wsd_rules() def start(self) -> None: if self._running: return + _ensure_wsd_libs() if _ThreadedWSDiscovery is None: self._logger.warning("WSD discovery unavailable: install package WSDiscovery (PyPI)") return @@ -502,6 +433,8 @@ def stop(self) -> None: if self._probe_thread is not None: self._probe_thread.join(timeout=1.0) self._probe_thread = None + self._wsd_known_eprs.clear() + self._wsd_miss_counts.clear() self._logger.info("WSD discovery stopped") def refresh(self) -> None: @@ -521,10 +454,14 @@ def _run_once(self) -> None: eng = self._engine if eng is None or not self._running: return + # Clear accumulated remote services before each sweep so only devices that respond in + # THIS cycle are counted. The grace period of _wsd_grace_sweeps absorbs hosts that + # occasionally skip a probe due to network timing. + try: + eng.clearRemoteServices() + except Exception: + self._logger.debug("WSD clearRemoteServices failed", exc_info=True) try: - # Do not call clearRemoteServices() each cycle — Windows hosts often reply slower or skip a - # probe entirely; wiping _remoteServices would drop the PC from the merged set while leaving - # faster responders (e.g. printers) as the sole entry until the next lucky reply window. # Typed DPWS probe first, broad probe last: ThreadedWSDiscovery stores one ``Service`` per # EPR — a later ProbeMatch overwrites the earlier. A narrow typed match can carry thinner # metadata than a broad ProbeMatch; running broad last keeps fuller ``Types`` / ``XAddrs``. @@ -537,20 +474,22 @@ def _run_once(self) -> None: try: eng.searchServices(timeout=broad_s) except Exception: + # Transient failure — don't penalise known hosts with a miss-count increment. self._logger.debug("WSD broad searchServices failed", exc_info=True) return # Second broad sweep — some stacks (esp. mobile / Wi‑Fi) answer after the first window. - try: - eng.searchServices(timeout=min(5.0, max(3.0, broad_s * 0.45))) - except Exception: - self._logger.debug("WSD second broad searchServices failed", exc_info=True) + if self._running: + try: + eng.searchServices(timeout=min(5.0, max(3.0, broad_s * 0.45))) + except Exception: + self._logger.debug("WSD second broad searchServices failed") # ThreadedWSDiscovery keeps matches in _remoteServices (no public accessor). try: services = list(getattr(eng, "_remoteServices", {}).values()) except Exception: services = [] except Exception: - self._logger.debug("WSD probe sequence failed", exc_info=True) + self._logger.warning("WSD probe sequence failed", exc_info=True) return self._prune_sticky_epr_map() if not services: @@ -558,18 +497,44 @@ def _run_once(self) -> None: "WSD: no responses (firewall may block UDP 3702; many Windows PCs do not expose a " "useful WSD endpoint — NetBIOS browse may still be required)" ) - return - self._logger.debug("WSD: combined service count=%d", len(services)) + else: + self._logger.debug("WSD: combined service count=%d", len(services)) + + # Build payloads for devices found in this sweep. + current_payloads: dict[str, dict] = {} for svc in services: try: payload = self._service_to_payload(svc) if payload: - self._emit("device", payload) + md = payload.get("metadata") or {} + epr = (md.get("wsd_epr") or "").strip().lower() + key = epr if epr else f"{payload['ip']}:{payload['port']}" + current_payloads[key] = payload else: self._log_skip_reason(svc, "no usable LAN IP") except Exception: self._logger.debug("WSD service→payload failed", exc_info=True) + # TTL: emit offline for previously-known devices absent this sweep for ≥ grace sweeps. + for k in list(self._wsd_known_eprs): + if k not in current_payloads: + miss = self._wsd_miss_counts.get(k, 0) + 1 + self._wsd_miss_counts[k] = miss + if miss >= self._wsd_grace_sweeps: + offline_payload = dict(self._wsd_known_eprs[k]) + offline_payload["online"] = False + self._emit("device", offline_payload) + self._logger.info("WSD: %s offline after %d missed sweep(s)", k, miss) + del self._wsd_known_eprs[k] + self._wsd_miss_counts.pop(k, None) + else: + self._wsd_miss_counts.pop(k, None) + + # Emit live devices and update known. + for k, payload in current_payloads.items(): + self._wsd_known_eprs[k] = payload + self._emit("device", payload) + def _prune_sticky_epr_map(self) -> None: now = time.monotonic() ttl = _STICKY_LAN_IPV4_TTL_S @@ -644,7 +609,7 @@ def _service_to_payload(self, svc) -> dict | None: pass if not epr: return None - dev_type = _infer_type_from_qnames(svc.getTypes()) + dev_type = infer_type_from_qnames(svc.getTypes(), self._wsd_rules) if dev_type != "computer": # Windows often advertises only print QNames; still surface the host (category may be Printers). self._logger.debug( @@ -683,7 +648,7 @@ def _service_to_payload(self, svc) -> dict | None: "ip": ip_s, "port": int(port), "type": dev_type, - "category": _category_for_wsd_type(dev_type), + "category": category_for_device_type(dev_type), "source": self.source, "url": url, "metadata": metadata, diff --git a/discovery/wsdd_client.py b/app/discovery/wsdd_client.py similarity index 79% rename from discovery/wsdd_client.py rename to app/discovery/wsdd_client.py index 26c7ba85..f43126fb 100644 --- a/discovery/wsdd_client.py +++ b/app/discovery/wsdd_client.py @@ -1,5 +1,5 @@ -# File wsdd_client.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File wsdd_client.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Poll the local `wsdd` control socket (``-l``) for WSD discovery cache — often includes Windows computer names. @@ -156,6 +156,10 @@ def __init__( self._thread: threading.Thread | None = None self._stop = threading.Event() self._last_warned_missing = 0.0 + # TTL tracking: emit offline for hosts absent ≥ _wsdd_grace_polls consecutive polls. + self._wsdd_known: dict[str, dict] = {} # uri → last payload + self._wsdd_miss_counts: dict[str, int] = {} # uri → consecutive missed polls + self._wsdd_grace_polls: int = 2 def start(self) -> None: if not self._listen: @@ -174,6 +178,8 @@ def stop(self) -> None: self._thread = None if t is not None: t.join(timeout=2.0) + self._wsdd_known.clear() + self._wsdd_miss_counts.clear() self._logger.info("wsdd socket discovery stopped") def refresh(self) -> None: @@ -205,11 +211,13 @@ def _poll_once(self) -> None: self._listen, e, ) - return + return # socket failure — don't penalise known hosts except Exception: self._logger.debug("wsdd list exchange failed", exc_info=True) return + # Build payloads for devices in the current list response. + current_payloads: dict[str, dict] = {} for row in _parse_list_response(text): uri, name, belongs, _last_seen, addr_field, types_csv = row addrs = _parse_address_field(addr_field) @@ -225,18 +233,36 @@ def _poll_once(self) -> None: "wsdd_types": (types_csv or "").strip(), "wsdd_addresses": (addr_field or "").strip(), } - self._emit( - "device", - { - "name": display, - "ip": ip_s, - "port": _WSDD_DEVICE_PORT, - "type": dev_type, - "category": category, - "source": "wsdd", - "url": None, - "metadata": meta, - "online": True, - "icon": None, - }, - ) + key = uri.strip().lower() + current_payloads[key] = { + "name": display, + "ip": ip_s, + "port": _WSDD_DEVICE_PORT, + "type": dev_type, + "category": category, + "source": "wsdd", + "url": None, + "metadata": meta, + "online": True, + "icon": None, + } + + # TTL: emit offline for devices absent from the current list for ≥ grace polls. + for k in list(self._wsdd_known): + if k not in current_payloads: + miss = self._wsdd_miss_counts.get(k, 0) + 1 + self._wsdd_miss_counts[k] = miss + if miss >= self._wsdd_grace_polls: + offline_payload = dict(self._wsdd_known[k]) + offline_payload["online"] = False + self._emit("device", offline_payload) + self._logger.info("wsdd: %s offline after %d missed poll(s)", k, miss) + del self._wsdd_known[k] + self._wsdd_miss_counts.pop(k, None) + else: + self._wsdd_miss_counts.pop(k, None) + + # Emit live devices and update known. + for k, payload in current_payloads.items(): + self._wsdd_known[k] = payload + self._emit("device", payload) diff --git a/i18n.py b/app/i18n.py similarity index 75% rename from i18n.py rename to app/i18n.py index 3ea725a0..fe75f0c0 100644 --- a/i18n.py +++ b/app/i18n.py @@ -1,5 +1,5 @@ -# File i18n.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File i18n.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Minimal i18n bootstrap using gettext.""" @@ -51,27 +51,24 @@ def _add(code: str) -> None: return langs +_active_language: str | None = None + + +def active_language() -> str | None: + """Return the language code that was actually installed (e.g. ``'zh_CN'``, ``'fr'``), or None for English.""" + return _active_language + + def setup_i18n() -> None: + global _active_language locale_dir = Path(__file__).resolve().parent / "locale" languages = _detect_languages() - # Set the C library locale from the environment so GTK uses it for its own - # built-in widget labels (dialog buttons "Close", "Yes", "No", etc.). try: locale.setlocale(locale.LC_ALL, "") except locale.Error: pass - # On Ubuntu/Mint, GTK translations live under locale-langpack rather than - # the standard /usr/share/locale. Tell GLib about both paths so that GTK's - # own strings (button labels etc.) are translated. - for gtk_domain in ("gtk30", "gtk30-properties"): - for lp in ("/usr/share/locale-langpack", "/usr/share/locale"): - try: - locale.bindtextdomain(gtk_domain, lp) # type: ignore[attr-defined] - except (AttributeError, OSError): - break - # Register our locale dir for modules that use `from gettext import gettext as _`. gettext.bindtextdomain(APP_DOMAIN, str(locale_dir)) gettext.textdomain(APP_DOMAIN) @@ -83,6 +80,8 @@ def setup_i18n() -> None: languages=languages if languages else None, ) translation.install() + _active_language = languages[0] if languages else None except FileNotFoundError: # No .mo file for the detected language — fall back to English (no-op) gettext.install(APP_DOMAIN, localedir=str(locale_dir)) + _active_language = None diff --git a/app/locale/de/LC_MESSAGES/netneighbor.mo b/app/locale/de/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..58e3f471 Binary files /dev/null and b/app/locale/de/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/de/LC_MESSAGES/netneighbor.po b/app/locale/de/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..efc9b53f --- /dev/null +++ b/app/locale/de/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1423 @@ +# German translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: German\n" +"Language: de\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "Ansicht" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "Neu laden" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "Anzeige:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "Symbole" + +#: ui/main_window.py:113 +msgid "List" +msgstr "Liste" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "Anordnung:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "Unsortiert" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "Nach Typ" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "Nach Standort" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "Einstellungen" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "Benachrichtigungen aus" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "Nur überwachte Geräte" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "Alle Geräte" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "Standort-Voreinstellungen" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "Typ-Voreinstellungen" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "" +"Im Systembereich weiterhin ausgeführt, wenn das Fenster geschlossen wird" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "Minimiert im Systembereich starten" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "NetNeighbor beim Anmelden starten" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "Beenden" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "Extras" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "Externe Anwendungen…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "Benachrichtigungsverlauf" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "Hilfe" + +#: ui/main_window.py:214 +msgid "About" +msgstr "Über" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "Sitzungsstart" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "Später" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "Speichern" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "NetNeighbor im Hintergrund ausführen?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"Sie können NetNeighbor im Systembereich beibehalten, wenn Sie das Fenster " +"schließen. Das Starten mit Ihrer Sitzung hält die LAN-Erkennung im " +"Hintergrund aktiv. Sie können dies jederzeit unter Ansicht → Einstellungen " +"ändern." + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "NetNeighbor beim Anmelden starten" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"Nach dem Schließen dieses Dialogs wird das Hauptfenster in die Systemleiste " +"ausgeblendet — klicken Sie auf das NetNeighbor-Symbol in der Systemleiste, " +"um es zu öffnen (empfohlen nach der Installation)." + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — LAN-Erkennung" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "NetNeighbor öffnen" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "In die Systemleiste minimieren" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "Büro" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "Zimmer" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "Wohnzimmer" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "Küche" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "Werkstatt" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "Garage" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "Standortvorgaben verwalten." + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "Im Netzwerk erkannte Standorte automatisch zu dieser Liste hinzufügen" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" +"Wenn aktiviert, können Raumnamen und ähnliche Zeichenfolgen von Geräten (z. " +"B. einige Lautsprecher) zur Vorlagenliste hinzugefügt werden, wenn sie " +"erkannt werden." + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "Vorlage" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "Hinzufügen" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "Umbenennen" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "Entfernen" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "Alles löschen" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "Abbrechen" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "OK" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "Standortvorgabe hinzufügen" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "Standortvorgabe umbenennen" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "Computer" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "Router" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "Medienserver" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "Drucker" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "Multifunktionsdrucker" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "Drucker (Netzwerk / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "SmartSpeaker" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "SmartTV" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "SmartDevice" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "Kamera" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "Haushaltsgerät" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "3D-Drucker" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" +"Verwalten Sie die im Kontextmenü angezeigten Gerätetyp-Voreinstellungen." + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "Beschriftung" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "Typ-ID" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "Standardwerte wiederherstellen" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "Bezeichnung:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "Typ-ID:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "z. B. nas, router, camera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "Typ-Voreinstellung hinzufügen" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "Typ-Voreinstellung umbenennen" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "Externe Anwendungen" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "Leer = Systemstandard" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "Zurücksetzen" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "Standardbefehl wiederherstellen" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "Diesen Befehl auf seinen Standardwert zurücksetzen?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "Nein" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "Ja" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "Leer = deaktiviert" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "Löschen" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "Den globalen benutzerdefinierten Befehl entfernen" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "Den globalen benutzerdefinierten Befehl löschen?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "Benutzerdefiniert:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "Vollständige Adresse" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "Geräte-IP" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "Serviceport" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "Gerätename" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "Gerätetyp" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "Kategorie" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "Danksagungen" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "Lizenz" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "Schließen" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "Geräte im lokalen Netzwerk entdecken und überwachen." + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Python-Bibliotheken" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "GitHub-Projekt" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "Benachrichtigungsverlauf" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "Datum/Uhrzeit" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "Gerät" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "Status" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "Kein Standort" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "Alle Orte" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "Alle Typen" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "Ports" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "Typ" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" +"Vorläufige IPv6-Identität — hervorgehobene Zeile pulsiert während die " +"Erkennung dem Hostnamen / IPv4 entspricht." + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" +"Gerätesymbol wird im Hintergrund abgerufen — Kachel pulsiert bis es ankommt." + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "Öffnen ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "Öffnen" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "Benutzerdefinierten Befehl ausführen" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "Details" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "Optionen" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "Nicht mehr folgen" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "Überwachen" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "Standort" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "Automatisch" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "Gerätetyp" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "Gerät umbenennen" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "Benutzerdefinierter Name" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "Befehl konnte nicht gestartet werden: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "" +"Benutzerdefinierten Befehl konnte nicht geparst werden (Platzhalter prüfen)." + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "Rohes XML anzeigen" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "Name" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "IP-Adresse" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (link-local)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "Übersicht" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "Gerätedetails" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" +"Feldmappingregeln pro Gerät. Wählen Sie Zeilen aus und entfernen Sie diese " +"bei Bedarf." + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "Auswählen" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "Ziel" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "Quellfeld" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "Ausgewählte entfernen" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "Alle entfernen" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "Regeln" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "Dienste" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "Dienst" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "Port" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "Feld" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "Wert" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "Informationen zur Fehlerbehebung" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "Eintrag" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "TXT-Einträge" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "XML-Speicherort" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "In Zwischenablage kopieren" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "Gerätedaten" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "Überschreiben" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "Zusätzlich" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "Diesen Befehl entfernen" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "Diesen Befehlseintrag entfernen?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ Befehl hinzufügen" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "Benutzerdefinierter Befehl" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "z.B. x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "Benutzerdefinierter Befehl pro Gerät löschen?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "Geräteüberschreibung entfernen (globalen Befehl verwenden)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "Symbol verwenden von:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "System" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "Vom Gerät" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "Benutzerdefiniert" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "Ordner mit benutzerdefinierten Symbolen öffnen" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "nicht verfügbar" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "Bild vom Gerät" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "keine" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "Ausgewähltes Symbol" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "Symbol auswählen" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "Anzeigename" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "Informationen" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "Als {target} verwenden" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "Regel {target} entfernen" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "Regel gespeichert" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "Regel entfernt" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "Ausgewählte Regeln entfernt" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "Alle Regeln entfernt" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "Keine TXT-Einträge" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "Unbekannt" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "HTTP-Gerät" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "HTTPS-Gerät" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "Smart Speaker" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "Smart TV" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "Smart Device" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "Haushaltsgerät" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "ESP3D Gerät" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "Scanner" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "Zuletzt gesehen" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "Hersteller" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "Hersteller-URL" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "Modell" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "Modell-URL" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "MAC-Adresse" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "Seriennummer" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "Eindeutige Kennung" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "Hostname" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "Router und Gateways" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "Medienserver" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "Drucker" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "Smart Speaker" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "Smart TVs" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "Smart Devices" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "Kameras" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "Haushaltsgeräte" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "CNC-Maschinen" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "3D-Drucker" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / Dateiserver" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "Computer" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "ESP3D-Geräte" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "Unbekannte Geräte" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "Über NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "App-Logo unter assets/icons: Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "Anwendungen" + +#: ui/ +msgid "Apply" +msgstr "Anwenden" + +#: ui/ +msgid "Author: Luc" +msgstr "Autor: Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "In den Systembereich schließen statt beenden" + +#: ui/ +msgid "Command" +msgstr "Befehl" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" +"Befehlsvorlagen zum Öffnen von Geräteverbindungen. Leer lassen, um die " +"Systemstandards zu verwenden." + +#: ui/ +msgid "Commands" +msgstr "Befehle" + +#: ui/ +msgid "Custom command (additional)" +msgstr "Benutzerdefinierter Befehl (zusätzlich)" + +#: ui/ +msgid "Dark" +msgstr "Dunkel" + +#: ui/ +msgid "Date / Time" +msgstr "Datum / Uhrzeit" + +#: ui/ +msgid "Delete" +msgstr "Löschen" + +#: ui/ +msgid "Desktop notifications" +msgstr "Desktop-Benachrichtigungen" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "Erkennung-Aktualisierung angefordert" + +#: ui/ +msgid "Edit" +msgstr "Bearbeiten" + +#: ui/ +msgid "Edit type preset" +msgstr "Typvoreinstellung bearbeiten" + +#: ui/ +msgid "Error" +msgstr "Fehler" + +#: ui/ +msgid "Extra large" +msgstr "Sehr groß" + +#: ui/ +msgid "Field mapping rules" +msgstr "Feldzuordnungsregeln" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "GNU Lesser General Public License Version 3 oder später" + +#: ui/ +msgid "General" +msgstr "Allgemein" + +#: ui/ +msgid "Hidden devices" +msgstr "Ausgeblendete Geräte" + +#: ui/ +msgid "Hide device" +msgstr "Gerät ausblenden" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "Gerät löschen" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"{name} ({ip}) aus dem Cache und allen Einstellungen entfernen?\n" +"\n" +"Dies kann nicht rückgängig gemacht werden. Das Gerät erscheint erneut, wenn es im Netzwerk wiederentdeckt wird." + +#: ui/ +msgid "Hide sidebar" +msgstr "Seitenleiste ausblenden" + +#: ui/ +msgid "Hide window" +msgstr "Fenster ausblenden" + +#: ui/ +msgid "Icons size" +msgstr "Symbolgröße" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "Ungültige Befehlsvorlage für dieses Protokoll." + +#: ui/ +msgid "Large" +msgstr "Groß" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "Zuletzt gesehen: vor {n} Tagen" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "Zuletzt gesehen: vor {n} Std." + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "Zuletzt gesehen: vor {n} Min." + +#: ui/ +msgid "Light" +msgstr "Hell" + +#: ui/ +msgid "Location name:" +msgstr "Standortname:" + +#: ui/ +msgid "Locations" +msgstr "Standorte" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "Standortvoreinstellungen im Kontextmenü verwalten." + +#: ui/ +msgid "Medium" +msgstr "Mittel" + +#: ui/ +msgid "Mode" +msgstr "Modus" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "Neuer Name:" + +#: ui/ +msgid "No devices yet" +msgstr "Noch keine Geräte" + +#: ui/ +msgid "No hidden devices" +msgstr "Keine ausgeblendeten Geräte" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" +"Die Benachrichtigungsübermittlung hängt vom Betriebssystem und der Sitzung " +"ab. Das tray-basierte Verhalten (In Tray schließen, minimierter Start) wird " +"ausgerichtet, sobald der Systemtray implementiert ist." + +#: ui/ +msgid "Notifications" +msgstr "Benachrichtigungen" + +#: ui/ +msgid "Offline" +msgstr "Offline" + +#: ui/ +msgid "Online" +msgstr "Online" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"Verbindungsendpunkte pro Protokoll überschreiben oder hinzufügen. Für das " +"Schema 'custom' geben Sie die Befehlsvorlage in IP/Host ({ip}, {ip_raw}, " +"{port}, {name}, {type}, {category}, {url}) ein. IP/Host und Port sind für " +"andere Schemata optional." + +#: ui/ +msgid "Preferences…" +msgstr "Einstellungen…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Qt-Python-Bindungen" + +#: ui/ +msgid "Reload discovery" +msgstr "Erkennung neu laden" + +#: ui/ +msgid "Scheme" +msgstr "Schema" + +#: ui/ +msgid "See the" +msgstr "Siehe die" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "" +"Wählen Sie ein Symbol, dann OK. IDs werden in Ihren Einstellungen " +"gespeichert." + +#: ui/ +msgid "Service type" +msgstr "Diensttyp" + +#: ui/ +msgid "Session" +msgstr "Sitzung" + +#: ui/ +msgid "Show sidebar" +msgstr "Seitenleiste anzeigen" + +#: ui/ +msgid "Show window" +msgstr "Fenster anzeigen" + +#: ui/ +msgid "Sidebar" +msgstr "Seitenleiste" + +#: ui/ +msgid "Small" +msgstr "Klein" + +#: ui/ +msgid "Start Scanning…" +msgstr "Scan wird gestartet…" + +#: ui/ +msgid "Theme" +msgstr "Thema" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "Für dieses Programm besteht keinerlei Garantie." + +#: ui/ +msgid "Types" +msgstr "Typen" + +#: ui/ +msgid "Use as Friendly name" +msgstr "Als Anzeigenamen verwenden" + +#: ui/ +msgid "Use as Information" +msgstr "Als Information verwenden" + +#: ui/ +msgid "Use as Location" +msgstr "Als Standort verwenden" + +#: ui/ +msgid "Use icon from" +msgstr "Symbol verwenden von" + +#: ui/ +msgid "Version {version}" +msgstr "Version {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery (Windows-Geräte)" + +#: ui/ +msgid "for details." +msgstr "für Details." + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "mDNS/DNS-SD-Erkennung" + +#: ui/ +msgid "not yet downloaded" +msgstr "noch nicht heruntergeladen" + +#: ui/ +msgid "{} devices" +msgstr "{} Geräte" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "Wartung" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "Alle Anwendungsdaten zurücksetzen…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "Alle Anwendungsdaten zurücksetzen?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"Alle Einstellungen, gecachten Symbole, Erkennungsdaten und Protokolle werden dauerhaft gelöscht:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor verwendet beim nächsten Start die Standardeinstellungen.\n" +"Diese Aktion kann nicht rückgängig gemacht werden." + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "Zurückgesetzt — bitte neu starten" + +#: ui/ +msgid "App icon pack" +msgstr "App-Symbolpaket" + +#: ui/ +msgid "Download failed" +msgstr "Download fehlgeschlagen" + +#: ui/ +msgid "Downloading…" +msgstr "Wird heruntergeladen…" + +#: ui/ +msgid "Icon pack" +msgstr "Icon-Pack" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (integriert)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"Keine Symbole gefunden. Fügen Sie PNGs unter assets/icons/netneighbor oder " +"~/.config/netneighbor/custom_icons/ hinzu." + +#: ui/ +msgid "Open folder…" +msgstr "Ordner öffnen…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "Beschädigte Installation" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"NetNeighbor kann nicht starten, da erforderliche Dateien fehlen oder beschädigt sind:\n" +"\n" +"{details}\n" +"\n" +"Bitte installieren Sie das Programm neu." + +#: ui/ +msgid "All-in-one computer" +msgstr "All-in-One-Computer" + +#: ui/ +msgid "Desktop computer" +msgstr "Desktop-Computer" + +#: ui/ +msgid "Laptop" +msgstr "Laptop" + +#: ui/ +msgid "Mini PC" +msgstr "Mini-PC" + +#: ui/ +msgid "Rack server" +msgstr "Rack-Server" + +#: ui/ +msgid "Server" +msgstr "Server" + +#: ui/ +msgid "Servers" +msgstr "Server" + +#: ui/ +msgid "Phones & Tablets" +msgstr "Telefone & Tablets" + +#: ui/ +msgid "Smartphone" +msgstr "Smartphone" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"Der Modus „disabled“ blendet den automatisch erkannten Eintrag dieses " +"Protokolls aus (bei „custom“ den globalen benutzerdefinierten Befehl); die " +"übrigen Felder werden ignoriert." + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"Verbindungsendpunkte pro Protokoll überschreiben oder hinzufügen. " +"Platzhalter: {ip}, {port}, {name}, {type}, {category}, {url}. Für das Schema" +" 'custom' ist Befehl die auszuführende Befehlszeile. Bei anderen Schemata " +"ist Befehl der Host oder die Adresse, die geöffnet werden soll (z. B. {ip}, " +"{url}, http://{ip}:8080/admin); Befehl und Port sind optional." + +#: ui/ +msgid "Could not open Spotify." +msgstr "Konnte Spotify nicht öffnen." diff --git a/app/locale/es/LC_MESSAGES/netneighbor.mo b/app/locale/es/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..c956d37e Binary files /dev/null and b/app/locale/es/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/es/LC_MESSAGES/netneighbor.po b/app/locale/es/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..e168a4d0 --- /dev/null +++ b/app/locale/es/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1425 @@ +# Spanish translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Spanish\n" +"Language: es\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "Ver" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "Recargar" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "Mostrar:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "Iconos" + +#: ui/main_window.py:113 +msgid "List" +msgstr "Lista" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "Ordenar:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "Sin ordenar" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "por Tipo" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "por Ubicación" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "Preferencias" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "Notificaciones desactivadas" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "Solo dispositivos monitoreados" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "Todos los dispositivos" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "Presets de ubicación" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "Presets de tipo" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "Mantener en ejecución en la bandeja al cerrar la ventana" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "Iniciar minimizado en la bandeja" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "Iniciar NetNeighbor al iniciar sesión" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "Salir" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "Herramientas" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "Aplicaciones externas…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "Historial de notificaciones" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "Ayuda" + +#: ui/main_window.py:214 +msgid "About" +msgstr "Acerca de" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "Inicio de sesión" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "Ahora no" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "Guardar" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "¿Ejecutar NetNeighbor en segundo plano?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"Puede mantener NetNeighbor en la bandeja del sistema al cerrar la ventana. " +"Iniciarlo con su sesión mantiene el descubrimiento de LAN en ejecución en " +"segundo plano. Puede cambiar esto en cualquier momento en Vista → " +"Preferencias." + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "Iniciar NetNeighbor cuando inicio sesión" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"Después de cerrar este diálogo, la ventana principal se oculta en la bandeja" +" del sistema — haga clic en el icono de NetNeighbor en la bandeja para " +"abrirlo (recomendado después de la instalación)." + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — Descubrimiento de LAN" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "Abrir NetNeighbor" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "Minimizar a la bandeja" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "Oficina" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "Sala" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "Sala de estar" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "Cocina" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "Taller" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "Garaje" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "Gestionar ajustes preestablecidos de ubicación." + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "" +"Añadir automáticamente las ubicaciones descubiertas en la red a esta lista" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" +"Cuando está habilitado, los nombres de salas y cadenas similares de " +"dispositivos (por ejemplo algunos altavoces) se pueden añadir a la lista de " +"ajustes preestablecidos conforme se detecten." + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "Ajuste preestablecido" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "Añadir" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "Renombrar" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "Eliminar" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "Borrar todo" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "Cancelar" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "Aceptar" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "Añadir ajuste preestablecido de ubicación" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "Renombrar ajuste preestablecido de ubicación" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "Ordenador" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "Router" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "Servidor multimedia" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "Impresora" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "Impresora multifunción" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "Impresora (red / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "Altavoz inteligente" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "TV inteligente" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "Dispositivo inteligente" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "Cámara" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "Electrodoméstico" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "Impresora 3D" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" +"Administrar presets de tipo de dispositivo que se muestran en el menú " +"contextual." + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "Etiqueta" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "ID de tipo" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "Restaurar valores predeterminados" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "Etiqueta:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "ID de tipo:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "p. ej. nas, router, cámara…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "Añadir preset de tipo" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "Renombrar preset de tipo" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "Aplicaciones externas" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "Vacío = predeterminado del sistema" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "Restablecer" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "Restaurar comando predeterminado" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "¿Restablecer este comando a su valor predeterminado?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "No" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "Sí" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "Vacío = deshabilitado" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "Limpiar" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "Eliminar el comando personalizado global" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "¿Borrar el comando personalizado global?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "Personalizado:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "dirección completa" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "IP del dispositivo" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "puerto de servicio" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "nombre del dispositivo" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "tipo de dispositivo" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "categoría" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "Créditos" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "Licencia" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "Cerrar" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "Descubra y monitoree dispositivos en su red local." + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Librerías de Python" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "Proyecto de GitHub" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "Historial de notificaciones" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "Fecha/Hora" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "Dispositivo" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "Estado" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "Sin ubicación" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "Todas las ubicaciones" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "Todos los tipos" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "Puertos" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "Tipo" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" +"Identidad IPv6 provisional — la fila resaltada parpadea mientras el " +"descubrimiento coincide con el nombre de host / IPv4." + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" +"Obteniendo icono del dispositivo en segundo plano — el mosaico parpadea " +"hasta que llega." + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "Abrir ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "Abrir" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "Ejecutar comando personalizado" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "Detalles" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "Opciones" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "Dejar de seguir" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "Monitorizar" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "Ubicación" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "Automático" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "Tipo de dispositivo" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "Renombrar dispositivo" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "Nombre personalizado" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "No se pudo iniciar el comando: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "" +"No se pudo analizar el comando personalizado (comprueba los marcadores de " +"posición)." + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "Mostrar XML sin procesar" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "Nombre" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "Dirección IP" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (link-local)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "Descripción general" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "Detalles del dispositivo" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" +"Reglas de asignación de campos por dispositivo. Selecciona filas y elimina " +"si es necesario." + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "Seleccionar" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "Destino" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "Campo de origen" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "Eliminar seleccionados" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "Eliminar todo" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "Reglas" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "Servicios" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "Servicio" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "Puerto" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "Campo" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "Valor" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "Información de solución de problemas" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "Registro" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "Registros TXT" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "Ubicación XML" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "Copiar al portapapeles" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "Datos del dispositivo" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "Anular" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "Adicional" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "Eliminar este comando" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "¿Eliminar esta entrada de comando?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ Agregar comando" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "Comando personalizado" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "p. ej. x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "¿Borrar el comando personalizado por dispositivo?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "Eliminar la anulación por dispositivo (usar comando global)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "Usar icono de:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "Sistema" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "Del dispositivo" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "Personalizado" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "Abrir carpeta de iconos personalizados" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "no disponible" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "Imagen del dispositivo" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "ninguno" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "Icono seleccionado" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "Elegir icono" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "Nombre descriptivo" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "Información" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "Usar como {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "Eliminar regla {target}" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "Regla guardada" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "Regla eliminada" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "Reglas seleccionadas eliminadas" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "Todas las reglas eliminadas" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "Sin registros TXT" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "Desconocido" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "Dispositivo HTTP" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "Dispositivo HTTPS" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "Altavoz inteligente" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "Smart TV" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "Dispositivo inteligente" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "Electrodoméstico" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "Dispositivo ESP3D" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "Escáner" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "Última vez visto" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "Fabricante" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "URL del fabricante" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "Modelo" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "URL del modelo" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "Dirección MAC" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "Número de serie" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "Identificador único" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "Nombre de host" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "Enrutadores y puertas de enlace" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "Servidores multimedia" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "Impresoras" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "Altavoces inteligentes" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "Televisores inteligentes" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "Dispositivos inteligentes" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "Cámaras" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "Electrodomésticos" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "Máquinas CNC" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "Impresoras 3D" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / Servidores de archivos" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "Computadoras" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "Dispositivos ESP3D" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "Dispositivos desconocidos" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "Acerca de NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "Logo de la app en assets/icons: Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "Aplicaciones" + +#: ui/ +msgid "Apply" +msgstr "Aplicar" + +#: ui/ +msgid "Author: Luc" +msgstr "Autor: Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "Cerrar al área de notificación en lugar de salir" + +#: ui/ +msgid "Command" +msgstr "Comando" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" +"Plantillas de comandos para abrir conexiones de dispositivos. Dejar vacío " +"para usar el valor predeterminado del sistema." + +#: ui/ +msgid "Commands" +msgstr "Comandos" + +#: ui/ +msgid "Custom command (additional)" +msgstr "Comando personalizado (adicional)" + +#: ui/ +msgid "Dark" +msgstr "Oscuro" + +#: ui/ +msgid "Date / Time" +msgstr "Fecha / Hora" + +#: ui/ +msgid "Delete" +msgstr "Eliminar" + +#: ui/ +msgid "Desktop notifications" +msgstr "Notificaciones de escritorio" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "Actualización de detección solicitada" + +#: ui/ +msgid "Edit" +msgstr "Editar" + +#: ui/ +msgid "Edit type preset" +msgstr "Editar preajuste de tipo" + +#: ui/ +msgid "Error" +msgstr "Error" + +#: ui/ +msgid "Extra large" +msgstr "Muy grande" + +#: ui/ +msgid "Field mapping rules" +msgstr "Reglas de mapeo de campos" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "Licencia Pública General Reducida de GNU versión 3 o posterior" + +#: ui/ +msgid "General" +msgstr "General" + +#: ui/ +msgid "Hidden devices" +msgstr "Dispositivos ocultos" + +#: ui/ +msgid "Hide device" +msgstr "Ocultar dispositivo" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "Borrar dispositivo" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"¿Eliminar {name} ({ip}) del caché y todas las preferencias?\n" +"\n" +"Esta acción no se puede deshacer. El dispositivo volverá a aparecer si se redescubre en la red." + +#: ui/ +msgid "Hide sidebar" +msgstr "Ocultar barra lateral" + +#: ui/ +msgid "Hide window" +msgstr "Ocultar ventana" + +#: ui/ +msgid "Icons size" +msgstr "Tamaño de iconos" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "Plantilla de comando no válida para este protocolo." + +#: ui/ +msgid "Large" +msgstr "Grande" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "Visto hace: {n} d" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "Visto hace: {n} h" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "Visto hace: {n} min" + +#: ui/ +msgid "Light" +msgstr "Claro" + +#: ui/ +msgid "Location name:" +msgstr "Nombre de ubicación:" + +#: ui/ +msgid "Locations" +msgstr "Ubicaciones" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "" +"Administrar los preajustes de ubicación mostrados en el menú contextual." + +#: ui/ +msgid "Medium" +msgstr "Mediano" + +#: ui/ +msgid "Mode" +msgstr "Modo" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "Nuevo nombre:" + +#: ui/ +msgid "No devices yet" +msgstr "Aún no hay dispositivos" + +#: ui/ +msgid "No hidden devices" +msgstr "No hay dispositivos ocultos" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" +"La entrega de notificaciones depende del sistema operativo y la sesión. El " +"comportamiento respaldado por la bandeja (cerrar en la bandeja, inicio " +"minimizado) se alineará una vez que se implemente la bandeja del sistema." + +#: ui/ +msgid "Notifications" +msgstr "Notificaciones" + +#: ui/ +msgid "Offline" +msgstr "Sin conexión" + +#: ui/ +msgid "Online" +msgstr "En línea" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"Anular o agregar puntos de conexión por protocolo. Para el esquema 'custom'," +" ingrese la plantilla de comando en IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host y Puerto son opcionales para otros esquemas." + +#: ui/ +msgid "Preferences…" +msgstr "Preferencias…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Enlaces Qt para Python" + +#: ui/ +msgid "Reload discovery" +msgstr "Recargar detección" + +#: ui/ +msgid "Scheme" +msgstr "Esquema" + +#: ui/ +msgid "See the" +msgstr "Consulte la" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "" +"Seleccione un icono, luego OK. Los IDs se guardan en sus preferencias." + +#: ui/ +msgid "Service type" +msgstr "Tipo de servicio" + +#: ui/ +msgid "Session" +msgstr "Sesión" + +#: ui/ +msgid "Show sidebar" +msgstr "Mostrar barra lateral" + +#: ui/ +msgid "Show window" +msgstr "Mostrar ventana" + +#: ui/ +msgid "Sidebar" +msgstr "Barra lateral" + +#: ui/ +msgid "Small" +msgstr "Pequeño" + +#: ui/ +msgid "Start Scanning…" +msgstr "Iniciando escaneo…" + +#: ui/ +msgid "Theme" +msgstr "Tema" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "Este programa no ofrece ningún tipo de garantía." + +#: ui/ +msgid "Types" +msgstr "Tipos" + +#: ui/ +msgid "Use as Friendly name" +msgstr "Usar como nombre descriptivo" + +#: ui/ +msgid "Use as Information" +msgstr "Usar como información" + +#: ui/ +msgid "Use as Location" +msgstr "Usar como ubicación" + +#: ui/ +msgid "Use icon from" +msgstr "Usar icono de" + +#: ui/ +msgid "Version {version}" +msgstr "Versión {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery (dispositivos Windows)" + +#: ui/ +msgid "for details." +msgstr "para más detalles." + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "Detección mDNS/DNS-SD" + +#: ui/ +msgid "not yet downloaded" +msgstr "aún no descargado" + +#: ui/ +msgid "{} devices" +msgstr "{} dispositivos" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "Mantenimiento" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "Restablecer todos los datos de la aplicación…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "¿Restablecer todos los datos de la aplicación?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"Todas las preferencias, iconos en caché, datos de descubrimiento y registros se eliminarán permanentemente:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor usará la configuración predeterminada en el próximo inicio.\n" +"Esta acción no se puede deshacer." + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "Restablecimiento completado — reinicie la aplicación" + +#: ui/ +msgid "App icon pack" +msgstr "Paquete de iconos de la aplicación" + +#: ui/ +msgid "Download failed" +msgstr "Descarga fallida" + +#: ui/ +msgid "Downloading…" +msgstr "Descargando…" + +#: ui/ +msgid "Icon pack" +msgstr "Paquete de iconos" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (integrado)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"No se encontraron iconos. Agregue PNGs en assets/icons/netneighbor o " +"~/.config/netneighbor/custom_icons/." + +#: ui/ +msgid "Open folder…" +msgstr "Abrir carpeta…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "Instalación dañada" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"NetNeighbor no puede iniciarse porque faltan archivos necesarios o están dañados:\n" +"\n" +"{details}\n" +"\n" +"Vuelva a instalar el programa." + +#: ui/ +msgid "All-in-one computer" +msgstr "Ordenador todo en uno" + +#: ui/ +msgid "Desktop computer" +msgstr "Ordenador de escritorio" + +#: ui/ +msgid "Laptop" +msgstr "Portátil" + +#: ui/ +msgid "Mini PC" +msgstr "Mini PC" + +#: ui/ +msgid "Rack server" +msgstr "Servidor rack" + +#: ui/ +msgid "Server" +msgstr "Servidor" + +#: ui/ +msgid "Servers" +msgstr "Servidores" + +#: ui/ +msgid "Phones & Tablets" +msgstr "Teléfonos y tabletas" + +#: ui/ +msgid "Smartphone" +msgstr "Smartphone" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"El modo «disabled» oculta la entrada detectada automáticamente de ese " +"protocolo (para «custom», el comando personalizado global); sus demás campos" +" se ignoran." + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"Anule o añada puntos de conexión por protocolo. Marcadores de posición: " +"{ip}, {port}, {name}, {type}, {category}, {url}. Para el esquema 'custom', " +"Comando es la línea de comandos a ejecutar. Para otros esquemas, Comando es " +"el host o dirección a abrir (p. ej. {ip}, {url}, http://{ip}:8080/admin); " +"Comando y Puerto son opcionales." + +#: ui/ +msgid "Could not open Spotify." +msgstr "No se pudo abrir Spotify." diff --git a/app/locale/fr/LC_MESSAGES/netneighbor.mo b/app/locale/fr/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..670e2886 Binary files /dev/null and b/app/locale/fr/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/fr/LC_MESSAGES/netneighbor.po b/app/locale/fr/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..1586895e --- /dev/null +++ b/app/locale/fr/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1426 @@ +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.1.0-dev\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-04-29 13:30+0800\n" +"Last-Translator: Luc\n" +"Language-Team: French\n" +"Language: fr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "Affichage" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "Recharger" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "Affichage :" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "Icônes" + +#: ui/main_window.py:113 +msgid "List" +msgstr "Liste" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "Organiser :" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "Non trié" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "par type" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "par localisation" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "Preferences" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "Notifications désactivées" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "Appareils surveillés uniquement" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "Tous les appareils" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "Présets d'emplacement" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "Présets de type" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "" +"Continuer à s'exécuter dans la barre d'état système lors de la fermeture de " +"la fenêtre" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "Démarrer réduit dans la barre d'état système" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "Démarrer NetNeighbor lors de la connexion" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "Quitter" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "Outils" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "Applications externes…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "Historique des notifications" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "Aide" + +#: ui/main_window.py:214 +msgid "About" +msgstr "A propos" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "Démarrage de session" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "Pas maintenant" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "Enregistrer" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "Exécuter NetNeighbor en arrière-plan ?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"Vous pouvez garder NetNeighbor dans la barre système lorsque vous fermez la " +"fenêtre. Le démarrer avec votre session maintient la découverte LAN active " +"en arrière-plan. Vous pouvez modifier ceci à tout moment dans Affichage → " +"Préférences." + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "Lancer NetNeighbor à la connexion" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"Après fermeture de cette boîte de dialogue, la fenêtre principale se masque " +"dans la barre système — cliquez sur l'icône NetNeighbor dans la barre " +"système pour l'ouvrir (recommandé après l'installation)." + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — Découverte LAN" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "Ouvrir NetNeighbor" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "Réduire à la barre système" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "Bureau" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "Pièce" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "Salon" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "Cuisine" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "Atelier" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "Garage" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "Gérer les présélections de localisation." + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "" +"Ajouter automatiquement les localisations découvertes sur le réseau à cette " +"liste" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" +"Lorsque cette option est activée, les noms de pièces et les chaînes " +"similaires provenant des appareils (par exemple certains haut-parleurs) " +"peuvent être ajoutés à la liste des présélections au fur et à mesure qu'ils " +"sont détectés." + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "Présélection" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "Ajouter" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "Renommer" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "Supprimer" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "Effacer tout" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "Annuler" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "OK" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "Ajouter un préset de localisation" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "Renommer un préset de localisation" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "Ordinateur" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "Routeur" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "Serveur multimedia" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "Imprimante" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "Imprimante multifonction" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "Imprimante (réseau / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "Enceinte intelligente" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "SmartTV" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "SmartDevice" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "Camera" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "HomeAppliance" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "Imprimante 3D" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" +"Gérer les présets de type d'appareil affichés dans le menu contextuel." + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "Étiquette" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "ID de type" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "Restaurer les valeurs par défaut" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "Étiquette :" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "ID de type :" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "p. ex. nas, routeur, caméra…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "Ajouter un préset de type" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "Renommer le préset de type" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "Applications externes" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "Vide = paramètre par défaut du système" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "Réinitialiser" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "Restaurer la commande par défaut" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "Réinitialiser cette commande à sa valeur par défaut ?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "Non" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "Oui" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "Vide = désactivé" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "Effacer" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "Supprimer la commande personnalisée globale" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "Effacer la commande personnalisée globale ?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "Personnalisé :" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "adresse complète" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "adresse IP du périphérique" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "port de service" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "nom du périphérique" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "type de périphérique" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "catégorie" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "Crédits" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "Licence" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "Fermer" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "Découvrez et surveillez les appareils de votre réseau local." + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Bibliothèques Python" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "Projet GitHub" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "Historique des notifications" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "Date/Heure" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "Appareil" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "État" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "Aucune localisation" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "Toutes les localisations" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "Tous les types" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "Ports" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "Type" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" +"Identité IPv6 provisoire — la ligne en surbrillance pulse pendant que la " +"découverte correspond au nom d'hôte / IPv4." + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" +"Récupération de l'icône de l'appareil en arrière-plan — la tuile pulse " +"jusqu'à son arrivée." + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "Ouvrir ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "Ouvrir" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "Exécuter une commande personnalisée" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "Details" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "Options" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "Ne plus surveiller" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "Surveiller" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "Localisation" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "Auto" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "Type d'appareil" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "Renommer l'appareil" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "Nom personnalisé" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "Impossible de démarrer la commande : {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "" +"Impossible d'analyser la commande personnalisée (vérifiez les espaces " +"réservés)." + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "Afficher le XML brut" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "Nom" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "Adresse IP" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (lien-local)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "Aperçu" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "Details appareil" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" +"Règles de mappage des champs par appareil. Sélectionnez les lignes et " +"supprimez si nécessaire." + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "Sélectionner" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "Cible" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "Champ source" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "Supprimer la sélection" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "Tout supprimer" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "Règles" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "Services" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "Service" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "Port" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "Champ" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "Valeur" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "Informations de dépannage" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "Enregistrement" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "Enregistrements TXT" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "Emplacement XML" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "Copier dans le presse-papiers" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "Donnees appareil" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "Remplacer" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "Supplémentaire" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "Adresse IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "Supprimer cette commande" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "Supprimer cette entrée de commande ?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ Ajouter une commande" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "Commande personnalisée" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "p. ex. x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "Effacer la commande personnalisée par appareil ?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "Supprimer le remplacement par appareil (utiliser la commande globale)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "Utiliser l'icône de :" + +#: ui/device_details.py:587 +msgid "System" +msgstr "Système" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "Depuis l'appareil" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "Personnalisé" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "Ouvrir le dossier des icônes personnalisées" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "indisponible" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "Image de l'appareil" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "aucun" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "Icône sélectionnée" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "Choisir une icône" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "Nom convivial" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "Informations" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "Utiliser comme {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "Supprimer la règle {target}" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "Règle enregistrée" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "Règle supprimée" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "Règles sélectionnées supprimées" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "Toutes les règles supprimées" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "Aucun enregistrement TXT" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "Inconnu" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "Appareil HTTP" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "Appareil HTTPS" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "Enceinte intelligente" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "Téléviseur intelligent" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "Appareil intelligent" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "Électroménager" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "Appareil ESP3D" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "Analyseur" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "Derniere apparition" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "Fabricant" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "URL du fabricant" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "Modèle" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "URL du modèle" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "Adresse MAC" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "Numéro de série" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "Identifiant unique" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "Nom d'hôte" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "Routeurs et passerelles" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "Serveurs multimédias" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "Imprimantes" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "Enceintes intelligentes" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "Téléviseurs intelligents" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "Appareils intelligents" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "Caméras" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "Électroménagers" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "Machines CNC" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "Imprimantes 3D" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / Serveurs de fichiers" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "Ordinateurs" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "Appareils ESP3D" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "Appareils inconnus" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "À propos de NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "Logo de l'application dans assets/icons : Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "Applications" + +#: ui/ +msgid "Apply" +msgstr "Appliquer" + +#: ui/ +msgid "Author: Luc" +msgstr "Auteur : Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "Réduire dans la barre système au lieu de quitter" + +#: ui/ +msgid "Command" +msgstr "Commande" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" +"Modèles de commandes pour ouvrir les connexions d'appareils. Laisser vide " +"pour utiliser le défaut système." + +#: ui/ +msgid "Commands" +msgstr "Commandes" + +#: ui/ +msgid "Custom command (additional)" +msgstr "Commande personnalisée (supplémentaire)" + +#: ui/ +msgid "Dark" +msgstr "Sombre" + +#: ui/ +msgid "Date / Time" +msgstr "Date / Heure" + +#: ui/ +msgid "Delete" +msgstr "Supprimer" + +#: ui/ +msgid "Desktop notifications" +msgstr "Notifications de bureau" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "Actualisation de la découverte demandée" + +#: ui/ +msgid "Edit" +msgstr "Modifier" + +#: ui/ +msgid "Edit type preset" +msgstr "Modifier le préréglage de type" + +#: ui/ +msgid "Error" +msgstr "Erreur" + +#: ui/ +msgid "Extra large" +msgstr "Très grand" + +#: ui/ +msgid "Field mapping rules" +msgstr "Règles de mappage de champs" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "Licence publique générale limitée GNU version 3 ou ultérieure" + +#: ui/ +msgid "General" +msgstr "Général" + +#: ui/ +msgid "Hidden devices" +msgstr "Appareils masqués" + +#: ui/ +msgid "Hide device" +msgstr "Masquer l'appareil" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "Effacer l'appareil" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"Supprimer {name} ({ip}) du cache et de toutes les préférences ?\n" +"\n" +"Cette action est irréversible. L'appareil réapparaîtra s'il est redécouvert sur le réseau." + +#: ui/ +msgid "Hide sidebar" +msgstr "Masquer la barre latérale" + +#: ui/ +msgid "Hide window" +msgstr "Masquer la fenêtre" + +#: ui/ +msgid "Icons size" +msgstr "Taille des icônes" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "Modèle de commande invalide pour ce protocole." + +#: ui/ +msgid "Large" +msgstr "Grand" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "Vu il y a : {n} j" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "Vu il y a : {n} h" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "Vu il y a : {n} min" + +#: ui/ +msgid "Light" +msgstr "Clair" + +#: ui/ +msgid "Location name:" +msgstr "Nom de l'emplacement :" + +#: ui/ +msgid "Locations" +msgstr "Emplacements" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "Gérer les préréglages de lieu affichés dans le menu contextuel." + +#: ui/ +msgid "Medium" +msgstr "Moyen" + +#: ui/ +msgid "Mode" +msgstr "Mode" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "Nouveau nom :" + +#: ui/ +msgid "No devices yet" +msgstr "Aucun appareil pour l'instant" + +#: ui/ +msgid "No hidden devices" +msgstr "Aucun appareil masqué" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" +"La livraison des notifications dépend du système d'exploitation et de la " +"session. Le comportement basé sur la barre système (fermeture dans la barre," +" démarrage minimisé) sera aligné une fois la barre système implémentée." + +#: ui/ +msgid "Notifications" +msgstr "Notifications" + +#: ui/ +msgid "Offline" +msgstr "Hors ligne" + +#: ui/ +msgid "Online" +msgstr "En ligne" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"Remplacez ou ajoutez des points de connexion par protocole. Pour le schème " +"'custom', entrez le modèle de commande dans IP/Hôte ({ip}, {ip_raw}, {port}," +" {name}, {type}, {category}, {url}). IP/Hôte et Port sont optionnels pour " +"les autres schèmes." + +#: ui/ +msgid "Preferences…" +msgstr "Préférences…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Liaisons Qt pour Python" + +#: ui/ +msgid "Reload discovery" +msgstr "Recharger la découverte" + +#: ui/ +msgid "Scheme" +msgstr "Schème" + +#: ui/ +msgid "See the" +msgstr "Voir la" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "" +"Sélectionnez une icône, puis OK. Les IDs sont enregistrés dans vos " +"préférences." + +#: ui/ +msgid "Service type" +msgstr "Type de service" + +#: ui/ +msgid "Session" +msgstr "Session" + +#: ui/ +msgid "Show sidebar" +msgstr "Afficher la barre latérale" + +#: ui/ +msgid "Show window" +msgstr "Afficher la fenêtre" + +#: ui/ +msgid "Sidebar" +msgstr "Barre latérale" + +#: ui/ +msgid "Small" +msgstr "Petit" + +#: ui/ +msgid "Start Scanning…" +msgstr "Démarrage du scan…" + +#: ui/ +msgid "Theme" +msgstr "Thème" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "Ce programme ne comporte absolument aucune garantie." + +#: ui/ +msgid "Types" +msgstr "Types" + +#: ui/ +msgid "Use as Friendly name" +msgstr "Utiliser comme nom convivial" + +#: ui/ +msgid "Use as Information" +msgstr "Utiliser comme informations" + +#: ui/ +msgid "Use as Location" +msgstr "Utiliser comme emplacement" + +#: ui/ +msgid "Use icon from" +msgstr "Utiliser l'icône de" + +#: ui/ +msgid "Version {version}" +msgstr "Version {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery (appareils Windows)" + +#: ui/ +msgid "for details." +msgstr "pour plus de détails." + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "Découverte mDNS/DNS-SD" + +#: ui/ +msgid "not yet downloaded" +msgstr "pas encore téléchargé" + +#: ui/ +msgid "{} devices" +msgstr "{} appareils" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "Maintenance" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "Réinitialiser toutes les données…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "Réinitialiser toutes les données ?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"Toutes les préférences, icônes en cache, données de découverte et journaux seront supprimés définitivement :\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor utilisera les paramètres par défaut au prochain démarrage.\n" +"Cette action est irréversible." + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "Réinitialisation effectuée — veuillez redémarrer" + +#: ui/ +msgid "App icon pack" +msgstr "Pack d'icônes d'application" + +#: ui/ +msgid "Download failed" +msgstr "Téléchargement échoué" + +#: ui/ +msgid "Downloading…" +msgstr "Téléchargement…" + +#: ui/ +msgid "Icon pack" +msgstr "Pack d'icônes" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (intégré)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"Aucune icône trouvée. Ajoutez des PNG dans assets/icons/netneighbor ou " +"~/.config/netneighbor/custom_icons/." + +#: ui/ +msgid "Open folder…" +msgstr "Ouvrir le dossier…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "Installation corrompue" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"NetNeighbor ne peut pas démarrer car des fichiers requis sont manquants ou corrompus :\n" +"\n" +"{details}\n" +"\n" +"Veuillez réinstaller le programme." + +#: ui/ +msgid "All-in-one computer" +msgstr "Ordinateur tout-en-un" + +#: ui/ +msgid "Desktop computer" +msgstr "Ordinateur de bureau" + +#: ui/ +msgid "Laptop" +msgstr "Ordinateur portable" + +#: ui/ +msgid "Mini PC" +msgstr "Mini PC" + +#: ui/ +msgid "Rack server" +msgstr "Serveur en rack" + +#: ui/ +msgid "Server" +msgstr "Serveur" + +#: ui/ +msgid "Servers" +msgstr "Serveurs" + +#: ui/ +msgid "Phones & Tablets" +msgstr "Téléphones et tablettes" + +#: ui/ +msgid "Smartphone" +msgstr "Smartphone" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"Le mode « disabled » masque l'entrée détectée automatiquement pour ce " +"protocole (pour « custom », la commande personnalisée globale) ; ses autres " +"champs sont ignorés." + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"Remplacer ou ajouter des points de terminaison de connexion par protocole. " +"Espaces réservés : {ip}, {port}, {name}, {type}, {category}, {url}. Pour le " +"schéma « custom », la commande est la ligne de commande à exécuter. Pour les" +" autres schémas, la commande est l'hôte ou l'adresse à ouvrir (par exemple " +"{ip}, {url}, http://{ip}:8080/admin) ; la commande et le port sont " +"facultatifs." + +#: ui/ +msgid "Could not open Spotify." +msgstr "Impossible d'ouvrir Spotify." diff --git a/app/locale/it/LC_MESSAGES/netneighbor.mo b/app/locale/it/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..4ead6f9e Binary files /dev/null and b/app/locale/it/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/it/LC_MESSAGES/netneighbor.po b/app/locale/it/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..ed5d605d --- /dev/null +++ b/app/locale/it/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1423 @@ +# Italian translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Italian\n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "Visualizza" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "Ricarica" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "Visualizzazione:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "Icone" + +#: ui/main_window.py:113 +msgid "List" +msgstr "Elenco" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "Ordina:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "Non ordinato" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "per Tipo" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "per Posizione" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "Preferenze" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "Notifiche disattivate" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "Solo dispositivi monitorati" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "Tutti i dispositivi" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "Preset di posizione" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "Predefinizioni di tipo" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "Continua l'esecuzione nel vassoio quando chiudi la finestra" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "Avvia ridotto a icona nel vassoio" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "Avvia NetNeighbor all'accesso" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "Esci" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "Strumenti" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "Applicazioni esterne…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "Cronologia notifiche" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "Aiuto" + +#: ui/main_window.py:214 +msgid "About" +msgstr "Informazioni" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "Avvio della sessione" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "Non adesso" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "Salva" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "Eseguire NetNeighbor in background?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"Puoi mantenere NetNeighbor nel vassoio di sistema quando chiudi la finestra." +" Avviarlo con la tua sessione mantiene la scoperta LAN in esecuzione in " +"background. Puoi modificare questa impostazione in qualsiasi momento in " +"Visualizza → Preferenze." + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "Avvia NetNeighbor all'accesso" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"Dopo aver chiuso questa finestra di dialogo, la finestra principale si " +"nasconde nel vassoio di sistema — fai clic sull'icona NetNeighbor nel " +"vassoio per aprirla (consigliato dopo l'installazione)." + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — Scoperta LAN" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "Apri NetNeighbor" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "Riduci a icona" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "Ufficio" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "Stanza" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "Soggiorno" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "Cucina" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "Laboratorio" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "Garage" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "Gestisci i preset di posizione." + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "" +"Aggiungi automaticamente le posizioni scoperte sulla rete a questo elenco" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" +"Se abilitato, i nomi delle stanze e stringhe simili dai dispositivi (ad " +"esempio alcuni altoparlanti) possono essere aggiunti all'elenco dei preset " +"mentre vengono rilevati." + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "Preset" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "Aggiungi" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "Rinomina" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "Rimuovi" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "Cancella tutto" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "Annulla" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "OK" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "Aggiungi preset di posizione" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "Rinomina preset di posizione" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "Computer" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "Router" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "Media server" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "Stampante" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "Stampante multifunzione" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "Stampante (rete / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "SmartSpeaker" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "SmartTV" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "SmartDevice" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "Fotocamera" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "Elettrodomestico" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "Stampante 3D" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" +"Gestisci le predefinizioni di tipo di dispositivo visualizzate nel menu di " +"scelta rapida." + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "Etichetta" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "ID tipo" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "Ripristina predefinizioni" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "Etichetta:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "ID tipo:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "ad es. nas, router, fotocamera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "Aggiungi predefinizione di tipo" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "Rinomina predefinizione di tipo" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "Applicazioni esterne" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "Vuoto = impostazione predefinita di sistema" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "Ripristina" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "Ripristina comando predefinito" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "Ripristinare questo comando al valore predefinito?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "No" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "Sì" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "Vuoto = disabilitato" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "Cancella" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "Rimuovi il comando personalizzato globale" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "Cancellare il comando personalizzato globale?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "Personalizzato:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "indirizzo completo" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "IP dispositivo" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "porta servizio" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "nome dispositivo" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "tipo dispositivo" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "categoria" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "Crediti" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "Licenza" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "Chiudi" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "Scopri e monitora i dispositivi sulla tua rete locale." + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Librerie Python" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "Progetto GitHub" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "Cronologia notifiche" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "Data/Ora" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "Dispositivo" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "Stato" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "Nessuna posizione" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "Tutte le posizioni" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "Tutti i tipi" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "Porte" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "Tipo" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" +"Identità IPv6 provvisoria — la riga evidenziata pulsa mentre " +"l'individuazione corrisponde al nome host / IPv4." + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" +"Recupero icona dispositivo in background — il riquadro pulsa fino al suo " +"arrivo." + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "Apri ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "Apri" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "Esegui comando personalizzato" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "Dettagli" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "Opzioni" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "Smetti di seguire" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "Monitora" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "Posizione" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "Automatico" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "Tipo di dispositivo" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "Rinomina dispositivo" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "Nome personalizzato" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "Impossibile avviare il comando: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "" +"Impossibile analizzare il comando personalizzato (controllare i segnaposti)." + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "Mostra XML grezzo" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "Nome" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "Indirizzo IP" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (link-local)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "Panoramica" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "Dettagli dispositivo" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" +"Regole di mappatura dei campi per dispositivo. Selezionare le righe e " +"rimuovere se necessario." + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "Seleziona" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "Destinazione" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "Campo sorgente" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "Rimuovi selezionati" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "Rimuovi tutto" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "Regole" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "Servizi" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "Servizio" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "Porta" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "Campo" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "Valore" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "Informazioni sulla risoluzione dei problemi" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "Record" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "Record TXT" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "Posizione XML" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "Copia negli appunti" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "Dati del dispositivo" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "Sovrascrivi" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "Aggiuntivo" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "Rimuovi questo comando" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "Rimuovere questa voce di comando?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ Aggiungi comando" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "Comando personalizzato" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "es. x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "Cancellare il comando personalizzato per dispositivo?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "Rimuovi override per dispositivo (usa comando globale)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "Usa icona da:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "Sistema" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "Dal dispositivo" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "Personalizzato" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "Apri cartella icone personalizzate" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "non disponibile" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "Immagine dal dispositivo" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "nessuno" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "Icona selezionata" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "Scegli icona" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "Nome descrittivo" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "Informazioni" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "Usa come {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "Rimuovi regola {target}" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "Regola salvata" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "Regola rimossa" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "Regole selezionate rimosse" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "Tutte le regole rimosse" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "Nessun record TXT" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "Sconosciuto" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "Dispositivo HTTP" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "Dispositivo HTTPS" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "Altoparlante intelligente" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "TV intelligente" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "Dispositivo intelligente" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "Elettrodomestico" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "Dispositivo ESP3D" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "Scanner" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "Ultimo avvistamento" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "Produttore" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "URL del produttore" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "Modello" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "URL del modello" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "Indirizzo MAC" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "Numero di serie" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "Identificativo univoco" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "Nome host" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "Router e Gateway" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "Server Multimediali" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "Stampanti" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "Smart Speaker" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "Smart TV" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "Dispositivi Intelligenti" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "Telecamere" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "Elettrodomestici" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "Macchine CNC" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "Stampanti 3D" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / Server di file" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "Computer" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "Dispositivi ESP3D" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "Dispositivi Sconosciuti" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "Informazioni su NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "Logo app in assets/icons: Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "Applicazioni" + +#: ui/ +msgid "Apply" +msgstr "Applica" + +#: ui/ +msgid "Author: Luc" +msgstr "Autore: Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "Chiudi nell'area di notifica invece di uscire" + +#: ui/ +msgid "Command" +msgstr "Comando" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" +"Modelli di comandi per aprire connessioni ai dispositivi. Lasciare vuoto per" +" usare il predefinito di sistema." + +#: ui/ +msgid "Commands" +msgstr "Comandi" + +#: ui/ +msgid "Custom command (additional)" +msgstr "Comando personalizzato (aggiuntivo)" + +#: ui/ +msgid "Dark" +msgstr "Scuro" + +#: ui/ +msgid "Date / Time" +msgstr "Data / Ora" + +#: ui/ +msgid "Delete" +msgstr "Elimina" + +#: ui/ +msgid "Desktop notifications" +msgstr "Notifiche desktop" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "Aggiornamento rilevamento richiesto" + +#: ui/ +msgid "Edit" +msgstr "Modifica" + +#: ui/ +msgid "Edit type preset" +msgstr "Modifica preset tipo" + +#: ui/ +msgid "Error" +msgstr "Errore" + +#: ui/ +msgid "Extra large" +msgstr "Extra grande" + +#: ui/ +msgid "Field mapping rules" +msgstr "Regole di mappatura campi" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "Licenza pubblica generica minore GNU versione 3 o successiva" + +#: ui/ +msgid "General" +msgstr "Generale" + +#: ui/ +msgid "Hidden devices" +msgstr "Dispositivi nascosti" + +#: ui/ +msgid "Hide device" +msgstr "Nascondi dispositivo" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "Cancella dispositivo" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"Rimuovere {name} ({ip}) dalla cache e da tutte le preferenze?\n" +"\n" +"Questa azione non può essere annullata. Il dispositivo riapparirà se viene riscoperto nella rete." + +#: ui/ +msgid "Hide sidebar" +msgstr "Nascondi barra laterale" + +#: ui/ +msgid "Hide window" +msgstr "Nascondi finestra" + +#: ui/ +msgid "Icons size" +msgstr "Dimensione icone" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "Modello di comando non valido per questo protocollo." + +#: ui/ +msgid "Large" +msgstr "Grande" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "Visto: {n} g fa" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "Visto: {n} h fa" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "Visto: {n} min fa" + +#: ui/ +msgid "Light" +msgstr "Chiaro" + +#: ui/ +msgid "Location name:" +msgstr "Nome posizione:" + +#: ui/ +msgid "Locations" +msgstr "Posizioni" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "Gestisci i preset di posizione mostrati nel menu contestuale." + +#: ui/ +msgid "Medium" +msgstr "Medio" + +#: ui/ +msgid "Mode" +msgstr "Modalità" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "Nuovo nome:" + +#: ui/ +msgid "No devices yet" +msgstr "Nessun dispositivo ancora" + +#: ui/ +msgid "No hidden devices" +msgstr "Nessun dispositivo nascosto" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" +"La consegna delle notifiche dipende dal sistema operativo e dalla sessione. " +"Il comportamento basato sul vassoio (chiusura nel vassoio, avvio " +"minimizzato) sarà allineato una volta implementato il vassoio di sistema." + +#: ui/ +msgid "Notifications" +msgstr "Notifiche" + +#: ui/ +msgid "Offline" +msgstr "Offline" + +#: ui/ +msgid "Online" +msgstr "Online" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"Sovrascrivere o aggiungere endpoint di connessione per protocollo. Per lo " +"schema 'custom', inserire il modello di comando in IP/Host ({ip}, {port}, " +"{name}, {type}, {category}, {url}). IP/Host e Porta sono opzionali per altri" +" schemi." + +#: ui/ +msgid "Preferences…" +msgstr "Preferenze…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Binding Qt per Python" + +#: ui/ +msgid "Reload discovery" +msgstr "Ricarica rilevamento" + +#: ui/ +msgid "Scheme" +msgstr "Schema" + +#: ui/ +msgid "See the" +msgstr "Vedere la" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "Seleziona un'icona, poi OK. Gli ID vengono salvati nelle preferenze." + +#: ui/ +msgid "Service type" +msgstr "Tipo di servizio" + +#: ui/ +msgid "Session" +msgstr "Sessione" + +#: ui/ +msgid "Show sidebar" +msgstr "Mostra barra laterale" + +#: ui/ +msgid "Show window" +msgstr "Mostra finestra" + +#: ui/ +msgid "Sidebar" +msgstr "Barra laterale" + +#: ui/ +msgid "Small" +msgstr "Piccolo" + +#: ui/ +msgid "Start Scanning…" +msgstr "Avvio scansione…" + +#: ui/ +msgid "Theme" +msgstr "Tema" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "Questo programma non fornisce assolutamente alcuna garanzia." + +#: ui/ +msgid "Types" +msgstr "Tipi" + +#: ui/ +msgid "Use as Friendly name" +msgstr "Usa come nome descrittivo" + +#: ui/ +msgid "Use as Information" +msgstr "Usa come informazioni" + +#: ui/ +msgid "Use as Location" +msgstr "Usa come posizione" + +#: ui/ +msgid "Use icon from" +msgstr "Usa icona da" + +#: ui/ +msgid "Version {version}" +msgstr "Versione {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery (dispositivi Windows)" + +#: ui/ +msgid "for details." +msgstr "per i dettagli." + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "Rilevamento mDNS/DNS-SD" + +#: ui/ +msgid "not yet downloaded" +msgstr "non ancora scaricato" + +#: ui/ +msgid "{} devices" +msgstr "{} dispositivi" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "Manutenzione" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "Reimposta tutti i dati dell'applicazione…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "Reimpostare tutti i dati dell'applicazione?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"Tutte le preferenze, le icone nella cache, i dati di rilevamento e i log verranno eliminati definitivamente:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor utilizzerà le impostazioni predefinite al prossimo avvio.\n" +"Questa azione non può essere annullata." + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "Reimpostazione eseguita — riavviare l'applicazione" + +#: ui/ +msgid "App icon pack" +msgstr "Pacchetto icone app" + +#: ui/ +msgid "Download failed" +msgstr "Download non riuscito" + +#: ui/ +msgid "Downloading…" +msgstr "Download in corso…" + +#: ui/ +msgid "Icon pack" +msgstr "Pacchetto icone" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (integrato)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"Nessuna icona trovata. Aggiungere PNG in assets/icons/netneighbor o " +"~/.config/netneighbor/custom_icons/." + +#: ui/ +msgid "Open folder…" +msgstr "Apri cartella…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "Installazione danneggiata" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"NetNeighbor non può avviarsi perché alcuni file necessari mancano o sono danneggiati:\n" +"\n" +"{details}\n" +"\n" +"Reinstalla il programma." + +#: ui/ +msgid "All-in-one computer" +msgstr "Computer all-in-one" + +#: ui/ +msgid "Desktop computer" +msgstr "Computer desktop" + +#: ui/ +msgid "Laptop" +msgstr "Laptop" + +#: ui/ +msgid "Mini PC" +msgstr "Mini PC" + +#: ui/ +msgid "Rack server" +msgstr "Server rack" + +#: ui/ +msgid "Server" +msgstr "Server" + +#: ui/ +msgid "Servers" +msgstr "Server" + +#: ui/ +msgid "Phones & Tablets" +msgstr "Telefoni e tablet" + +#: ui/ +msgid "Smartphone" +msgstr "Smartphone" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"La modalità «disabled» nasconde la voce rilevata automaticamente per quel " +"protocollo (per «custom», il comando personalizzato globale); gli altri " +"campi vengono ignorati." + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"Sostituisci o aggiungi endpoint di connessione per protocollo. Segnaposti: " +"{ip}, {port}, {name}, {type}, {category}, {url}. Per lo schema 'custom', " +"Comando è la riga di comando da eseguire. Per altri schemi, Comando è l'host" +" o l'indirizzo da aprire (ad es. {ip}, {url}, http://{ip}:8080/admin); " +"Comando e Porta sono facoltativi." + +#: ui/ +msgid "Could not open Spotify." +msgstr "Impossibile aprire Spotify." diff --git a/app/locale/ja/LC_MESSAGES/netneighbor.mo b/app/locale/ja/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..2059d0bc Binary files /dev/null and b/app/locale/ja/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/ja/LC_MESSAGES/netneighbor.po b/app/locale/ja/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..9236eee5 --- /dev/null +++ b/app/locale/ja/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1396 @@ +# Japanese translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Japanese\n" +"Language: ja\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "表示" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "再読み込み" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "表示:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "アイコン" + +#: ui/main_window.py:113 +msgid "List" +msgstr "リスト" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "並べ方:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "未分類" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "タイプ別" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "場所別" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "設定" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "通知をオフ" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "監視対象デバイスのみ" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "すべてのデバイス" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "位置情報プリセット" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "タイププリセット" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "ウィンドウを閉じるときトレイで実行し続ける" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "最小化してトレイで起動" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "ログイン時にNetNeighborを起動" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "終了" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "ツール" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "外部アプリケーション…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "通知履歴" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "ヘルプ" + +#: ui/main_window.py:214 +msgid "About" +msgstr "について" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "セッション起動" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "後で" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "保存" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "NetNeighborをバックグラウンドで実行しますか?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"ウィンドウを閉じるときNetNeighborをシステムトレイに保持できます。セッションで起動すると、LAN検出がバックグラウンドで実行されます。この設定はいつでも[表示]" +" → [設定]で変更できます。" + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "ログイン時にNetNeighborを起動" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"このダイアログを閉じた後、メインウィンドウはシステムトレイに非表示になります。NetNeighborトレイアイコンをクリックして開きます(インストール後の推奨)。" + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — LAN検出" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "NetNeighborを開く" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "トレイに最小化" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "オフィス" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "部屋" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "リビングルーム" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "キッチン" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "ワークショップ" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "ガレージ" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "ロケーションプリセットを管理します。" + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "ネットワークで検出されたロケーションをこのリストに自動的に追加" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "有効にすると、デバイスからのルーム名および類似の文字列(例えば、いくつかのスピーカー)を検出したときにプリセットリストに追加できます。" + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "プリセット" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "追加" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "名前変更" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "削除" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "すべてクリア" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "キャンセル" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "OK" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "ロケーションプリセットを追加" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "ロケーションプリセットの名前を変更" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "コンピューター" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "ルーター" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "メディアサーバー" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "プリンター" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "複合機" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "プリンター (ネットワーク / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "スマートスピーカー" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "スマートTV" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "スマートデバイス" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "カメラ" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "家庭用電化製品" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "3Dプリンター" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "右クリックメニューに表示されるデバイスタイプのプリセットを管理します。" + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "ラベル" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "タイプ ID" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "デフォルトに戻す" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "ラベル:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "タイプ ID:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "例: nas、router、camera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "タイププリセットを追加" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "タイププリセットの名前を変更" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "外部アプリケーション" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "空白 = システムデフォルト" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "リセット" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "デフォルトコマンドを復元" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "このコマンドをデフォルト値にリセットしますか?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "いいえ" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "はい" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "空白 = 無効" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "クリア" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "グローバルカスタムコマンドを削除" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "グローバルカスタムコマンドをクリアしますか?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "カスタム:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "完全なアドレス" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "デバイス IP" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "サービスポート" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "デバイス名" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "デバイスタイプ" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "カテゴリ" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "クレジット" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "ライセンス" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "閉じる" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "ローカルネットワーク上のデバイスを検出して監視します。" + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Pythonライブラリ" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "GitHubプロジェクト" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "通知履歴" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "日時" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "デバイス" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "ステータス" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "場所なし" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "すべての場所" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "すべてのタイプ" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "ポート" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "タイプ" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "仮のIPv6 ID — 検出がホスト名/IPv4と一致している間、強調表示された行が点滅します。" + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "背景でデバイスアイコンを取得中 — 到着するまでタイルが点滅します。" + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "開く ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "開く" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "カスタムコマンドを実行" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "詳細" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "オプション" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "フォローを解除" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "監視" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "場所" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "自動" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "デバイスタイプ" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "デバイスの名前を変更" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "カスタム名" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "コマンドを開始できませんでした: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "カスタムコマンドを解析できませんでした (プレースホルダーを確認してください)。" + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "生のXMLを表示" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "名前" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "IPアドレス" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (リンクローカル)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "概要" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "デバイスの詳細" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "デバイスごとのフィールドマッピングルール。必要に応じて行を選択して削除します。" + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "選択" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "ターゲット" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "ソースフィールド" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "選択項目を削除" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "すべて削除" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "ルール" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "サービス" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "サービス" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "ポート" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "フィールド" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "値" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "トラブルシューティング情報" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "レコード" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "TXTレコード" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "XML の場所" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "クリップボードにコピー" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "デバイスデータ" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "上書き" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "追加" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "このコマンドを削除" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "このコマンドエントリを削除しますか?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ コマンドを追加" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "カスタムコマンド" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "例: x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "デバイスごとのカスタムコマンドをクリアしますか?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "デバイスごとのオーバーライドを削除(グローバルコマンドを使用)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "アイコンの取得元:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "システム" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "デバイスから" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "カスタム" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "カスタムアイコンフォルダを開く" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "利用不可" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "デバイスからの画像" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "なし" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "選択されたアイコン" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "アイコンを選択" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "フレンドリー名" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "情報" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "{target}として使用" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "{target}ルールを削除" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "ルールが保存されました" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "ルールが削除されました" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "選択したルールが削除されました" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "すべてのルールが削除されました" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "TXTレコードなし" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "不明" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "HTTPデバイス" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "HTTPSデバイス" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "スマートスピーカー" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "スマートTV" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "スマートデバイス" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "ホームアプライアンス" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "ESP3D デバイス" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "スキャナー" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "最後に見た" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "製造元" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "製造元のURL" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "モデル" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "モデルURL" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "MACアドレス" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "シリアル番号" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "一意の識別子" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "ホスト名" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "ルーター&ゲートウェイ" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "メディアサーバー" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "プリンター" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "スマートスピーカー" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "スマートテレビ" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "スマートデバイス" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "カメラ" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "家電" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "CNCマシン" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "3D プリンター" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / ファイルサーバー" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "コンピューター" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "ESP3D デバイス" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "不明なデバイス" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "NetNeighbor について" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "アプリロゴ(assets/icons): Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "アプリケーション" + +#: ui/ +msgid "Apply" +msgstr "適用" + +#: ui/ +msgid "Author: Luc" +msgstr "作者: Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "終了の代わりにシステムトレイに閉じる" + +#: ui/ +msgid "Command" +msgstr "コマンド" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "デバイス接続を開くためのコマンドテンプレート。システムのデフォルトを使用するには空白のままにしてください。" + +#: ui/ +msgid "Commands" +msgstr "コマンド" + +#: ui/ +msgid "Custom command (additional)" +msgstr "カスタムコマンド(追加)" + +#: ui/ +msgid "Dark" +msgstr "ダーク" + +#: ui/ +msgid "Date / Time" +msgstr "日付 / 時刻" + +#: ui/ +msgid "Delete" +msgstr "削除" + +#: ui/ +msgid "Desktop notifications" +msgstr "デスクトップ通知" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "検出の更新を要求しました" + +#: ui/ +msgid "Edit" +msgstr "編集" + +#: ui/ +msgid "Edit type preset" +msgstr "タイププリセットを編集" + +#: ui/ +msgid "Error" +msgstr "エラー" + +#: ui/ +msgid "Extra large" +msgstr "特大" + +#: ui/ +msgid "Field mapping rules" +msgstr "フィールドマッピングルール" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "GNU劣等一般公衆利用許諾書 バージョン3以降" + +#: ui/ +msgid "General" +msgstr "一般" + +#: ui/ +msgid "Hidden devices" +msgstr "非表示デバイス" + +#: ui/ +msgid "Hide device" +msgstr "デバイスを非表示" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "デバイスを削除" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"{name}({ip})をキャッシュとすべての設定から削除しますか?\n" +"\n" +"この操作は元に戻せません。ネットワークで再検出された場合、デバイスは再び表示されます。" + +#: ui/ +msgid "Hide sidebar" +msgstr "サイドバーを非表示" + +#: ui/ +msgid "Hide window" +msgstr "ウィンドウを非表示" + +#: ui/ +msgid "Icons size" +msgstr "アイコンサイズ" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "このプロトコルに対するコマンドテンプレートが無効です。" + +#: ui/ +msgid "Large" +msgstr "大" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "最終確認: {n} 日前" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "最終確認: {n} 時間前" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "最終確認: {n} 分前" + +#: ui/ +msgid "Light" +msgstr "ライト" + +#: ui/ +msgid "Location name:" +msgstr "場所の名前:" + +#: ui/ +msgid "Locations" +msgstr "場所" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "右クリックメニューに表示される場所プリセットを管理します。" + +#: ui/ +msgid "Medium" +msgstr "中" + +#: ui/ +msgid "Mode" +msgstr "モード" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "新しい名前:" + +#: ui/ +msgid "No devices yet" +msgstr "デバイスがありません" + +#: ui/ +msgid "No hidden devices" +msgstr "非表示デバイスなし" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "通知の配信はOSとセッションに依存します。トレイベースの動作(トレイに閉じる、最小化起動)はシステムトレイが実装されると揃います。" + +#: ui/ +msgid "Notifications" +msgstr "通知" + +#: ui/ +msgid "Offline" +msgstr "オフライン" + +#: ui/ +msgid "Online" +msgstr "オンライン" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"プロトコルごとに接続エンドポイントを上書きまたは追加します。'custom' スキームの場合、IP/ホスト ({ip}, {port}, {name}," +" {type}, {category}, {url}) のコマンドテンプレートを入力してください。IP/ホストとポートは他のスキームでは省略可能です。" + +#: ui/ +msgid "Preferences…" +msgstr "設定…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Qt for Python バインディング" + +#: ui/ +msgid "Reload discovery" +msgstr "検出を再読み込み" + +#: ui/ +msgid "Scheme" +msgstr "スキーム" + +#: ui/ +msgid "See the" +msgstr "詳細については" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "アイコンを選択してOKを押してください。IDは設定に保存されます。" + +#: ui/ +msgid "Service type" +msgstr "サービスタイプ" + +#: ui/ +msgid "Session" +msgstr "セッション" + +#: ui/ +msgid "Show sidebar" +msgstr "サイドバーを表示" + +#: ui/ +msgid "Show window" +msgstr "ウィンドウを表示" + +#: ui/ +msgid "Sidebar" +msgstr "サイドバー" + +#: ui/ +msgid "Small" +msgstr "小" + +#: ui/ +msgid "Start Scanning…" +msgstr "スキャン中…" + +#: ui/ +msgid "Theme" +msgstr "テーマ" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "このプログラムには一切の保証がありません。" + +#: ui/ +msgid "Types" +msgstr "タイプ" + +#: ui/ +msgid "Use as Friendly name" +msgstr "フレンドリー名として使用" + +#: ui/ +msgid "Use as Information" +msgstr "情報として使用" + +#: ui/ +msgid "Use as Location" +msgstr "場所として使用" + +#: ui/ +msgid "Use icon from" +msgstr "アイコンを使用する場所:" + +#: ui/ +msgid "Version {version}" +msgstr "バージョン {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery(Windowsデバイス)" + +#: ui/ +msgid "for details." +msgstr "を参照してください。" + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "mDNS/DNS-SD 検出" + +#: ui/ +msgid "not yet downloaded" +msgstr "まだダウンロードされていません" + +#: ui/ +msgid "{} devices" +msgstr "{} デバイス" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "メンテナンス" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "すべてのアプリデータをリセット…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "すべてのアプリデータをリセットしますか?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"すべての設定、キャッシュされたアイコン、探索データおよびログが完全に削除されます:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"次回起動時にデフォルト設定が使用されます。\n" +"この操作は元に戻せません。" + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "リセット完了 — 再起動してください" + +#: ui/ +msgid "App icon pack" +msgstr "アプリアイコンパック" + +#: ui/ +msgid "Download failed" +msgstr "ダウンロード失敗" + +#: ui/ +msgid "Downloading…" +msgstr "ダウンロード中…" + +#: ui/ +msgid "Icon pack" +msgstr "アイコンパック" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (組み込み)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"アイコンが見つかりません。assets/icons/netneighbor または " +"~/.config/netneighbor/custom_icons/ に PNG を追加してください。" + +#: ui/ +msgid "Open folder…" +msgstr "フォルダを開く…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "インストールが破損しています" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"必要なファイルが見つからないか破損しているため、NetNeighbor を起動できません:\n" +"\n" +"{details}\n" +"\n" +"プログラムを再インストールしてください。" + +#: ui/ +msgid "All-in-one computer" +msgstr "オールインワンコンピュータ" + +#: ui/ +msgid "Desktop computer" +msgstr "デスクトップコンピュータ" + +#: ui/ +msgid "Laptop" +msgstr "ノートパソコン" + +#: ui/ +msgid "Mini PC" +msgstr "ミニPC" + +#: ui/ +msgid "Rack server" +msgstr "ラックサーバー" + +#: ui/ +msgid "Server" +msgstr "サーバー" + +#: ui/ +msgid "Servers" +msgstr "サーバー" + +#: ui/ +msgid "Phones & Tablets" +msgstr "電話とタブレット" + +#: ui/ +msgid "Smartphone" +msgstr "スマートフォン" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"モード「disabled」は、そのプロトコルの自動検出エントリを非表示にします(「custom」の場合はグローバルなカスタムコマンド)。その他のフィールドは無視されます。" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"プロトコルごとに接続エンドポイントをオーバーライドまたは追加します。プレースホルダー: {ip}, {port}, {name}, {type}, " +"{category}, " +"{url}。「custom」スキームの場合、コマンドは実行するコマンドラインです。その他のスキームの場合、コマンドはホストまたはアドレス(例:{ip}," +" {url}, http://{ip}:8080/admin)です。コマンドとポートはオプションです。" + +#: ui/ +msgid "Could not open Spotify." +msgstr "Spotifyを開けませんでした。" diff --git a/app/locale/netneighbor.pot b/app/locale/netneighbor.pot new file mode 100644 index 00000000..6c9fcfba --- /dev/null +++ b/app/locale/netneighbor.pot @@ -0,0 +1,1377 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "" + +#: ui/main_window.py:113 +msgid "List" +msgstr "" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "" + +#: ui/main_window.py:214 +msgid "About" +msgstr "" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "" + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "" + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "" + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "" + +#: ui/device_details.py:587 +msgid "System" +msgstr "" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "" + +#: ui/ +msgid "About NetNeighbor" +msgstr "" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "" + +#: ui/ +msgid "Applications" +msgstr "" + +#: ui/ +msgid "Apply" +msgstr "" + +#: ui/ +msgid "Author: Luc" +msgstr "" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "" + +#: ui/ +msgid "Command" +msgstr "" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" + +#: ui/ +msgid "Commands" +msgstr "" + +#: ui/ +msgid "Custom command (additional)" +msgstr "" + +#: ui/ +msgid "Dark" +msgstr "" + +#: ui/ +msgid "Date / Time" +msgstr "" + +#: ui/ +msgid "Delete" +msgstr "" + +#: ui/ +msgid "Desktop notifications" +msgstr "" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "" + +#: ui/ +msgid "Edit" +msgstr "" + +#: ui/ +msgid "Edit type preset" +msgstr "" + +#: ui/ +msgid "Error" +msgstr "" + +#: ui/ +msgid "Extra large" +msgstr "" + +#: ui/ +msgid "Field mapping rules" +msgstr "" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "" + +#: ui/ +msgid "General" +msgstr "" + +#: ui/ +msgid "Hidden devices" +msgstr "" + +#: ui/ +msgid "Hide device" +msgstr "" + +#: ui/ +msgid "Hide sidebar" +msgstr "" + +#: ui/ +msgid "Hide window" +msgstr "" + +#: ui/ +msgid "Icons size" +msgstr "" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "" + +#: ui/ +msgid "Large" +msgstr "" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "" + +#: ui/ +msgid "Light" +msgstr "" + +#: ui/ +msgid "Location name:" +msgstr "" + +#: ui/ +msgid "Locations" +msgstr "" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "" + +#: ui/ +msgid "Medium" +msgstr "" + +#: ui/ +msgid "Mode" +msgstr "" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "" + +#: ui/ +msgid "New name:" +msgstr "" + +#: ui/ +msgid "No devices yet" +msgstr "" + +#: ui/ +msgid "No hidden devices" +msgstr "" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" + +#: ui/ +msgid "Notifications" +msgstr "" + +#: ui/ +msgid "Offline" +msgstr "" + +#: ui/ +msgid "Online" +msgstr "" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" + +#: ui/ +msgid "Preferences…" +msgstr "" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "" + +#: ui/ +msgid "Reload discovery" +msgstr "" + +#: ui/ +msgid "Scheme" +msgstr "" + +#: ui/ +msgid "See the" +msgstr "" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "" + +#: ui/ +msgid "Service type" +msgstr "" + +#: ui/ +msgid "Session" +msgstr "" + +#: ui/ +msgid "Show sidebar" +msgstr "" + +#: ui/ +msgid "Show window" +msgstr "" + +#: ui/ +msgid "Sidebar" +msgstr "" + +#: ui/ +msgid "Small" +msgstr "" + +#: ui/ +msgid "Start Scanning…" +msgstr "" + +#: ui/ +msgid "Theme" +msgstr "" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "" + +#: ui/ +msgid "Types" +msgstr "" + +#: ui/ +msgid "Use as Friendly name" +msgstr "" + +#: ui/ +msgid "Use as Information" +msgstr "" + +#: ui/ +msgid "Use as Location" +msgstr "" + +#: ui/ +msgid "Use icon from" +msgstr "" + +#: ui/ +msgid "Version {version}" +msgstr "" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "" + +#: ui/ +msgid "for details." +msgstr "" + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "" + +#: ui/ +msgid "not yet downloaded" +msgstr "" + +#: ui/ +msgid "{} devices" +msgstr "" + +#: ui/ +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" + +#: ui/ +msgid "App icon pack" +msgstr "" + +#: ui/ +msgid "Download failed" +msgstr "" + +#: ui/ +msgid "Downloading…" +msgstr "" + +#: ui/ +msgid "Icon pack" +msgstr "" + +#: ui/ +msgid "Maintenance" +msgstr "" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" + +#: ui/ +msgid "Open folder…" +msgstr "" + +#: ui/ +msgid "Reset all application data?" +msgstr "" + +#: ui/ +msgid "Reset all application data…" +msgstr "" + +#: ui/ +msgid "Reset done — please restart" +msgstr "" + +#: ui/ +msgid "NetNeighbor" +msgstr "" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" + +#: ui/ +msgid "All-in-one computer" +msgstr "" + +#: ui/ +msgid "Desktop computer" +msgstr "" + +#: ui/ +msgid "Laptop" +msgstr "" + +#: ui/ +msgid "Mini PC" +msgstr "" + +#: ui/ +msgid "Rack server" +msgstr "" + +#: ui/ +msgid "Server" +msgstr "" + +#: ui/ +msgid "Servers" +msgstr "" + + +#: ui/ +msgid "Phones & Tablets" +msgstr "" + +#: ui/ +msgid "Smartphone" +msgstr "" + + + + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for 'c" +"ustom', the global custom command); its other fields are ignored." +msgstr "" + + + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}," +" {port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Comma" +"nd is the command line to run. For other schemes, Command is the host " +"or address to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command" +" and Port are optional." +msgstr "" + + + +#: ui/ +msgid "Could not open Spotify." +msgstr "" diff --git a/app/locale/nl/LC_MESSAGES/netneighbor.mo b/app/locale/nl/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..ce9e74a3 Binary files /dev/null and b/app/locale/nl/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/nl/LC_MESSAGES/netneighbor.po b/app/locale/nl/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..add6cff9 --- /dev/null +++ b/app/locale/nl/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1421 @@ +# Dutch translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Dutch\n" +"Language: nl\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "Weergave" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "Vernieuwen" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "Weergave:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "Pictogrammen" + +#: ui/main_window.py:113 +msgid "List" +msgstr "Lijst" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "Rangschikken:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "Ongesorteerd" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "op Type" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "op Locatie" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "Voorkeuren" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "Meldingen uit" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "Alleen gecontroleerde apparaten" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "Alle apparaten" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "Locatievoorinstellingen" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "Type-instellingen" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "Doorgaan in systeemvak wanneer venster wordt gesloten" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "Geminimaliseerd naar systeemvak starten" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "NetNeighbor starten bij aanmelden" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "Afsluiten" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "Hulpprogramma's" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "Externe toepassingen…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "Meldingsgeschiedenis" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "Help" + +#: ui/main_window.py:214 +msgid "About" +msgstr "Over" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "Sessie starten" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "Niet nu" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "Opslaan" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "NetNeighbor op de achtergrond uitvoeren?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"U kunt NetNeighbor in het systeemvak houden wanneer u het venster sluit. Als" +" u het met uw sessie start, blijft LAN-detectie op de achtergrond actief. U " +"kunt dit op elk moment wijzigen onder Beeld → Voorkeuren." + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "NetNeighbor starten wanneer ik me aanmeld" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "" +"Nadat u dit dialoogvenster sluit, wordt het hoofdvenster verborgen in het " +"systeemvak — klik op het NetNeighbor-systeemvakpictogram om het te openen " +"(aanbevolen na installatie)." + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — LAN-detectie" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "NetNeighbor openen" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "Minimaliseren naar systeemvak" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "Kantoor" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "Kamer" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "Woonkamer" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "Keuken" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "Werkplaats" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "Garage" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "Locatievoorinstellingen beheren." + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "" +"Automatisch locaties die op het netwerk zijn ontdekt aan deze lijst " +"toevoegen" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "" +"Wanneer ingeschakeld, kunnen kamernamen en vergelijkbare tekenreeksen van " +"apparaten (bijvoorbeeld enkele luidsprekers) aan de voorinstellingenlijst " +"worden toegevoegd wanneer ze worden gezien." + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "Voorinstelling" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "Toevoegen" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "Hernoemen" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "Verwijderen" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "Alles wissen" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "Annuleren" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "OK" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "Locatievoorinstelling toevoegen" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "Locatievoorinstelling hernoemen" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "Computer" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "Router" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "Mediaserver" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "Printer" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "Multifunctionele printer" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "Printer (netwerk / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "SmartSpeaker" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "SmartTV" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "SmartDevice" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "Camera" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "Huishoudapparaat" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "CNC" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "3D-printer" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "" +"Beheer apparaattype-instellingen die worden weergegeven in het contextmenu." + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "Label" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "Type-ID" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "Standaardwaarden herstellen" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "Label:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "Type-ID:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "bijv. nas, router, camera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "Type-instelling toevoegen" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "Type-instelling hernoemen" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "Externe toepassingen" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "Leeg = systeemstandaard" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "Opnieuw instellen" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "Standaardopdracht herstellen" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "Dit commando naar de standaardwaarde herstellen?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "Nee" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "Ja" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "Leeg = uitgeschakeld" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "Wissen" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "Verwijder de globale aangepaste opdracht" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "De globale aangepaste opdracht wissen?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "Aangepast:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "volledig adres" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "apparaat-IP" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "servicepoort" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "apparaatnaam" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "apparaattype" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "categorie" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "Credits" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "Licentie" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "Sluiten" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "Apparaten in uw lokale netwerk ontdekken en bewaken." + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Python-bibliotheken" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "GitHub-project" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "Meldingsgeschiedenis" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "Datum/Tijd" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "Apparaat" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "Status" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "Geen locatie" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "Alle locaties" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "Alle typen" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "Poorten" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "Type" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "" +"Voorlopige IPv6-identiteit — gemarkeerde rij pulseert terwijl detectie " +"overeenkomt met hostnaam / IPv4." + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "" +"Apparaatpictogram wordt op de achtergrond opgehaald — tegel pulseert totdat " +"het aankomt." + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "Openen ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "Openen" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "Aangepaste opdracht uitvoeren" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "Details" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "Opties" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "Niet meer volgen" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "Controleren" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "Locatie" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "Automatisch" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "Apparaattype" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "Apparaat hernoemen" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "Aangepaste naam" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "Kon de opdracht niet starten: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "Kon de aangepaste opdracht niet parseren (controleer placeholders)." + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "Onbewerkte XML weergeven" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "Naam" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "IP-adres" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (link-local)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "Overzicht" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "Apparaatgegevens" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "" +"Toewijzingsregels per apparaat. Selecteer rijen en verwijder indien nodig." + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "Selecteren" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "Doel" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "Bronveld" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "Geselecteerde items verwijderen" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "Alles verwijderen" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "Regels" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "Services" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "Service" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "Poort" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "Veld" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "Waarde" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "Informatie voor probleemoplossing" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "Record" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "TXT-records" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "XML-locatie" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "Naar klembord kopiëren" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "Apparaatgegevens" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "Overschrijven" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "Aanvullend" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "Deze opdracht verwijderen" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "Deze opdrachtvermelding verwijderen?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ Commando toevoegen" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "Aangepaste opdracht" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "bijv. x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "De aangepaste opdracht per apparaat wissen?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "Apparaatspecifieke override verwijderen (globale opdracht gebruiken)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "Pictogram gebruiken van:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "Systeem" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "Van apparaat" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "Aangepast" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "Map met aangepaste pictogrammen openen" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "niet beschikbaar" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "Afbeelding van apparaat" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "geen" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "Geselecteerde pictogram" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "Pictogram kiezen" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "Gebruiksvriendelijke naam" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "Informatie" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "Gebruiken als {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "Regel {target} verwijderen" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "Regel opgeslagen" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "Regel verwijderd" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "Geselecteerde regels verwijderd" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "Alle regels verwijderd" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "Geen TXT-records" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "Onbekend" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "HTTP-apparaat" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "HTTPS-apparaat" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "Slimme spreker" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "Slimme TV" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "Slim apparaat" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "Huishoudelijk apparaat" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "ESP3D Apparaat" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "Scanner" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "Laatst gezien" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "Fabrikant" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "URL fabrikant" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "Model" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "Model-URL" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "MAC-adres" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "Serienummer" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "Unieke identifier" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "Hostnaam" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "Routers & Gateways" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "Mediaservers" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "Printers" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "Slimme Luidsprekers" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "Slimme TV's" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "Slimme Apparaten" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "Camera's" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "Huishoudelijke Apparaten" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "CNC-machines" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "3D-printers" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / Bestandsservers" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "Computers" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "ESP3D-apparaten" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "Onbekende Apparaten" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "Over NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "App-logo onder assets/icons: Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "Toepassingen" + +#: ui/ +msgid "Apply" +msgstr "Toepassen" + +#: ui/ +msgid "Author: Luc" +msgstr "Auteur: Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "Sluiten naar systeemvak in plaats van afsluiten" + +#: ui/ +msgid "Command" +msgstr "Opdracht" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "" +"Opdrachtsjablonen voor het openen van apparaatverbindingen. Leeg laten om de" +" systeemstandaard te gebruiken." + +#: ui/ +msgid "Commands" +msgstr "Opdrachten" + +#: ui/ +msgid "Custom command (additional)" +msgstr "Aangepaste opdracht (aanvullend)" + +#: ui/ +msgid "Dark" +msgstr "Donker" + +#: ui/ +msgid "Date / Time" +msgstr "Datum / Tijd" + +#: ui/ +msgid "Delete" +msgstr "Verwijderen" + +#: ui/ +msgid "Desktop notifications" +msgstr "Bureaubladmeldingen" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "Ontdekkingsvernieuwing aangevraagd" + +#: ui/ +msgid "Edit" +msgstr "Bewerken" + +#: ui/ +msgid "Edit type preset" +msgstr "Typepreset bewerken" + +#: ui/ +msgid "Error" +msgstr "Fout" + +#: ui/ +msgid "Extra large" +msgstr "Extra groot" + +#: ui/ +msgid "Field mapping rules" +msgstr "Veldtoewijzingsregels" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "GNU Lesser General Public License versie 3 of later" + +#: ui/ +msgid "General" +msgstr "Algemeen" + +#: ui/ +msgid "Hidden devices" +msgstr "Verborgen apparaten" + +#: ui/ +msgid "Hide device" +msgstr "Apparaat verbergen" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "Apparaat wissen" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"{name} ({ip}) verwijderen uit de cache en alle voorkeuren?\n" +"\n" +"Dit kan niet ongedaan worden gemaakt. Het apparaat verschijnt opnieuw als het opnieuw wordt ontdekt in het netwerk." + +#: ui/ +msgid "Hide sidebar" +msgstr "Zijbalk verbergen" + +#: ui/ +msgid "Hide window" +msgstr "Venster verbergen" + +#: ui/ +msgid "Icons size" +msgstr "Pictogramgrootte" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "Ongeldig opdrachtsjabloon voor dit protocol." + +#: ui/ +msgid "Large" +msgstr "Groot" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "Gezien: {n} dagen geleden" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "Gezien: {n} uur geleden" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "Gezien: {n} min geleden" + +#: ui/ +msgid "Light" +msgstr "Licht" + +#: ui/ +msgid "Location name:" +msgstr "Locatienaam:" + +#: ui/ +msgid "Locations" +msgstr "Locaties" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "Locatiepresets beheren die worden weergegeven in het contextmenu." + +#: ui/ +msgid "Medium" +msgstr "Middel" + +#: ui/ +msgid "Mode" +msgstr "Modus" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "Nieuwe naam:" + +#: ui/ +msgid "No devices yet" +msgstr "Nog geen apparaten" + +#: ui/ +msgid "No hidden devices" +msgstr "Geen verborgen apparaten" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "" +"Meldingslevering is afhankelijk van het besturingssysteem en de sessie. Het " +"tray-gebaseerde gedrag (sluiten naar tray, geminimaliseerd starten) wordt " +"uitgelijnd zodra de systeemtray is geïmplementeerd." + +#: ui/ +msgid "Notifications" +msgstr "Meldingen" + +#: ui/ +msgid "Offline" +msgstr "Offline" + +#: ui/ +msgid "Online" +msgstr "Online" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"Verbindingseindpunten per protocol overschrijven of toevoegen. Voor het " +"schema 'custom' voert u de opdrachtsjabloon in IP/Host ({ip}, {ip_raw}, " +"{port}, {name}, {type}, {category}, {url}) in. IP/Host en poort zijn " +"optioneel voor andere schema's." + +#: ui/ +msgid "Preferences…" +msgstr "Voorkeuren…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Qt voor Python-bindingen" + +#: ui/ +msgid "Reload discovery" +msgstr "Ontdekking herladen" + +#: ui/ +msgid "Scheme" +msgstr "Schema" + +#: ui/ +msgid "See the" +msgstr "Zie de" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "" +"Selecteer een pictogram, dan OK. ID's worden opgeslagen in uw voorkeuren." + +#: ui/ +msgid "Service type" +msgstr "Servicetype" + +#: ui/ +msgid "Session" +msgstr "Sessie" + +#: ui/ +msgid "Show sidebar" +msgstr "Zijbalk tonen" + +#: ui/ +msgid "Show window" +msgstr "Venster tonen" + +#: ui/ +msgid "Sidebar" +msgstr "Zijbalk" + +#: ui/ +msgid "Small" +msgstr "Klein" + +#: ui/ +msgid "Start Scanning…" +msgstr "Scannen starten…" + +#: ui/ +msgid "Theme" +msgstr "Thema" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "Dit programma wordt geleverd zonder enige garantie." + +#: ui/ +msgid "Types" +msgstr "Types" + +#: ui/ +msgid "Use as Friendly name" +msgstr "Gebruiken als beschrijvende naam" + +#: ui/ +msgid "Use as Information" +msgstr "Gebruiken als informatie" + +#: ui/ +msgid "Use as Location" +msgstr "Gebruiken als locatie" + +#: ui/ +msgid "Use icon from" +msgstr "Pictogram gebruiken van" + +#: ui/ +msgid "Version {version}" +msgstr "Versie {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery (Windows-apparaten)" + +#: ui/ +msgid "for details." +msgstr "voor details." + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "mDNS/DNS-SD-ontdekking" + +#: ui/ +msgid "not yet downloaded" +msgstr "nog niet gedownload" + +#: ui/ +msgid "{} devices" +msgstr "{} apparaten" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "Onderhoud" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "Alle applicatiegegevens wissen…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "Alle applicatiegegevens wissen?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"Alle voorkeuren, gecachte pictogrammen, ontdekkingsgegevens en logbestanden worden definitief verwijderd:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor gebruikt standaardinstellingen bij de volgende start.\n" +"Deze actie kan niet ongedaan worden gemaakt." + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "Gewist — herstart de applicatie" + +#: ui/ +msgid "App icon pack" +msgstr "App-pictogrampakket" + +#: ui/ +msgid "Download failed" +msgstr "Download mislukt" + +#: ui/ +msgid "Downloading…" +msgstr "Downloaden…" + +#: ui/ +msgid "Icon pack" +msgstr "Icoonpakket" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor (ingebouwd)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"Geen pictogrammen gevonden. Voeg PNG's toe onder assets/icons/netneighbor of" +" ~/.config/netneighbor/custom_icons/." + +#: ui/ +msgid "Open folder…" +msgstr "Map openen…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "Beschadigde installatie" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"NetNeighbor kan niet starten omdat vereiste bestanden ontbreken of beschadigd zijn:\n" +"\n" +"{details}\n" +"\n" +"Installeer het programma opnieuw." + +#: ui/ +msgid "All-in-one computer" +msgstr "All-in-one-computer" + +#: ui/ +msgid "Desktop computer" +msgstr "Desktopcomputer" + +#: ui/ +msgid "Laptop" +msgstr "Laptop" + +#: ui/ +msgid "Mini PC" +msgstr "Mini-pc" + +#: ui/ +msgid "Rack server" +msgstr "Rack-server" + +#: ui/ +msgid "Server" +msgstr "Server" + +#: ui/ +msgid "Servers" +msgstr "Servers" + +#: ui/ +msgid "Phones & Tablets" +msgstr "Telefoons en tablets" + +#: ui/ +msgid "Smartphone" +msgstr "Smartphone" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "" +"De modus 'disabled' verbergt de automatisch gedetecteerde vermelding van dat" +" protocol (bij 'custom' de globale aangepaste opdracht); de overige velden " +"worden genegeerd." + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"Overschrijf of voeg verbindingseindpunten per protocol toe. Aanduidingen: " +"{ip}, {port}, {name}, {type}, {category}, {url}. Voor 'custom' schema is " +"Opdracht de opdrachtregel die moet worden uitgevoerd. Voor andere schema's " +"is Opdracht de host of adres die moet worden geopend (bijv. {ip}, {url}, " +"http://{ip}:8080/admin); Opdracht en Poort zijn optioneel." + +#: ui/ +msgid "Could not open Spotify." +msgstr "Kon Spotify niet openen." diff --git a/app/locale/zh_CN/LC_MESSAGES/netneighbor.mo b/app/locale/zh_CN/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..50836884 Binary files /dev/null and b/app/locale/zh_CN/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/zh_CN/LC_MESSAGES/netneighbor.po b/app/locale/zh_CN/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..7da0c4f2 --- /dev/null +++ b/app/locale/zh_CN/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1393 @@ +# Chinese translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Chinese Simplified\n" +"Language: zh_CN\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "查看" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "重新加载" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "显示:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "图标" + +#: ui/main_window.py:113 +msgid "List" +msgstr "列表" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "排列:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "未排序" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "按类型" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "按位置" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "偏好设置" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "通知已关闭" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "仅监控设备" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "所有设备" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "位置预设" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "类型预设" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "关闭窗口时保持在托盘中运行" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "最小化至托盘启动" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "登录时启动 NetNeighbor" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "退出" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "工具" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "外部应用程序…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "通知历史记录" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "帮助" + +#: ui/main_window.py:214 +msgid "About" +msgstr "关于" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "会话启动" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "暂不" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "保存" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "在后台运行 NetNeighbor?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"关闭窗口时可以将 NetNeighbor 保持在系统托盘中。使用您的会话启动它可以使 LAN 发现在后台运行。您可以随时在\"查看\" → " +"\"偏好设置\"下更改此设置。" + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "我登录时启动 NetNeighbor" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "关闭此对话框后,主窗口将隐藏到系统托盘中 — 单击 NetNeighbor 托盘图标打开它(安装后推荐)。" + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — LAN 发现" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "打开 NetNeighbor" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "最小化到托盘" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "办公室" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "房间" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "客厅" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "厨房" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "工作室" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "车库" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "管理位置预设。" + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "自动将网络上发现的位置添加到此列表" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "启用后,设备中的房间名称和类似字符串(例如某些扬声器)可以在发现时添加到预设列表中。" + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "预设" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "添加" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "重命名" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "移除" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "全部清除" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "取消" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "确定" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "添加位置预设" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "重命名位置预设" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "网络附加存储" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "计算机" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "路由器" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "媒体服务器" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "打印机" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "多功能打印机" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "打印机 (网络 / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "智能音箱" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "智能电视" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "智能设备" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "摄像头" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "家用电器" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "数控机床" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "3D打印机" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "管理在右键菜单中显示的设备类型预设。" + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "标签" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "类型 ID" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "恢复默认值" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "标签:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "类型 ID:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "例如 nas、router、camera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "添加类型预设" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "重命名类型预设" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "外部应用程序" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "空白 = 系统默认" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "重置" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "恢复默认命令" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "要将此命令重置为默认值吗?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "否" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "是" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "空白 = 已禁用" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "清除" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "移除全局自定义命令" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "清除全局自定义命令?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "自定义:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "完整地址" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "设备IP" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "服务端口" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "设备名称" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "设备类型" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "分类" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "致谢" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "许可证" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "关闭" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "发现并监控本地网络上的设备。" + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Python 库" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "GitHub 项目" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "通知历史" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "日期/时间" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "设备" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "状态" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "无位置" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "所有位置" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "所有类型" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "端口" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "类型" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "临时 IPv6 身份 — 突出显示的行在发现与主机名/IPv4 匹配时闪烁。" + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "正在后台获取设备图标 — 磁贴在到达前闪烁。" + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "打开 ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "打开" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "运行自定义命令" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "详情" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "选项" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "取消关注" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "监控" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "位置" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "自动" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "设备类型" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "重命名设备" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "自定义名称" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "无法启动命令:{error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "无法解析自定义命令(检查占位符)。" + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "显示原始XML" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "名称" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "IP 地址" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6(链接本地)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "概述" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "设备详情" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "按设备字段映射规则。选择行并在需要时删除。" + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "选择" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "目标" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "源字段" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "删除选定项" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "全部删除" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "规则" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "服务" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "服务" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "端口" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "字段" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "值" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "故障排除信息" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "记录" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "TXT 记录" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "XML 位置" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "复制到剪贴板" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "设备数据" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "覆盖" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "其他" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "删除此命令" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "删除此命令条目?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ 添加命令" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "自定义命令" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "例如 x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "清除按设备的自定义命令?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "移除每个设备的覆盖(使用全局命令)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "使用图标来自:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "系统" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "来自设备" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "自定义" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "打开自定义图标文件夹" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "不可用" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "来自设备的图像" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "无" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "选定的图标" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "选择图标" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "友好名称" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "信息" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "用作 {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "删除 {target} 规则" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "规则已保存" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "规则已删除" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "选定的规则已删除" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "所有规则已删除" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "无 TXT 记录" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "未知" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "HTTP 设备" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "HTTPS 设备" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "智能音箱" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "智能电视" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "智能设备" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "家用电器" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "ESP3D 设备" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "扫描仪" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "最后看到" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "制造商" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "制造商URL" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "型号" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "型号URL" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "MAC 地址" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "序列号" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "唯一标识符" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "主机名" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "路由器和网关" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "媒体服务器" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "打印机" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "智能音箱" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "智能电视" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "智能设备" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "摄像头" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "家用电器" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "数控机床" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "3D 打印机" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS/文件服务器" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "计算机" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "ESP3D 设备" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "未知设备" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "关于 NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "应用图标来自 assets/icons:Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "应用程序" + +#: ui/ +msgid "Apply" +msgstr "应用" + +#: ui/ +msgid "Author: Luc" +msgstr "作者:Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "关闭到系统托盘而非退出" + +#: ui/ +msgid "Command" +msgstr "命令" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "打开设备连接的命令模板。留空则使用系统默认值。" + +#: ui/ +msgid "Commands" +msgstr "命令" + +#: ui/ +msgid "Custom command (additional)" +msgstr "自定义命令(附加)" + +#: ui/ +msgid "Dark" +msgstr "深色" + +#: ui/ +msgid "Date / Time" +msgstr "日期 / 时间" + +#: ui/ +msgid "Delete" +msgstr "删除" + +#: ui/ +msgid "Desktop notifications" +msgstr "桌面通知" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "已请求刷新发现" + +#: ui/ +msgid "Edit" +msgstr "编辑" + +#: ui/ +msgid "Edit type preset" +msgstr "编辑类型预设" + +#: ui/ +msgid "Error" +msgstr "错误" + +#: ui/ +msgid "Extra large" +msgstr "特大" + +#: ui/ +msgid "Field mapping rules" +msgstr "字段映射规则" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "GNU 宽通用公共许可证第3版或更高版本" + +#: ui/ +msgid "General" +msgstr "通用" + +#: ui/ +msgid "Hidden devices" +msgstr "隐藏的设备" + +#: ui/ +msgid "Hide device" +msgstr "隐藏设备" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "清除设备" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"将 {name}({ip})从缓存和所有首选项中删除?\n" +"\n" +"此操作无法撤销。如果在网络上重新发现该设备,它将再次出现。" + +#: ui/ +msgid "Hide sidebar" +msgstr "隐藏侧边栏" + +#: ui/ +msgid "Hide window" +msgstr "隐藏窗口" + +#: ui/ +msgid "Icons size" +msgstr "图标大小" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "此协议的命令模板无效。" + +#: ui/ +msgid "Large" +msgstr "大" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "最后发现:{n} 天前" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "最后发现:{n} 小时前" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "最后发现:{n} 分钟前" + +#: ui/ +msgid "Light" +msgstr "浅色" + +#: ui/ +msgid "Location name:" +msgstr "位置名称:" + +#: ui/ +msgid "Locations" +msgstr "位置" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "管理右键菜单中显示的位置预设。" + +#: ui/ +msgid "Medium" +msgstr "中" + +#: ui/ +msgid "Mode" +msgstr "模式" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "新名称:" + +#: ui/ +msgid "No devices yet" +msgstr "暂无设备" + +#: ui/ +msgid "No hidden devices" +msgstr "没有隐藏的设备" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "通知的发送取决于操作系统和会话。基于托盘的行为(关闭到托盘、最小化启动)将在系统托盘实现后对齐。" + +#: ui/ +msgid "Notifications" +msgstr "通知" + +#: ui/ +msgid "Offline" +msgstr "离线" + +#: ui/ +msgid "Online" +msgstr "在线" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"按协议覆盖或添加连接端点。对于 'custom' 方案,请在 IP/主机 ({ip}, {port}, {name}, {type}, " +"{category}, {url}) 中输入命令模板。对于其他方案,IP/主机和端口是可选的。" + +#: ui/ +msgid "Preferences…" +msgstr "首选项…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Qt for Python 绑定" + +#: ui/ +msgid "Reload discovery" +msgstr "重新加载发现" + +#: ui/ +msgid "Scheme" +msgstr "方案" + +#: ui/ +msgid "See the" +msgstr "请参阅" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "选择图标,然后点击确定。ID 存储在您的首选项中。" + +#: ui/ +msgid "Service type" +msgstr "服务类型" + +#: ui/ +msgid "Session" +msgstr "会话" + +#: ui/ +msgid "Show sidebar" +msgstr "显示侧边栏" + +#: ui/ +msgid "Show window" +msgstr "显示窗口" + +#: ui/ +msgid "Sidebar" +msgstr "侧边栏" + +#: ui/ +msgid "Small" +msgstr "小" + +#: ui/ +msgid "Start Scanning…" +msgstr "正在扫描…" + +#: ui/ +msgid "Theme" +msgstr "主题" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "本程序不提供任何保证。" + +#: ui/ +msgid "Types" +msgstr "类型" + +#: ui/ +msgid "Use as Friendly name" +msgstr "用作友好名称" + +#: ui/ +msgid "Use as Information" +msgstr "用作信息" + +#: ui/ +msgid "Use as Location" +msgstr "用作位置" + +#: ui/ +msgid "Use icon from" +msgstr "使用图标来自" + +#: ui/ +msgid "Version {version}" +msgstr "版本 {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery(Windows 设备)" + +#: ui/ +msgid "for details." +msgstr "以了解详情。" + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "mDNS/DNS-SD 发现" + +#: ui/ +msgid "not yet downloaded" +msgstr "尚未下载" + +#: ui/ +msgid "{} devices" +msgstr "{} 个设备" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "维护" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "重置所有应用数据…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "重置所有应用数据?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"所有偏好设置、缓存图标、发现数据和日志将被永久删除:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"下次启动时 NetNeighbor 将使用默认设置。\n" +"此操作无法撤销。" + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "重置完成 — 请重启应用" + +#: ui/ +msgid "App icon pack" +msgstr "应用图标包" + +#: ui/ +msgid "Download failed" +msgstr "下载失败" + +#: ui/ +msgid "Downloading…" +msgstr "正在下载…" + +#: ui/ +msgid "Icon pack" +msgstr "图标包" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor(内置)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"未找到图标。请在 assets/icons/netneighbor 或 ~/.config/netneighbor/custom_icons/ 中添加 " +"PNG。" + +#: ui/ +msgid "Open folder…" +msgstr "打开文件夹…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "安装已损坏" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"由于缺少必需的文件或文件已损坏,NetNeighbor 无法启动:\n" +"\n" +"{details}\n" +"\n" +"请重新安装该程序。" + +#: ui/ +msgid "All-in-one computer" +msgstr "一体化计算机" + +#: ui/ +msgid "Desktop computer" +msgstr "台式计算机" + +#: ui/ +msgid "Laptop" +msgstr "笔记本电脑" + +#: ui/ +msgid "Mini PC" +msgstr "迷你电脑" + +#: ui/ +msgid "Rack server" +msgstr "机架服务器" + +#: ui/ +msgid "Server" +msgstr "服务器" + +#: ui/ +msgid "Servers" +msgstr "服务器" + +#: ui/ +msgid "Phones & Tablets" +msgstr "手机和平板电脑" + +#: ui/ +msgid "Smartphone" +msgstr "智能手机" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "“disabled”模式会隐藏该协议的自动检测条目(对于“custom”,则隐藏全局自定义命令);其他字段将被忽略。" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"按协议覆盖或添加连接端点。占位符:{ip}、{port}、{name}、{type}、{category}、{url}。对于 'custom' " +"方案,命令为要运行的命令行。对于其他方案,命令为要打开的主机或地址(例如 " +"{ip}、{url}、http://{ip}:8080/admin);命令和端口为可选项。" + +#: ui/ +msgid "Could not open Spotify." +msgstr "无法打开 Spotify。" diff --git a/app/locale/zh_TW/LC_MESSAGES/netneighbor.mo b/app/locale/zh_TW/LC_MESSAGES/netneighbor.mo new file mode 100644 index 00000000..74eb1cfe Binary files /dev/null and b/app/locale/zh_TW/LC_MESSAGES/netneighbor.mo differ diff --git a/app/locale/zh_TW/LC_MESSAGES/netneighbor.po b/app/locale/zh_TW/LC_MESSAGES/netneighbor.po new file mode 100644 index 00000000..186cee49 --- /dev/null +++ b/app/locale/zh_TW/LC_MESSAGES/netneighbor.po @@ -0,0 +1,1393 @@ +# Chinese translations for NetNeighbor package. +# Copyright (C) 2026 THE NetNeighbor'S COPYRIGHT HOLDER +# This file is distributed under the same license as the NetNeighbor package. +# Automatically generated, 2026. +# +msgid "" +msgstr "" +"Project-Id-Version: NetNeighbor 0.8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-05-06 22:22+0800\n" +"PO-Revision-Date: 2026-05-05 11:49+0800\n" +"Last-Translator: Automatically generated\n" +"Language-Team: Chinese Traditional (Taiwan)\n" +"Language: zh_TW\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: ui/main_window.py:88 +msgid "View" +msgstr "檢視" + +#: ui/main_window.py:93 +msgid "Reload" +msgstr "重新載入" + +#: ui/main_window.py:108 +msgid "Display:" +msgstr "顯示:" + +#: ui/main_window.py:112 ui/main_window.py:1094 +msgid "Icons" +msgstr "圖示" + +#: ui/main_window.py:113 +msgid "List" +msgstr "清單" + +#: ui/main_window.py:120 +msgid "Arrange:" +msgstr "排列:" + +#: ui/main_window.py:123 +msgid "Unsorted" +msgstr "未排序" + +#: ui/main_window.py:125 +msgid "by Type" +msgstr "依類型" + +#: ui/main_window.py:128 +msgid "by Location" +msgstr "依位置" + +#: ui/main_window.py:138 +msgid "Preferences" +msgstr "偏好設定" + +#: ui/main_window.py:143 +msgid "Notifications off" +msgstr "通知已關閉" + +#: ui/main_window.py:144 +msgid "Monitored devices only" +msgstr "僅監控裝置" + +#: ui/main_window.py:145 ui/device_list.py:438 +msgid "All devices" +msgstr "所有裝置" + +#: ui/main_window.py:159 ui/main_window.py:582 +msgid "Location presets" +msgstr "位置預設" + +#: ui/main_window.py:162 ui/main_window.py:741 +msgid "Type presets" +msgstr "類型預設" + +#: ui/main_window.py:168 +msgid "Keep running in tray when closing window" +msgstr "關閉視窗時保持在系統匣中執行" + +#: ui/main_window.py:174 +msgid "Start minimized to tray" +msgstr "最小化到系統匣啟動" + +#: ui/main_window.py:179 +msgid "Start NetNeighbor when logging in" +msgstr "登入時啟動 NetNeighbor" + +#: ui/main_window.py:185 ui/main_window.py:382 +msgid "Quit" +msgstr "結束" + +#: ui/main_window.py:198 +msgid "Tools" +msgstr "工具" + +#: ui/main_window.py:202 +msgid "External applications…" +msgstr "外部應用程式…" + +#: ui/main_window.py:205 +msgid "Notifications history" +msgstr "通知歷史記錄" + +#: ui/main_window.py:209 +msgid "Help" +msgstr "說明" + +#: ui/main_window.py:214 +msgid "About" +msgstr "關於" + +#: ui/main_window.py:289 +msgid "Session startup" +msgstr "工作階段啟動" + +#: ui/main_window.py:295 +msgid "Not now" +msgstr "暫時不要" + +#: ui/main_window.py:296 ui/main_window.py:709 ui/main_window.py:875 +#: ui/main_window.py:1020 ui/device_list.py:732 +msgid "Save" +msgstr "儲存" + +#: ui/main_window.py:304 +msgid "Run NetNeighbor in the background?" +msgstr "在背景執行 NetNeighbor?" + +#: ui/main_window.py:308 +msgid "" +"You can keep NetNeighbor in the system tray when you close the window. " +"Starting it with your session keeps LAN discovery running in the background." +" You can change this anytime under View → Preferences." +msgstr "" +"關閉視窗時,您可以將 NetNeighbor 保留在系統匣中。使用您的工作階段啟動它可以讓 LAN 探索在背景中持續執行。您可以隨時在 [檢視] → " +"[偏好設定] 下變更此設定。" + +#: ui/main_window.py:317 +msgid "Launch NetNeighbor when I log in" +msgstr "登入時啟動 NetNeighbor" + +#: ui/main_window.py:325 +msgid "" +"After you close this dialog, the main window hides to the system tray — " +"click the NetNeighbor tray icon to open it (recommended after install)." +msgstr "關閉此對話框後,主視窗將隱藏到系統匣 — 按一下 NetNeighbor 系統匣圖示來開啟它(安裝後建議使用)。" + +#: ui/main_window.py:380 +msgid "NetNeighbor — LAN discovery" +msgstr "NetNeighbor — LAN 探索" + +#: ui/main_window.py:381 +msgid "Open NetNeighbor" +msgstr "開啟 NetNeighbor" + +#: ui/main_window.py:383 +msgid "Minimize to tray" +msgstr "最小化到系統匣" + +#: ui/main_window.py:572 +msgid "Office" +msgstr "辦公室" + +#: ui/main_window.py:573 +msgid "Room" +msgstr "房間" + +#: ui/main_window.py:574 +msgid "Living room" +msgstr "客廳" + +#: ui/main_window.py:575 +msgid "Kitchen" +msgstr "廚房" + +#: ui/main_window.py:576 +msgid "Workshop" +msgstr "工作室" + +#: ui/main_window.py:577 +msgid "Garage" +msgstr "車庫" + +#: ui/main_window.py:588 +msgid "Manage location presets." +msgstr "管理位置預設。" + +#: ui/main_window.py:595 +msgid "Automatically add locations discovered on the network to this list" +msgstr "自動將網路上發現的位置新增到此清單" + +#: ui/main_window.py:600 +msgid "" +"When enabled, room names and similar strings from devices (for example some " +"speakers) can be added to the preset list as they are seen." +msgstr "啟用時,來自裝置的房間名稱和類似字串(例如某些揚聲器)可在發現時新增到預設清單。" + +#: ui/main_window.py:615 +msgid "Preset" +msgstr "預設" + +#: ui/main_window.py:624 ui/main_window.py:777 +msgid "Add" +msgstr "新增" + +#: ui/main_window.py:625 ui/main_window.py:778 ui/device_list.py:605 +msgid "Rename" +msgstr "重新命名" + +#: ui/main_window.py:626 ui/main_window.py:779 +msgid "Remove" +msgstr "移除" + +#: ui/main_window.py:627 +msgid "Clear all" +msgstr "全部清除" + +#: ui/main_window.py:646 ui/main_window.py:708 ui/main_window.py:809 +#: ui/main_window.py:874 ui/main_window.py:1019 ui/device_list.py:731 +#: ui/device_details.py:774 +msgid "Cancel" +msgstr "取消" + +#: ui/main_window.py:647 ui/main_window.py:810 +msgid "OK" +msgstr "確定" + +#: ui/main_window.py:672 +msgid "Add location preset" +msgstr "新增位置預設" + +#: ui/main_window.py:686 +msgid "Rename location preset" +msgstr "重新命名位置預設" + +#: ui/main_window.py:724 ui/device_list.py:640 utils/details_payload.py:117 +msgid "NAS" +msgstr "NAS" + +#: ui/main_window.py:725 ui/device_list.py:641 utils/details_payload.py:118 +msgid "Computer" +msgstr "電腦" + +#: ui/main_window.py:726 ui/device_list.py:642 utils/details_payload.py:105 +msgid "Router" +msgstr "路由器" + +#: ui/main_window.py:727 ui/device_list.py:643 utils/details_payload.py:106 +msgid "Media server" +msgstr "媒體伺服器" + +#: ui/main_window.py:728 ui/device_list.py:644 utils/details_payload.py:107 +#: utils/details_payload.py:108 +msgid "Printer" +msgstr "印表機" + +#: ui/main_window.py:729 ui/device_list.py:645 utils/details_payload.py:109 +msgid "Multifunction printer" +msgstr "多功能印表機" + +#: ui/main_window.py:730 ui/device_list.py:646 +msgid "Printer (network / IPP)" +msgstr "印表機 (網路 / IPP)" + +#: ui/main_window.py:731 ui/device_list.py:647 +msgid "SmartSpeaker" +msgstr "智慧喇叭" + +#: ui/main_window.py:732 ui/device_list.py:648 +msgid "SmartTV" +msgstr "智慧電視" + +#: ui/main_window.py:733 ui/device_list.py:649 +msgid "SmartDevice" +msgstr "智慧裝置" + +#: ui/main_window.py:734 ui/device_list.py:650 utils/details_payload.py:113 +msgid "Camera" +msgstr "相機" + +#: ui/main_window.py:735 ui/device_list.py:651 +msgid "HomeAppliance" +msgstr "家用電器" + +#: ui/main_window.py:736 ui/device_list.py:652 utils/details_payload.py:115 +msgid "CNC" +msgstr "數控機床" + +#: ui/main_window.py:737 ui/device_list.py:653 utils/details_payload.py:116 +msgid "3D printer" +msgstr "3D 印表機" + +#: ui/main_window.py:747 +msgid "Manage device type presets shown in the right-click menu." +msgstr "管理在右鍵菜單中顯示的設備類型預設。" + +#: ui/main_window.py:767 ui/device_details.py:415 +msgid "Label" +msgstr "標籤" + +#: ui/main_window.py:768 +msgid "Type ID" +msgstr "類型 ID" + +#: ui/main_window.py:780 +msgid "Restore defaults" +msgstr "恢復預設值" + +#: ui/main_window.py:796 +msgid "Label:" +msgstr "標籤:" + +#: ui/main_window.py:797 +msgid "Type ID:" +msgstr "類型 ID:" + +#: ui/main_window.py:803 +msgid "e.g. nas, router, camera…" +msgstr "例如 nas、router、camera…" + +#: ui/main_window.py:835 +msgid "Add type preset" +msgstr "新增類型預設" + +#: ui/main_window.py:849 +msgid "Rename type preset" +msgstr "重新命名類型預設" + +#: ui/main_window.py:912 +msgid "External applications" +msgstr "外部應用程式" + +#: ui/main_window.py:934 +msgid "HTTP" +msgstr "HTTP" + +#: ui/main_window.py:935 +msgid "HTTPS" +msgstr "HTTPS" + +#: ui/main_window.py:936 +msgid "SMB" +msgstr "SMB" + +#: ui/main_window.py:937 +msgid "FTP" +msgstr "FTP" + +#: ui/main_window.py:938 +msgid "SSH" +msgstr "SSH" + +#: ui/main_window.py:939 +msgid "Telnet" +msgstr "Telnet" + +#: ui/main_window.py:940 +msgid "SFTP" +msgstr "SFTP" + +#: ui/main_window.py:947 +msgid "Empty = system default" +msgstr "空白 = 系統預設" + +#: ui/main_window.py:948 ui/device_list.py:730 +msgid "Reset" +msgstr "重設" + +#: ui/main_window.py:949 +msgid "Restore default command" +msgstr "還原預設命令" + +#: ui/main_window.py:957 +msgid "Reset this command to its default value?" +msgstr "將此命令重設為預設值?" + +#: ui/main_window.py:959 ui/main_window.py:986 ui/device_details.py:384 +msgid "No" +msgstr "否" + +#: ui/main_window.py:960 ui/main_window.py:987 ui/device_details.py:385 +msgid "Yes" +msgstr "是" + +#: ui/main_window.py:975 +msgid "Empty = disabled" +msgstr "空白 = 已停用" + +#: ui/main_window.py:976 ui/main_window.py:1140 ui/device_details.py:565 +msgid "Clear" +msgstr "清除" + +#: ui/main_window.py:977 +msgid "Remove the global custom command" +msgstr "移除全域自訂命令" + +#: ui/main_window.py:984 +msgid "Clear the global custom command?" +msgstr "清除全域自訂命令?" + +#: ui/main_window.py:995 +msgid "Custom:" +msgstr "自訂:" + +#: ui/main_window.py:1004 +msgid "full address" +msgstr "完整位址" + +#: ui/main_window.py:1005 +msgid "device IP" +msgstr "裝置 IP" + +#: ui/main_window.py:1006 +msgid "service port" +msgstr "服務連接埠" + +#: ui/main_window.py:1007 +msgid "device name" +msgstr "裝置名稱" + +#: ui/main_window.py:1008 +msgid "device type" +msgstr "裝置類型" + +#: ui/main_window.py:1009 +msgid "category" +msgstr "類別" + +#: ui/main_window.py:1041 +msgid "Credits" +msgstr "製作人員" + +#: ui/main_window.py:1042 +msgid "License" +msgstr "授權條款" + +#: ui/main_window.py:1043 ui/main_window.py:1142 ui/device_details.py:85 +msgid "Close" +msgstr "關閉" + +#: ui/main_window.py:1084 +msgid "Discover and monitor devices on your local network." +msgstr "探索並監控本地網路上的裝置。" + +#: ui/main_window.py:1086 +msgid "Python libraries" +msgstr "Python 函式庫" + +#: ui/main_window.py:1101 +msgid "GitHub Project" +msgstr "GitHub 專案" + +#: ui/main_window.py:1118 +msgid "Notification history" +msgstr "通知歷史記錄" + +#: ui/main_window.py:1129 +msgid "Date/Time" +msgstr "日期/時間" + +#: ui/main_window.py:1129 +msgid "Device" +msgstr "裝置" + +#: ui/main_window.py:1129 +msgid "Status" +msgstr "狀態" + +#: ui/main_window.py:1327 ui/main_window.py:1360 ui/main_window.py:1364 +#: ui/main_window.py:1365 ui/device_list.py:462 ui/device_list.py:464 +#: ui/device_list.py:465 ui/device_list.py:496 ui/device_list.py:1594 +msgid "No location" +msgstr "無位置" + +#: ui/main_window.py:1350 +msgid "All Locations" +msgstr "所有位置" + +#: ui/main_window.py:1350 +msgid "All Types" +msgstr "所有類型" + +#: ui/device_list.py:233 utils/details_payload.py:94 +#: utils/details_payload.py:269 utils/details_payload.py:346 +msgid "Ports" +msgstr "連接埠" + +#: ui/device_list.py:234 ui/device_details.py:157 utils/details_payload.py:268 +#: utils/details_payload.py:345 +msgid "Type" +msgstr "類型" + +#: ui/device_list.py:547 +msgid "" +"Provisional IPv6 identity — highlighted row pulses while discovery matches " +"hostname / IPv4." +msgstr "暫時性 IPv6 身份 — 當探索符合主機名稱 / IPv4 時,反白顯示的列會閃爍。" + +#: ui/device_list.py:550 +msgid "Fetching device icon in the background — tile pulses until it arrives." +msgstr "在背景中擷取裝置圖示 — 在圖示到達前,磚會閃爍。" + +#: ui/device_list.py:571 +#, python-brace-format +msgid "Open ({label})" +msgstr "開啟 ({label})" + +#: ui/device_list.py:575 +msgid "Open" +msgstr "開啟" + +#: ui/device_list.py:585 +msgid "Run custom command" +msgstr "執行自訂命令" + +#: ui/device_list.py:589 +msgid "Details" +msgstr "詳細資訊" + +#: ui/device_list.py:592 ui/device_details.py:628 +msgid "Options" +msgstr "選項" + +#: ui/device_list.py:597 +msgid "Unfollow" +msgstr "取消追蹤" + +#: ui/device_list.py:601 +msgid "Monitor" +msgstr "監控" + +#: ui/device_list.py:610 ui/device_details.py:156 ui/device_details.py:852 +#: utils/details_payload.py:270 utils/details_payload.py:347 +msgid "Location" +msgstr "位置" + +#: ui/device_list.py:621 ui/device_list.py:655 +msgid "Auto" +msgstr "自動" + +#: ui/device_list.py:634 +msgid "Device type" +msgstr "裝置類型" + +#: ui/device_list.py:719 +msgid "Rename device" +msgstr "重新命名裝置" + +#: ui/device_list.py:724 +msgid "Custom name" +msgstr "自訂名稱" + +#: ui/device_list.py:775 ui/device_list.py:823 ui/device_list.py:996 +#, python-brace-format +msgid "Could not start the command: {error}" +msgstr "無法啟動命令: {error}" + +#: ui/device_list.py:818 +msgid "Could not parse the custom command (check placeholders)." +msgstr "無法解析自訂命令 (檢查佔位符)。" + +#: ui/device_list.py:932 +msgid "Show raw XML" +msgstr "顯示原始 XML" + +#: ui/device_details.py:154 ui/device_details.py:292 ui/device_details.py:1102 +msgid "Name" +msgstr "名稱" + +#: ui/device_details.py:155 +msgid "IP address" +msgstr "IP 位址" + +#: ui/device_details.py:175 +msgid "IPv6 (link-local)" +msgstr "IPv6 (本地連結)" + +#: ui/device_details.py:208 +msgid "Overview" +msgstr "概覽" + +#: ui/device_details.py:208 +msgid "Device details" +msgstr "裝置詳細資料" + +#: ui/device_details.py:218 +msgid "Per-device field mapping rules. Select rows and remove if needed." +msgstr "每個裝置的欄位對應規則。選取列並在需要時移除。" + +#: ui/device_details.py:228 ui/device_details.py:775 +msgid "Select" +msgstr "選取" + +#: ui/device_details.py:229 ui/device_details.py:264 +msgid "Target" +msgstr "目標" + +#: ui/device_details.py:230 +msgid "Source field" +msgstr "來源欄位" + +#: ui/device_details.py:239 +msgid "Remove selected" +msgstr "移除已選取項" + +#: ui/device_details.py:242 +msgid "Remove all" +msgstr "全部移除" + +#: ui/device_details.py:248 +msgid "Rules" +msgstr "規則" + +#: ui/device_details.py:256 ui/device_details.py:271 +msgid "Services" +msgstr "服務" + +#: ui/device_details.py:263 ui/device_details.py:1026 +msgid "Service" +msgstr "服務" + +#: ui/device_details.py:265 +msgid "Port" +msgstr "連接埠" + +#: ui/device_details.py:278 +msgid "Field" +msgstr "欄位" + +#: ui/device_details.py:279 ui/device_details.py:1103 +msgid "Value" +msgstr "值" + +#: ui/device_details.py:285 +msgid "Troubleshooting Information" +msgstr "疑難排解資訊" + +#: ui/device_details.py:293 +msgid "Record" +msgstr "記錄" + +#: ui/device_details.py:299 +msgid "TXT records" +msgstr "TXT 記錄" + +#: ui/device_details.py:309 +msgid "XML location" +msgstr "XML 位置" + +#: ui/device_details.py:314 +msgid "Copy to clipboard" +msgstr "複製到剪貼板" + +#: ui/device_details.py:333 +msgid "Device data" +msgstr "裝置資料" + +#: ui/device_details.py:363 ui/device_details.py:406 +msgid "Override" +msgstr "覆蓋" + +#: ui/device_details.py:363 ui/device_details.py:407 +msgid "Additional" +msgstr "其他" + +#: ui/device_details.py:422 utils/details_payload.py:267 +#: utils/details_payload.py:344 +msgid "IP" +msgstr "IP" + +#: ui/device_details.py:483 +msgid "Remove this command" +msgstr "移除此命令" + +#: ui/device_details.py:488 +msgid "Remove this command entry?" +msgstr "移除此命令項目?" + +#: ui/device_details.py:512 +msgid "+ Add command" +msgstr "+ 新增命令" + +#: ui/device_details.py:532 +msgid "Custom command" +msgstr "自訂命令" + +#: ui/device_details.py:539 +#, python-brace-format +msgid "e.g. x-terminal-emulator -e ssh -p {port} {ip}" +msgstr "例如 x-terminal-emulator -e ssh -p {port} {ip}" + +#: ui/device_details.py:560 +msgid "Clear the per-device custom command?" +msgstr "清除逐裝置的自訂命令?" + +#: ui/device_details.py:566 +msgid "Remove per-device override (use global command)" +msgstr "移除各裝置覆蓋(使用全域命令)" + +#: ui/device_details.py:585 +msgid "Use icon from:" +msgstr "使用圖示來自:" + +#: ui/device_details.py:587 +msgid "System" +msgstr "系統" + +#: ui/device_details.py:589 +msgid "From device" +msgstr "來自裝置" + +#: ui/device_details.py:592 +msgid "Custom" +msgstr "自訂" + +#: ui/device_details.py:604 +msgid "Open custom icons folder" +msgstr "開啟自訂圖示資料夾" + +#: ui/device_details.py:674 ui/device_details.py:1027 +#: ui/device_details.py:1028 ui/device_details.py:1161 +msgid "unavailable" +msgstr "無法使用" + +#: ui/device_details.py:675 +msgid "Image from device" +msgstr "來自裝置的影像" + +#: ui/device_details.py:677 ui/device_details.py:683 +msgid "none" +msgstr "無" + +#: ui/device_details.py:678 +msgid "Selected icon" +msgstr "選取的圖示" + +#: ui/device_details.py:733 +msgid "Choose icon" +msgstr "選擇圖示" + +#: ui/device_details.py:851 utils/details_payload.py:272 +#: utils/details_payload.py:349 +msgid "Friendly name" +msgstr "易記名稱" + +#: ui/device_details.py:853 utils/details_payload.py:273 +#: utils/details_payload.py:356 +msgid "Information" +msgstr "資訊" + +#: ui/device_details.py:858 +#, python-brace-format +msgid "Use as {target}" +msgstr "用作 {target}" + +#: ui/device_details.py:863 +#, python-brace-format +msgid "Remove {target} rule" +msgstr "移除 {target} 規則" + +#: ui/device_details.py:880 +msgid "Rule saved" +msgstr "規則已儲存" + +#: ui/device_details.py:890 +msgid "Rule removed" +msgstr "規則已移除" + +#: ui/device_details.py:934 +msgid "Selected rules removed" +msgstr "選定的規則已移除" + +#: ui/device_details.py:946 +msgid "All rules removed" +msgstr "所有規則已移除" + +#: ui/device_details.py:1094 +msgid "No TXT records" +msgstr "沒有 TXT 記錄" + +#: utils/details_payload.py:102 utils/details_payload.py:126 +msgid "Unknown" +msgstr "未知" + +#: utils/details_payload.py:103 +msgid "HTTP device" +msgstr "HTTP 裝置" + +#: utils/details_payload.py:104 +msgid "HTTPS device" +msgstr "HTTPS 裝置" + +#: utils/details_payload.py:110 +msgid "Smart speaker" +msgstr "智慧音箱" + +#: utils/details_payload.py:111 +msgid "Smart TV" +msgstr "智慧電視" + +#: utils/details_payload.py:112 +msgid "Smart device" +msgstr "智慧裝置" + +#: utils/details_payload.py:114 +msgid "Home appliance" +msgstr "家電" + +#: utils/details_payload.py:119 +msgid "ESP3D Device" +msgstr "ESP3D 設備" + +#: utils/details_payload.py:120 +msgid "Scanner" +msgstr "掃描器" + +#: utils/details_payload.py:271 utils/details_payload.py:348 +#: utils/details_payload.py:608 +msgid "Last seen" +msgstr "上次查看" + +#: utils/details_payload.py:274 utils/details_payload.py:352 +msgid "Manufacturer" +msgstr "製造商" + +#: utils/details_payload.py:275 utils/details_payload.py:353 +msgid "Manufacturer URL" +msgstr "製造商 URL" + +#: utils/details_payload.py:276 utils/details_payload.py:354 +msgid "Model" +msgstr "型號" + +#: utils/details_payload.py:277 utils/details_payload.py:355 +msgid "Model URL" +msgstr "型號 URL" + +#: utils/details_payload.py:278 utils/details_payload.py:351 +msgid "MAC address" +msgstr "MAC 位址" + +#: utils/details_payload.py:284 +msgid "Serial number" +msgstr "序號" + +#: utils/details_payload.py:286 +msgid "Unique identifier" +msgstr "唯一識別碼" + +#: utils/details_payload.py:350 +msgid "Hostname" +msgstr "主機名稱" + +#: discovery/manager.py:2485 discovery/ssdp.py:509 discovery/mdns.py:916 +#: discovery/wsd.py:94 +msgid "Routers & Gateways" +msgstr "路由器與閘道" + +#: discovery/manager.py:2486 discovery/ssdp.py:510 discovery/mdns.py:917 +#: discovery/wsd.py:95 +msgid "Media Servers" +msgstr "媒體伺服器" + +#: discovery/manager.py:2487 discovery/manager.py:2488 +#: discovery/manager.py:2489 discovery/ssdp.py:511 discovery/ssdp.py:512 +#: discovery/ssdp.py:513 discovery/mdns.py:918 discovery/mdns.py:919 +#: discovery/mdns.py:920 discovery/mdns.py:921 discovery/wsd.py:96 +#: discovery/wsd.py:97 discovery/wsd.py:98 discovery/wsdd_client.py:86 +msgid "Printers" +msgstr "印表機" + +#: discovery/manager.py:2490 discovery/ssdp.py:514 discovery/mdns.py:922 +#: discovery/wsd.py:99 +msgid "Smart Speakers" +msgstr "智慧喇叭" + +#: discovery/manager.py:2491 discovery/ssdp.py:515 discovery/mdns.py:923 +#: discovery/wsd.py:100 +msgid "Smart TVs" +msgstr "智慧電視" + +#: discovery/manager.py:2492 discovery/ssdp.py:516 discovery/mdns.py:924 +#: discovery/wsd.py:101 +msgid "Smart Devices" +msgstr "智慧裝置" + +#: discovery/manager.py:2493 discovery/ssdp.py:517 discovery/mdns.py:925 +#: discovery/wsd.py:102 +msgid "Cameras" +msgstr "攝影機" + +#: discovery/manager.py:2494 discovery/ssdp.py:518 discovery/mdns.py:926 +#: discovery/wsd.py:103 +msgid "Home Appliances" +msgstr "家用電器" + +#: discovery/manager.py:2495 discovery/ssdp.py:519 discovery/mdns.py:927 +#: discovery/wsd.py:104 +msgid "CNC Machines" +msgstr "CNC 機械" + +#: discovery/manager.py:2496 discovery/ssdp.py:520 discovery/mdns.py:928 +#: discovery/wsd.py:105 +msgid "3D Printers" +msgstr "3D 印表機" + +#: discovery/manager.py:2497 discovery/ssdp.py:521 discovery/mdns.py:929 +#: discovery/wsd.py:106 +msgid "NAS / File Servers" +msgstr "NAS / 檔案伺服器" + +#: discovery/manager.py:2498 discovery/ssdp.py:522 discovery/mdns.py:930 +#: discovery/wsd.py:107 discovery/wsdd_client.py:84 discovery/netbios.py:360 +msgid "Computers" +msgstr "電腦" + +#: discovery/manager.py:2499 discovery/mdns.py:931 discovery/wsd.py:108 +msgid "ESP3D Devices" +msgstr "ESP3D 裝置" + +#: discovery/manager.py:2500 discovery/manager.py:2501 discovery/ssdp.py:523 +#: discovery/ssdp.py:524 discovery/mdns.py:445 discovery/mdns.py:492 +#: discovery/mdns.py:774 discovery/mdns.py:874 discovery/mdns.py:932 +#: discovery/mdns.py:933 discovery/mdns.py:934 discovery/wsd.py:109 +#: discovery/wsd.py:110 discovery/wsdd_client.py:87 +msgid "Unknown Devices" +msgstr "未知裝置" + +#: ui/ +#, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format, python-brace-format +msgid "About NetNeighbor" +msgstr "關於 NetNeighbor" + +#: ui/ +msgid "App logo under assets/icons: Luc LEBOSSE" +msgstr "應用程式圖示位於 assets/icons:Luc LEBOSSE" + +#: ui/ +msgid "Applications" +msgstr "應用程式" + +#: ui/ +msgid "Apply" +msgstr "套用" + +#: ui/ +msgid "Author: Luc" +msgstr "作者:Luc" + +#: ui/ +msgid "Close to system tray / panel instead of exiting" +msgstr "關閉至系統匣而非結束" + +#: ui/ +msgid "Command" +msgstr "命令" + +#: ui/ +msgid "" +"Command templates for opening device connections. Leave empty to use the " +"system default." +msgstr "開啟裝置連線的命令範本。留空則使用系統預設值。" + +#: ui/ +msgid "Commands" +msgstr "命令" + +#: ui/ +msgid "Custom command (additional)" +msgstr "自訂命令(附加)" + +#: ui/ +msgid "Dark" +msgstr "深色" + +#: ui/ +msgid "Date / Time" +msgstr "日期 / 時間" + +#: ui/ +msgid "Delete" +msgstr "刪除" + +#: ui/ +msgid "Desktop notifications" +msgstr "桌面通知" + +#: ui/ +msgid "Discovery refresh requested" +msgstr "已要求重新整理探索" + +#: ui/ +msgid "Edit" +msgstr "編輯" + +#: ui/ +msgid "Edit type preset" +msgstr "編輯類型預設" + +#: ui/ +msgid "Error" +msgstr "錯誤" + +#: ui/ +msgid "Extra large" +msgstr "特大" + +#: ui/ +msgid "Field mapping rules" +msgstr "欄位對應規則" + +#: ui/ +msgid "GNU Lesser General Public License version 3 or later" +msgstr "GNU 寬鬆通用公共授權條款第3版或更高版本" + +#: ui/ +msgid "General" +msgstr "一般" + +#: ui/ +msgid "Hidden devices" +msgstr "隱藏的裝置" + +#: ui/ +msgid "Hide device" +msgstr "隱藏裝置" + +#: ui/device_context_menu.py ui/main_window.py +msgid "Clear device" +msgstr "清除裝置" + +#: ui/main_window.py +#, python-brace-format +msgid "" +"Remove {name} ({ip}) from the cache and all preferences?\n" +"\n" +"This cannot be undone. The device will reappear if rediscovered on the network." +msgstr "" +"將 {name}({ip})從快取和所有偏好設定中移除?\n" +"\n" +"此操作無法復原。如果在網路上重新發現該裝置,它將再次出現。" + +#: ui/ +msgid "Hide sidebar" +msgstr "隱藏側邊欄" + +#: ui/ +msgid "Hide window" +msgstr "隱藏視窗" + +#: ui/ +msgid "Icons size" +msgstr "圖示大小" + +#: ui/ +msgid "Invalid command template for this protocol." +msgstr "此協議的命令範本無效。" + +#: ui/ +msgid "Large" +msgstr "大" + +#: ui/ +msgid "Last seen: {n} d ago" +msgstr "最後發現:{n} 天前" + +#: ui/ +msgid "Last seen: {n} h ago" +msgstr "最後發現:{n} 小時前" + +#: ui/ +msgid "Last seen: {n} min ago" +msgstr "最後發現:{n} 分鐘前" + +#: ui/ +msgid "Light" +msgstr "淺色" + +#: ui/ +msgid "Location name:" +msgstr "位置名稱:" + +#: ui/ +msgid "Locations" +msgstr "位置" + +#: ui/ +msgid "Manage location presets shown in the right-click menu." +msgstr "管理右鍵選單中顯示的位置預設。" + +#: ui/ +msgid "Medium" +msgstr "中" + +#: ui/ +msgid "Mode" +msgstr "模式" + +#: ui/ +msgid "NetNeighbor {}" +msgstr "NetNeighbor {}" + +#: ui/ +msgid "New name:" +msgstr "新名稱:" + +#: ui/ +msgid "No devices yet" +msgstr "尚無裝置" + +#: ui/ +msgid "No hidden devices" +msgstr "沒有隱藏的裝置" + +#: ui/ +msgid "" +"Notification delivery depends on the OS and session. Tray-backed behaviour " +"(close to tray, minimized start) will align once the system tray is " +"implemented." +msgstr "通知的發送取決於作業系統和工作階段。基於托盤的行為(關閉至托盤、最小化啟動)將在系統托盤實作後對齊。" + +#: ui/ +msgid "Notifications" +msgstr "通知" + +#: ui/ +msgid "Offline" +msgstr "離線" + +#: ui/ +msgid "Online" +msgstr "線上" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. For 'custom' scheme, " +"enter the command template in IP/Host ({ip}, {port}, {name}, {type}, " +"{category}, {url}). IP/Host and Port are optional for other schemes." +msgstr "" +"依協議覆蓋或新增連線端點。對於 'custom' 方案,請在 IP/主機 ({ip}, {port}, {name}, {type}, " +"{category}, {url}) 中輸入命令範本。對於其他方案,IP/主機和連接埠是選擇性的。" + +#: ui/ +msgid "Preferences…" +msgstr "偏好設定…" + +#: ui/ +msgid "Qt for Python bindings" +msgstr "Qt for Python 繫結" + +#: ui/ +msgid "Reload discovery" +msgstr "重新載入探索" + +#: ui/ +msgid "Scheme" +msgstr "方案" + +#: ui/ +msgid "See the" +msgstr "請參閱" + +#: ui/ +msgid "Select an icon, then OK. IDs are stored in your preferences." +msgstr "選擇圖示,然後點擊確定。ID 儲存在您的偏好設定中。" + +#: ui/ +msgid "Service type" +msgstr "服務類型" + +#: ui/ +msgid "Session" +msgstr "工作階段" + +#: ui/ +msgid "Show sidebar" +msgstr "顯示側邊欄" + +#: ui/ +msgid "Show window" +msgstr "顯示視窗" + +#: ui/ +msgid "Sidebar" +msgstr "側邊欄" + +#: ui/ +msgid "Small" +msgstr "小" + +#: ui/ +msgid "Start Scanning…" +msgstr "正在掃描…" + +#: ui/ +msgid "Theme" +msgstr "主題" + +#: ui/ +msgid "This program comes with absolutely no warranty." +msgstr "本程式不提供任何保證。" + +#: ui/ +msgid "Types" +msgstr "類型" + +#: ui/ +msgid "Use as Friendly name" +msgstr "用作易記名稱" + +#: ui/ +msgid "Use as Information" +msgstr "用作資訊" + +#: ui/ +msgid "Use as Location" +msgstr "用作位置" + +#: ui/ +msgid "Use icon from" +msgstr "使用圖示來自" + +#: ui/ +msgid "Version {version}" +msgstr "版本 {version}" + +#: ui/ +msgid "WS-Discovery (Windows devices)" +msgstr "WS-Discovery(Windows 裝置)" + +#: ui/ +msgid "for details." +msgstr "以瞭解詳情。" + +#: ui/ +msgid "mDNS/DNS-SD discovery" +msgstr "mDNS/DNS-SD 探索" + +#: ui/ +msgid "not yet downloaded" +msgstr "尚未下載" + +#: ui/ +msgid "{} devices" +msgstr "{} 個裝置" + +#: ui/preferences_dialog.py +msgid "Maintenance" +msgstr "維護" + +#: ui/preferences_dialog.py +msgid "Reset all application data…" +msgstr "重設所有應用程式資料…" + +#: ui/preferences_dialog.py +msgid "Reset all application data?" +msgstr "重設所有應用程式資料?" + +#: ui/preferences_dialog.py +msgid "" +"All preferences, cached icons, discovery data and logs will be permanently deleted:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"NetNeighbor will use default settings on next start.\n" +"This action cannot be undone." +msgstr "" +"所有偏好設定、快取圖示、探索資料和日誌將被永久刪除:\n" +"• ~/.config/netneighbor\n" +"• ~/.cache/netneighbor\n" +"\n" +"下次啟動時 NetNeighbor 將使用預設設定。\n" +"此操作無法復原。" + +#: ui/preferences_dialog.py +msgid "Reset done — please restart" +msgstr "重設完成 — 請重新啟動應用程式" + +#: ui/ +msgid "App icon pack" +msgstr "應用程式圖示包" + +#: ui/ +msgid "Download failed" +msgstr "下載失敗" + +#: ui/ +msgid "Downloading…" +msgstr "下載中…" + +#: ui/ +msgid "Icon pack" +msgstr "圖示包" + +#: ui/ +msgid "NetNeighbor (built-in)" +msgstr "NetNeighbor(內建)" + +#: ui/ +msgid "" +"No icons found. Add PNGs under assets/icons/netneighbor or " +"~/.config/netneighbor/custom_icons/." +msgstr "" +"找不到圖示。請在 assets/icons/netneighbor 或 ~/.config/netneighbor/custom_icons/ 下新增 " +"PNG。" + +#: ui/ +msgid "Open folder…" +msgstr "開啟資料夾…" + +#: ui/ +msgid "NetNeighbor" +msgstr "NetNeighbor" + +#. app_qt.py:136 +msgid "Corrupted installation" +msgstr "安裝已損毀" + +#. app_qt.py:138 +msgid "" +"NetNeighbor cannot start because required files are missing or corrupted:\n" +"\n" +"{details}\n" +"\n" +"Please reinstall the program." +msgstr "" +"由於缺少必要檔案或檔案已損毀,NetNeighbor 無法啟動:\n" +"\n" +"{details}\n" +"\n" +"請重新安裝程式。" + +#: ui/ +msgid "All-in-one computer" +msgstr "一體化電腦" + +#: ui/ +msgid "Desktop computer" +msgstr "桌上型電腦" + +#: ui/ +msgid "Laptop" +msgstr "筆記型電腦" + +#: ui/ +msgid "Mini PC" +msgstr "迷你電腦" + +#: ui/ +msgid "Rack server" +msgstr "機架伺服器" + +#: ui/ +msgid "Server" +msgstr "伺服器" + +#: ui/ +msgid "Servers" +msgstr "伺服器" + +#: ui/ +msgid "Phones & Tablets" +msgstr "手機與平板電腦" + +#: ui/ +msgid "Smartphone" +msgstr "智慧型手機" + +#: ui/ +msgid "" +"Mode 'disabled' hides the auto-detected entry of that protocol (for " +"'custom', the global custom command); its other fields are ignored." +msgstr "「disabled」模式會隱藏該協定的自動偵測項目(對於「custom」,則隱藏全域自訂命令);其他欄位將被忽略。" + +#: ui/ +msgid "" +"Override or add connection endpoints per protocol. Placeholders: {ip}, " +"{port}, {name}, {type}, {category}, {url}. For 'custom' scheme, Command is " +"the command line to run. For other schemes, Command is the host or address " +"to open (e.g. {ip}, {url}, http://{ip}:8080/admin); Command and Port are " +"optional." +msgstr "" +"依通訊協定覆寫或新增連線端點。預留位置: {ip}、{port}、{name}、{type}、{category}、{url}。若為 'custom' " +"配置,命令是要執行的命令列。若為其他配置,命令是要開啟的主機或位址 (例如 " +"{ip}、{url}、http://{ip}:8080/admin);命令和連接埠為選用項。" + +#: ui/ +msgid "Could not open Spotify." +msgstr "無法開啟 Spotify。" diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..5f79fb0f --- /dev/null +++ b/app/main.py @@ -0,0 +1,46 @@ +# File main.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Application entry point.""" + +import multiprocessing +import os +import sys + +if __name__ == "__main__": + # Required for PyInstaller on Windows: prevents frozen child processes from + # re-running the full app when multiprocessing spawns a worker. + multiprocessing.freeze_support() + # PySide6 6.5.x crashes on macOS in QLocale.system() when LANG is unset + # (apps launched from Finder/Dock don't inherit shell env vars). + # Detect the system locale; fall back to C.UTF-8 (encoding-safe, language-neutral). + # libpng warning from Qt/PySide6 internal resources on macOS — not fixable at source. + if sys.platform == "darwin": + os.environ.setdefault("QT_LOGGING_RULES", "qt.gui.imageio=false") + if sys.platform == "darwin" and not os.environ.get("LANG"): + import locale as _locale + try: + _locale.setlocale(_locale.LC_ALL, "") + _loc, _enc = _locale.getlocale() + _lang = f"{_loc}.{_enc}" if _loc else "C.UTF-8" + except Exception: + _lang = "C.UTF-8" + os.environ["LANG"] = _lang + os.environ.setdefault("LC_ALL", _lang) + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + # zeroconf uses asyncio internally; on Windows the default ProactorEventLoop is + # unstable with UDP sockets and crashes (WinError 59) when interfaces change or + # devices disconnect mid-scan. Force the SelectorEventLoop before zeroconf is + # imported anywhere in the process. + if sys.platform == "win32": + import asyncio + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + try: + asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + except Exception: + pass + from app_qt import main + raise SystemExit(main()) diff --git a/app/model/__init__.py b/app/model/__init__.py new file mode 100644 index 00000000..f36905c8 --- /dev/null +++ b/app/model/__init__.py @@ -0,0 +1,5 @@ +# File __init__.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Data model package.""" diff --git a/model/device.py b/app/model/device.py similarity index 77% rename from model/device.py rename to app/model/device.py index 6f5de53d..cd582a3c 100644 --- a/model/device.py +++ b/app/model/device.py @@ -1,5 +1,5 @@ -# File device.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File device.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Device model used by the UI and discovery layers.""" @@ -21,6 +21,7 @@ class Device: last_seen: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) online: bool = True monitored: bool = False + hidden: bool = False icon: str | None = None @property @@ -28,14 +29,21 @@ def key(self) -> str: metadata = self.metadata if isinstance(self.metadata, dict) else {} if self.source == "ssdp": xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - udn = xml_fields.get("UDN") or metadata.get("udn") - if isinstance(udn, str) and udn.strip(): - return f"ssdp:udn:{udn.strip().lower()}" + # Prefer SSDP USN (unique per advertisement) over XML UDN — bundled descriptors + # (e.g. Sonos group XML) can repeat the same UDN across different speakers. usn = metadata.get("usn") if isinstance(usn, str) and usn.strip(): usn_base = usn.strip().lower().split("::", 1)[0] if usn_base: return f"ssdp:usn:{usn_base}" + # Profile-cache bootstrap rows often have no USN on disk; never collapse by duplicate UDN. + if metadata.get("from_ssdp_cache"): + ip_s = str(self.ip).strip() + if ip_s and ip_s not in {"", "0.0.0.0"}: + return f"ssdp:cache:{ip_s}:{int(self.port)}" + udn = xml_fields.get("UDN") or metadata.get("udn") + if isinstance(udn, str) and udn.strip(): + return f"ssdp:udn:{udn.strip().lower()}" mac = ( xml_fields.get("mac") or metadata.get("mac") diff --git a/app/ui/__init__.py b/app/ui/__init__.py new file mode 100644 index 00000000..611588c6 --- /dev/null +++ b/app/ui/__init__.py @@ -0,0 +1,20 @@ +# File __init__.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Desktop UI package — NetNeighbor 2.0 (PySide6).""" + +from .icon_picker_dialog import IconPickerDialog, pick_device_icon_id +from .main_window import NetNeighborMainWindow +from .preferences_dialog import PreferencesDialog +from .scheduler import MainThreadScheduler +from .systray import NetNeighborTray + +__all__ = [ + "IconPickerDialog", + "MainThreadScheduler", + "NetNeighborMainWindow", + "NetNeighborTray", + "PreferencesDialog", + "pick_device_icon_id", +] diff --git a/app/ui/about_dialog.py b/app/ui/about_dialog.py new file mode 100644 index 00000000..fabea7a0 --- /dev/null +++ b/app/ui/about_dialog.py @@ -0,0 +1,196 @@ +# File about_dialog.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""About dialog — same content as GTK V1 (GitHub, license link, in-dialog Credits).""" + +from __future__ import annotations + +import html +from gettext import gettext as _ + +from PySide6.QtCore import Qt +from PySide6.QtGui import QPixmap +from PySide6.QtWidgets import ( + QDialog, + QDialogButtonBox, + QHBoxLayout, + QLabel, + QPushButton, + QStackedWidget, + QTextBrowser, + QVBoxLayout, + QWidget, +) + +from ui.icons import resolve_app_logo_path +from utils.about_content import ( + GITHUB_PROJECT_URL, + about_comments, + about_copyright_line, + about_license_notice_html, + about_program_name, + about_warranty_line, + about_website_label, + credits_html, +) +from utils.app_version import get_app_version + +_PAGE_ABOUT = 0 +_PAGE_CREDITS = 1 + + +def _centered_label( + text: str, + *, + rich: bool = False, + external_links: bool = False, +) -> QLabel: + lbl = QLabel(text) + lbl.setWordWrap(True) + lbl.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop) + if rich: + lbl.setTextFormat(Qt.TextFormat.RichText) + if external_links: + lbl.setOpenExternalLinks(True) + lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction) + return lbl + + +class AboutDialog(QDialog): + """Modal About box with Credits page in the same window (GTK-style).""" + + def __init__(self, parent: QWidget | None = None) -> None: + super().__init__(parent) + self.setWindowTitle(_("About NetNeighbor")) + self.setModal(True) + self.resize(480, 420) + + self._stack = QStackedWidget() + self._stack.addWidget(self._build_about_page()) + self._stack.addWidget(self._build_credits_page()) + self._stack.currentChanged.connect(self._on_page_changed) + + self._btn_credits = QPushButton(_("Credits")) + self._btn_credits.clicked.connect(self._on_credits_clicked) + + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + buttons.rejected.connect(self.reject) + close_btn = buttons.button(QDialogButtonBox.StandardButton.Close) + if close_btn is not None: + close_btn.setText(_("Close")) + close_btn.setDefault(True) + close_btn.setAutoDefault(True) + + footer = QHBoxLayout() + footer.addWidget(self._btn_credits) + footer.addStretch(1) + footer.addWidget(buttons) + + root = QVBoxLayout(self) + root.addWidget(self._stack, stretch=1) + root.addLayout(footer) + + self._on_page_changed(_PAGE_ABOUT) + + def _build_about_page(self) -> QWidget: + page = QWidget() + outer = QVBoxLayout(page) + outer.setContentsMargins(16, 16, 16, 8) + outer.addStretch(1) + + logo_lbl = QLabel() + logo_lbl.setAlignment(Qt.AlignmentFlag.AlignHCenter) + logo_path = resolve_app_logo_path() + if logo_path is not None: + pix = QPixmap(str(logo_path)) + if not pix.isNull(): + logo_lbl.setPixmap( + pix.scaled( + 128, + 128, + Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + ) + outer.addWidget(logo_lbl) + outer.addSpacing(12) + + outer.addWidget( + _centered_label( + f"{html_escape(about_program_name())}", rich=True + ) + ) + outer.addWidget( + _centered_label( + _("Version {version}").format(version=html_escape(get_app_version())), + rich=True, + ) + ) + outer.addSpacing(8) + outer.addWidget( + _centered_label(html_escape(about_comments()), rich=True) + ) + outer.addSpacing(12) + outer.addWidget( + _centered_label( + '{label}'.format( + url=html_escape_attr(GITHUB_PROJECT_URL), + label=html_escape(about_website_label()), + ), + rich=True, + external_links=True, + ) + ) + outer.addSpacing(10) + outer.addWidget(_centered_label(html_escape(about_warranty_line()), rich=True)) + outer.addSpacing(6) + outer.addWidget( + _centered_label(about_license_notice_html(), rich=True, external_links=True) + ) + outer.addSpacing(12) + outer.addWidget(_centered_label(html_escape(_("Author: Luc")), rich=True)) + outer.addWidget( + _centered_label(html_escape(about_copyright_line()), rich=True) + ) + outer.addStretch(1) + + return page + + def _build_credits_page(self) -> QWidget: + page = QWidget() + layout = QVBoxLayout(page) + layout.setContentsMargins(12, 12, 12, 8) + heading = QLabel(f"{html_escape(_('Credits'))}") + heading.setTextFormat(Qt.TextFormat.RichText) + browser = QTextBrowser() + browser.setOpenExternalLinks(True) + browser.setHtml(credits_html()) + browser.setFrameShape(QTextBrowser.Shape.NoFrame) + layout.addWidget(heading) + layout.addWidget(browser, stretch=1) + return page + + def _on_credits_clicked(self) -> None: + if self._stack.currentIndex() == _PAGE_CREDITS: + self._stack.setCurrentIndex(_PAGE_ABOUT) + else: + self._stack.setCurrentIndex(_PAGE_CREDITS) + + def _on_page_changed(self, index: int) -> None: + if index == _PAGE_CREDITS: + self._btn_credits.setText(_("About")) + else: + self._btn_credits.setText(_("Credits")) + + +def html_escape(text: str) -> str: + return html.escape(text, quote=False) + + +def html_escape_attr(text: str) -> str: + return html.escape(text, quote=True) + + +def show_about_dialog(parent: QWidget | None = None) -> None: + AboutDialog(parent).exec() diff --git a/app/ui/app_theme.py b/app/ui/app_theme.py new file mode 100644 index 00000000..0fd844d7 --- /dev/null +++ b/app/ui/app_theme.py @@ -0,0 +1,153 @@ +# File app_theme.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Fusion color-scheme management: OS dark/light detection + runtime switching. + +Entry point: call ``setup_fusion_theme(app)`` once after ``app.setStyle("Fusion")``. +Add dialog / widget stylesheet overrides here as the UI evolves. + +Hover / active color contract (used by all widget stylesheets): + - hover → palette(alternate-base) light blue tint, both themes + - active → palette(highlight) full blue, both themes +""" + +from __future__ import annotations + +import logging +import sys + +from PySide6.QtCore import Qt +from PySide6.QtGui import QColor, QPalette +from PySide6.QtWidgets import QApplication + +_LOG = logging.getLogger(__name__) + +# Light blue used as hover tint in both themes (alternate-base palette role). +_HOVER_LIGHT = QColor(225, 240, 255) # very pale blue on white backgrounds +_HOVER_DARK = QColor(38, 58, 84) # dark blue tint on dark backgrounds + + +def _make_fusion_dark_palette() -> QPalette: + p = QPalette() + p.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53)) + p.setColor(QPalette.ColorRole.WindowText, Qt.GlobalColor.white) + p.setColor(QPalette.ColorRole.Base, QColor(25, 25, 25)) + p.setColor(QPalette.ColorRole.AlternateBase, _HOVER_DARK) + p.setColor(QPalette.ColorRole.ToolTipBase, QColor(40, 40, 40)) + p.setColor(QPalette.ColorRole.ToolTipText, Qt.GlobalColor.white) + p.setColor(QPalette.ColorRole.Text, Qt.GlobalColor.white) + p.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53)) + p.setColor(QPalette.ColorRole.ButtonText, Qt.GlobalColor.white) + p.setColor(QPalette.ColorRole.BrightText, Qt.GlobalColor.red) + p.setColor(QPalette.ColorRole.Link, QColor(42, 130, 218)) + p.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218)) + p.setColor(QPalette.ColorRole.HighlightedText, Qt.GlobalColor.black) + p.setColor(QPalette.ColorRole.Mid, QColor(40, 40, 40)) + p.setColor(QPalette.ColorRole.Shadow, QColor(20, 20, 20)) + _disabled = QPalette.ColorGroup.Disabled + _grey = QColor(127, 127, 127) + p.setColor(_disabled, QPalette.ColorRole.WindowText, _grey) + p.setColor(_disabled, QPalette.ColorRole.Text, _grey) + p.setColor(_disabled, QPalette.ColorRole.ButtonText, _grey) + p.setColor(_disabled, QPalette.ColorRole.Highlight, QColor(80, 80, 80)) + return p + + +# Global stylesheet applied on QApplication for widgets without their own stylesheet. +# Covers QMenuBar top-level items (Fusion leaves them without any hover by default). +_GLOBAL_QSS = ( + "QDialog { background-color: palette(base); }" + "QMenuBar::item:selected {" + " background-color: palette(alternate-base);" + " color: palette(text);" + " border-radius: 2px;" + "}" + "QMenu::item:selected {" + " background-color: palette(alternate-base);" + " color: palette(text);" + "}" + "QGroupBox {" + " background-color: palette(base);" + " border: 1px solid palette(mid);" + " border-radius: 4px;" + " margin-top: 16px;" + " padding: 8px 4px 4px 4px;" + "}" + "QGroupBox::title {" + " subcontrol-origin: margin;" + " subcontrol-position: top left;" + " left: 8px;" + " top: 2px;" + " background-color: palette(base);" + " padding: 0 4px;" + " color: palette(text);" + "}" +) + + +def _set_windows_titlebar_dark(dark: bool) -> None: + """Tell DWM to use dark or light title bars for all current top-level windows.""" + if sys.platform != "win32": + return + try: + import ctypes + DWMWA_USE_IMMERSIVE_DARK_MODE = 20 + value = ctypes.c_int(1 if dark else 0) + for widget in QApplication.topLevelWidgets(): + hwnd = int(widget.winId()) + if hwnd: + ctypes.windll.dwmapi.DwmSetWindowAttribute( + hwnd, + DWMWA_USE_IMMERSIVE_DARK_MODE, + ctypes.byref(value), + ctypes.sizeof(value), + ) + except Exception: + _LOG.debug("DwmSetWindowAttribute failed", exc_info=True) + + +def _apply_color_scheme(app: QApplication, scheme: Qt.ColorScheme) -> None: + if scheme == Qt.ColorScheme.Dark: + _LOG.debug("Applying Fusion dark palette") + app.setPalette(_make_fusion_dark_palette()) + else: + _LOG.debug("Applying Fusion light palette") + palette = app.style().standardPalette() + palette.setColor(QPalette.ColorRole.AlternateBase, _HOVER_LIGHT) + app.setPalette(palette) + app.setStyleSheet(_GLOBAL_QSS) + dark = scheme == Qt.ColorScheme.Dark + _set_windows_titlebar_dark(dark) + # Deferred call covers windows not yet shown at startup (no HWND yet on first call). + from PySide6.QtCore import QTimer + QTimer.singleShot(0, lambda: _set_windows_titlebar_dark(dark)) + + +def apply_color_scheme(app: QApplication, scheme: Qt.ColorScheme | None = None) -> None: + """Apply a color scheme immediately without touching the colorSchemeChanged signal. + + Pass ``None`` to re-apply the current OS preference. + """ + if scheme is None: + scheme = app.styleHints().colorScheme() + _apply_color_scheme(app, scheme) + + +def setup_fusion_theme( + app: QApplication, + *, + forced_scheme: Qt.ColorScheme | None = None, +) -> None: + """Apply Fusion palette and track OS color-scheme changes. + + Pass ``forced_scheme`` (Dark or Light) to lock the theme regardless of the OS setting. + When ``None`` (default) the OS preference is used and runtime changes are tracked. + """ + if forced_scheme is not None: + _LOG.debug("Color scheme forced to %s", forced_scheme) + _apply_color_scheme(app, forced_scheme) + return + hints = app.styleHints() + _apply_color_scheme(app, hints.colorScheme()) + hints.colorSchemeChanged.connect(lambda scheme: _apply_color_scheme(app, scheme)) diff --git a/app/ui/device_actions.py b/app/ui/device_actions.py new file mode 100644 index 00000000..82924444 --- /dev/null +++ b/app/ui/device_actions.py @@ -0,0 +1,194 @@ +# File device_actions.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Device actions shared by the Qt main window (open, rename, commands).""" + +from __future__ import annotations + +from gettext import gettext as _ + +from PySide6.QtWidgets import ( + QDialog, + QDialogButtonBox, + QHBoxLayout, + QLabel, + QLineEdit, + QMessageBox, + QPushButton, + QVBoxLayout, + QWidget, +) + +from utils.connect_launcher import launch_connect_for_uri +from utils.custom_command import build_argv_from_template, spawn_custom_command_detached +from utils.device_bundles import DeviceBundle + + +def show_command_error(parent: QWidget, message: str) -> None: + QMessageBox.critical(parent, _("Error"), message) + + +def bundle_custom_command(bundle: DeviceBundle) -> str: + for dev in bundle.devices: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + # New: look for custom scheme override in device_commands + cmds = md.get("device_commands") + if isinstance(cmds, list): + for c in cmds: + if (isinstance(c, dict) + and c.get("scheme") == "custom" + and c.get("mode") == "override"): + tmpl = str(c.get("ip", "")).strip() + if tmpl: + return tmpl + # Legacy: flat custom_command field + cmd = md.get("custom_command") + if isinstance(cmd, str) and cmd.strip(): + return cmd.strip() + return "" + + +def bundle_global_custom_command_disabled(bundle: DeviceBundle) -> bool: + """True when the device has a ``custom`` entry in ``disabled`` mode (hide the global command).""" + for dev in bundle.devices: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + cmds = md.get("device_commands") + if isinstance(cmds, list): + return any( + isinstance(c, dict) and c.get("scheme") == "custom" and c.get("mode") == "disabled" + for c in cmds + ) + return False + + +def effective_global_custom_command(bundle: DeviceBundle, global_template: str) -> str: + """Global custom command template, or ``""`` when disabled for this device.""" + if bundle_global_custom_command_disabled(bundle): + return "" + return (global_template or "").strip() + + +def bundle_all_custom_commands(bundle: DeviceBundle) -> list[tuple[str, str]]: + """Return all custom scheme entries as (label, template) pairs (override first).""" + result: list[tuple[str, str]] = [] + seen: set[str] = set() + for dev in bundle.devices: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + cmds = md.get("device_commands") + if isinstance(cmds, list): + for c in cmds: + if not isinstance(c, dict) or c.get("scheme") != "custom": + continue + tmpl = str(c.get("ip", "")).strip() + if not tmpl or tmpl in seen: + continue + seen.add(tmpl) + label = str(c.get("label", "")).strip() or ( + _("Custom command") if c.get("mode") == "override" + else _("Custom command (additional)") + ) + result.append((label, tmpl)) + # Legacy flat field (only if no device_commands custom entry yet) + if not result: + cmd = md.get("custom_command") + if isinstance(cmd, str) and cmd.strip() and cmd.strip() not in seen: + seen.add(cmd.strip()) + result.append((_("Custom command"), cmd.strip())) + return result + + +def run_custom_command_for_bundle( + parent: QWidget, + bundle: DeviceBundle, + *, + global_template: str, + connect_templates: dict[str, str], +) -> None: + per_device = bundle_custom_command(bundle) + tmpl = per_device or effective_global_custom_command(bundle, global_template) + if not tmpl: + return + d = bundle.primary + argv = build_argv_from_template( + tmpl, + ip=bundle.ip, + port=int(bundle.port), + name=bundle.name or "", + type_=d.type or "", + category=d.category or "", + url="", + ) + if argv is None: + show_command_error( + parent, _("Could not parse the custom command (check placeholders).") + ) + return + + def _on_err(msg: str) -> None: + show_command_error( + parent, + _("Could not start the command: {error}").format(error=msg), + ) + + spawn_custom_command_detached(argv, on_error=_on_err) + + +def launch_open_uri( + parent: QWidget, + bundle: DeviceBundle, + uri: str, + *, + connect_templates: dict[str, str], + global_custom_command: str, +) -> None: + d = bundle.primary + err = launch_connect_for_uri( + uri, + connect_templates, + ip=bundle.ip, + port=int(bundle.port), + name=bundle.name or "", + type_=d.type or "", + category=d.category or "", + device_cmd_override=( + bundle_custom_command(bundle) + or effective_global_custom_command(bundle, global_custom_command) + ), + ) + if err: + show_command_error( + parent, + _("Could not start the command: {error}").format(error=err), + ) + + +def prompt_rename_device(parent: QWidget, current_name: str) -> str | None | object: + """Return new name, ``None`` to clear override, or ``False`` if cancelled.""" + dlg = QDialog(parent) + dlg.setWindowTitle(_("Rename device")) + dlg.setModal(True) + dlg.resize(360, 120) + layout = QVBoxLayout(dlg) + layout.addWidget(QLabel(_("Custom name"))) + entry = QLineEdit() + entry.setText(current_name) + entry.selectAll() + layout.addWidget(entry) + buttons = QDialogButtonBox() + btn_reset = buttons.addButton(_("Reset"), QDialogButtonBox.ButtonRole.ResetRole) + buttons.addButton(QDialogButtonBox.StandardButton.Cancel) + buttons.addButton(QDialogButtonBox.StandardButton.Save) + buttons.accepted.connect(dlg.accept) + buttons.rejected.connect(dlg.reject) + _reset_code = 2 + btn_reset.clicked.connect(lambda: dlg.done(_reset_code)) + layout.addWidget(buttons) + + result = dlg.exec() + if result == QDialog.DialogCode.Rejected: + return False + if result == _reset_code: + return None + value = entry.text().strip() + return value if value else None diff --git a/app/ui/device_context_menu.py b/app/ui/device_context_menu.py new file mode 100644 index 00000000..07a3a4cc --- /dev/null +++ b/app/ui/device_context_menu.py @@ -0,0 +1,143 @@ +# File device_context_menu.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Right-click context menu for devices (parity with GTK ``DeviceList``).""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from gettext import gettext as _ + +from PySide6.QtCore import QPoint +from PySide6.QtWidgets import QMenu, QWidget + +from utils.device_bundles import DeviceBundle + + +def _default_type_choices() -> list[tuple[str, str | None]]: + return [ + (_("Auto"), None), + (_("NAS"), "nas"), + (_("Server"), "server"), + (_("Rack server"), "rackserver"), + (_("Computer"), "computer"), + (_("Desktop computer"), "desktop"), + (_("Mini PC"), "minipc"), + (_("All-in-one computer"), "allinone"), + (_("Laptop"), "laptop"), + (_("Smartphone"), "smartphone"), + (_("Router"), "router"), + (_("Media server"), "mediaserver"), + (_("Printer"), "printer"), + (_("Multifunction printer"), "multifunction_printer"), + (_("Printer (network / IPP)"), "networkprinter"), + (_("SmartSpeaker"), "smartspeaker"), + (_("SmartTV"), "smarttv"), + (_("SmartDevice"), "smartdevice"), + (_("Camera"), "camera"), + (_("HomeAppliance"), "homeappliance"), + (_("CNC"), "cnc"), + (_("3D printer"), "3dprinter"), + ] + + +def show_device_context_menu( + parent: QWidget, + global_pos: QPoint, + bundle: DeviceBundle, + *, + connect_targets: Sequence[tuple[str, str]], + location_options: Sequence[str], + type_options: Sequence[tuple[str, str]], + has_custom_command: bool, + on_open_uri: Callable[[str], None], + on_custom_command: Callable[[], None], + on_details: Callable[[], None], + on_options: Callable[[], None], + on_monitor: Callable[[bool], None], + on_hide: Callable[[], None], + on_rename: Callable[[], None], + on_location: Callable[[str | None], None], + on_type: Callable[[str | None], None], + on_clear: Callable[[], None], +) -> None: + menu = QMenu(parent) + + if len(connect_targets) == 1: + label, uri = connect_targets[0] + act = menu.addAction(_("Open ({label})").format(label=label)) + act.triggered.connect(lambda _checked=False, u=uri: on_open_uri(u)) + elif connect_targets: + sub = menu.addMenu(_("Open")) + for label, uri in connect_targets: + act = sub.addAction(label) + act.triggered.connect(lambda _checked=False, u=uri: on_open_uri(u)) + + if has_custom_command: + act_cmd = menu.addAction(_("Run custom command")) + act_cmd.triggered.connect(on_custom_command) + + act_details = menu.addAction(_("Details")) + act_details.triggered.connect(on_details) + + act_options = menu.addAction(_("Options")) + act_options.triggered.connect(on_options) + + if bundle.monitored: + act_unfollow = menu.addAction(_("Unfollow")) + act_unfollow.triggered.connect(lambda: on_monitor(False)) + else: + act_follow = menu.addAction(_("Monitor")) + act_follow.triggered.connect(lambda: on_monitor(True)) + + act_hide = menu.addAction(_("Hide device")) + act_hide.triggered.connect(on_hide) + + act_rename = menu.addAction(_("Rename")) + act_rename.triggered.connect(on_rename) + menu.addSeparator() + + act_clear = menu.addAction(_("Clear device")) + act_clear.triggered.connect(on_clear) + menu.addSeparator() + + current_location: str | None = None + for device in bundle.devices: + md = device.metadata if isinstance(device.metadata, dict) else {} + value = md.get("user_location") + if isinstance(value, str) and value.strip(): + current_location = value.strip() + break + + loc_menu = menu.addMenu(_("Location")) + auto_loc = loc_menu.addAction(_("Auto")) + auto_loc.setCheckable(True) + auto_loc.setChecked(current_location is None) + auto_loc.triggered.connect(lambda: on_location(None)) + for loc in location_options: + act = loc_menu.addAction(loc) + act.setCheckable(True) + act.setChecked(loc == current_location) + act.triggered.connect(lambda _c=False, v=loc: on_location(v)) + + type_menu = menu.addMenu(_("Device type")) + current_type = ( + bundle.primary.type.strip().lower() + if isinstance(bundle.primary.type, str) + else "unknown" + ) + choices = list(type_options) if type_options else _default_type_choices() + known = {slug for _lbl, slug in choices if slug is not None} + for label, type_value in choices: + act = type_menu.addAction(label) + act.setCheckable(True) + if type_value is None: + act.setChecked(current_type not in known) + else: + act.setChecked(current_type == type_value) + act.triggered.connect( + lambda _c=False, tv=type_value: on_type(tv) + ) + + menu.exec(global_pos) diff --git a/app/ui/device_details_dialog.py b/app/ui/device_details_dialog.py new file mode 100644 index 00000000..e6b12ca9 --- /dev/null +++ b/app/ui/device_details_dialog.py @@ -0,0 +1,1013 @@ +# File device_details_dialog.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Device details dialog (Qt port of ``ui/device_details.py`` — core tabs).""" + +from __future__ import annotations + +import logging +import subprocess +import sys +from collections.abc import Callable +from dataclasses import dataclass, field +from gettext import gettext as _ +import os +from typing import Any + +_LOG = logging.getLogger("ui.device_details") + +from PySide6.QtCore import QPoint, QUrl, Qt +from PySide6.QtGui import QDesktopServices, QFontDatabase, QGuiApplication, QPixmap +from PySide6.QtWidgets import ( + QAbstractItemView, + QButtonGroup, + QComboBox, + QDialog, + QDialogButtonBox, + QFrame, + QGridLayout, + QGroupBox, + QHBoxLayout, + QHeaderView, + QLabel, + QMenu, + QPushButton, + QRadioButton, + QScrollArea, + QSizePolicy, + QTabWidget, + QTableWidget, + QTableWidgetItem, + QTextBrowser, + QVBoxLayout, + QWidget, +) + +from ui.icons import user_custom_icons_dir +from utils.details_payload import detail_field_value_visible +from utils.device_details_view import DeviceDetailsViewModel + + +_VALID_SCHEMES = ["http", "https", "smb", "ftp", "ssh", "sftp", "telnet", "spotify", "custom"] +_VALID_MODES = ["override", "additional", "disabled"] + + +@dataclass(slots=True) +class DeviceCommandSettings: + device_commands: list[dict] = field(default_factory=list) + on_set_device_commands: Callable[[list[dict]], None] = field(default=lambda _: None) + + +@dataclass(slots=True) +class DeviceIconSettings: + icon_mode: str + has_device_icon_source: bool + provided_icon_display: str | None + selected_custom_icon_id: str | None + on_apply: Callable[[str, str | None], None] + on_pick_custom: Callable[[], str | None] + provided_icon_pixmap: QPixmap | None = None + provided_icon_native_size: tuple[int, int] | None = None + icon_cache: Any = None + icon_devices: list = field(default_factory=list) + + +class DeviceDetailsDialog(QDialog): + def __init__( + self, + parent: QWidget | None, + model: DeviceDetailsViewModel, + *, + initial_tab: str | None = None, + icon_settings: DeviceIconSettings | None = None, + command_settings: DeviceCommandSettings | None = None, + on_set_field_rule: Callable[[str, str], None] | None = None, + field_rules: dict[str, list[str]] | None = None, + on_delete_field_rule: Callable[[str, str], None] | None = None, + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Device details") + f" - {model.title}") + self.setModal(True) + self.resize(720, 520) + + self._icon_settings = icon_settings + self._on_set_field_rule = on_set_field_rule + self._field_rules: dict[str, list[str]] = field_rules or {} + self._on_delete_field_rule = on_delete_field_rule + self._field_rules_table: QTableWidget | None = None + self._field_rules_rows: list[tuple[str, str]] = [] + self._field_rules_del_btn: QPushButton | None = None + self._icon_mode_group: QButtonGroup | None = None + self._icon_detail_label: QLabel | None = None + self._provided_icon_preview: QLabel | None = None + self._provided_icon_size_lbl: QLabel | None = None + self._suppress_icon_signals = False + self._last_icon_mode = "provided" + self._cmd_table: QTableWidget | None = None + self._live_icon_cache: Any = None + self._live_icon_settings: DeviceIconSettings | None = None + + tabs = QTabWidget() + tabs.addTab(self._build_overview_tab(model), _("Overview")) + services = self._build_services_tab(model) + if services is not None: + tabs.addTab(services, _("Services")) + raw = self._build_raw_tab(model) + if raw is not None: + tabs.addTab(raw, _("Device data")) + if icon_settings is not None or command_settings is not None: + tabs.addTab( + self._build_options_tab(icon_settings, command_settings, model), + _("Options"), + ) + + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + buttons.rejected.connect(self.reject) + close_btn = buttons.button(QDialogButtonBox.StandardButton.Close) + if close_btn is not None: + close_btn.setText(_("Close")) + + layout = QVBoxLayout(self) + layout.addWidget(tabs, stretch=1) + layout.addWidget(buttons) + + if initial_tab == "options": + for i in range(tabs.count()): + if tabs.tabText(i) == _("Options"): + tabs.setCurrentIndex(i) + break + + def _build_overview_tab(self, model: DeviceDetailsViewModel) -> QWidget: + page = QWidget() + outer = QVBoxLayout(page) + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + inner = QWidget() + inner.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + # Scoped by objectName: an unscoped rule cascades into every child, + # including QComboBox popups, whose selected item then renders + # white-on-white (base background + highlighted-text colour). + inner.setObjectName("nnDetailsPageInner") + inner.setStyleSheet("#nnDetailsPageInner { background-color: palette(base); }") + grid = QGridLayout(inner) + grid.setColumnStretch(1, 1) + grid.setHorizontalSpacing(16) + grid.setVerticalSpacing(8) + + row = 0 + ov = model.overview + for label_key, key in ( + (_("Name"), "name"), + (_("IP address"), "ip"), + (_("Location"), "location"), + (_("Type"), "type"), + ): + val = (ov.get(key) or "").strip() if isinstance(ov.get(key), str) else "" + if not detail_field_value_visible(val): + continue + row = self._add_overview_row(grid, row, label_key, val) + + ip6 = (ov.get("ipv6_link_local") or "").strip() + ip_field = (ov.get("ip") or "").strip() + if detail_field_value_visible(ip6) and ip6 not in ip_field: + row = self._add_overview_row(grid, row, _("IPv6 (link-local)"), ip6) + + for key, value in model.fields: + if not detail_field_value_visible(value): + continue + row = self._add_overview_row(grid, row, str(key), value) + + grid.setRowStretch(row, 1) + scroll.setWidget(inner) + outer.addWidget(scroll) + return page + + @staticmethod + def _add_overview_row(grid: QGridLayout, row: int, label: str, value: str) -> int: + key_lbl = QLabel(f"{label}:") + key_lbl.setAlignment( + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop + ) + key_lbl.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum) + val_lbl = QLabel(value) + val_lbl.setWordWrap(True) + val_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + val_lbl.setSizePolicy( + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum + ) + val_lbl.setMinimumWidth(420) + grid.addWidget(key_lbl, row, 0) + grid.addWidget(val_lbl, row, 1) + return row + 1 + + def _build_services_tab(self, model: DeviceDetailsViewModel) -> QWidget | None: + show_rules = ( + self._on_set_field_rule is not None + or self._on_delete_field_rule is not None + or bool(self._field_rules) + ) + rules_box: QWidget | None = None + if show_rules: + rules_box = self._build_field_rules_box( + self._field_rules, + self._on_delete_field_rule or (lambda t, f: None), + ) + + if model.mdns_service_sections: + return self._build_mdns_services_page(model.mdns_service_sections, prefix_widget=rules_box) + + if not model.services_records: + if rules_box is None: + return None + page = QWidget() + lay = QVBoxLayout(page) + lay.setContentsMargins(12, 12, 12, 12) + lay.addWidget(rules_box) + lay.addStretch(1) + return page + + table = QTableWidget(len(model.services_records), 3) + table.setHorizontalHeaderLabels([_("Service"), _("Target"), _("Port")]) + table.horizontalHeader().setStretchLastSection(True) + table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) + for r, (svc, target, port) in enumerate(model.services_records): + table.setItem(r, 0, QTableWidgetItem(svc)) + table.setItem(r, 1, QTableWidgetItem(target)) + table.setItem(r, 2, QTableWidgetItem(port)) + table.resizeColumnsToContents() + if rules_box is None: + return table + page = QWidget() + lay = QVBoxLayout(page) + lay.setContentsMargins(12, 12, 12, 12) + lay.setSpacing(8) + lay.addWidget(rules_box) + lay.addWidget(table, stretch=1) + return page + + def _build_mdns_services_page( + self, sections: list[dict[str, Any]], *, prefix_widget: QWidget | None = None + ) -> QWidget: + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + inner = QWidget() + inner.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + # Scoped by objectName: an unscoped rule cascades into every child, + # including QComboBox popups, whose selected item then renders + # white-on-white (base background + highlighted-text colour). + inner.setObjectName("nnDetailsPageInner") + inner.setStyleSheet("#nnDetailsPageInner { background-color: palette(base); }") + layout = QVBoxLayout(inner) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(8) + if prefix_widget is not None: + layout.addWidget(prefix_widget) + txt_rule_handler = self._handle_txt_rule if self._on_set_field_rule is not None else None + for raw in sections: + if isinstance(raw, dict): + layout.addWidget( + MdnsServiceSection( + raw, + expanded=False, + on_txt_rule=txt_rule_handler, + ) + ) + layout.addStretch(1) + scroll.setWidget(inner) + return scroll + + def _build_field_rules_box( + self, + rules: dict[str, list[str]], + on_delete: Callable[[str, str], None], + ) -> QGroupBox: + self._field_rules_rows.clear() + for target_key, paths in rules.items(): + for path in paths: + self._field_rules_rows.append((target_key, path)) + + box = QGroupBox(_("Field mapping rules")) + box_layout = QVBoxLayout(box) + box_layout.setContentsMargins(8, 4, 8, 8) + box_layout.setSpacing(4) + + table = QTableWidget(len(self._field_rules_rows), 2) + self._field_rules_table = table + table.setHorizontalHeaderLabels([_("Target"), _("Field")]) + # Per-column resize modes instead of resizeColumnsToContents(): calling + # that on an already-visible table (rule added live) shrank the + # stretched last column to its content width until the next resize. + rules_hdr = table.horizontalHeader() + rules_hdr.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents) + rules_hdr.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + table.verticalHeader().setVisible(False) + self._populate_field_rules_table() + self._fit_field_rules_table_height() + box_layout.addWidget(table) + + btn_row = QHBoxLayout() + btn_row.addStretch(1) + del_btn = QPushButton(_("Remove")) + self._field_rules_del_btn = del_btn + del_btn.setEnabled(False) + btn_row.addWidget(del_btn) + box_layout.addLayout(btn_row) + + def _on_selection() -> None: + del_btn.setEnabled(table.currentRow() >= 0) + + def _on_remove() -> None: + r = table.currentRow() + if r < 0 or r >= len(self._field_rules_rows): + return + tk, fp = self._field_rules_rows[r] + self._field_rules_rows.pop(r) + # Keep _field_rules in sync + bucket = self._field_rules.get(tk, []) + if fp in bucket: + bucket.remove(fp) + if not bucket: + self._field_rules.pop(tk, None) + table.removeRow(r) + self._fit_field_rules_table_height() + del_btn.setEnabled(table.rowCount() > 0 and table.currentRow() >= 0) + on_delete(tk, fp) + + table.itemSelectionChanged.connect(_on_selection) + del_btn.clicked.connect(_on_remove) + return box + + def _populate_field_rules_table(self) -> None: + """Fill the rules table from self._field_rules_rows (no resize).""" + if self._field_rules_table is None: + return + target_labels = { + "name": _("Friendly name"), + "location": _("Location"), + "information": _("Information"), + } + table = self._field_rules_table + for r, (tk, fp) in enumerate(self._field_rules_rows): + tgt_item = QTableWidgetItem(target_labels.get(tk, tk)) + tgt_item.setData(Qt.ItemDataRole.UserRole, tk) + fp_item = QTableWidgetItem(fp) + flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable + tgt_item.setFlags(flags) + fp_item.setFlags(flags) + table.setItem(r, 0, tgt_item) + table.setItem(r, 1, fp_item) + + def _fit_field_rules_table_height(self) -> None: + """Fix the rules table height to its row count (header + rows).""" + table = self._field_rules_table + if table is None: + return + h = table.horizontalHeader().height() + len(self._field_rules_rows) * 26 + 8 + table.setFixedHeight(max(60, h)) + + def _refresh_field_rules_table(self) -> None: + """Rebuild rules rows from self._field_rules and repopulate the table.""" + if self._field_rules_table is None: + return + self._field_rules_rows.clear() + for tk, paths in self._field_rules.items(): + for fp in paths: + self._field_rules_rows.append((tk, fp)) + table = self._field_rules_table + table.setRowCount(len(self._field_rules_rows)) + self._populate_field_rules_table() + self._fit_field_rules_table_height() + if self._field_rules_del_btn is not None: + self._field_rules_del_btn.setEnabled(False) + + def _handle_txt_rule(self, target: str, field_path: str) -> None: + """Intercepts TXT right-click rule assignment: updates local state then calls external cb.""" + # Replace semantics: one path per target + self._field_rules[target] = [field_path] + self._refresh_field_rules_table() + if self._on_set_field_rule is not None: + self._on_set_field_rule(target, field_path) + + def _build_raw_tab(self, model: DeviceDetailsViewModel) -> QWidget | None: + raw = model.raw_content + if not isinstance(raw, str) or not raw.strip(): + return None + page = QWidget() + layout = QVBoxLayout(page) + if model.raw_xml_location: + loc = QLabel(_("XML location") + ": " + model.raw_xml_location) + loc.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + loc.setWordWrap(True) + layout.addWidget(loc) + copy_btn = QPushButton(_("Copy to clipboard")) + copy_btn.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed) + copy_btn.clicked.connect(lambda: QGuiApplication.clipboard().setText(raw)) + layout.addWidget(copy_btn) + browser = QTextBrowser() + # Monospace so the pretty-printed XML indentation lines up. + browser.setFont(QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)) + browser.setPlainText(raw) + browser.setLineWrapMode(QTextBrowser.LineWrapMode.WidgetWidth) + layout.addWidget(browser, stretch=1) + return page + + def _build_options_tab( + self, + icon: DeviceIconSettings | None, + cmd: DeviceCommandSettings | None, + model: DeviceDetailsViewModel, + ) -> QWidget: + page = QWidget() + outer = QVBoxLayout(page) + outer.setContentsMargins(0, 0, 0, 0) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + inner = QWidget() + inner.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + # Scoped by objectName: an unscoped rule cascades into every child, + # including QComboBox popups, whose selected item then renders + # white-on-white (base background + highlighted-text colour). + inner.setObjectName("nnDetailsPageInner") + inner.setStyleSheet("#nnDetailsPageInner { background-color: palette(base); }") + layout = QVBoxLayout(inner) + + if icon is not None: + icon_box = QGroupBox(_("Use icon from")) + icon_layout = QVBoxLayout(icon_box) + self._icon_mode_group = QButtonGroup(self) + + rb_system = QRadioButton(_("System")) + rb_provided = QRadioButton(_("From device")) + rb_custom = QRadioButton(_("Custom")) + self._icon_mode_group.addButton(rb_system, 0) + self._icon_mode_group.addButton(rb_provided, 1) + self._icon_mode_group.addButton(rb_custom, 2) + icon_layout.addWidget(rb_system) + if icon.has_device_icon_source: + icon_layout.addWidget(rb_provided) + icon_layout.addWidget(rb_custom) + + self._icon_detail_label = QLabel() + self._icon_detail_label.setWordWrap(True) + self._icon_detail_label.setTextInteractionFlags( + Qt.TextInteractionFlag.TextSelectableByMouse + ) + icon_layout.addWidget(self._icon_detail_label) + + self._provided_icon_preview = QLabel() + self._provided_icon_preview.setFixedSize(48, 48) + self._provided_icon_preview.setAlignment(Qt.AlignmentFlag.AlignCenter) + self._provided_icon_preview.setStyleSheet("background: transparent;") + self._provided_icon_size_lbl = QLabel() + self._provided_icon_size_lbl.setStyleSheet("color: palette(mid);") + preview_row = QHBoxLayout() + preview_row.setContentsMargins(0, 0, 0, 0) + preview_row.addWidget(self._provided_icon_preview) + preview_row.addWidget(self._provided_icon_size_lbl) + preview_row.addStretch(1) + icon_layout.addLayout(preview_row) + self._refresh_provided_icon_preview(icon) + + open_folder_btn = QPushButton(_("Open custom icons folder")) + open_folder_btn.setSizePolicy( + QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed + ) + open_folder_btn.clicked.connect(self._on_open_custom_icons_folder) + icon_layout.addWidget(open_folder_btn, alignment=Qt.AlignmentFlag.AlignLeft) + + mode = icon.icon_mode if icon.icon_mode in {"system", "provided", "custom"} else "provided" + if mode == "provided" and not icon.has_device_icon_source: + mode = "system" + self._last_icon_mode = mode + + self._suppress_icon_signals = True + if mode == "system": + rb_system.setChecked(True) + elif mode == "custom": + rb_custom.setChecked(True) + else: + rb_provided.setChecked(True) + self._suppress_icon_signals = False + self._refresh_icon_detail_line(icon) + + self._icon_mode_group.idClicked.connect( + lambda btn_id: self._on_icon_mode_clicked(btn_id, icon) + ) + layout.addWidget(icon_box) + + if icon.icon_cache is not None: + self._live_icon_settings = icon + self._live_icon_cache = icon.icon_cache + _LOG.warning("dialog: triggering fetch for %d icon_devices", len(icon.icon_devices)) + for dev in icon.icon_devices: + _LOG.warning("dialog: trigger_fetch ip=%s source=%s", dev.ip, dev.source) + icon.icon_cache.trigger_fetch_for_device(dev) + icon.icon_cache.icons_ready.connect(self._on_icon_cache_ready) + self.finished.connect(self._disconnect_icon_cache) + + if cmd is not None: + layout.addWidget(self._build_device_commands_box(cmd)) + + layout.addStretch(1) + scroll.setWidget(inner) + outer.addWidget(scroll) + return page + + def _build_device_commands_box(self, cmd: DeviceCommandSettings) -> QGroupBox: + box = QGroupBox(_("Commands")) + bl = QVBoxLayout(box) + + hint = QLabel( + _("Override or add connection endpoints per protocol. " + "Placeholders: {ip}, {port}, {name}, {type}, {category}, {url}. " + "For 'custom' scheme, Command is the command line to run. " + "For other schemes, Command is the host or address to open " + "(e.g. {ip}, {url}, http://{ip}:8080/admin); " + "Command and Port are optional.") + ) + hint.setWordWrap(True) + hint.setStyleSheet("color: palette(mid);") + bl.addWidget(hint) + hint_disabled = QLabel( + _("Mode 'disabled' hides the auto-detected entry of that protocol " + "(for 'custom', the global custom command); its other fields are ignored.") + ) + hint_disabled.setWordWrap(True) + hint_disabled.setStyleSheet("color: palette(mid);") + bl.addWidget(hint_disabled) + + self._cmd_table = QTableWidget(0, 5) + self._cmd_table.setHorizontalHeaderLabels( + [_("Scheme"), _("Command"), _("Port"), _("Mode"), _("Label")] + ) + hdr = self._cmd_table.horizontalHeader() + hdr.setStretchLastSection(True) + hdr.resizeSection(0, 90) + hdr.resizeSection(2, 60) + hdr.resizeSection(3, 100) + self._cmd_table.verticalHeader().setVisible(False) + self._cmd_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self._cmd_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + + for entry in (cmd.device_commands or []): + self._append_command_row(entry) + + bl.addWidget(self._cmd_table) + + btns = QHBoxLayout() + add_btn = QPushButton(_("Add")) + add_btn.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + add_btn.clicked.connect(self._on_cmd_add_row) + del_btn = QPushButton(_("Delete")) + del_btn.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + del_btn.clicked.connect(self._on_cmd_delete_row) + apply_btn = QPushButton(_("Apply")) + apply_btn.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + apply_btn.clicked.connect(lambda: self._on_cmd_table_apply(cmd)) + btns.addWidget(add_btn) + btns.addWidget(del_btn) + btns.addStretch(1) + btns.addWidget(apply_btn) + bl.addLayout(btns) + return box + + def _append_command_row(self, entry: dict | None = None) -> None: + if self._cmd_table is None: + return + r = self._cmd_table.rowCount() + self._cmd_table.insertRow(r) + + scheme_combo = QComboBox() + for s in _VALID_SCHEMES: + scheme_combo.addItem(s) + if entry: + idx = scheme_combo.findText(str(entry.get("scheme", "http"))) + scheme_combo.setCurrentIndex(max(0, idx)) + self._cmd_table.setCellWidget(r, 0, scheme_combo) + + ip_item = QTableWidgetItem(str(entry.get("ip", "")) if entry else "") + self._cmd_table.setItem(r, 1, ip_item) + + port_val = entry.get("port", 0) if entry else 0 + port_item = QTableWidgetItem(str(port_val) if port_val else "") + self._cmd_table.setItem(r, 2, port_item) + + mode_combo = QComboBox() + for m in _VALID_MODES: + mode_combo.addItem(m) + if entry: + idx = mode_combo.findText(str(entry.get("mode", "override"))) + mode_combo.setCurrentIndex(max(0, idx)) + self._cmd_table.setCellWidget(r, 3, mode_combo) + + label_item = QTableWidgetItem(str(entry.get("label", "")) if entry else "") + self._cmd_table.setItem(r, 4, label_item) + + def _on_cmd_add_row(self) -> None: + self._append_command_row(None) + + def _on_cmd_delete_row(self) -> None: + if self._cmd_table is None: + return + row = self._cmd_table.currentRow() + if row >= 0: + self._cmd_table.removeRow(row) + + def _read_cmd_table_rows(self) -> list[dict]: + if self._cmd_table is None: + return [] + result = [] + for r in range(self._cmd_table.rowCount()): + scheme_w = self._cmd_table.cellWidget(r, 0) + scheme = scheme_w.currentText() if isinstance(scheme_w, QComboBox) else "http" + ip_item = self._cmd_table.item(r, 1) + ip = ip_item.text().strip() if ip_item else "" + port_item = self._cmd_table.item(r, 2) + port_str = port_item.text().strip() if port_item else "" + try: + port = int(port_str) if port_str else 0 + except ValueError: + port = 0 + mode_w = self._cmd_table.cellWidget(r, 3) + mode = mode_w.currentText() if isinstance(mode_w, QComboBox) else "override" + label_item = self._cmd_table.item(r, 4) + label = label_item.text().strip() if label_item else "" + result.append({"scheme": scheme, "ip": ip, "port": port, "mode": mode, "label": label}) + return result + + def _on_cmd_table_apply(self, cmd: DeviceCommandSettings) -> None: + rows = self._read_cmd_table_rows() + cmd.device_commands = rows + cmd.on_set_device_commands(rows) + + def _current_icon_mode(self, icon: DeviceIconSettings) -> str: + if self._icon_mode_group is None: + return "system" + btn_id = self._icon_mode_group.checkedId() + if btn_id == 0: + return "system" + if btn_id == 2: + return "custom" + if icon.has_device_icon_source and btn_id == 1: + return "provided" + return "system" + + def _refresh_icon_detail_line(self, icon: DeviceIconSettings) -> None: + if self._icon_detail_label is None: + return + mode = self._current_icon_mode(icon) + if mode == "system": + self._icon_detail_label.hide() + return + self._icon_detail_label.show() + if mode == "provided": + detail = icon.provided_icon_display or _("unavailable") + self._icon_detail_label.setText(_("Image from device") + ": " + detail) + else: + label = icon.selected_custom_icon_id or _("none") + self._icon_detail_label.setText(_("Selected icon") + ": " + label) + + def _refresh_provided_icon_preview(self, icon: DeviceIconSettings) -> None: + if self._provided_icon_preview is None: + return + pix = icon.provided_icon_pixmap + nat = icon.provided_icon_native_size + has_source = icon.has_device_icon_source + mode = self._current_icon_mode(icon) + + if not has_source or mode != "provided": + self._provided_icon_preview.hide() + self._provided_icon_size_lbl.hide() + return + + self._provided_icon_preview.show() + self._provided_icon_size_lbl.show() + + if pix is not None and not pix.isNull(): + self._provided_icon_preview.setPixmap( + pix.scaled(48, 48, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation) + ) + if nat: + self._provided_icon_size_lbl.setText(f"{nat[0]} × {nat[1]} px") + else: + self._provided_icon_size_lbl.setText(f"{pix.width()} × {pix.height()} px (cached)") + else: + self._provided_icon_preview.setText("?") + if nat is None and icon.provided_icon_display: + status = "missing" + if icon.icon_cache is not None: + for dev in icon.icon_devices: + s = icon.icon_cache.fetch_status_for_device(dev) + if s != "missing": + status = s + break + if status == "fetching": + self._provided_icon_size_lbl.setText(_("Downloading…")) + elif status == "failed": + self._provided_icon_size_lbl.setText(_("Download failed")) + else: + self._provided_icon_size_lbl.setText(_("not yet downloaded")) + else: + self._provided_icon_size_lbl.setText(_("unavailable")) + + def _restore_icon_mode_radio(self, icon: DeviceIconSettings) -> None: + if self._icon_mode_group is None: + return + self._suppress_icon_signals = True + target_id = 0 + if self._last_icon_mode == "custom": + target_id = 2 + elif self._last_icon_mode == "provided" and icon.has_device_icon_source: + target_id = 1 + btn = self._icon_mode_group.button(target_id) + if btn is not None: + btn.setChecked(True) + self._suppress_icon_signals = False + + def _on_icon_mode_clicked(self, btn_id: int, icon: DeviceIconSettings) -> None: + if self._suppress_icon_signals: + return + if btn_id == 2: + picked = icon.on_pick_custom() + if not picked: + self._restore_icon_mode_radio(icon) + return + icon.on_apply("custom", picked) + icon.selected_custom_icon_id = picked + self._last_icon_mode = "custom" + self._refresh_icon_detail_line(icon) + self._refresh_provided_icon_preview(icon) + return + mode = "system" if btn_id == 0 else "provided" + if mode == "provided" and not icon.has_device_icon_source: + self._restore_icon_mode_radio(icon) + return + icon.on_apply(mode, None) + self._last_icon_mode = mode + self._refresh_icon_detail_line(icon) + self._refresh_provided_icon_preview(icon) + + def _on_open_custom_icons_folder(self) -> None: + folder = user_custom_icons_dir() + try: + folder.mkdir(parents=True, exist_ok=True) + if sys.platform == "win32": + os.startfile(str(folder)) # noqa: S606 + elif sys.platform == "darwin": + subprocess.Popen(["open", str(folder)]) + else: + subprocess.Popen(["xdg-open", str(folder)]) + except OSError: + QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder))) + + def _on_icon_cache_ready(self) -> None: + _LOG.warning("dialog: _on_icon_cache_ready fired") + icon = self._live_icon_settings + cache = self._live_icon_cache + if icon is None or cache is None: + _LOG.warning("dialog: _on_icon_cache_ready — no live settings/cache, ignoring") + return + found_bytes = False + for dev in icon.icon_devices: + raw = cache.bytes_for_device(dev) + _LOG.warning("dialog: bytes_for_device ip=%s → %s bytes", dev.ip, len(raw) if raw else None) + if raw: + from ui.remote_icon_cache import pixmap_from_icon_bytes + pix = pixmap_from_icon_bytes(raw, 128) + if pix is not None and not pix.isNull(): + icon.provided_icon_pixmap = pix + icon.provided_icon_native_size = (pix.width(), pix.height()) + found_bytes = True + break + _LOG.warning("dialog: _on_icon_cache_ready found_bytes=%s, refreshing preview", found_bytes) + self._refresh_provided_icon_preview(icon) + + def _disconnect_icon_cache(self) -> None: + cache = self._live_icon_cache + if cache is not None: + try: + cache.icons_ready.disconnect(self._on_icon_cache_ready) + except RuntimeError: + pass + self._live_icon_cache = None + self._live_icon_settings = None + + +def _filter_mdns_txt_pairs(pairs: list[tuple[str, str]]) -> list[tuple[str, str]]: + cleaned: list[tuple[str, str]] = [] + for key, value in pairs: + key_str = str(key).strip() + vs = value.strip().lower() if isinstance(value, str) else str(value).strip().lower() + if vs == "unavailable" or not key_str: + continue + cleaned.append((key_str, value if isinstance(value, str) else str(value))) + return cleaned + + +class MdnsServiceSection(QFrame): + """One mDNS service block with a collapsible TXT / metadata body (GTK parity).""" + + def __init__( + self, + section: dict[str, Any], + *, + expanded: bool = False, + on_txt_rule: Callable[[str, str], None] | None = None, + ) -> None: + super().__init__() + self._on_txt_rule = on_txt_rule + self.setObjectName("nnMdnsServiceSection") + self.setFrameShape(QFrame.Shape.NoFrame) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + + heading = section.get("heading") or section.get("service_type") or _("Service") + title = str(heading) + + outer = QVBoxLayout(self) + outer.setContentsMargins(0, 0, 0, 0) + outer.setSpacing(0) + + self._title = title + self._header = QPushButton() + self._header.setObjectName("nnMdnsServiceHeader") + self._header.setStyleSheet( + "QPushButton#nnMdnsServiceHeader {" + " background-color: palette(base);" + " color: palette(text);" + " border: none;" + " border-bottom: 1px solid palette(mid);" + " border-radius: 0px;" + " padding: 6px 8px;" + " font-weight: bold;" + " text-align: left;" + "}" + "QPushButton#nnMdnsServiceHeader:hover {" + " background-color: palette(alternate-base);" + "}" + ) + self._header.setCheckable(True) + self._header.setChecked(expanded) + self._header.setFlat(True) + self._header.setCursor(Qt.CursorShape.PointingHandCursor) + self._header.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self._header.toggled.connect(self._on_header_toggled) + self._update_header_text(expanded) + outer.addWidget(self._header) + + self._body = QWidget() + body_layout = QVBoxLayout(self._body) + body_layout.setContentsMargins(12, 4, 8, 8) + body_layout.setSpacing(8) + + meta = QGridLayout() + meta.setColumnStretch(1, 1) + meta.setHorizontalSpacing(10) + meta.setVerticalSpacing(4) + row = 0 + service_type = str(section.get("service_type", "")).strip() + target = str(section.get("target", "")).strip() + port = str(section.get("port", "")).strip() + for label_key, val in ( + (_("Service type"), service_type), + (_("Target"), target), + (_("Port"), port or "—"), + ): + if label_key != _("Port") and not detail_field_value_visible(val): + continue + row = MdnsServiceSection._add_overview_row_to_grid(meta, row, label_key, val) + + body_layout.addLayout(meta) + + txt_lbl = QLabel(_("TXT records") + ":") + txt_lbl.setStyleSheet("color: palette(mid);") + body_layout.addWidget(txt_lbl) + + pairs: list[tuple[str, str]] = [] + pairs_raw = section.get("txt_records") + if isinstance(pairs_raw, list): + for item in pairs_raw: + if isinstance(item, (list, tuple)) and len(item) >= 2: + pairs.append((str(item[0]), "" if item[1] is None else str(item[1]))) + filtered = _filter_mdns_txt_pairs(pairs) + if not filtered: + none_lbl = QLabel(_("No TXT records")) + none_lbl.setStyleSheet("color: palette(mid);") + body_layout.addWidget(none_lbl) + else: + table = QTableWidget(len(filtered), 2) + table.setHorizontalHeaderLabels([_("Name"), _("Value")]) + table.horizontalHeader().setStretchLastSection(True) + table.verticalHeader().setVisible(False) + table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + table.setFocusPolicy(Qt.FocusPolicy.NoFocus) + table.viewport().setCursor(Qt.CursorShape.ArrowCursor) + if self._on_txt_rule is not None: + table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + table.customContextMenuRequested.connect( + lambda pos, t=table: self._show_txt_context_menu(pos, t) + ) + else: + table.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) + table.setStyleSheet( + "QTableWidget { outline: none; }" + "QTableWidget::item { border: none; }" + "QTableWidget::item:focus { outline: none; border: none; }" + ) + table.setSizePolicy( + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed + ) + for r, (tk, tv) in enumerate(filtered): + key_item = QTableWidgetItem(tk) + val_item = QTableWidgetItem(tv) + flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable + key_item.setFlags(flags) + val_item.setFlags(flags) + table.setItem(r, 0, key_item) + table.setItem(r, 1, val_item) + table.resizeColumnsToContents() + row_h = table.horizontalHeader().height() + len(filtered) * 26 + 8 + table.setFixedHeight(max(60, row_h)) + body_layout.addWidget(table) + + outer.addWidget(self._body) + self._body.setVisible(expanded) + + def _show_txt_context_menu(self, pos: QPoint, table: QTableWidget) -> None: + if self._on_txt_rule is None: + return + item = table.itemAt(pos) + if item is None: + return + key_item = table.item(item.row(), 0) + if key_item is None: + return + key = key_item.text() + menu = QMenu(table) + menu.addAction( + _("Use as Friendly name"), + lambda: self._on_txt_rule("name", f"txt:{key}"), # type: ignore[misc] + ) + menu.addAction( + _("Use as Location"), + lambda: self._on_txt_rule("location", f"txt:{key}"), # type: ignore[misc] + ) + menu.addAction( + _("Use as Information"), + lambda: self._on_txt_rule("information", f"txt:{key}"), # type: ignore[misc] + ) + menu.exec(table.viewport().mapToGlobal(pos)) + + def _update_header_text(self, expanded: bool) -> None: + chevron = "▾" if expanded else "▸" + self._header.setText(f"{chevron} {self._title}") + + def _on_header_toggled(self, expanded: bool) -> None: + self._update_header_text(expanded) + self._body.setVisible(expanded) + + @staticmethod + def _add_overview_row_to_grid(grid: QGridLayout, row: int, label: str, value: str) -> int: + key_lbl = QLabel(f"{label}:") + key_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop) + val_lbl = QLabel(value) + val_lbl.setWordWrap(True) + val_lbl.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) + val_lbl.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + grid.addWidget(key_lbl, row, 0) + grid.addWidget(val_lbl, row, 1) + return row + 1 + + +def show_device_details_dialog( + parent: QWidget | None, + model: DeviceDetailsViewModel, + *, + initial_tab: str | None = None, + icon_settings: DeviceIconSettings | None = None, + command_settings: DeviceCommandSettings | None = None, + on_set_field_rule: Callable[[str, str], None] | None = None, + field_rules: dict[str, list[str]] | None = None, + on_delete_field_rule: Callable[[str, str], None] | None = None, +) -> None: + DeviceDetailsDialog( + parent, + model, + initial_tab=initial_tab, + icon_settings=icon_settings, + command_settings=command_settings, + on_set_field_rule=on_set_field_rule, + field_rules=field_rules, + on_delete_field_rule=on_delete_field_rule, + ).exec() diff --git a/app/ui/grouped_icon_sections.py b/app/ui/grouped_icon_sections.py new file mode 100644 index 00000000..6d962d53 --- /dev/null +++ b/app/ui/grouped_icon_sections.py @@ -0,0 +1,396 @@ +# File grouped_icon_sections.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Collapsible icon sections (by type / location) for the main window.""" + +from __future__ import annotations + +import logging +from collections import OrderedDict +from collections.abc import Callable, Iterable + +_LOG = logging.getLogger(__name__) + +from PySide6.QtCore import QPoint, QSize, Qt, Signal +from PySide6.QtWidgets import ( + QAbstractScrollArea, + QFrame, + QHBoxLayout, + QLabel, + QListView, + QListWidget, + QListWidgetItem, + QScrollArea, + QSizePolicy, + QVBoxLayout, + QWidget, +) + +from utils.device_bundles import DeviceBundle, bundle_location_label +from utils.details_payload import format_device_type_for_details + +from .icon_grid_layout import ( + IconListViewportResizeFilter, + create_icon_tile_list_item, + icon_list_spacing_for_cell, + relayout_icon_mode_list, +) + +from .icon_list_qss import ICON_MODE_LIST_QSS +from .icon_tile_delegate import IconTileItemDelegate + + +class _SectionHeader(QWidget): + """Clickable header: grey chevron + bold black title. Hover = light-blue bg + dark chevron.""" + + toggled = Signal(bool) + + def __init__(self, title: str, expanded: bool, parent=None) -> None: + super().__init__(parent) + self._checked = expanded + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setObjectName("nnSectionHeader") + + self._chevron = QLabel() + self._chevron.setFixedWidth(12) + + self._title_lbl = QLabel(title) + self._title_lbl.setStyleSheet("font-weight: bold; color: palette(text);") + + row = QHBoxLayout(self) + row.setContentsMargins(8, 6, 8, 6) + row.setSpacing(8) + row.addWidget(self._chevron) + row.addWidget(self._title_lbl) + row.addStretch(1) + + self._apply_style(hovered=False) + self._update_chevron(expanded) + + def _apply_style(self, hovered: bool) -> None: + bg = "palette(alternate-base)" if hovered else "palette(base)" + self.setStyleSheet( + f"#nnSectionHeader {{ background-color: {bg}; border-bottom: 1px solid palette(mid); }}" + "QLabel { background-color: transparent; }" + ) + self._chevron.setStyleSheet( + "color: palette(text);" if hovered else "color: palette(mid);" + ) + + def _update_chevron(self, expanded: bool) -> None: + self._chevron.setText("▾" if expanded else "▸") + + def setChecked(self, checked: bool) -> None: + self._checked = checked + self._update_chevron(checked) + + def mousePressEvent(self, event) -> None: + if event.button() == Qt.MouseButton.LeftButton: + self._checked = not self._checked + self._update_chevron(self._checked) + self.toggled.emit(self._checked) + super().mousePressEvent(event) + + def enterEvent(self, event) -> None: + self._apply_style(hovered=True) + super().enterEvent(event) + + def leaveEvent(self, event) -> None: + self._apply_style(hovered=False) + super().leaveEvent(event) + + +class IconGroupSection(QFrame): + """One titled, collapsible block with an icon-mode ``QListWidget``.""" + + toggled = Signal(str, bool) + + def __init__( + self, + group_id: str, + title: str, + bundles: list[DeviceBundle], + *, + expanded: bool, + icon_for_bundle: Callable[[DeviceBundle], object], + tooltip_for_bundle: Callable[[DeviceBundle], str], + icon_size: QSize, + on_tile_context_menu: Callable[[QPoint, DeviceBundle], None] | None = None, + on_tile_double_clicked: Callable[[DeviceBundle], None] | None = None, + ) -> None: + super().__init__() + self._group_id = group_id + self.setObjectName("nnIconGroupSection") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setStyleSheet( + "QFrame#nnIconGroupSection { background-color: palette(base); border: none; }" + ) + self.setFrameShape(QFrame.Shape.NoFrame) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + self._bundles_for_items = list(bundles) + self._on_tile_context_menu_cb = on_tile_context_menu + self._on_tile_double_clicked_cb = on_tile_double_clicked + self._icon_size = QSize(icon_size) + self._title = title + + self._header = _SectionHeader(title, expanded) + self._header.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self._header.toggled.connect(self._on_header_toggled) + + self._list = QListWidget() + self._list.setViewMode(QListWidget.ViewMode.IconMode) + self._list.setUniformItemSizes(True) + self._list.setMovement(QListWidget.Movement.Static) + self._list.setResizeMode(QListWidget.ResizeMode.Adjust) + self._list.setSpacing(icon_list_spacing_for_cell(self._icon_size)) + self._list.setIconSize(self._icon_size) + self._list.setWrapping(True) + self._list.setWordWrap(True) + self._list.setFrameShape(QFrame.Shape.NoFrame) + self._list.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._list.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._list.setSizeAdjustPolicy(QAbstractScrollArea.SizeAdjustPolicy.AdjustToContents) + self._list.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) + self._list.setLayoutMode(QListView.LayoutMode.Batched) + self._list.setBatchSize(32) + self._list.setStyleSheet(ICON_MODE_LIST_QSS) + self._list.setItemDelegate(IconTileItemDelegate(self._list)) + self._viewport_resize_filter = IconListViewportResizeFilter( + self._relayout_icon_grid, self + ) + self._list.viewport().installEventFilter(self._viewport_resize_filter) + + if self._on_tile_context_menu_cb is not None: + self._list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self._list.customContextMenuRequested.connect(self._on_list_context_menu) + if self._on_tile_double_clicked_cb is not None: + self._list.itemDoubleClicked.connect(self._on_list_item_double_clicked) + + self._list.setVisible(False) + vp = self._list.viewport() + self._list.setUpdatesEnabled(False) + vp.setUpdatesEnabled(False) + try: + for bundle in bundles: + d = bundle.primary + it = create_icon_tile_list_item( + icon_for_bundle(bundle), d.name or "" + ) + it.setToolTip(tooltip_for_bundle(bundle)) + self._list.addItem(it) + finally: + self._list.setUpdatesEnabled(True) + vp.setUpdatesEnabled(True) + + self._relayout_icon_grid(force=True) + + outer = QVBoxLayout(self) + outer.setContentsMargins(0, 0, 0, 0) + outer.setSpacing(6) + outer.addWidget(self._header) + outer.addWidget(self._list) + # setVisible must be called after addWidget so the list is already parented; + # calling it on a parentless widget would create a transient top-level OS window. + self._list.setVisible(expanded) + + def _relayout_icon_grid(self, *, force: bool = False) -> None: + fallback = 0 + if self._list.isVisible(): + fallback = max(200, self.width() - 16) + parent = self.parentWidget() + while parent is not None: + if isinstance(parent, QScrollArea): + fallback = max(fallback, parent.viewport().width() - 16) + break + parent = parent.parentWidget() + relayout_icon_mode_list( + self._list, + self._icon_size, + compact_height=True, + fallback_viewport_width=fallback, + force=force, + ) + + def resync_icons(self, icon_for_bundle: Callable[[DeviceBundle], object]) -> None: + for row, bundle in enumerate(self._bundles_for_items): + it = self._list.item(row) + if it is None: + continue + it.setIcon(icon_for_bundle(bundle)) + self._relayout_icon_grid() + + def showEvent(self, event) -> None: + super().showEvent(event) + self._relayout_icon_grid() + + def _on_list_context_menu(self, pos: QPoint) -> None: + if self._on_tile_context_menu_cb is None: + return + it = self._list.itemAt(pos) + if it is None: + return + row = self._list.row(it) + if row < 0 or row >= len(self._bundles_for_items): + return + gpos = self._list.viewport().mapToGlobal(pos) + self._on_tile_context_menu_cb(gpos, self._bundles_for_items[row]) + + def _on_list_item_double_clicked(self, item) -> None: + if self._on_tile_double_clicked_cb is None: + return + row = self._list.row(item) + if 0 <= row < len(self._bundles_for_items): + self._on_tile_double_clicked_cb(self._bundles_for_items[row]) + + def _on_header_toggled(self, expanded: bool) -> None: + self._list.setVisible(expanded) + if expanded: + self._relayout_icon_grid() + self.toggled.emit(self._group_id, expanded) + + +def bucket_bundles_by_type( + ordered_bundles: Iterable[DeviceBundle], +) -> OrderedDict[str, list[DeviceBundle]]: + buckets: OrderedDict[str, list[DeviceBundle]] = OrderedDict() + for b in ordered_bundles: + slug = (b.primary.type or "unknown").strip().lower() + buckets.setdefault(slug, []).append(b) + return buckets + + +def bucket_bundles_by_location( + ordered_bundles: Iterable[DeviceBundle], + *, + no_location_label: str, +) -> OrderedDict[str, list[DeviceBundle]]: + buckets: OrderedDict[str, list[DeviceBundle]] = OrderedDict() + for b in ordered_bundles: + loc = bundle_location_label(b, no_location_label=no_location_label) + buckets.setdefault(loc, []).append(b) + return buckets + + +def ordered_type_group_ids(buckets: OrderedDict[str, list[DeviceBundle]]) -> list[str]: + def label_for(slug: str) -> str: + ref = buckets[slug][0].primary + return format_device_type_for_details(ref) + + return sorted(buckets.keys(), key=lambda s: label_for(s).lower()) + + +def ordered_location_group_keys( + buckets: OrderedDict[str, list[DeviceBundle]], + *, + no_location_label: str, +) -> list[str]: + keys = list(buckets.keys()) + rest = [k for k in keys if k != no_location_label] + rest.sort(key=lambda k: k.lower()) + out = rest + if no_location_label in buckets: + out = rest + [no_location_label] + return out + + +def build_grouped_icon_scroll( + parent: QWidget | None, + *, + mode: str, + ordered_bundles: list[DeviceBundle], + no_location_label: str, + expanded_map: dict[str, bool], + icon_for_bundle: Callable[[DeviceBundle], object], + tooltip_for_bundle: Callable[[DeviceBundle], str], + icon_size: QSize, + on_section_toggled: Callable[[str, bool], None], + on_tile_context_menu: Callable[[QPoint, DeviceBundle], None] | None = None, + on_tile_double_clicked: Callable[[DeviceBundle], None] | None = None, +) -> QScrollArea: + """Build scroll area with one collapsible section per group; ``mode`` is ``sorted`` or ``location``.""" + scroll = QScrollArea(parent) + scroll.setObjectName("nnGroupedIconScroll") + scroll.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + scroll.setStyleSheet( + "QScrollArea#nnGroupedIconScroll { background-color: palette(base); border: none; }" + ) + scroll.setVisible(False) + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + vp = scroll.viewport() + vp.setObjectName("nnGroupedIconViewport") + vp.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + vp.setStyleSheet("#nnGroupedIconViewport { background-color: palette(base); }") + + inner = QWidget() + inner.setObjectName("nnGroupedIconInner") + inner.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + inner.setStyleSheet("#nnGroupedIconInner { background-color: palette(base); }") + layout = QVBoxLayout(inner) + layout.setContentsMargins(8, 0, 8, 8) + layout.setSpacing(4) + + if mode == "sorted": + buckets = bucket_bundles_by_type(ordered_bundles) + order = ordered_type_group_ids(buckets) + elif mode == "location": + buckets = bucket_bundles_by_location(ordered_bundles, no_location_label=no_location_label) + order = ordered_location_group_keys(buckets, no_location_label=no_location_label) + else: + buckets = OrderedDict() + order = [] + + sections: list[IconGroupSection] = [] + + for slug_or_loc in order: + group_bundles = buckets.get(slug_or_loc, []) + if not group_bundles: + continue + if mode == "sorted": + group_id = f"type:{slug_or_loc}" + title_text = "{} ({})".format( + format_device_type_for_details(group_bundles[0].primary), + len(group_bundles), + ) + else: + group_id = ( + "location:__none__" + if slug_or_loc == no_location_label + else f"location:{slug_or_loc}" + ) + title_text = "{} ({})".format(slug_or_loc, len(group_bundles)) + + expanded = expanded_map.get(group_id, True) + section = IconGroupSection( + group_id, + title_text, + group_bundles, + expanded=expanded, + icon_for_bundle=icon_for_bundle, + tooltip_for_bundle=tooltip_for_bundle, + icon_size=icon_size, + on_tile_context_menu=on_tile_context_menu, + on_tile_double_clicked=on_tile_double_clicked, + ) + section.toggled.connect(on_section_toggled) + layout.addWidget(section) + sections.append(section) + + def _relayout_all_sections() -> None: + for section in sections: + section._relayout_icon_grid() + + scroll._icon_group_sections = sections # type: ignore[attr-defined] + scroll._icon_sections_relayout_filter = IconListViewportResizeFilter( + _relayout_all_sections, scroll + ) + vp.installEventFilter(scroll._icon_sections_relayout_filter) + + layout.addStretch(1) + scroll.setWidget(inner) + scroll.setVisible(True) + _relayout_all_sections() + return scroll diff --git a/app/ui/hidden_devices_dialog.py b/app/ui/hidden_devices_dialog.py new file mode 100644 index 00000000..8023a241 --- /dev/null +++ b/app/ui/hidden_devices_dialog.py @@ -0,0 +1,119 @@ +# File hidden_devices_dialog.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Dialog listing user-hidden devices with per-row remove actions.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from gettext import gettext as _ + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import ( + QAbstractItemView, + QDialog, + QDialogButtonBox, + QHeaderView, + QPushButton, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) + + +@dataclass(frozen=True, slots=True) +class HiddenDeviceRow: + host_key: str + name: str + ip: str + port: int + + +class HiddenDevicesDialog(QDialog): + def __init__( + self, + parent: QWidget | None, + rows: Sequence[HiddenDeviceRow], + on_remove: Callable[[str], None], + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Hidden devices")) + self.setModal(True) + self.resize(640, 360) + self._on_remove = on_remove + self._row_keys: list[str] = [] + + layout = QVBoxLayout(self) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(8) + + self._table = QTableWidget(0, 3) + self._table.setHorizontalHeaderLabels([_("Device"), _("IP"), ""]) + header = self._table.horizontalHeader() + header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents) + self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + self._table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self._table.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) + self._table.verticalHeader().setVisible(False) + self._table.setAlternatingRowColors(True) + + for row in rows: + self._append_row(row) + + if not rows: + self._show_empty_placeholder() + + layout.addWidget(self._table) + + close_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + close_box.rejected.connect(self.reject) + close_btn = close_box.button(QDialogButtonBox.StandardButton.Close) + if close_btn: + close_btn.setText(_("Close")) + layout.addWidget(close_box) + + def _append_row(self, row: HiddenDeviceRow) -> None: + if self._table.rowCount() == 1 and self._table.cellWidget(0, 2) is None: + self._table.setRowCount(0) + self._row_keys.clear() + r = self._table.rowCount() + self._table.insertRow(r) + self._row_keys.append(row.host_key) + self._table.setItem(r, 0, QTableWidgetItem(row.name)) + ip_item = QTableWidgetItem(row.ip) + ip_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + self._table.setItem(r, 1, ip_item) + remove_btn = QPushButton(_("Remove")) + remove_btn.clicked.connect(lambda _checked=False, key=row.host_key: self._remove_row(key)) + self._table.setCellWidget(r, 2, remove_btn) + + def _show_empty_placeholder(self) -> None: + self._table.setRowCount(1) + self._row_keys.clear() + empty = QTableWidgetItem(_("No hidden devices")) + empty.setFlags(Qt.ItemFlag.NoItemFlags) + self._table.setItem(0, 0, empty) + self._table.setSpan(0, 0, 1, 3) + + def _remove_row(self, host_key: str) -> None: + self._on_remove(host_key) + for r, key in enumerate(list(self._row_keys)): + if key == host_key: + self._table.removeRow(r) + self._row_keys.pop(r) + break + if not self._row_keys: + self._show_empty_placeholder() + + +def show_hidden_devices_dialog( + parent: QWidget | None, + rows: Sequence[HiddenDeviceRow], + on_remove: Callable[[str], None], +) -> None: + HiddenDevicesDialog(parent, rows, on_remove).exec() diff --git a/app/ui/icon_grid_layout.py b/app/ui/icon_grid_layout.py new file mode 100644 index 00000000..0a7a3cbf --- /dev/null +++ b/app/ui/icon_grid_layout.py @@ -0,0 +1,290 @@ +# File icon_grid_layout.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Adaptive cell sizing for icon-mode ``QListWidget`` grids (flat + grouped sections).""" + +from __future__ import annotations + +import logging +from collections.abc import Callable, Sequence + +from PySide6.QtCore import QEvent, QObject, QRect, QSize, Qt, QTimer +from PySide6.QtGui import QFont, QFontMetrics, QIcon +from PySide6.QtWidgets import QListWidget, QListWidgetItem + +from ui.icon_tile_label import ( + ICON_TILE_LABEL_ROLE, + LONG_NAME_WRAP_MIN_WIDTH_FACTOR, + MIN_LINES_BEFORE_ELLIPSIS, + TILE_H_MARGIN, + _ITEM_EXTRA_PAD, + _ITEM_INSET_LR, + _label_max_horizontal_advance, + format_icon_tile_label, + icon_mode_label_font, + icon_tile_cell_height, + icon_tile_label_paint_rect, + max_label_block_height_for_labels, + normalize_icon_tile_label, + refresh_icon_tile_display_cache, +) + +_LOG = logging.getLogger(__name__) + +# Re-export for callers that imported these from icon_grid_layout. +__all__ = [ + "ICON_TILE_LABEL_ROLE", + "TILE_H_MARGIN", + "format_icon_tile_label", + "normalize_icon_tile_label", + "set_icon_tile_item_label", + "collect_icon_tile_labels", + "icon_mode_label_font", + "relayout_icon_mode_list", + "apply_icon_mode_list_layout", + "IconListViewportResizeFilter", + "icon_list_spacing_for_cell", + "icon_list_content_height", + "labels_from_icon_list", +] + + +def create_icon_tile_list_item(icon: QIcon, name: str) -> QListWidgetItem: + """``QListWidgetItem`` requires ``(icon, text)`` in PySide6 — never pass icon alone.""" + item = QListWidgetItem(icon, "") + set_icon_tile_item_label(item, name) + return item + + +def set_icon_tile_item_label(item: QListWidgetItem, name: str) -> str: + """Store the unbroken label on *item*; returns the normalized string.""" + label = normalize_icon_tile_label(name) + item.setData(ICON_TILE_LABEL_ROLE, label) + item.setText(label) + return label + + +def collect_icon_tile_labels(list_widget: QListWidget) -> list[str]: + out: list[str] = [] + for i in range(list_widget.count()): + it = list_widget.item(i) + if it is None: + continue + stored = it.data(ICON_TILE_LABEL_ROLE) + if isinstance(stored, str) and stored: + out.append(stored) + else: + out.append(normalize_icon_tile_label(it.text())) + return out + + +def compute_icon_mode_cell_size( + viewport_width: int, + icon_size: QSize, + labels: list[str], + font: QFont, + *, + list_spacing: int = 10, + horizontal_pad: int = 10, + label_gap: int = 6, + min_cell_width: int | None = None, + max_cell_width: int | None = None, +) -> QSize: + """Return grid cell size; label height from ``QTextLayout`` (min four lines).""" + iw = max(1, icon_size.width()) + ih = max(1, icon_size.height()) + min_w = min_cell_width if min_cell_width is not None else iw + 20 + long_name_min_w = min_w * LONG_NAME_WRAP_MIN_WIDTH_FACTOR + + fm = QFontMetrics(font) + if labels: + text_w = max(_label_max_horizontal_advance(fm, lbl) for lbl in labels) + else: + text_w = fm.horizontalAdvance("—") + + has_long_names = text_w > min_w + text_inner_min = text_w + horizontal_pad * 2 + _ITEM_INSET_LR + max_cell_w = max(min_w, iw + horizontal_pad * 2 + _ITEM_INSET_LR, text_inner_min) + + count = len(labels) + if count <= 0: + dummy = QRect(0, 0, min_w, 10000) + empty_h = max_label_block_height_for_labels([], font, icon_tile_label_paint_rect(dummy, ih).width()) + return QSize(min_w, icon_tile_cell_height(ih, empty_h)) + + vp = max(min_w, viewport_width) + + def _fits_one_row(cell_w: int) -> bool: + # Qt adds list_spacing on all 4 viewport sides: (count+1) gaps total. + return count * cell_w + (count + 1) * list_spacing <= vp + + if _fits_one_row(max_cell_w): + cell_w = max_cell_w + elif count == 1: + cell_w = min(max_cell_w, vp) + else: + cell_w = max(min_w, (vp - (count + 1) * list_spacing) // count) + cell_w = min(cell_w, max_cell_w) + if not _fits_one_row(cell_w): + cols = max(1, (vp - list_spacing) // (min_w + list_spacing)) + cell_w = max(min_w, (vp - list_spacing * (cols + 1)) // cols) + cell_w = min(cell_w, max_cell_w) + + if has_long_names: + cell_w = max(cell_w, long_name_min_w) + + if max_cell_width is not None: + cell_w = max(min_w, max_cell_width) + + dummy_cell = QRect(0, 0, cell_w, 10000) + zone_w = icon_tile_label_paint_rect(dummy_cell, ih).width() + max_text_h = max_label_block_height_for_labels(labels, font, zone_w) + cell_h = icon_tile_cell_height(ih, max_text_h) + + _LOG.debug( + "cell_size icon=%dpx vp=%d count=%d cell_w=%d zone=%d text_h=%d cell_h=%d", + iw, viewport_width, count, cell_w, zone_w, max_text_h, cell_h, + ) + return QSize(cell_w, cell_h) + + +def icon_list_spacing_for_cell(icon_size: QSize) -> int: + h = max(1, icon_size.height()) + return max(4, min(12, h // 8)) + + +def icon_list_content_height( + list_widget: QListWidget, + grid_cell: QSize, + *, + item_count: int | None = None, + viewport_width: int | None = None, +) -> int: + count = item_count if item_count is not None else list_widget.count() + if count <= 0: + return 0 + vp_w = viewport_width if (viewport_width is not None and viewport_width > 0) else max(1, list_widget.viewport().width()) + cw = max(1, grid_cell.width()) + ch = max(1, grid_cell.height()) + spacing = list_widget.spacing() + cols = max(1, (vp_w - spacing) // (cw + spacing)) + rows = (count + cols - 1) // cols + return rows * ch + (rows + 1) * spacing + + +def apply_icon_mode_list_layout( + list_widget: QListWidget, + icon_size: QSize, + labels: list[str], + *, + set_min_height: bool = False, + compact_height: bool = False, + fallback_viewport_width: int = 0, +) -> None: + list_widget.setSpacing(icon_list_spacing_for_cell(icon_size)) + list_widget.setIconSize(icon_size) + + vp_w = list_widget.viewport().width() + if vp_w <= 0 and fallback_viewport_width > 0: + vp_w = fallback_viewport_width + + iw = icon_size.width() + if iw >= 256: + max_cw = iw + 20 + elif iw >= 96: + max_cw = iw + 96 + else: + max_cw = 3 * 48 + + cell = compute_icon_mode_cell_size( + vp_w, + icon_size, + labels, + icon_mode_label_font(list_widget), + list_spacing=list_widget.spacing(), + max_cell_width=max_cw, + ) + list_widget.setWordWrap(False) + list_widget.setTextElideMode(Qt.TextElideMode.ElideNone) + list_widget.setGridSize(cell) + list_widget.setMinimumHeight(0) + list_widget.setMaximumHeight(16777215) + list_widget.doItemsLayout() + list_widget.updateGeometries() + if compact_height: + content_h = icon_list_content_height(list_widget, cell, viewport_width=vp_w) + if content_h > 0: + list_widget.setFixedHeight(content_h) + elif set_min_height: + ih = icon_size.height() + list_widget.setMinimumHeight(max(96, cell.height(), ih + 56)) + + +def relayout_icon_mode_list( + list_widget: QListWidget, + icon_size: QSize, + *, + labels: Sequence[str] | None = None, + compact_height: bool = False, + set_min_height: bool = False, + fallback_viewport_width: int = 0, + force: bool = False, +) -> None: + """Resize grid cells; precompute wrapped lines once (delegate reads cache).""" + label_list = list(labels) if labels is not None else collect_icon_tile_labels(list_widget) + if not label_list and list_widget.count() <= 0: + return + + vp_w = list_widget.viewport().width() + if vp_w <= 0 and fallback_viewport_width > 0: + vp_w = fallback_viewport_width + layout_key = (vp_w, icon_size.width(), icon_size.height(), len(label_list)) + if not force and getattr(list_widget, "_nn_icon_layout_key", None) == layout_key: + return + list_widget._nn_icon_layout_key = layout_key # type: ignore[attr-defined] + + apply_icon_mode_list_layout( + list_widget, + icon_size, + label_list, + compact_height=compact_height, + set_min_height=set_min_height, + fallback_viewport_width=fallback_viewport_width, + ) + refresh_icon_tile_display_cache(list_widget, icon_size, label_list) + for i, orig in enumerate(label_list): + it = list_widget.item(i) + if it is None: + continue + if it.data(ICON_TILE_LABEL_ROLE) != orig: + it.setData(ICON_TILE_LABEL_ROLE, orig) + if it.text() != orig: + it.setText(orig) + + +class IconListViewportResizeFilter(QObject): + """Debounce resize storms (each pixel was relayouting every label).""" + + def __init__( + self, + on_resize: Callable[[], None], + parent: QObject | None = None, + *, + debounce_ms: int = 80, + ) -> None: + super().__init__(parent) + self._on_resize = on_resize + self._timer = QTimer(self) + self._timer.setSingleShot(True) + self._timer.setInterval(max(0, debounce_ms)) + self._timer.timeout.connect(self._on_resize) + + def eventFilter(self, watched: QObject, event: QEvent) -> bool: + if event.type() == QEvent.Type.Resize: + self._timer.start() + return False + + +def labels_from_icon_list(list_widget: QListWidget) -> list[str]: + return collect_icon_tile_labels(list_widget) diff --git a/app/ui/icon_list_qss.py b/app/ui/icon_list_qss.py new file mode 100644 index 00000000..4c027320 --- /dev/null +++ b/app/ui/icon_list_qss.py @@ -0,0 +1,42 @@ +# File icon_list_qss.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Shared QSS for icon-mode ``QListWidget`` tiles (flat list + grouped sections). + +Uses ``palette(...)`` roles so light/dark and high-contrast themes propagate from +``QApplication``. The 1px transparent border is kept in all states to prevent +layout shifts (border-box sizing stays constant). + +Hover/selected color contract (mirrors the rest of the UI): + hover → palette(alternate-base) light blue tint + selected → palette(alternate-base) same tint, stays lit after click (no border) +""" + +# 1px transparent border in every state avoids layout jumps on state changes. +ICON_MODE_LIST_QSS = ( + "QListWidget { background-color: palette(base); outline: none; show-decoration-selected: 0; }" + "QListWidget::item {" + " padding: 2px;" + " border: 1px solid transparent;" + " font-size: smaller;" + "}" + "QListWidget::item:hover {" + " background-color: palette(alternate-base);" + "}" + "QListWidget::item:selected," + "QListWidget::item:selected:active," + "QListWidget::item:selected:!active {" + " background-color: palette(base);" + " color: palette(text);" + " border: 1px solid transparent;" + " outline: none;" + "}" + "QListWidget::item:selected:hover {" + " background-color: palette(alternate-base);" + " color: palette(text);" + " border: 1px solid transparent;" + " outline: none;" + "}" + "QListWidget::item:focus { border: 1px solid transparent; outline: none; }" +) diff --git a/app/ui/icon_picker_dialog.py b/app/ui/icon_picker_dialog.py new file mode 100644 index 00000000..36d1515c --- /dev/null +++ b/app/ui/icon_picker_dialog.py @@ -0,0 +1,191 @@ +# File icon_picker_dialog.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Modal grid to pick a device icon (bundled pack + user PNGs); ids match the legacy details dialog.""" + +from __future__ import annotations + +from gettext import gettext as _ + +from PySide6.QtCore import QSize, Qt, QUrl +from PySide6.QtGui import QDesktopServices, QIcon +from PySide6.QtWidgets import ( + QButtonGroup, + QDialog, + QDialogButtonBox, + QFrame, + QGridLayout, + QHBoxLayout, + QLabel, + QPushButton, + QScrollArea, + QToolButton, + QVBoxLayout, + QWidget, +) + +from pathlib import Path + +from ui.icons import iter_icon_picker_entries, user_custom_icons_dir + + +def pick_device_icon_id( + parent: QWidget | None, + *, + preferred_type: str | None, + current_id: str | None, + active_pack_root: Path | None = None, +) -> str | None: + """Run modal picker; returns ``bundled:…`` / ``custom:…`` id or ``None`` if cancelled.""" + dlg = IconPickerDialog( + parent, + preferred_type=preferred_type, + current_id=current_id, + active_pack_root=active_pack_root, + ) + if dlg.exec() != QDialog.DialogCode.Accepted: + return None + return dlg.selected_icon_id() + + +class IconPickerDialog(QDialog): + """Grid of pack + custom icons (same ids as the legacy device details dialog).""" + + def __init__( + self, + parent: QWidget | None, + *, + preferred_type: str | None, + current_id: str | None, + active_pack_root: Path | None = None, + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Choose icon")) + self.resize(620, 484) + self._selected_id: str | None = current_id.strip() if isinstance(current_id, str) and current_id.strip() else None + self._group = QButtonGroup(self) + self._group.setExclusive(True) + + hint = QLabel( + _("Select an icon, then OK. IDs are stored in your preferences.") + ) + hint.setWordWrap(True) + + entries = iter_icon_picker_entries(preferred_type, active_pack_root) + scroll: QScrollArea | None = None + if not entries: + empty = QLabel( + _( + "No icons found. Add PNGs under assets/icons/netneighbor or ~/.config/netneighbor/custom_icons/." + ) + ) + empty.setWordWrap(True) + else: + empty = None + + if entries: + inner = QWidget() + inner.setObjectName("nnIconPickerGrid") + inner.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + inner.setStyleSheet( + "#nnIconPickerGrid { background-color: palette(base); }" + "QToolButton {" + " background-color: palette(base);" + " border: 1px solid palette(mid);" + " border-radius: 4px;" + "}" + "QToolButton:hover {" + " background-color: palette(alternate-base);" + " border-color: palette(highlight);" + "}" + "QToolButton:checked {" + " background-color: palette(highlight);" + " border-color: palette(shadow);" + "}" + "QToolButton:checked:hover {" + " background-color: palette(highlight);" + " border-color: palette(shadow);" + "}" + ) + grid = QGridLayout(inner) + grid.setContentsMargins(6, 6, 6, 6) + grid.setHorizontalSpacing(6) + grid.setVerticalSpacing(6) + cols = 6 + row = col = 0 + first_btn: QToolButton | None = None + matched = False + for icon_id, label, path in entries: + btn = QToolButton() + btn.setToolTip(label) + btn.setFixedSize(88, 88) + btn.setIconSize(QSize(56, 56)) + if path is not None and path.is_file(): + btn.setIcon(QIcon(str(path))) + else: + btn.setText("?") + btn.setCheckable(True) + self._group.addButton(btn) + + def _on_toggled(checked: bool, iid: str = icon_id) -> None: + if checked: + self._selected_id = iid + + btn.toggled.connect(_on_toggled) + grid.addWidget(btn, row, col) + if first_btn is None: + first_btn = btn + if self._selected_id and icon_id == self._selected_id: + btn.setChecked(True) + matched = True + col += 1 + if col >= cols: + col = 0 + row += 1 + + if not matched: + self._selected_id = entries[0][0] + if first_btn is not None: + first_btn.setChecked(True) + + scroll = QScrollArea() + scroll.setWidgetResizable(True) + scroll.setFrameShape(QFrame.Shape.NoFrame) + scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + scroll.setWidget(inner) + + folder_btn = QPushButton(_("Open custom icons folder")) + folder_btn.clicked.connect(self._open_custom_folder) + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + if not entries: + buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False) + + row_btns = QHBoxLayout() + row_btns.addWidget(folder_btn) + row_btns.addStretch(1) + + outer = QVBoxLayout(self) + outer.addWidget(hint) + if empty is not None: + outer.addWidget(empty) + if scroll is not None: + outer.addWidget(scroll, 1) + outer.addLayout(row_btns) + outer.addWidget(buttons) + + def selected_icon_id(self) -> str | None: + return self._selected_id + + def _open_custom_folder(self) -> None: + d = user_custom_icons_dir() + try: + d.mkdir(parents=True, exist_ok=True) + except OSError: + return + QDesktopServices.openUrl(QUrl.fromLocalFile(str(d.resolve()))) diff --git a/app/ui/icon_tile_delegate.py b/app/ui/icon_tile_delegate.py new file mode 100644 index 00000000..673f99a3 --- /dev/null +++ b/app/ui/icon_tile_delegate.py @@ -0,0 +1,121 @@ +# File icon_tile_delegate.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Delegate for icon-mode tiles: cached Qt text layout, no focus ring.""" + +from __future__ import annotations + +from PySide6.QtCore import QRect, QSize, Qt +from PySide6.QtGui import QColor, QFontMetrics, QIcon, QPainter +from PySide6.QtWidgets import ( + QApplication, + QListWidget, + QStyle, + QStyleOptionViewItem, + QStyledItemDelegate, +) + +from ui.icon_tile_label import ( + ICON_TILE_DISPLAY_HEIGHTS_ROLE, + ICON_TILE_DISPLAY_LINES_ROLE, + ICON_TILE_LABEL_ROLE, + display_lines_for_tile, + icon_mode_label_font, + icon_tile_cell_rect, + icon_tile_icon_rect, + icon_tile_label_paint_rect, + layout_icon_tile_label, +) + + +class IconTileItemDelegate(QStyledItemDelegate): + def sizeHint(self, option: QStyleOptionViewItem, index) -> QSize: # type: ignore[override] + widget = option.widget + if isinstance(widget, QListWidget): + grid = widget.gridSize() + if grid.width() > 0 and grid.height() > 0: + return QSize(grid) + return super().sizeHint(option, index) + + def initStyleOption(self, option: QStyleOptionViewItem, index) -> None: # type: ignore[override] + super().initStyleOption(option, index) + option.textElideMode = Qt.TextElideMode.ElideNone + option.features &= ~QStyleOptionViewItem.ViewItemFeature.WrapText + option.text = "" + list_widget = option.widget + if isinstance(list_widget, QListWidget): + option.rect = icon_tile_cell_rect(list_widget, option.rect) + + def paint(self, painter: QPainter, option: QStyleOptionViewItem, index) -> None: + opt = QStyleOptionViewItem(option) + self.initStyleOption(opt, index) + + list_widget = opt.widget if isinstance(opt.widget, QListWidget) else None + if list_widget is not None: + opt.rect = list_widget.visualRect(index) + + opt.state &= ~QStyle.StateFlag.State_HasFocus + opt.state &= ~QStyle.StateFlag.State_Selected + + widget = opt.widget + style = widget.style() if widget is not None else QApplication.style() + style.drawPrimitive(QStyle.PrimitiveElement.PE_PanelItemViewItem, opt, painter, widget) + + cell = icon_tile_cell_rect(list_widget, opt.rect) + icon_size = list_widget.iconSize() if list_widget is not None else QSize(48, 48) + + icon = index.data(Qt.ItemDataRole.DecorationRole) + if icon is not None and isinstance(icon, QIcon) and not icon.isNull(): + icon.paint(painter, icon_tile_icon_rect(cell, icon_size), Qt.AlignmentFlag.AlignCenter) + + label = index.data(ICON_TILE_LABEL_ROLE) + if not isinstance(label, str) or not label.strip(): + label = index.data(Qt.ItemDataRole.DisplayRole) + if not isinstance(label, str) or not label.strip(): + return + + font = icon_mode_label_font(list_widget) if list_widget is not None else opt.font + painter.save() + painter.setFont(font) + + text_rect = icon_tile_label_paint_rect(cell, icon_size.height()) + text_w = max(8, text_rect.width()) + + lines_data = index.data(ICON_TILE_DISPLAY_LINES_ROLE) + heights_data = index.data(ICON_TILE_DISPLAY_HEIGHTS_ROLE) + if isinstance(lines_data, (list, tuple)) and lines_data: + lines = tuple(str(x) for x in lines_data) + heights = ( + tuple(int(x) for x in heights_data) + if isinstance(heights_data, (list, tuple)) and len(heights_data) == len(lines) + else None + ) + else: + laid_out = layout_icon_tile_label(label, font, text_w) + lines = display_lines_for_tile(laid_out, font=font, text_width_px=text_w) + heights = laid_out.line_heights + + fm = QFontMetrics(font) + default_h = fm.lineSpacing() + color = opt.palette.color( + opt.palette.currentColorGroup(), + opt.palette.ColorRole.Text, + ) + painter.setPen(QColor(color)) + + y = text_rect.top() + for i, line in enumerate(lines): + line_h = ( + max(1, int(heights[i])) + if heights is not None and i < len(heights) + else default_h + ) + painter.drawText( + QRect(text_rect.left(), y, text_rect.width(), line_h), + int(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop), + line, + ) + y += line_h + + painter.restore() diff --git a/app/ui/icon_tile_label.py b/app/ui/icon_tile_label.py new file mode 100644 index 00000000..fd5fe200 --- /dev/null +++ b/app/ui/icon_tile_label.py @@ -0,0 +1,236 @@ +# File icon_tile_label.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Qt-native wrapping and measurement for icon-tile device names.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass + +from PySide6.QtCore import QRect, QSize, Qt +from PySide6.QtGui import QFont, QFontMetrics, QTextLayout, QTextOption +from PySide6.QtWidgets import QListWidget + +# No ellipsis while the wrapped label fits on this many lines or fewer. +MIN_LINES_BEFORE_ELLIPSIS = 4 + +# Shared tile geometry (measurement + delegate paint must match). +ICON_TILE_TOP_PAD = 4 +ICON_TILE_ICON_LABEL_GAP = 6 +ICON_TILE_SIDE_PAD = 4 +ICON_TILE_BOTTOM_PAD = 4 + +# Must match ``ICON_MODE_LIST_QSS`` (1px border + 2px padding on each side). +_ITEM_BORDER_PX = 1 +_ITEM_PADDING_PX = 2 +_ITEM_INSET_LR = 2 * (_ITEM_BORDER_PX + _ITEM_PADDING_PX) +_ITEM_EXTRA_PAD = 4 + +ICON_TILE_LABEL_ROLE = Qt.ItemDataRole.UserRole + 2 +ICON_TILE_DISPLAY_LINES_ROLE = Qt.ItemDataRole.UserRole + 3 +ICON_TILE_DISPLAY_HEIGHTS_ROLE = Qt.ItemDataRole.UserRole + 4 + +LONG_NAME_WRAP_MIN_WIDTH_FACTOR = 3 +# Legacy alias: horizontal text inset is ``2 * ICON_TILE_SIDE_PAD``. +TILE_H_MARGIN = 2 * ICON_TILE_SIDE_PAD + _ITEM_INSET_LR + + +@dataclass(frozen=True, slots=True) +class IconTileLabelLayout: + lines: tuple[str, ...] + line_heights: tuple[int, ...] + total_height: int + + @property + def line_count(self) -> int: + return len(self.lines) + + +def normalize_icon_tile_label(name: str) -> str: + return (name or "").strip() or "—" + + +def format_icon_tile_label(name: str) -> str: + return normalize_icon_tile_label(name) + + +def icon_mode_label_font(list_widget: QListWidget) -> QFont: + font = QFont(list_widget.font()) + pt = font.pointSizeF() + if pt > 0: + font.setPointSizeF(max(1.0, pt * 0.85)) + return font + + +def icon_tile_text_zone_width(cell_width: int) -> int: + return max(30, cell_width - 2 * ICON_TILE_SIDE_PAD) + + +def icon_tile_text_top(icon_height: int) -> int: + return ICON_TILE_TOP_PAD + max(1, icon_height) + ICON_TILE_ICON_LABEL_GAP + + +def icon_tile_cell_rect(list_widget: QListWidget | None, item_rect: QRect) -> QRect: + cell = QRect(item_rect) + if list_widget is not None: + grid = list_widget.gridSize() + if grid.width() > 0: + cell.setWidth(grid.width()) + if grid.height() > 0: + cell.setHeight(grid.height()) + return cell + + +def icon_tile_icon_rect(cell: QRect, icon_size: QSize) -> QRect: + """Icon anchored at top-centre of the tile (not vertically centred in the cell).""" + iw = max(1, icon_size.width()) + ih = max(1, icon_size.height()) + x = cell.left() + max(0, (cell.width() - iw) // 2) + y = cell.top() + ICON_TILE_TOP_PAD + return QRect(x, y, iw, ih) + + +def icon_tile_label_paint_rect(cell: QRect, icon_height: int) -> QRect: + """Text block below the icon, relative to *cell* coordinates.""" + top = cell.top() + icon_tile_text_top(icon_height) + return QRect( + cell.left() + ICON_TILE_SIDE_PAD, + top, + max(30, cell.width() - 2 * ICON_TILE_SIDE_PAD), + max(1, cell.bottom() - top - ICON_TILE_BOTTOM_PAD + 1), + ) + + +def layout_icon_tile_label(text: str, font: QFont, text_width_px: int) -> IconTileLabelLayout: + if text_width_px <= 0: + fm = QFontMetrics(font) + return IconTileLabelLayout((text or "—",), (fm.lineSpacing(),), fm.lineSpacing()) + + option = QTextOption() + option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere) + + layout = QTextLayout(text, font) + layout.setTextOption(option) + layout.beginLayout() + + lines: list[str] = [] + heights: list[int] = [] + total = 0 + while True: + line = layout.createLine() + if not line.isValid(): + break + line.setLineWidth(float(text_width_px)) + start = line.textStart() + length = line.textLength() + lines.append(text[start : start + length]) + h = max(1, int(line.height())) + heights.append(h) + total += h + + layout.endLayout() + + if not lines: + fm = QFontMetrics(font) + h = fm.lineSpacing() + return IconTileLabelLayout((text or "—",), (h,), h) + + return IconTileLabelLayout(tuple(lines), tuple(heights), total) + + +def display_lines_for_tile( + laid_out: IconTileLabelLayout, + *, + font: QFont, + text_width_px: int, +) -> tuple[str, ...]: + lines = laid_out.lines + if len(lines) <= MIN_LINES_BEFORE_ELLIPSIS: + return lines + + fm = QFontMetrics(font) + tail = " ".join(lines[MIN_LINES_BEFORE_ELLIPSIS:]) + elided = fm.elidedText(tail, Qt.TextElideMode.ElideRight, text_width_px) + return (*lines[:MIN_LINES_BEFORE_ELLIPSIS], elided) + + +def display_block_height( + display_lines: Sequence[str], + line_heights: Sequence[int], + font: QFont, +) -> int: + """Pixel height of the lines actually shown (no empty 4-line floor).""" + if line_heights and len(line_heights) >= len(display_lines): + return sum(int(line_heights[i]) for i in range(len(display_lines))) + fm = QFontMetrics(font) + return len(display_lines) * fm.lineSpacing() + + +def icon_tile_cell_height(icon_height: int, label_block_height: int) -> int: + return ( + icon_tile_text_top(icon_height) + + label_block_height + + ICON_TILE_BOTTOM_PAD + + _ITEM_INSET_LR + + _ITEM_EXTRA_PAD + ) + + +def _label_max_horizontal_advance(fm: QFontMetrics, lbl: str) -> int: + return fm.horizontalAdvance(lbl or "—") + + +def refresh_icon_tile_display_cache( + list_widget: QListWidget, + icon_size: QSize, + labels: Sequence[str], +) -> None: + cell_w = list_widget.gridSize().width() + if cell_w <= 0: + return + if not isinstance(icon_size, QSize): + icon_size = QSize(icon_size) + font = icon_mode_label_font(list_widget) + icon_h = max(1, icon_size.height()) + dummy_cell = QRect(0, 0, cell_w, 10000) + text_w = icon_tile_label_paint_rect(dummy_cell, icon_h).width() + fm = QFontMetrics(font) + default_h = fm.lineSpacing() + for i, orig in enumerate(labels): + it = list_widget.item(i) + if it is None: + continue + laid_out = layout_icon_tile_label(orig, font, text_w) + display = display_lines_for_tile(laid_out, font=font, text_width_px=text_w) + heights = tuple( + laid_out.line_heights[j] if j < len(laid_out.line_heights) else default_h + for j in range(len(display)) + ) + if len(display) > MIN_LINES_BEFORE_ELLIPSIS and len(heights) == len(display): + heights = (*heights[:-1], default_h) + it.setData(ICON_TILE_DISPLAY_LINES_ROLE, display) + it.setData(ICON_TILE_DISPLAY_HEIGHTS_ROLE, heights) + + +def max_label_block_height_for_labels( + labels: Sequence[str], + font: QFont, + text_width_px: int, +) -> int: + fm = QFontMetrics(font) + if not labels: + return fm.lineSpacing() + max_h = 0 + for lbl in labels: + laid_out = layout_icon_tile_label(lbl, font, text_width_px) + display = display_lines_for_tile(laid_out, font=font, text_width_px=text_width_px) + heights = tuple( + laid_out.line_heights[j] if j < len(laid_out.line_heights) else QFontMetrics(font).lineSpacing() + for j in range(len(display)) + ) + if len(display) > MIN_LINES_BEFORE_ELLIPSIS: + heights = (*heights[:-1], QFontMetrics(font).lineSpacing()) + max_h = max(max_h, display_block_height(display, heights, font)) + return max_h diff --git a/app/ui/icons.py b/app/ui/icons.py new file mode 100644 index 00000000..63b34288 --- /dev/null +++ b/app/ui/icons.py @@ -0,0 +1,246 @@ +# File icons.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Icon resolution helpers.""" + +import sys +from pathlib import Path + +_bfd_sizes_cache: tuple[int, ...] | None = None +_bfd_sizes_mtime: float | None = None + + +def resolve_asset_icon_file(icon_name: str | None) -> Path | None: + """Return a path under ``assets/icons`` only when that file exists. + + Unlike :func:`resolve_icon_path`, this does **not** fall back to ``unknown.png``, + so callers can detect a missing bundled asset and use type-based system icons instead. + """ + if not icon_name: + return None + base = Path(__file__).resolve().parent.parent / "assets" / "icons" + name = Path(str(icon_name).strip()).name + if not name: + return None + candidate = base / name + if candidate.is_file(): + return candidate + alt_svg = candidate.with_suffix(".svg") + if alt_svg.is_file(): + return alt_svg + return None + + +def _bundled_freedesktop_root() -> Path: + return Path(__file__).resolve().parent.parent / "assets" / "icons" / "netneighbor" + + +def bundled_freedesktop_png_side_sizes() -> tuple[int, ...]: + """Available icon sizes under ``assets/icons/netneighbor``, sorted ascending. + + Supports both flat ``{N}/`` and square ``{N}x{N}/`` subdirectory naming. + Discovered at runtime (cached until the directory mtime changes). + """ + global _bfd_sizes_cache, _bfd_sizes_mtime + root = _bundled_freedesktop_root() + if not root.is_dir(): + return () + try: + mtime = root.stat().st_mtime + except OSError: + return () + if _bfd_sizes_cache is not None and _bfd_sizes_mtime == mtime: + return _bfd_sizes_cache + from utils.icon_packs import scan_pack_sizes + out = tuple(sorted(scan_pack_sizes(root))) + _bfd_sizes_cache = out + _bfd_sizes_mtime = mtime + return out + + +def user_custom_icons_dir() -> Path: + """``~/.config/netneighbor/custom_icons`` (PNG overrides, shared GTK/Qt).""" + return Path.home() / ".config" / "netneighbor" / "custom_icons" + + +def iter_bundled_freedesktop_choice_basenames() -> list[str]: + """Unique ``*.png`` stems under any size subfolder of ``assets/icons/netneighbor`` (sorted).""" + root = _bundled_freedesktop_root() + names: set[str] = set() + try: + for sz in bundled_freedesktop_png_side_sizes(): + for fmt in (f"{sz}x{sz}", str(sz)): + d = root / fmt + if d.is_dir(): + for p in d.glob("*.png"): + names.add(p.stem) + break + except OSError: + return [] + return sorted(names) + + +def resolve_persisted_icon_id_to_path( + icon_id: str | None, + active_pack_root: Path | None = None, +) -> Path | None: + """Resolve a stored icon id (``bundled:stem``, ``custom:file.png``, ``builtin:file.png``). + + For ``bundled:`` ids, *active_pack_root* is tried first; falls back to the built-in pack. + """ + if not icon_id or not isinstance(icon_id, str): + return None + s = icon_id.strip() + if not s: + return None + if ":" in s: + prefix, rest = s.split(":", 1) + rest = rest.strip() + name = Path(rest).name + if not name: + return None + pfx = prefix.strip().lower() + if pfx == "bundled": + stem = Path(name).stem + return _resolve_picker_preview(stem, active_pack_root) + if pfx == "custom": + p = user_custom_icons_dir() / name + return p if p.is_file() else None + if pfx == "builtin": + return resolve_asset_icon_file(name) + return resolve_asset_icon_file(Path(s).name) + + +def resolve_bundled_freedesktop_icon(icon_name: str | None) -> Path | None: + """One file under ``assets/icons/netneighbor`` for a Freedesktop basename. + + Prefers the **largest** existing ``{N}x{N}/{name}.png``, then flat ``{name}.png`` / ``{name}.svg``. + For Qt multi-resolution icons, ``utils.qt_device_icons`` registers every ``NxN`` size found. + """ + if not icon_name: + return None + raw = str(icon_name).strip() + stem = Path(raw).name + if not stem or stem != raw: + return None + from utils.icon_packs import find_icon_in_pack + base = _bundled_freedesktop_root() + for sz in reversed(bundled_freedesktop_png_side_sizes()): + candidate = find_icon_in_pack(base, sz, stem) + if candidate is not None: + return candidate + for ext in (".svg", ".png"): + candidate = base / f"{stem}{ext}" + if candidate.is_file(): + return candidate + return None + + +def _resolve_picker_preview(stem: str, active_pack_root: Path | None) -> Path | None: + """Return best preview path for *stem*: active pack → built-in fallback.""" + if active_pack_root is not None: + from utils.icon_packs import find_icon_in_pack, scan_pack_sizes + for sz in reversed(scan_pack_sizes(active_pack_root)): + candidate = find_icon_in_pack(active_pack_root, sz, stem) + if candidate is not None: + return candidate + return resolve_bundled_freedesktop_icon(stem) + + +def iter_icon_picker_entries( + preferred_type: str | None, + active_pack_root: Path | None = None, +) -> list[tuple[str, str, Path | None]]: + """Rows for GTK/Qt icon pickers: ``(icon_id, label, preview_path)``. + + ``preview_path`` may be ``None`` only if a file disappeared between scan and open. + Icons are previewed from *active_pack_root* when provided, falling back to built-in. + """ + from gettext import gettext as _ + + from utils.type_icon_config import type_icon_basenames_for_slug + + rows: list[tuple[str, str, Path | None]] = [] + for stem in iter_bundled_freedesktop_choice_basenames(): + p = _resolve_picker_preview(stem, active_pack_root) + rows.append((f"bundled:{stem}", f"{stem} ({_('App icon pack')})", p)) + cdir = user_custom_icons_dir() + if cdir.is_dir(): + for icon_path in sorted(cdir.glob("*.png")): + rows.append( + ( + f"custom:{icon_path.name}", + f"{icon_path.name} ({_('Custom')})", + icon_path if icon_path.is_file() else None, + ) + ) + slug = (preferred_type or "").strip().lower() + preferred: set[str] = set(type_icon_basenames_for_slug(slug)) if slug else set() + + def _sort_key(t: tuple[str, str, Path | None]) -> tuple[int, str]: + icon_id, label, _p = t + stem = "" + if icon_id.startswith("bundled:"): + stem = icon_id.split(":", 1)[1] + is_pref = 0 if stem in preferred else 1 + return (is_pref, label.lower()) + + rows.sort(key=_sort_key) + return rows + + +def resolve_icon_path(icon_name: str | None) -> Path: + base = Path(__file__).resolve().parent.parent / "assets" / "icons" + if icon_name: + candidate = base / icon_name + if candidate.exists(): + return candidate + alt_svg = candidate.with_suffix(".svg") + if alt_svg.exists(): + return alt_svg + unknown_png = base / "unknown.png" + if unknown_png.exists(): + return unknown_png + unknown_svg = base / "unknown.svg" + if unknown_svg.exists(): + return unknown_svg + return unknown_png + + +def resolve_app_icon_paths_in_order() -> list[Path]: + """Bundled app icon paths in preference order. + + On Windows, a multi-resolution ``.ico`` is preferred for the taskbar when running under + ``python.exe``; place ``assets/icons/netneighbor.ico`` (or ``app.ico``) if you have one. + """ + root = Path(__file__).resolve().parent.parent + out: list[Path] = [] + icons_dir = root / "assets" / "icons" + if sys.platform == "win32": + for name in ("netneighbor.ico", "app.ico", "netneighbor_icon.ico"): + candidate = icons_dir / name + if candidate.is_file(): + out.append(candidate) + svg_dir = root / "assets" / "svg" + for name in ("netneighbor_icon.svg", "netneighbor.svg"): + candidate = svg_dir / name + if candidate.is_file(): + out.append(candidate) + base = icons_dir + for name in ("logo.png", "logo.svg", "netneighbor.png", "netneighbor.svg", "app.png", "app.svg"): + candidate = base / name + if candidate.exists(): + out.append(candidate) + return out + + +def resolve_app_icon_path() -> Path | None: + """Return the window/taskbar icon path (``.ico`` on Windows if present, else SVG / PNG).""" + paths = resolve_app_icon_paths_in_order() + return paths[0] if paths else None + + +def resolve_app_logo_path() -> Path | None: + """Return the high-res logo path used in the About dialog (same preference order).""" + return resolve_app_icon_path() diff --git a/app/ui/main_window.py b/app/ui/main_window.py new file mode 100644 index 00000000..4acd73b2 --- /dev/null +++ b/app/ui/main_window.py @@ -0,0 +1,2405 @@ +# File main_window.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Main window — list & icon views (NetNeighbor 2.0).""" + +from __future__ import annotations + +import logging +import os +import sys +import threading +import time +from collections.abc import Callable, Iterable, Sequence +from pathlib import Path +from datetime import datetime, timezone + +from gettext import gettext as _ +from PySide6.QtCore import QDateTime, QEvent, QObject, QPoint, QRect, QSize, Qt, QTimer, Signal +from PySide6.QtGui import QAction, QActionGroup, QColor, QIcon, QKeySequence, QPainter, QPalette, QPixmap, QResizeEvent, QShowEvent +from PySide6.QtWidgets import ( + QAbstractItemView, + QApplication, + QFrame, + QHBoxLayout, + QHeaderView, + QListView, + QListWidget, + QListWidgetItem, + QMainWindow, + QMenu, + QMessageBox, + QSizePolicy, + QSplitter, + QStackedWidget, + QTableWidget, + QTableWidgetItem, + QSystemTrayIcon, + QToolButton, + QVBoxLayout, + QWidget, +) + +from discovery.manager import DiscoveryManager +from model.device import Device +from ui.icons import resolve_asset_icon_file, resolve_persisted_icon_id_to_path +from ui.grouped_icon_sections import build_grouped_icon_scroll +from ui.icon_grid_layout import ( + IconListViewportResizeFilter, + create_icon_tile_list_item, + relayout_icon_mode_list, + set_icon_tile_item_label, +) +from ui.device_actions import ( + bundle_custom_command, + effective_global_custom_command, + launch_open_uri, + prompt_rename_device, + run_custom_command_for_bundle, +) +from ui.device_context_menu import show_device_context_menu +from ui.device_details_dialog import DeviceCommandSettings, DeviceIconSettings, show_device_details_dialog +from ui.icon_picker_dialog import pick_device_icon_id +from ui.icon_tile_delegate import IconTileItemDelegate +from ui.no_focus_item_delegate import NoFocusItemDelegate +from utils.details_payload import format_device_type_for_details +from utils.device_bundles import ( + DeviceBundle, + apply_bundle_category_filter, + build_device_bundles, + bundle_location_label, + bundle_remote_icon_hint, + bundle_snapshot_ui_fingerprint, +) +from utils.connect_launcher import normalize_connect_templates +from utils.device_details_view import build_device_details_view_model +from utils.device_remote_icon import ( + bundle_has_device_icon_source, + bundle_provided_icon_display, + purge_remote_icon_for_ip, +) +from utils.discovery_cache import purge_device_from_discovery_cache +from utils.discovery_config import normalize_information_precedence_list +from utils.double_click_open import resolve_all_connect_targets, resolve_connect_target +from utils.location_label import location_options_with_current, normalize_location_options +from utils.icon_view_prefs import ( + DEVICE_ICON_REFERENCE_PX, + ICON_SIZE_PRESET_PIXELS, + icon_size_preset_to_qsize, + normalize_icon_size_preset, +) +from ui.remote_icon_cache import QtRemoteIconCache +from utils.qt_device_icons import qt_icon_for_device_type +from utils.ui_prefs import load_ui_preferences, save_ui_preferences + +from .icon_list_qss import ICON_MODE_LIST_QSS + + +_LOG = logging.getLogger("ui") + + +_LIST_ITEM_INTERACTION_QSS = ( + "QListWidget { background-color: palette(base); outline: none; show-decoration-selected: 0; }" + "QListWidget::item { padding: 4px 6px; border: 1px solid transparent; }" + "QListWidget::item:hover {" + " background-color: palette(alternate-base);" + "}" + "QListWidget::item:selected, QListWidget::item:selected:active, QListWidget::item:selected:!active {" + " background-color: palette(highlight);" + " color: palette(highlighted-text);" + " border: none;" + " outline: none;" + "}" + "QListWidget::item:selected:hover {" + " background-color: palette(highlight);" + " color: palette(highlighted-text);" + "}" + "QListWidget::item:focus { border: none; outline: none; }" +) + +_TABLE_BODY_QSS = ( + "QTableWidget {" + " gridline-color: palette(mid);" + " background-color: palette(base);" + " alternate-background-color: palette(alternate-base);" + " outline: none;" + "}" + "QTableWidget::item { padding: 4px 6px; border: 1px solid transparent; }" + "QTableWidget::item:selected, QTableWidget::item:selected:active, QTableWidget::item:selected:!active {" + " background-color: palette(highlight);" + " color: palette(highlighted-text);" + " border: none;" + " outline: none;" + "}" + "QTableWidget::item:focus { border: none; outline: none; }" +) + + +class _ScanningOverlay(QWidget): + """Animated spinner overlay — a background thread drives the animation via Signal. + + Using a Python thread + Signal (QueuedConnection) ensures the repaint request + reaches the main thread even when it is briefly busy at startup, without any + dependency on QTimer delivery timing. + """ + + _FRAMES = 10 + _INTERVAL_S = 0.10 # 10 fps + _MAX_MS = 12_000 + # SVG viewBox is 200×250 (4:5 ratio); render at this width (height computed from ratio). + _SVG_W = 160 + _SVG_H = 200 # 160 * 250 / 200 + + _tick_signal = Signal() # emitted from bg thread → received on main thread + + def __init__(self, main_window: QWidget, content_frame: QWidget) -> None: + super().__init__(main_window) + self._content_frame = content_frame + self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground) + self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent) + self._step = 0 + self._tick_count = 0 + self._hide_requested = False + self._alive = False + self._tick_signal.connect(self._on_tick, Qt.ConnectionType.QueuedConnection) + self._guard = QTimer(self) + self._guard.setSingleShot(True) + self._guard.setInterval(self._MAX_MS) + self._guard.timeout.connect(self.hide) + content_frame.installEventFilter(self) + main_window.installEventFilter(self) + + from PySide6.QtSvg import QSvgRenderer + svg_dir = Path(__file__).resolve().parent.parent / "assets" / "spinner" + self._renderers: list = [] + for i in range(self._FRAMES): + p = svg_dir / f"spinner-{i}.svg" + r = QSvgRenderer(str(p), self) if p.is_file() else None + self._renderers.append(r) + + # ── geometry sync ────────────────────────────────────────────────────────── + + def _update_geometry(self) -> None: + p = self._content_frame + mw = self.parent() + if p is None or mw is None: + return + tl = p.mapTo(mw, QPoint(0, 0)) + self.setGeometry(tl.x(), tl.y(), p.width(), p.height()) + + def eventFilter(self, obj, event) -> bool: + if event.type() in (QEvent.Type.Resize, QEvent.Type.Move): + self._update_geometry() + if self.isVisible(): + self.raise_() + return False + + # ── show / hide ──────────────────────────────────────────────────────────── + + def showEvent(self, event) -> None: + super().showEvent(event) + self._update_geometry() + self.raise_() + self._guard.start() + self._tick_count = 0 + self._hide_requested = False + self._alive = True + t = threading.Thread(target=self._anim_loop, daemon=True, name="overlay-anim") + t.start() + + def hideEvent(self, event) -> None: + super().hideEvent(event) + self._alive = False + self._guard.stop() + + # ── animation thread ─────────────────────────────────────────────────────── + + def _anim_loop(self) -> None: + while self._alive: + self._tick_signal.emit() + time.sleep(self._INTERVAL_S) + + def request_hide(self) -> None: + """Hide after the current cycle completes (minimum one full 0→9 loop).""" + if self._tick_count >= self._FRAMES: + self.hide() + else: + self._hide_requested = True + + def _on_tick(self) -> None: + if not self.isVisible(): + return + self._tick_count += 1 + self._step = self._tick_count % self._FRAMES + self.raise_() + self.repaint() + if self._hide_requested and self._tick_count >= self._FRAMES: + self.hide() + + # ── painting ─────────────────────────────────────────────────────────────── + + def paintEvent(self, _event) -> None: + from PySide6.QtCore import QRectF + painter = QPainter(self) + painter.setRenderHint(QPainter.RenderHint.Antialiasing) + painter.fillRect(self.rect(), self.palette().color(QPalette.ColorRole.Base)) + + cx = self.width() / 2.0 + # Centre the SVG slightly above mid-height to leave room for text below. + svg_top = self.height() / 2.0 - self._SVG_H / 2.0 - 16 + svg_rect = QRectF(cx - self._SVG_W / 2.0, svg_top, self._SVG_W, self._SVG_H) + + renderer = self._renderers[self._step % self._FRAMES] if self._renderers else None + if renderer is not None and renderer.isValid(): + renderer.render(painter, svg_rect) + + font = painter.font() + font.setPointSize(11) + painter.setFont(font) + painter.setPen(self.palette().color(QPalette.ColorRole.Text)) + text_top = int(svg_top + self._SVG_H + 10) + painter.drawText( + QRect(0, text_top, self.width(), 32), + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop, + _("Start Scanning…"), + ) + painter.end() + + +class _UserActivityGuard(QObject): + """Application-level event filter that tracks the last user input timestamp.""" + + _WATCHED = frozenset({ + QEvent.Type.MouseMove, + QEvent.Type.MouseButtonPress, + QEvent.Type.MouseButtonRelease, + QEvent.Type.MouseButtonDblClick, + QEvent.Type.Wheel, + QEvent.Type.KeyPress, + }) + + def __init__(self, parent: QObject | None = None) -> None: + super().__init__(parent) + self._last_ms: int = 0 + + def eventFilter(self, obj: QObject, event: QEvent) -> bool: + if event.type() in self._WATCHED: + self._last_ms = QDateTime.currentMSecsSinceEpoch() + return False + + def idle_ms(self) -> int: + """Milliseconds since the last user input event.""" + return QDateTime.currentMSecsSinceEpoch() - self._last_ms + + +class NetNeighborMainWindow(QMainWindow): + """Table (list) and icon-mode list; view options stored in ``ui_prefs.json``.""" + + _notification_received = Signal(str, str, str) # datetime_str, device_name, status + _location_prefs_dirty = Signal() # emitted from discovery threads → persist on main thread + + _FILTER_ROLE = Qt.ItemDataRole.UserRole + _BUNDLE_KEY_ROLE = Qt.ItemDataRole.UserRole + 1 + + def __init__( + self, + parent=None, + *, + discovery_manager: DiscoveryManager | None = None, + information_precedence: Sequence[str] | None = None, + ) -> None: + super().__init__(parent) + self._discovery_manager = discovery_manager + self._information_precedence = ( + list(information_precedence) + if information_precedence + else normalize_information_precedence_list(None) + ) + + prefs = load_ui_preferences() + self._view_mode = str(prefs.get("view_mode", "icons")) + if self._view_mode not in {"icons", "list"}: + self._view_mode = "icons" + self._icon_sort_mode = str(prefs.get("icon_sort_mode", "sorted")) + if self._icon_sort_mode not in {"appearance", "sorted", "location"}: + self._icon_sort_mode = "sorted" + + self._icon_size_preset = normalize_icon_size_preset(prefs.get("icon_size_preset")) + + sc = prefs.get("selected_category") + self._selected_category: str | None = sc if isinstance(sc, str) else None + + self._sidebar_position = int(prefs.get("sidebar_position", 220)) + self._sidebar_position = max(160, min(self._sidebar_position, 480)) + self._sidebar_collapsed_pref = bool(prefs.get("sidebar_collapsed", False)) + + raw_exp = prefs.get("icon_group_expanded") + self._icon_group_expanded: dict[str, bool] = {} + if isinstance(raw_exp, dict): + for k, v in raw_exp.items(): + if isinstance(k, str) and isinstance(v, bool): + self._icon_group_expanded[k] = v + + self._icon_source_overrides: dict[tuple[str, int], str] = {} + raw_iso = prefs.get("icon_source_overrides") + if isinstance(raw_iso, dict): + for key, mode in raw_iso.items(): + if mode not in {"auto", "provided", "system", "custom"}: + continue + if not isinstance(key, str) or ":" not in key: + continue + ip, port_text = key.rsplit(":", 1) + try: + port = int(port_text) + except ValueError: + continue + self._icon_source_overrides[(ip, port)] = mode + + self._custom_icon_overrides: dict[tuple[str, int], str] = {} + raw_cio = prefs.get("custom_icon_overrides") + if isinstance(raw_cio, dict): + for key, icon_name in raw_cio.items(): + if not isinstance(icon_name, str) or not icon_name.strip(): + continue + if not isinstance(key, str) or ":" not in key: + continue + ip, port_text = key.rsplit(":", 1) + try: + port = int(port_text) + except ValueError: + continue + self._custom_icon_overrides[(ip, port)] = icon_name.strip() + + self._location_options: list[str] = [] + raw_locs = prefs.get("location_options") + if isinstance(raw_locs, list): + self._location_options = normalize_location_options( + [str(v).strip() for v in raw_locs if isinstance(v, str) and str(v).strip()] + ) + if not self._location_options: + from ui.preset_editors import _default_location_presets + self._location_options = _default_location_presets() + self._type_options: list[tuple[str, str]] = [] + raw_types = prefs.get("type_options") + if isinstance(raw_types, list): + for entry in raw_types: + if not isinstance(entry, dict): + continue + label = entry.get("label") + slug = entry.get("slug") + if isinstance(label, str) and isinstance(slug, str) and slug.strip(): + self._type_options.append((label, slug.strip().lower())) + self._connect_command_templates = normalize_connect_templates( + prefs.get("connect_command_templates") + ) + self._custom_command_template = str(prefs.get("custom_command_template", "") or "") + + if discovery_manager is not None: + raw_dc = prefs.get("device_commands") + if isinstance(raw_dc, dict): + discovery_manager.set_device_commands_overrides(raw_dc) + raw_cc = prefs.get("custom_command_overrides") + if isinstance(raw_cc, dict): + discovery_manager.set_custom_command_overrides(raw_cc) + raw_fmr = prefs.get("field_mapping_rules") + if isinstance(raw_fmr, dict): + discovery_manager.set_field_mapping_rules(raw_fmr) + raw_mon = prefs.get("monitored_overrides") + if isinstance(raw_mon, dict): + discovery_manager.set_monitored_overrides(raw_mon) + raw_hidden = prefs.get("hidden_overrides") + if isinstance(raw_hidden, dict): + discovery_manager.set_hidden_overrides(raw_hidden) + raw_type_o = prefs.get("type_overrides") + if isinstance(raw_type_o, dict): + discovery_manager.set_type_overrides(raw_type_o) + raw_name_o = prefs.get("name_overrides") + if isinstance(raw_name_o, dict): + discovery_manager.set_name_overrides(raw_name_o) + raw_loc_o = prefs.get("location_overrides") + if isinstance(raw_loc_o, dict): + discovery_manager.set_location_overrides(raw_loc_o) + discovery_manager.set_location_policy( + self._location_options, + bool(prefs.get("auto_add_discovered_locations", False)), + ) + + raw_hidden_meta = prefs.get("hidden_device_meta") + self._hidden_device_meta: dict[str, dict[str, object]] = {} + if isinstance(raw_hidden_meta, dict): + for key, value in raw_hidden_meta.items(): + if isinstance(key, str) and isinstance(value, dict): + self._hidden_device_meta[key] = dict(value) + + self._notification_log: list[tuple[str, str, str]] = [] + self._notification_received.connect(self._append_notification) + self._location_prefs_dirty.connect(self._schedule_persist_ui_prefs) + if discovery_manager is not None: + discovery_manager.register_presence_transition_hook( + self._on_presence_transition + ) + discovery_manager.set_location_prefs_dirty_callback( + self._location_prefs_dirty.emit + ) + + self._last_devices: list[Device] = [] + self._bundles: list[DeviceBundle] = [] + self._sidebar_signature: tuple | None = None + self._last_device_view_sig: object | None = None + self._last_snapshot_fp: object | None = None + self._first_device_ui_flush_done = False + self._is_updating_sidebar = False + self._table_sort_programmatic = False + + self._pending_devices: list[Device] | None = None + self._device_refresh_timer = QTimer(self) + self._device_refresh_timer.setSingleShot(True) + self._device_refresh_timer.timeout.connect(self._flush_pending_devices) + + self._view_refresh_timer = QTimer(self) + self._view_refresh_timer.setSingleShot(True) + self._view_refresh_timer.timeout.connect(self._refresh_device_widgets) + + self._persist_prefs_timer = QTimer(self) + self._persist_prefs_timer.setSingleShot(True) + self._persist_prefs_timer.timeout.connect(self._persist_ui_prefs) + + self._activity_guard = _UserActivityGuard(self) + _app = QApplication.instance() + if _app is not None: + _app.installEventFilter(self._activity_guard) + + self._remote_icon_cache = QtRemoteIconCache(self) + self._remote_icon_cache.icons_ready.connect(self._on_remote_icons_ready) + self._remote_icon_cache.prefetch_from_index() + + self.setWindowTitle(_("NetNeighbor")) + + self._splitter = QSplitter(Qt.Orientation.Horizontal) + + self._sidebar_list = QListWidget() + self._sidebar_list.setMinimumWidth(140) + self._sidebar_list.setWordWrap(True) + self._sidebar_list.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self._sidebar_list.itemSelectionChanged.connect(self._on_sidebar_selection_changed) + self._sidebar_list.setStyleSheet(_LIST_ITEM_INTERACTION_QSS) + self._sidebar_list.setItemDelegate(NoFocusItemDelegate(self._sidebar_list)) + + self._sidebar_top_spacer = QWidget() + self._sidebar_top_spacer.setFixedHeight(0) + self._sidebar_top_spacer.setSizePolicy( + QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed + ) + self._sidebar_host = QWidget() + _sidebar_col = QVBoxLayout(self._sidebar_host) + _sidebar_col.setContentsMargins(0, 0, 0, 0) + _sidebar_col.setSpacing(0) + _sidebar_col.addWidget(self._sidebar_top_spacer) + _sidebar_col.addWidget(self._sidebar_list, stretch=1) + self._sidebar_host.setMinimumWidth(140) + self._sidebar_host.setObjectName("nnSidebarFrame") + self._sidebar_host.setStyleSheet( + "#nnSidebarFrame {" + " border: 1px solid palette(mid);" + " border-radius: 2px;" + " background: palette(base);" + "}" + ) + + self._stack = QStackedWidget() + self._table = QTableWidget(0, 5) + self._table.setHorizontalHeaderLabels( + [ + _("Name"), + _("IP"), + _("Type"), + _("Location"), + _("Online"), + ] + ) + self._table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self._table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self._table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + self._table.setAlternatingRowColors(True) + self._table.setWordWrap(True) + self._table.verticalHeader().setVisible(False) + self._table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self._table.customContextMenuRequested.connect(self._on_table_context_menu) + self._table.cellDoubleClicked.connect(self._on_table_double_clicked) + hdr = self._table.horizontalHeader() + hdr.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + hdr.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + hdr.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch) + hdr.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch) + hdr.setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents) + hdr.setStyleSheet( + "QHeaderView::section {" + " background-color: palette(button);" + " color: palette(button-text);" + " padding: 4px 6px;" + " border: none;" + " border-right: 1px solid palette(mid);" + " border-bottom: 1px solid palette(mid);" + "}" + ) + self._table.setStyleSheet(_TABLE_BODY_QSS) + self._table.setItemDelegate(NoFocusItemDelegate(self._table)) + self._table.horizontalHeader().sortIndicatorChanged.connect(self._on_table_sort_indicator_changed) + + self._icon_list = QListWidget() + self._icon_list.setViewMode(QListWidget.ViewMode.IconMode) + self._icon_list.setUniformItemSizes(True) + self._icon_list.setMovement(QListWidget.Movement.Static) + self._icon_list.setResizeMode(QListWidget.ResizeMode.Adjust) + self._icon_list.setWrapping(True) + self._icon_list.setWordWrap(True) + self._icon_list.setFrameShape(QFrame.Shape.NoFrame) + self._icon_list.setViewportMargins(8, 0, 8, 8) + # Windows native (Vista) style for QListView IconMode can create transient top-level HWNDs + # per layout pass; batched layout + a minimal stylesheet steer this widget through the + # style-polished path instead (taskbar entries titled like "python…" still pick up our AppID). + self._icon_list.setLayoutMode(QListView.LayoutMode.Batched) + self._icon_list.setBatchSize(32) + self._icon_list.setStyleSheet(ICON_MODE_LIST_QSS) + self._icon_list.setItemDelegate(IconTileItemDelegate(self._icon_list)) + self._icon_list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self._icon_list.customContextMenuRequested.connect(self._on_icon_list_context_menu) + self._icon_list.itemDoubleClicked.connect(self._on_icon_list_double_clicked) + self._flat_icon_viewport_filter = IconListViewportResizeFilter( + self._relayout_flat_icon_list, self + ) + self._icon_list.viewport().installEventFilter(self._flat_icon_viewport_filter) + self._apply_icon_list_dimensions() + + self._icon_page_stack = QStackedWidget() + self._icon_page_stack.addWidget(self._icon_list) + + self._grouped_icons_page = QWidget() + self._grouped_icons_page.setObjectName("nnGroupedIconsPage") + self._grouped_icons_page.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self._grouped_icons_page.setStyleSheet( + "#nnGroupedIconsPage { background-color: palette(base); }" + ) + self._grouped_icons_layout = QVBoxLayout(self._grouped_icons_page) + self._grouped_icons_layout.setContentsMargins(0, 0, 0, 0) + self._grouped_icons_layout.setSpacing(0) + self._icon_page_stack.addWidget(self._grouped_icons_page) + + self._stack.addWidget(self._table) + self._stack.addWidget(self._icon_page_stack) + + self._sidebar_toggle_btn = QToolButton(self) + self._sidebar_toggle_btn.setObjectName("nnSidebarToggle") + self._sidebar_toggle_btn.setAutoRaise(True) + self._sidebar_toggle_btn.setFixedWidth(14) + self._sidebar_toggle_btn.setSizePolicy( + QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding + ) + self._sidebar_toggle_btn.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly) + self._sidebar_toggle_btn.setCursor(Qt.CursorShape.PointingHandCursor) + self._sidebar_toggle_btn.clicked.connect(self._on_sidebar_handle_clicked) + self._sidebar_toggle_btn.setStyleSheet( + "QToolButton#nnSidebarToggle {" + " background-color: palette(button);" + " border: none;" + " border-left: 1px solid palette(mid);" + " border-right: 1px solid palette(mid);" + " color: palette(mid);" + " font-size: 11px;" + " padding: 0px;" + "}" + "QToolButton#nnSidebarToggle:hover {" + " background-color: palette(alternate-base);" + " border-left-color: palette(alternate-base);" + " border-right-color: palette(alternate-base);" + " color: palette(text);" + "}" + ) + + self._content_frame = QFrame() + self._content_frame.setObjectName("nnContentFrame") + self._content_frame.setFrameShape(QFrame.Shape.StyledPanel) + self._content_frame.setFrameShadow(QFrame.Shadow.Plain) + self._content_frame.setLineWidth(1) + self._content_frame.setStyleSheet( + "#nnContentFrame {" + " border: 1px solid palette(mid);" + " border-radius: 2px;" + " background: palette(base);" + "}" + ) + _content_layout = QVBoxLayout(self._content_frame) + _content_layout.setContentsMargins(0, 0, 0, 0) + _content_layout.setSpacing(0) + _content_layout.addWidget(self._stack) + + self._sidebar_toggle_host = QWidget() + _main_row = QHBoxLayout(self._sidebar_toggle_host) + _main_row.setContentsMargins(0, 0, 0, 0) + _main_row.setSpacing(0) + _main_row.addWidget(self._sidebar_toggle_btn) + _main_row.addWidget(self._content_frame, stretch=1) + + self._splitter.addWidget(self._sidebar_host) + self._splitter.addWidget(self._sidebar_toggle_host) + self._splitter.setChildrenCollapsible(True) + self._splitter.setCollapsible(0, True) + self._splitter.setStretchFactor(0, 0) + self._splitter.setStretchFactor(1, 1) + + total_w = max(self.width(), 900) + aside = min(self._sidebar_position, total_w // 2) + self._splitter.setSizes([aside, total_w - aside]) + self._refresh_sidebar_toggle_appearance() + + self.setCentralWidget(self._splitter) + + self.statusBar().showMessage(_("No devices yet")) + + self._setup_menu_bar() + self._splitter.splitterMoved.connect(self._on_splitter_moved) + self._sync_menu_checks_from_state() + self._apply_stack_page() + self._rebuild_sidebar() + QTimer.singleShot(0, self._apply_initial_sidebar_geometry) + + self._scanning_overlay = _ScanningOverlay(self, self._content_frame) + self._scanning_overlay.show() + + def showEvent(self, event: QShowEvent) -> None: + super().showEvent(event) + QTimer.singleShot(0, self._sync_sidebar_top_spacer) + + def resizeEvent(self, event: QResizeEvent) -> None: + super().resizeEvent(event) + self._sync_sidebar_top_spacer() + if self._view_mode == "icons" and self._icon_sort_mode == "appearance": + self._relayout_flat_icon_list() + + def _no_location_label(self) -> str: + return _("No location") + + def _sidebar_group_mode(self) -> str: + if self._icon_sort_mode == "location": + return "location" + return "category" + + def _on_splitter_moved(self, _pos: int, _index: int) -> None: + self._sync_sidebar_menu_from_splitter() + self._persist_ui_prefs() + + def _sync_sidebar_menu_from_splitter(self) -> None: + sz = self._splitter.sizes() + visible = bool(sz and sz[0] > 8) + self._act_sidebar.blockSignals(True) + self._act_sidebar.setChecked(visible) + self._act_sidebar.blockSignals(False) + self._refresh_sidebar_toggle_appearance() + + def _refresh_sidebar_toggle_appearance(self) -> None: + sz = self._splitter.sizes() + visible = bool(sz and sz[0] > 8) + if visible: + self._sidebar_toggle_btn.setText("◀") + self._sidebar_toggle_btn.setToolTip(_("Hide sidebar")) + else: + self._sidebar_toggle_btn.setText("▶") + self._sidebar_toggle_btn.setToolTip(_("Show sidebar")) + + def _on_sidebar_handle_clicked(self) -> None: + sz = self._splitter.sizes() + visible = bool(sz and sz[0] > 8) + self._on_sidebar_toggled(not visible) + self._sync_sidebar_menu_from_splitter() + + def _apply_initial_sidebar_geometry(self) -> None: + total = max(self._splitter.width(), self.width(), 600) + if self._sidebar_collapsed_pref: + self._splitter.setSizes([0, total]) + self._act_sidebar.blockSignals(True) + self._act_sidebar.setChecked(False) + self._act_sidebar.blockSignals(False) + self._refresh_sidebar_toggle_appearance() + else: + aside = min(self._sidebar_position, total // 2) + self._splitter.setSizes([aside, total - aside]) + self._sync_sidebar_menu_from_splitter() + self._sync_sidebar_top_spacer() + + def _on_sidebar_toggled(self, visible: bool) -> None: + total = max(self._splitter.width(), self.width(), 600) + if visible: + aside = max(160, min(self._sidebar_position, total // 2)) + self._splitter.setSizes([aside, total - aside]) + else: + sz = self._splitter.sizes() + if sz and sz[0] > 8: + self._sidebar_position = max(160, min(int(sz[0]), 480)) + self._splitter.setSizes([0, total]) + self._persist_ui_prefs() + self._refresh_sidebar_toggle_appearance() + + def _on_sidebar_selection_changed(self) -> None: + if self._is_updating_sidebar: + return + item = self._sidebar_list.currentItem() + if item is None: + return + raw = item.data(self._FILTER_ROLE) + if raw is None or raw == "": + self._selected_category = None + elif isinstance(raw, str): + self._selected_category = raw + else: + self._selected_category = None + self._persist_ui_prefs() + self._schedule_view_refresh() + + def _schedule_view_refresh(self, delay_ms: int = 40) -> None: + """Coalesce table/icon rebuilds (sidebar filter + discovery) to cut native-widget flicker.""" + self._view_refresh_timer.stop() + self._view_refresh_timer.start(int(delay_ms)) + + def _schedule_persist_ui_prefs(self) -> None: + """Write prefs on the next event-loop tick (keeps hide/unhide snappy).""" + self._persist_prefs_timer.start(0) + + def _update_visible_device_count_status(self) -> None: + n = len(self._filtered_bundles()) + self.statusBar().showMessage(_("{} devices").format(n)) + + def _rebuild_sidebar(self) -> None: + sidebar_mode = self._sidebar_group_mode() + if self._discovery_manager is not None: + all_bundles = [b for b in self._bundles if not self._discovery_manager.bundle_is_hidden(b.ip, b.port)] + else: + all_bundles = list(self._bundles) + counts: dict[str, int] = {} + bundle_filter_keys: dict[str, str] = {} + + for bundle in all_bundles: + if sidebar_mode == "location": + location = bundle_location_label(bundle, no_location_label=self._no_location_label()) + counts[location] = counts.get(location, 0) + 1 + nl = self._no_location_label() + bundle_filter_keys[location] = "location:__none__" if location == nl else f"location:{location}" + else: + slug = (bundle.primary.type or "unknown").strip().lower() + counts[slug] = counts.get(slug, 0) + 1 + bundle_filter_keys[slug] = slug + + signature = (sidebar_mode, len(all_bundles), tuple(sorted(counts.items()))) + if signature == self._sidebar_signature: + return + self._sidebar_signature = signature + + type_slug_labels: dict[str, str] = {} + if sidebar_mode != "location": + for b in all_bundles: + slug = (b.primary.type or "unknown").strip().lower() + if slug not in type_slug_labels: + type_slug_labels[slug] = format_device_type_for_details(b.primary) + + valid_filters: set[str | None] = {None} + valid_filters.update(bundle_filter_keys.values()) + if self._selected_category is not None and self._selected_category not in valid_filters: + self._selected_category = None + + self._is_updating_sidebar = True + self._sidebar_list.blockSignals(True) + self._sidebar_list.clear() + + all_text = _("All Locations") if sidebar_mode == "location" else _("All Types") + all_label = f"{all_text} ({len(all_bundles)})" + first = QListWidgetItem(all_label) + first.setData(self._FILTER_ROLE, None) + self._sidebar_list.addItem(first) + + for key in sorted( + counts.keys(), + key=lambda k: str(k).lower() + if sidebar_mode == "location" + else type_slug_labels.get(k, k).lower(), + ): + if sidebar_mode == "location" and key == self._no_location_label(): + continue + label = key if sidebar_mode == "location" else type_slug_labels.get(key, key) + row = QListWidgetItem(f"{label} ({counts[key]})") + row.setData(self._FILTER_ROLE, bundle_filter_keys[key]) + self._sidebar_list.addItem(row) + + if sidebar_mode == "location" and self._no_location_label() in counts: + nl = self._no_location_label() + row = QListWidgetItem(f"{nl} ({counts[nl]})") + row.setData(self._FILTER_ROLE, bundle_filter_keys[nl]) + self._sidebar_list.addItem(row) + + target_idx = 0 + for i in range(self._sidebar_list.count()): + it = self._sidebar_list.item(i) + fd = it.data(self._FILTER_ROLE) + if fd == self._selected_category or ( + self._selected_category is None and (fd is None or fd == "") + ): + target_idx = i + break + + self._sidebar_list.setCurrentRow(target_idx) + self._sidebar_list.blockSignals(False) + self._is_updating_sidebar = False + + def _setup_menu_bar(self) -> None: + menu_bar = self.menuBar() + + view_menu = menu_bar.addMenu(_("View")) + act_reload = QAction(_("Reload discovery"), self) + act_reload.setShortcut(QKeySequence.StandardKey.Refresh) + act_reload.triggered.connect(self._reload_discovery) + act_reload.setEnabled(self._discovery_manager is not None) + view_menu.addAction(act_reload) + + view_menu.addSeparator() + + self._act_sidebar = QAction(_("Sidebar"), self) + self._act_sidebar.setCheckable(True) + self._act_sidebar.setChecked(not self._sidebar_collapsed_pref) + self._act_sidebar.toggled.connect(self._on_sidebar_toggled) + view_menu.addAction(self._act_sidebar) + + view_menu.addSeparator() + + view_menu.addAction(_disabled_title_action(self, _("Display:"))) + self._grp_display = QActionGroup(self) + self._grp_display.setExclusive(True) + self._act_display_icons = QAction(_("Icons"), self) + self._act_display_icons.setCheckable(True) + self._act_display_list = QAction(_("List"), self) + self._act_display_list.setCheckable(True) + self._grp_display.addAction(self._act_display_icons) + self._grp_display.addAction(self._act_display_list) + view_menu.addAction(self._act_display_icons) + view_menu.addAction(self._act_display_list) + self._grp_display.triggered.connect(self._on_display_group_triggered) + + view_menu.addSeparator() + + view_menu.addAction(_disabled_title_action(self, _("Arrange:"))) + self._grp_arrange = QActionGroup(self) + self._grp_arrange.setExclusive(True) + self._act_arr_unsorted = QAction(_("Unsorted"), self) + self._act_arr_unsorted.setCheckable(True) + self._act_arr_type = QAction(_("by Type"), self) + self._act_arr_type.setCheckable(True) + self._act_arr_location = QAction(_("by Location"), self) + self._act_arr_location.setCheckable(True) + self._grp_arrange.addAction(self._act_arr_unsorted) + self._grp_arrange.addAction(self._act_arr_type) + self._grp_arrange.addAction(self._act_arr_location) + view_menu.addAction(self._act_arr_unsorted) + view_menu.addAction(self._act_arr_type) + view_menu.addAction(self._act_arr_location) + self._grp_arrange.triggered.connect(self._on_arrange_group_triggered) + + view_menu.addSeparator() + + self._menu_icon_size = QMenu(_("Icons size"), self) + self._grp_icon_size = QActionGroup(self) + self._grp_icon_size.setExclusive(True) + self._act_icon_sz_small = QAction(_("Small"), self) + self._act_icon_sz_medium = QAction(_("Medium"), self) + self._act_icon_sz_large = QAction(_("Large"), self) + self._act_icon_sz_xlarge = QAction(_("Extra large"), self) + for a in ( + self._act_icon_sz_small, + self._act_icon_sz_medium, + self._act_icon_sz_large, + self._act_icon_sz_xlarge, + ): + a.setCheckable(True) + self._grp_icon_size.addAction(a) + self._menu_icon_size.addAction(a) + self._grp_icon_size.triggered.connect(self._on_icon_size_group_triggered) + self._act_view_menu_icon_size = view_menu.addMenu(self._menu_icon_size) + + view_menu.addSeparator() + + act_prefs = QAction(_("Preferences…"), self) + act_prefs.setShortcut(QKeySequence.StandardKey.Preferences) + act_prefs.setMenuRole(QAction.MenuRole.NoRole) + act_prefs.triggered.connect(self._open_preferences) + view_menu.addAction(act_prefs) + + view_menu.addSeparator() + + act_quit = QAction(_("Quit"), self) + act_quit.setShortcut(QKeySequence.StandardKey.Quit) + act_quit.setMenuRole(QAction.MenuRole.NoRole) + act_quit.triggered.connect(self._quit_application) + view_menu.addAction(act_quit) + + tools_menu = menu_bar.addMenu(_("Tools")) + act_notif = QAction(_("Notifications history"), self) + act_notif.triggered.connect(self._open_notifications_history) + tools_menu.addAction(act_notif) + act_hidden = QAction(_("Hidden devices"), self) + act_hidden.triggered.connect(self._open_hidden_devices) + tools_menu.addAction(act_hidden) + + help_menu = menu_bar.addMenu(_("Help")) + act_about = QAction(_("About NetNeighbor"), self) + act_about.setMenuRole(QAction.MenuRole.AboutRole) + act_about.triggered.connect(self._show_about) + help_menu.addAction(act_about) + + def _on_display_group_triggered(self, action: QAction) -> None: + if action == self._act_display_icons: + self._apply_view_mode("icons") + elif action == self._act_display_list: + self._apply_view_mode("list") + + def _on_arrange_group_triggered(self, action: QAction) -> None: + if action == self._act_arr_unsorted: + mode = "appearance" + elif action == self._act_arr_type: + mode = "sorted" + elif action == self._act_arr_location: + mode = "location" + else: + return + self._apply_arrange_mode(mode) + + def _on_icon_size_group_triggered(self, action: QAction) -> None: + if action == self._act_icon_sz_small: + self._apply_icon_size_preset("small") + elif action == self._act_icon_sz_medium: + self._apply_icon_size_preset("medium") + elif action == self._act_icon_sz_large: + self._apply_icon_size_preset("large") + elif action == self._act_icon_sz_xlarge: + self._apply_icon_size_preset("xlarge") + + def _apply_icon_size_preset(self, preset: str) -> None: + if preset not in ICON_SIZE_PRESET_PIXELS: + return + self._icon_size_preset = preset + self._persist_ui_prefs() + self._apply_icon_list_dimensions() + if self._view_mode != "icons": + return + self.setUpdatesEnabled(False) + try: + if self._icon_sort_mode == "appearance": + self._resync_flat_icon_list_pixmaps() + else: + self._rebuild_grouped_icon_page(self._current_ordered_bundles_for_view()) + finally: + self.setUpdatesEnabled(True) + ordered = self._current_ordered_bundles_for_view() + self._last_device_view_sig = self._device_view_refresh_signature(ordered) + + def _apply_icon_list_dimensions(self) -> None: + self._relayout_flat_icon_list(force=True) + + def _relayout_flat_icon_list(self, *, force: bool = False) -> None: + if self._icon_list.count() <= 0: + return + fallback = 0 + if self._icon_list.viewport().width() <= 0: + fallback = max(240, self._content_frame.width() - 24) + relayout_icon_mode_list( + self._icon_list, + icon_size_preset_to_qsize(self._icon_size_preset), + fallback_viewport_width=fallback, + force=force, + ) + + def _apply_view_mode(self, mode: str) -> None: + if mode not in {"icons", "list"}: + return + self._view_mode = mode + self._last_device_view_sig = None + self._persist_ui_prefs() + self._sidebar_signature = None + self._rebuild_sidebar() + self._apply_stack_page() + self._refresh_device_widgets() + + def _apply_arrange_mode(self, mode: str) -> None: + if mode not in {"appearance", "sorted", "location"}: + return + self._icon_sort_mode = mode + self._last_device_view_sig = None + self._persist_ui_prefs() + self._sidebar_signature = None + self._rebuild_sidebar() + self._refresh_device_widgets() + + def _persist_ui_prefs(self) -> None: + prefs = load_ui_preferences() + prefs["view_mode"] = self._view_mode + prefs["icon_sort_mode"] = self._icon_sort_mode + prefs["icon_size_preset"] = self._icon_size_preset + prefs["selected_category"] = self._selected_category + prefs["icon_group_expanded"] = dict(self._icon_group_expanded) + sz = self._splitter.sizes() + collapsed = bool(sz and len(sz) >= 2 and int(sz[0]) <= 8) + prefs["sidebar_collapsed"] = collapsed + if sz and int(sz[0]) > 8: + self._sidebar_position = max(160, min(int(sz[0]), 480)) + prefs["sidebar_position"] = self._sidebar_position + prefs["icon_source_overrides"] = { + f"{ip}:{port}": mode for (ip, port), mode in self._icon_source_overrides.items() + } + prefs["custom_icon_overrides"] = { + f"{ip}:{port}": cid for (ip, port), cid in self._custom_icon_overrides.items() + } + if self._discovery_manager is not None: + prefs["device_commands"] = self._discovery_manager.get_device_commands_overrides() + prefs["custom_command_overrides"] = self._discovery_manager.get_custom_command_overrides() + prefs["field_mapping_rules"] = self._discovery_manager.get_field_mapping_rules() + prefs["monitored_overrides"] = self._discovery_manager.get_monitored_overrides() + prefs["hidden_overrides"] = self._discovery_manager.get_hidden_overrides() + prefs["type_overrides"] = self._discovery_manager.get_type_overrides() + prefs["name_overrides"] = self._discovery_manager.get_name_overrides() + prefs["location_overrides"] = self._discovery_manager.get_location_overrides() + self._prune_hidden_device_meta() + prefs["hidden_device_meta"] = dict(self._hidden_device_meta) + save_ui_preferences(prefs) + + def _sync_menu_checks_from_state(self) -> None: + if self._view_mode == "icons": + self._act_display_icons.setChecked(True) + else: + self._act_display_list.setChecked(True) + + if self._icon_sort_mode == "appearance": + self._act_arr_unsorted.setChecked(True) + elif self._icon_sort_mode == "location": + self._act_arr_location.setChecked(True) + else: + self._act_arr_type.setChecked(True) + + if self._icon_size_preset == "small": + self._act_icon_sz_small.setChecked(True) + elif self._icon_size_preset == "large": + self._act_icon_sz_large.setChecked(True) + elif self._icon_size_preset == "xlarge": + self._act_icon_sz_xlarge.setChecked(True) + else: + self._act_icon_sz_medium.setChecked(True) + + def _apply_stack_page(self) -> None: + if self._view_mode == "icons": + self._stack.setCurrentWidget(self._icon_page_stack) + self._sync_icon_page_stack_index() + else: + self._stack.setCurrentWidget(self._table) + self._update_arrange_actions_enabled() + self._sync_sidebar_top_spacer() + QTimer.singleShot(0, self._sync_sidebar_top_spacer) + + def _sync_sidebar_top_spacer(self) -> None: + self._sidebar_top_spacer.setFixedHeight(0) + + def _sync_icon_page_stack_index(self) -> None: + if self._icon_sort_mode == "appearance": + self._icon_page_stack.setCurrentWidget(self._icon_list) + else: + self._icon_page_stack.setCurrentWidget(self._grouped_icons_page) + + def _update_arrange_actions_enabled(self) -> None: + arrange_en = True + self._act_arr_unsorted.setEnabled(arrange_en) + self._act_arr_type.setEnabled(arrange_en) + self._act_arr_location.setEnabled(arrange_en) + icon_sz_en = self._view_mode == "icons" + self._act_view_menu_icon_size.setEnabled(icon_sz_en) + + def _quit_application(self) -> None: + app = QApplication.instance() + if app is not None: + app.quit() + + def _open_preferences(self) -> None: + from ui.preferences_dialog import PreferencesDialog + + dlg = PreferencesDialog( + self, + on_location_presets_saved=self._apply_location_presets, + on_type_presets_saved=self._apply_type_presets, + on_connect_templates_saved=self._apply_connect_templates, + on_clear_icon_cache=self._clear_icon_cache, + on_icon_pack_changed=self._apply_icon_pack, + on_restart=self._restart_app, + ) + dlg.exec() + + def _apply_location_presets(self, options: list[str], auto_add: bool) -> None: + self._location_options = options + if self._discovery_manager is not None: + self._discovery_manager.set_location_policy(options, auto_add) + + def _apply_type_presets(self, options: list[tuple[str, str]]) -> None: + self._type_options = options + + def _apply_connect_templates(self, templates: dict[str, str], custom: str) -> None: + self._connect_command_templates = templates + self._custom_command_template = custom + + def _clear_icon_cache(self) -> None: + from utils.device_remote_icon import clear_all_app_data + # Stop discovery *before* wiping: protocol stop() force-flushes in-memory caches + # (e.g. SSDP XML/profile cache) to disk. Stopping after the wipe (app_qt finally + # block) would rewrite discovery-cache.json with the previous session's devices. + # stop() is idempotent, so the later call in app_qt is a no-op. + if self._discovery_manager is not None: + self._discovery_manager.stop() + # The open log file is locked on Windows: close it so the wipe can delete it. + from utils.app_logging import close_file_log_handlers + _LOG.info("Reset all application data: discovery stopped, closing log file before wipe") + close_file_log_handlers() + clear_all_app_data() + self._remote_icon_cache.clear() + + def _restart_app(self) -> None: + import subprocess + import sys + from PySide6.QtNetwork import QLocalServer + from PySide6.QtWidgets import QApplication + from utils.qt_single_instance import SINGLETON_SERVER_NAME + app = QApplication.instance() + # Release the single-instance lock before the new process starts. + srv = getattr(app, "_qt_activation_server", None) + if srv is not None: + srv.close() + QLocalServer.removeServer(SINGLETON_SERVER_NAME) + if getattr(sys, "frozen", False): + subprocess.Popen([sys.executable]) + else: + subprocess.Popen([sys.executable, sys.argv[0]]) + app.quit() + + def _apply_icon_pack(self, pack_id: str) -> None: + from utils.icon_packs import invalidate_icon_pack_cache + from PySide6.QtGui import QPixmapCache + invalidate_icon_pack_cache() + QPixmapCache.clear() + self._last_snapshot_fp = None # force re-render even if devices unchanged + self.set_devices(self._last_devices) + + def _reload_discovery(self) -> None: + if self._discovery_manager is None: + return + self._discovery_manager.refresh() + self.statusBar().showMessage(_("Discovery refresh requested"), 3000) + + def _show_about(self) -> None: + from ui.about_dialog import show_about_dialog + + show_about_dialog(self) + + def _on_presence_transition(self, device: Device, kind: str) -> None: + """Called from the discovery thread on online/offline transitions.""" + if not getattr(device, "monitored", False): + return + dt_str = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S") + name = str(device.name or device.ip) + status = _("Online") if kind == "online" else _("Offline") + self._notification_received.emit(dt_str, name, status) + + def _append_notification(self, dt_str: str, name: str, status: str) -> None: + self._notification_log.append((dt_str, name, status)) + + def _open_notifications_history(self) -> None: + from ui.notifications_history_dialog import show_notifications_history_dialog + + def _clear() -> None: + self._notification_log.clear() + + show_notifications_history_dialog(self, list(self._notification_log), _clear) + + def _prune_hidden_device_meta(self) -> None: + if self._discovery_manager is None: + return + hidden = self._discovery_manager.get_hidden_overrides() + self._hidden_device_meta = { + key: meta + for key, meta in self._hidden_device_meta.items() + if hidden.get(key) is True + } + + def _hidden_device_rows(self) -> list: + from ui.hidden_devices_dialog import HiddenDeviceRow + + if self._discovery_manager is None: + return [] + hidden = self._discovery_manager.get_hidden_overrides() + rows: list[HiddenDeviceRow] = [] + seen: set[str] = set() + for host_key, flagged in hidden.items(): + if not flagged or host_key in seen: + continue + seen.add(host_key) + meta = self._hidden_device_meta.get(host_key) + name = "" + ip = "" + port = 0 + if isinstance(meta, dict): + name = str(meta.get("name", "") or "") + ip = str(meta.get("ip", "") or "") + try: + port = int(meta.get("port", 0) or 0) + except (TypeError, ValueError): + port = 0 + if not name and ip: + name = ip + if not name: + name = host_key + rows.append(HiddenDeviceRow(host_key=host_key, name=name, ip=ip, port=port)) + rows.sort(key=lambda row: row.name.lower()) + return rows + + def _open_hidden_devices(self) -> None: + from ui.hidden_devices_dialog import show_hidden_devices_dialog + + show_hidden_devices_dialog( + self, + self._hidden_device_rows(), + self._unhide_device_by_key, + ) + + def _bundle_for_host_key(self, host_key: str) -> DeviceBundle | None: + if self._discovery_manager is None or not host_key: + return None + for bundle in self._bundles: + if self._discovery_manager.canonical_host_identity_key(bundle.ip, bundle.port) == host_key: + return bundle + return None + + def _apply_hidden_visibility_immediate( + self, + *, + removed_bundle_key: str | None = None, + added_bundle: DeviceBundle | None = None, + ) -> None: + """Refresh views after hide/unhide without rebuilding discovery bundles.""" + self._sidebar_signature = None + self._last_device_view_sig = None + if removed_bundle_key and self._try_incremental_remove_bundle(removed_bundle_key): + self._rebuild_sidebar() + self._update_visible_device_count_status() + return + if added_bundle is not None and self._try_incremental_add_bundle(added_bundle): + self._rebuild_sidebar() + self._update_visible_device_count_status() + return + self._rebuild_sidebar() + self._refresh_device_widgets() + + def _try_incremental_remove_bundle(self, bundle_key: str) -> bool: + if self._view_mode == "list": + for row in range(self._table.rowCount()): + item = self._table.item(row, 0) + if item is not None and item.data(self._BUNDLE_KEY_ROLE) == bundle_key: + self._table.removeRow(row) + return True + return False + if self._view_mode == "icons" and self._icon_sort_mode == "appearance": + for index in range(self._icon_list.count()): + item = self._icon_list.item(index) + if item is not None and item.data(self._BUNDLE_KEY_ROLE) == bundle_key: + self._icon_list.takeItem(index) + self._relayout_flat_icon_list() + return True + return False + + def _try_incremental_add_bundle(self, bundle: DeviceBundle) -> bool: + ordered = self._current_ordered_bundles_for_view() + try: + insert_at = next(i for i, row in enumerate(ordered) if row.primary.key == bundle.primary.key) + except StopIteration: + return False + if self._view_mode == "list": + if self._table.isSortingEnabled(): + return False + self._table.insertRow(insert_at) + d = bundle.primary + name_item = QTableWidgetItem(_safe_str(d.name)) + name_item.setData(self._BUNDLE_KEY_ROLE, d.key) + self._table.setItem(insert_at, 0, name_item) + self._table.setItem(insert_at, 1, QTableWidgetItem(_safe_str(d.ip))) + self._table.setItem(insert_at, 2, QTableWidgetItem(format_device_type_for_details(d))) + loc = bundle_location_label(bundle, no_location_label=self._no_location_label()) + self._table.setItem(insert_at, 3, QTableWidgetItem(loc)) + on_txt = _("Yes") if d.online else _("No") + on_item = QTableWidgetItem(on_txt) + on_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + self._table.setItem(insert_at, 4, on_item) + self._table.resizeRowsToContents() + return True + if self._view_mode == "icons" and self._icon_sort_mode == "appearance": + item = create_icon_tile_list_item( + self._icon_for_bundle(bundle), _safe_str(bundle.primary.name) + ) + item.setData(self._BUNDLE_KEY_ROLE, bundle.primary.key) + item.setToolTip(self._bundle_tooltip(bundle)) + self._icon_list.insertItem(insert_at, item) + self._relayout_flat_icon_list() + return True + return False + + def _unhide_device_by_key(self, host_key: str) -> None: + if self._discovery_manager is None: + return + meta = self._hidden_device_meta.get(host_key) + ip = "" + port = 0 + if isinstance(meta, dict): + ip = str(meta.get("ip", "") or "") + try: + port = int(meta.get("port", 0) or 0) + except (TypeError, ValueError): + port = 0 + if ip: + self._discovery_manager.set_bundle_hidden(ip, port, False, notify=False) + else: + for device in list(self._discovery_manager.devices): + if self._discovery_manager.canonical_host_identity_key(device.ip, device.port) == host_key: + self._discovery_manager.set_bundle_hidden(device.ip, device.port, False, notify=False) + break + else: + overrides = self._discovery_manager.get_hidden_overrides() + overrides.pop(host_key, None) + self._discovery_manager.set_hidden_overrides(overrides, notify=False) + self._hidden_device_meta.pop(host_key, None) + self._schedule_persist_ui_prefs() + restored = self._bundle_for_host_key(host_key) + self._apply_hidden_visibility_immediate(added_bundle=restored) + + def _hide_bundle(self, bundle: DeviceBundle) -> None: + if self._discovery_manager is None: + return + host_key = self._discovery_manager.canonical_host_identity_key(bundle.ip, bundle.port) + removed_key = bundle.primary.key + self._discovery_manager.set_bundle_hidden(bundle.ip, bundle.port, True, notify=False) + if host_key: + self._hidden_device_meta[host_key] = { + "name": bundle.name, + "ip": bundle.ip, + "port": int(bundle.port), + } + self._schedule_persist_ui_prefs() + self._apply_hidden_visibility_immediate(removed_bundle_key=removed_key) + + def _clear_bundle(self, bundle: DeviceBundle) -> None: + """Completely purge a device bundle from cache, prefs, and in-memory state.""" + reply = QMessageBox.question( + self, + _("Clear device"), + _("Remove {name} ({ip}) from the cache and all preferences?\n\nThis cannot be undone. The device will reappear if rediscovered on the network.").format( + name=bundle.name, ip=bundle.ip + ), + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel, + QMessageBox.StandardButton.Cancel, + ) + if reply != QMessageBox.StandardButton.Yes: + return + + ip = bundle.ip + port = int(bundle.port) + ep = (ip, port) + + # Remove icon overrides (keyed by (ip, port)). + self._custom_icon_overrides.pop(ep, None) + self._icon_source_overrides.pop(ep, None) + + # Remove hidden device meta for this bundle. + if self._discovery_manager is not None: + host_key = self._discovery_manager.canonical_host_identity_key(ip, port) + if host_key: + self._hidden_device_meta.pop(host_key, None) + # Remove all in-memory devices and overrides from the manager. + self._discovery_manager.purge_bundle(ip, port) + + # Purge on-disk discovery cache entries for this IP. + purge_device_from_discovery_cache({ip}) + + # Purge on-disk and in-memory remote icon cache for this IP. + purge_remote_icon_for_ip(ip) + self._remote_icon_cache.evict_for_ip(ip) + + self._schedule_persist_ui_prefs() + + def set_devices(self, devices: Iterable[Device]) -> None: + """Replace views from discovery snapshot (coalesced to reduce flicker).""" + self._pending_devices = list(devices) + self._device_refresh_timer.stop() + delay_ms = 120 + if not self._first_device_ui_flush_done and self._pending_devices: + delay_ms = 0 + _LOG.debug( + "set_devices: scheduled flush n=%s delay_ms=%s", + len(self._pending_devices), + delay_ms, + ) + self._device_refresh_timer.start(delay_ms) + + def _flush_pending_devices(self) -> None: + if self._pending_devices is None: + return + # Defer while a popup (context menu) is open — rebuilding would close it. + _app = QApplication.instance() + if _app is not None and _app.activePopupWidget() is not None: + self._device_refresh_timer.start(400) + return + # Defer while the user is actively interacting (mouse moving, typing). + if self._activity_guard.idle_ms() < 200: + self._device_refresh_timer.start(250) + return + snapshot = self._pending_devices + self._pending_devices = None + _LOG.debug("_flush_pending_devices: applying n=%s", len(snapshot)) + self._apply_devices_snapshot(snapshot) + if len(self._last_devices) > 0: + self._first_device_ui_flush_done = True + if self._scanning_overlay.isVisible(): + self._scanning_overlay.request_hide() + + def _apply_devices_snapshot(self, devices: list[Device]) -> None: + """Apply a device list to bundles, sidebar, and main views (always merge like GTK).""" + device_list = list(devices) + device_fp = _device_snapshot_ui_fingerprint(device_list) + new_fp_prefix = (tuple(self._information_precedence), device_fp) + if ( + isinstance(self._last_snapshot_fp, tuple) + and len(self._last_snapshot_fp) >= 2 + and self._last_snapshot_fp[:2] == new_fp_prefix + and self._last_device_view_sig is not None + ): + _LOG.debug("_apply_devices_snapshot: skipped (fingerprint unchanged) n=%s", len(device_list)) + return + self._last_devices = device_list + self._bundles = build_device_bundles(device_list, self._information_precedence) + self._last_snapshot_fp = new_fp_prefix + (bundle_snapshot_ui_fingerprint(self._bundles),) + _LOG.debug("_apply_devices_snapshot: n=%s", len(device_list)) + self._maybe_auto_add_discovered_locations() + self._rebuild_sidebar() + self._last_device_view_sig = None + self._schedule_view_refresh() + + def _maybe_auto_add_discovered_locations(self) -> None: + prefs = load_ui_preferences() + if not prefs.get("auto_add_discovered_locations", False): + return + discovered: list[str] = [] + for bundle in self._bundles: + for device in bundle.devices: + md = device.metadata if isinstance(device.metadata, dict) else {} + loc = md.get("user_location") + if isinstance(loc, str) and loc.strip(): + discovered.append(loc.strip()) + if not discovered: + return + merged = normalize_location_options(self._location_options + discovered) + if merged == self._location_options: + return + self._location_options = merged + prefs["location_options"] = merged + save_ui_preferences(prefs) + if self._discovery_manager is not None: + self._discovery_manager.set_location_policy(merged, True) + + def _filtered_bundles(self) -> list[DeviceBundle]: + bundles = apply_bundle_category_filter( + self._bundles, + self._selected_category, + no_location_label=self._no_location_label(), + ) + if self._discovery_manager is None: + return bundles + return [ + bundle + for bundle in bundles + if not self._discovery_manager.bundle_is_hidden(bundle.ip, bundle.port) + ] + + def _current_ordered_bundles_for_view(self) -> list[DeviceBundle]: + filtered = self._filtered_bundles() + return _ordered_bundles( + filtered, + self._icon_sort_mode, + no_location_label=self._no_location_label(), + ) + + def _device_view_refresh_signature(self, ordered: list[DeviceBundle]) -> tuple: + """Detect duplicate discovery snapshots so we can skip rebuilding native icon widgets.""" + return ( + self._view_mode, + self._icon_sort_mode, + self._icon_size_preset, + self._selected_category, + tuple( + ( + b.primary.key, + _safe_str(b.primary.name), + _safe_str(b.primary.ip), + (b.primary.type or "").lower(), + bundle_location_label(b, no_location_label=self._no_location_label()), + bool(b.online), + # Remote-icon source per attached protocol device. A late SSDP descriptor + # enrichment (iconURL appearing after a generic fast-emit, when the primary is + # a different protocol) must rebuild the tile so the icon is fetched — otherwise + # the bundle keeps the generic type icon (see bundle_remote_icon_hint). + bundle_remote_icon_hint(b.ssdp_device), + bundle_remote_icon_hint(b.mdns_device), + bundle_remote_icon_hint(b.wsd_device), + bundle_remote_icon_hint(b.wsdd_device), + bundle_remote_icon_hint(b.nmb_device), + ) + for b in ordered + ), + ) + + def _refresh_device_widgets(self) -> None: + ordered_for_sig = self._current_ordered_bundles_for_view() + sig = self._device_view_refresh_signature(ordered_for_sig) + if sig == self._last_device_view_sig: + _LOG.debug( + "_refresh_device_widgets: skipped (unchanged snapshot) rows=%s", + len(ordered_for_sig), + ) + return + _LOG.debug( + "_refresh_device_widgets: view=%s arrange=%s icon_preset=%s rows=%s", + self._view_mode, + self._icon_sort_mode, + self._icon_size_preset, + len(ordered_for_sig), + ) + to_freeze = [ + self.centralWidget(), + self._splitter, + self._stack, + self._icon_page_stack, + self._grouped_icons_page, + self._icon_list, + self._table, + ] + for w in to_freeze: + if w is not None: + w.setUpdatesEnabled(False) + try: + table_rows = self._filtered_bundles() if self._view_mode == "list" else ordered_for_sig + self._fill_table(table_rows) + if self._view_mode == "icons": + self._sync_icon_page_stack_index() + if self._icon_sort_mode == "appearance": + self._clear_grouped_icons_page() + self._fill_flat_icon_list(ordered_for_sig) + else: + self._rebuild_grouped_icon_page(ordered_for_sig) + else: + self._clear_grouped_icons_page() + finally: + for w in reversed(to_freeze): + if w is not None: + w.setUpdatesEnabled(True) + self._last_device_view_sig = sig + self.statusBar().showMessage(_("{} devices").format(len(table_rows))) + if os.environ.get("NETNEIGHBOR_DEBUG_TOPLEVEL") and self._view_mode == "icons": + _debug_log_extra_top_level_widgets("_refresh_device_widgets done") + + def _bundle_for_primary_key(self, key: object) -> DeviceBundle | None: + if not isinstance(key, str) or not key: + return None + for b in self._filtered_bundles(): + if b.primary.key == key: + return b + return None + + def _on_icon_list_context_menu(self, pos: QPoint) -> None: + it = self._icon_list.itemAt(pos) + if it is None: + return + key = it.data(self._BUNDLE_KEY_ROLE) + bundle = self._bundle_for_primary_key(key) + if bundle is None: + return + gpos = self._icon_list.viewport().mapToGlobal(pos) + self._show_device_context_menu(gpos, bundle) + + def _on_table_context_menu(self, pos: QPoint) -> None: + idx = self._table.indexAt(pos) + if not idx.isValid(): + return + item = self._table.item(idx.row(), 0) + if item is None: + return + key = item.data(self._BUNDLE_KEY_ROLE) + bundle = self._bundle_for_primary_key(key) + if bundle is None: + return + gpos = self._table.viewport().mapToGlobal(pos) + self._show_device_context_menu(gpos, bundle) + + def _on_grouped_icon_context_menu(self, global_pos: QPoint, bundle: DeviceBundle) -> None: + self._show_device_context_menu(global_pos, bundle) + + def _on_tile_double_clicked(self, bundle: DeviceBundle) -> None: + uri = resolve_connect_target( + bundle_ip=bundle.ip, + primary_type=bundle.primary.type or "", + devices=bundle.devices, + ) + if uri: + launch_open_uri( + self, bundle, uri, + connect_templates=self._connect_command_templates, + global_custom_command=self._custom_command_template or "", + ) + + def _on_icon_list_double_clicked(self, item) -> None: + key = item.data(self._BUNDLE_KEY_ROLE) + bundle = self._bundle_for_primary_key(key) + if bundle is not None: + self._on_tile_double_clicked(bundle) + + def _on_table_double_clicked(self, row: int, _col: int) -> None: + item = self._table.item(row, 0) + if item is None: + return + bundle = self._bundle_for_primary_key(item.data(self._BUNDLE_KEY_ROLE)) + if bundle is not None: + self._on_tile_double_clicked(bundle) + + def _bundle_connect_targets(self, bundle: DeviceBundle) -> list[tuple[str, str]]: + return resolve_all_connect_targets( + bundle_ip=bundle.ip, + primary_type=bundle.primary.type or "", + devices=bundle.devices, + ) + + def _show_device_context_menu(self, global_pos: QPoint, bundle: DeviceBundle) -> None: + has_cmd = bool( + bundle_custom_command(bundle) + or effective_global_custom_command(bundle, self._custom_command_template or "") + ) + current_loc = bundle_location_label(bundle, no_location_label="") + loc_opts = location_options_with_current(self._location_options, current_loc) + show_device_context_menu( + self, + global_pos, + bundle, + connect_targets=self._bundle_connect_targets(bundle), + location_options=loc_opts, + type_options=self._type_options, + has_custom_command=has_cmd, + on_open_uri=lambda uri: launch_open_uri( + self, + bundle, + uri, + connect_templates=self._connect_command_templates, + global_custom_command=self._custom_command_template, + ), + on_custom_command=lambda: run_custom_command_for_bundle( + self, + bundle, + global_template=self._custom_command_template, + connect_templates=self._connect_command_templates, + ), + on_details=lambda: self._open_device_details(bundle), + on_options=lambda: self._open_device_details(bundle, initial_tab="options"), + on_monitor=lambda monitored: self._set_bundle_monitored(bundle, monitored), + on_hide=lambda: self._hide_bundle(bundle), + on_rename=lambda: self._rename_bundle(bundle), + on_location=lambda loc: self._set_bundle_location(bundle, loc), + on_type=lambda slug: self._set_bundle_type(bundle, slug), + on_clear=lambda: self._clear_bundle(bundle), + ) + + def _normalized_icon_mode(self, bundle: DeviceBundle) -> str: + raw = self._icon_source_overrides.get((bundle.ip, bundle.port), "provided") + if raw == "auto": + return "provided" + if raw in {"provided", "system", "custom"}: + return raw + return "provided" + + def _apply_bundle_icon_settings( + self, bundle: DeviceBundle, mode: str, custom_icon_id: str | None + ) -> None: + ep = (bundle.ip, bundle.port) + current = self._normalized_icon_mode(bundle) + if mode == current: + if mode != "custom": + if ep in self._custom_icon_overrides: + self._custom_icon_overrides.pop(ep, None) + self._persist_ui_prefs() + self._last_device_view_sig = None + self._refresh_device_widgets() + return + prev = self._custom_icon_overrides.get(ep) + if custom_icon_id and prev != custom_icon_id: + self._custom_icon_overrides[ep] = custom_icon_id + self._persist_ui_prefs() + self._last_device_view_sig = None + self._refresh_device_widgets() + return + self._icon_source_overrides[ep] = mode + if mode == "custom": + if custom_icon_id: + self._custom_icon_overrides[ep] = custom_icon_id + else: + self._custom_icon_overrides.pop(ep, None) + self._persist_ui_prefs() + self._last_device_view_sig = None + self._refresh_device_widgets() + + def _current_bundle_for(self, bundle: DeviceBundle) -> DeviceBundle: + """Return the freshest bundle for this host from the live snapshot. + + Row callbacks capture the bundle in a lambda at render time. After a "Clear device" the + host is rediscovered generic first, then re-enriched (SSDP descriptor / iconURL); if the + tile was not rebuilt in between, the captured bundle is stale and Details/Options would + show no XML and no device icon. Re-resolving by host here keeps them in sync. + """ + want_key = bundle.primary.key + want_ep = (str(bundle.ip).strip(), int(bundle.port or 0)) + best_by_ep: DeviceBundle | None = None + for b in self._bundles: + if b.primary.key == want_key: + return b + if (str(b.ip).strip(), int(b.port or 0)) == want_ep and best_by_ep is None: + best_by_ep = b + return best_by_ep or bundle + + def _open_device_details( + self, bundle: DeviceBundle, *, initial_tab: str | None = None + ) -> None: + bundle = self._current_bundle_for(bundle) + model = build_device_details_view_model( + bundle, no_location_label=self._no_location_label() + ) + ep = (bundle.ip, bundle.port) + mode = self._normalized_icon_mode(bundle) + custom_id = self._custom_icon_overrides.get(ep) if mode == "custom" else None + + def _pick_custom() -> str | None: + from utils.icon_packs import active_icon_pack_root + cur = self._custom_icon_overrides.get(ep) if mode == "custom" else None + return pick_device_icon_id( + self, + preferred_type=bundle.primary.type, + current_id=cur, + active_pack_root=active_icon_pack_root(), + ) + + provided_pixmap = None + provided_native_size = None + for dev in (bundle.ssdp_device, bundle.wsdd_device, bundle.wsd_device, + bundle.nmb_device, bundle.mdns_device): + if dev is None: + continue + raw_bytes = self._remote_icon_cache.bytes_for_device(dev) + if raw_bytes: + from ui.remote_icon_cache import pixmap_from_icon_bytes + pix = pixmap_from_icon_bytes(raw_bytes, 128) + if pix is not None and not pix.isNull(): + provided_native_size = (pix.width(), pix.height()) + provided_pixmap = pix + break + + icon_devices = [ + dev for dev in (bundle.ssdp_device, bundle.wsdd_device, bundle.wsd_device, + bundle.nmb_device, bundle.mdns_device) + if dev is not None + ] + icon_settings = DeviceIconSettings( + icon_mode=mode, + has_device_icon_source=bundle_has_device_icon_source(bundle), + provided_icon_display=bundle_provided_icon_display(bundle), + selected_custom_icon_id=custom_id, + on_apply=lambda m, cid: self._apply_bundle_icon_settings(bundle, m, cid), + on_pick_custom=_pick_custom, + provided_icon_pixmap=provided_pixmap, + provided_icon_native_size=provided_native_size, + icon_cache=self._remote_icon_cache, + icon_devices=icon_devices, + ) + + command_settings: DeviceCommandSettings | None = None + if self._discovery_manager is not None: + # Merge legacy custom_command into device_commands list as a "custom" override entry + initial_cmds = list(model.device_commands or []) + has_custom_override = any( + isinstance(c, dict) and c.get("scheme") == "custom" and c.get("mode") == "override" + for c in initial_cmds + ) + if not has_custom_override and model.custom_command: + initial_cmds = [ + {"scheme": "custom", "ip": model.custom_command, "port": 0, + "mode": "override", "label": ""} + ] + initial_cmds + + def _on_set_device_commands(cmds: list[dict]) -> None: + if self._discovery_manager is None: + return + for dev in bundle.devices: + self._discovery_manager.set_device_commands( + dev.source, dev.ip, dev.port, cmds + ) + # Keep legacy custom_command in sync for backward compat + custom_override = next( + (c for c in cmds + if isinstance(c, dict) + and c.get("scheme") == "custom" + and c.get("mode") == "override"), + None, + ) + legacy_tmpl = str(custom_override.get("ip", "")).strip() if custom_override else None + self._discovery_manager.set_device_custom_command( + dev.source, dev.ip, dev.port, legacy_tmpl or None + ) + self._persist_ui_prefs() + + command_settings = DeviceCommandSettings( + device_commands=initial_cmds, + on_set_device_commands=_on_set_device_commands, + ) + + field_rule_cb = None + field_rules: dict[str, list[str]] | None = None + delete_rule_cb = None + if self._discovery_manager is not None: + def _on_set_field_rule(target: str, field_path: str) -> None: + if self._discovery_manager is None: + return + for dev in bundle.devices: + self._discovery_manager.remove_device_field_mapping_rule( + dev.source, dev.ip, dev.port, target + ) + self._discovery_manager.set_device_field_mapping_rule( + dev.source, dev.ip, dev.port, target, field_path + ) + self._persist_ui_prefs() + field_rule_cb = _on_set_field_rule + + fr = self._discovery_manager.get_device_field_mapping_rules(bundle.primary) + if fr: + field_rules = fr + + def _on_delete_field_rule(target: str, field_path: str) -> None: + if self._discovery_manager is None: + return + for dev in bundle.devices: + self._discovery_manager.remove_device_field_mapping_rule( + dev.source, dev.ip, dev.port, target, field_path + ) + self._persist_ui_prefs() + delete_rule_cb = _on_delete_field_rule + + show_device_details_dialog( + self, + model, + initial_tab=initial_tab, + icon_settings=icon_settings, + command_settings=command_settings, + on_set_field_rule=field_rule_cb, + field_rules=field_rules, + on_delete_field_rule=delete_rule_cb, + ) + + def _set_bundle_monitored(self, bundle: DeviceBundle, monitored: bool) -> None: + if self._discovery_manager is None: + return + self._discovery_manager.set_bundle_monitored(bundle.ip, bundle.port, monitored) + self._persist_ui_prefs() + + def _rename_bundle(self, bundle: DeviceBundle) -> None: + if self._discovery_manager is None: + return + result = prompt_rename_device(self, bundle.name) + if result is False: + return + for device in bundle.devices: + self._discovery_manager.set_device_name_override( + device.source, device.ip, device.port, result + ) + self._persist_ui_prefs() + + def _set_bundle_location(self, bundle: DeviceBundle, location: str | None) -> None: + if self._discovery_manager is None: + return + for device in bundle.devices: + self._discovery_manager.set_device_location_override( + device.source, device.ip, device.port, location + ) + self._persist_ui_prefs() + self._sidebar_signature = None + self._rebuild_sidebar() + self._last_device_view_sig = None + self._refresh_device_widgets() + + def _set_bundle_type(self, bundle: DeviceBundle, device_type: str | None) -> None: + if self._discovery_manager is None: + return + self._discovery_manager.set_device_type_override( + bundle.primary.source, bundle.primary.ip, bundle.primary.port, device_type + ) + self._persist_ui_prefs() + self._sidebar_signature = None + self._rebuild_sidebar() + self._last_device_view_sig = None + self._refresh_device_widgets() + + def _icon_for_bundle(self, bundle: DeviceBundle) -> QIcon: + icon = self._base_icon_for_bundle(bundle) + if not bundle.online: + icon = self._dimmed_icon(icon) + return icon + + @staticmethod + def _dimmed_icon(icon: QIcon) -> QIcon: + """Render an offline device's icon faded + desaturated (greyed-out tile).""" + if icon.isNull(): + return icon + src = icon.pixmap(DEVICE_ICON_REFERENCE_PX, DEVICE_ICON_REFERENCE_PX) + if src.isNull(): + return icon + faded = QPixmap(src.size()) + faded.fill(Qt.GlobalColor.transparent) + painter = QPainter(faded) + # Global fade. + painter.setOpacity(0.3) + painter.drawPixmap(0, 0, src) + # Grey tint, applied only on the icon's own pixels (SourceAtop keeps the + # alpha shape) so the device reads clearly as "offline". + painter.setOpacity(0.55) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop) + painter.fillRect(faded.rect(), QColor(120, 120, 120)) + painter.end() + return QIcon(faded) + + def _base_icon_for_bundle(self, bundle: DeviceBundle) -> QIcon: + ep = (bundle.ip, bundle.port) + mode = self._normalized_icon_mode(bundle) + px = ICON_SIZE_PRESET_PIXELS.get( + normalize_icon_size_preset(self._icon_size_preset), + DEVICE_ICON_REFERENCE_PX, + ) + + if mode == "custom": + cid = self._custom_icon_overrides.get(ep) + if cid: + from utils.icon_packs import active_icon_pack_root + p = resolve_persisted_icon_id_to_path(cid, active_icon_pack_root()) + if p is not None: + ic = QIcon(str(p)) + if not ic.isNull(): + return ic + mode = "provided" + + if mode == "provided": + for dev in ( + bundle.ssdp_device, + bundle.wsdd_device, + bundle.wsd_device, + bundle.nmb_device, + bundle.mdns_device, + ): + if dev is None: + continue + remote = self._remote_icon_cache.icon_for_bundle_device( + bundle, dev, px + ) + if remote is not None and not remote.isNull(): + return remote + + return self._default_icon_for_bundle(bundle) + + def _default_icon_for_bundle(self, bundle: DeviceBundle) -> QIcon: + """Type icons from the 48px-based asset pack; avoid upscaling tiny device PNGs.""" + ic = qt_icon_for_device_type( + bundle.primary.type, + self.style(), + self, + icon_size_preset=self._icon_size_preset, + ) + if not ic.isNull(): + return ic + asset = resolve_asset_icon_file(bundle.primary.icon) + if asset is not None: + return QIcon(str(asset)) + return ic + + def _on_remote_icons_ready(self) -> None: + self._resync_device_icons() + + def _resync_device_icons(self) -> None: + if self._view_mode != "icons": + return + if self._icon_sort_mode == "appearance": + self._resync_flat_icon_list_pixmaps() + return + layout = self._grouped_icons_layout + for i in range(layout.count()): + item = layout.itemAt(i) + if item is None: + continue + scroll = item.widget() + if scroll is None: + continue + sections = getattr(scroll, "_icon_group_sections", None) + if not isinstance(sections, list): + continue + for section in sections: + section.resync_icons(self._icon_for_bundle) + + def _apply_list_table_sort_for_arrange_mode(self) -> None: + """List view: match View → Arrange to sorting by IP / Type / Location column (like header clicks).""" + if self._view_mode != "list": + return + hdr = self._table.horizontalHeader() + mode = self._icon_sort_mode + if mode == "appearance": + col = 1 + elif mode == "sorted": + col = 2 + elif mode == "location": + col = 3 + else: + col = 1 + self._table_sort_programmatic = True + hdr.blockSignals(True) + try: + self._table.setSortingEnabled(False) + self._table.setSortingEnabled(True) + self._table.sortByColumn(col, Qt.SortOrder.AscendingOrder) + finally: + hdr.blockSignals(False) + self._table_sort_programmatic = False + + def _on_table_sort_indicator_changed(self, logical_index: int, order: Qt.SortOrder) -> None: + if self._view_mode != "list" or self._table_sort_programmatic: + return + if logical_index == 1: + mode = "appearance" + elif logical_index == 2: + mode = "sorted" + elif logical_index == 3: + mode = "location" + else: + return + if mode == self._icon_sort_mode: + return + self._icon_sort_mode = mode + self._persist_ui_prefs() + self._sidebar_signature = None + self._rebuild_sidebar() + self._sync_menu_checks_from_state() + + def _fill_table(self, rows: list[DeviceBundle]) -> None: + saved_scroll = self._table.verticalScrollBar().value() + self._table.setSortingEnabled(False) + self._table.setRowCount(len(rows)) + for row, bundle in enumerate(rows): + d = bundle.primary + name_item = QTableWidgetItem(_safe_str(d.name)) + name_item.setData(self._BUNDLE_KEY_ROLE, d.key) + self._table.setItem(row, 0, name_item) + self._table.setItem(row, 1, QTableWidgetItem(_safe_str(d.ip))) + self._table.setItem(row, 2, QTableWidgetItem(format_device_type_for_details(d))) + loc = bundle_location_label(bundle, no_location_label=self._no_location_label()) + self._table.setItem(row, 3, QTableWidgetItem(loc)) + on_txt = _("Yes") if d.online else _("No") + on_item = QTableWidgetItem(on_txt) + on_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + self._table.setItem(row, 4, on_item) + self._table.resizeRowsToContents() + if self._view_mode == "list": + self._apply_list_table_sort_for_arrange_mode() + else: + self._table.setSortingEnabled(False) + if saved_scroll > 0: + self._table.verticalScrollBar().setValue(saved_scroll) + + def _bundle_tooltip(self, bundle: DeviceBundle) -> str: + d = bundle.primary + loc = bundle_location_label(bundle, no_location_label=self._no_location_label()) + parts = [_safe_str(d.ip), format_device_type_for_details(d)] + if loc: + parts.append(loc) + last_seen_str = _format_last_seen(d.last_seen) + if last_seen_str: + parts.append(last_seen_str) + return "\n".join(parts) + + def _run_flat_icon_list_batched(self, work: Callable[[], None]) -> None: + """Batch list mutations without disabling the widget (avoids stray Windows taskbar entries).""" + lst = self._icon_list + vp = lst.viewport() + lst.blockSignals(True) + vp.setUpdatesEnabled(False) + lst.setUpdatesEnabled(False) + try: + work() + finally: + lst.setUpdatesEnabled(True) + vp.setUpdatesEnabled(True) + lst.blockSignals(False) + + def _fill_flat_icon_list(self, rows: list[DeviceBundle]) -> None: + saved_scroll = self._icon_list.verticalScrollBar().value() + + def _fill() -> None: + self._icon_list.clear() + for bundle in rows: + it = create_icon_tile_list_item( + self._icon_for_bundle(bundle), _safe_str(bundle.primary.name) + ) + it.setData(self._BUNDLE_KEY_ROLE, bundle.primary.key) + it.setToolTip(self._bundle_tooltip(bundle)) + self._icon_list.addItem(it) + + self._run_flat_icon_list_batched(_fill) + self._relayout_flat_icon_list(force=True) + if saved_scroll > 0: + QTimer.singleShot(0, lambda: self._icon_list.verticalScrollBar().setValue(saved_scroll)) + + def _resync_flat_icon_list_pixmaps(self) -> None: + """Refresh icons after preset change without rebuilding the whole list.""" + ordered = self._current_ordered_bundles_for_view() + by_key = {b.primary.key: b for b in ordered} + + def _sync() -> None: + for i in range(self._icon_list.count()): + it = self._icon_list.item(i) + raw = it.data(self._BUNDLE_KEY_ROLE) + if not isinstance(raw, str): + continue + bundle = by_key.get(raw) + if bundle is None: + continue + it.setIcon(self._icon_for_bundle(bundle)) + set_icon_tile_item_label(it, _safe_str(bundle.primary.name)) + it.setToolTip(self._bundle_tooltip(bundle)) + + self._run_flat_icon_list_batched(_sync) + self._relayout_flat_icon_list() + + def _on_icon_section_toggled(self, group_id: str, expanded: bool) -> None: + self._icon_group_expanded[group_id] = expanded + self._persist_ui_prefs() + + def _clear_grouped_icons_page(self) -> None: + while self._grouped_icons_layout.count(): + item = self._grouped_icons_layout.takeAt(0) + w = item.widget() + if w is not None: + w.deleteLater() + + def _rebuild_grouped_icon_page(self, ordered: list[DeviceBundle]) -> None: + page = self._grouped_icons_page + was_page_visible = not page.isHidden() + + saved_scroll = 0 + if self._grouped_icons_layout.count(): + existing = self._grouped_icons_layout.itemAt(0) + if existing is not None and existing.widget() is not None: + saved_scroll = existing.widget().verticalScrollBar().value() + + new_scroll = None + page.setVisible(False) + try: + self._clear_grouped_icons_page() + + mode = self._icon_sort_mode + if mode not in {"sorted", "location"}: + return + + new_scroll = build_grouped_icon_scroll( + page, + mode=mode, + ordered_bundles=ordered, + no_location_label=self._no_location_label(), + expanded_map=self._icon_group_expanded, + icon_for_bundle=self._icon_for_bundle, + tooltip_for_bundle=self._bundle_tooltip, + icon_size=icon_size_preset_to_qsize(self._icon_size_preset), + on_section_toggled=self._on_icon_section_toggled, + on_tile_context_menu=self._on_grouped_icon_context_menu, + on_tile_double_clicked=self._on_tile_double_clicked, + ) + self._grouped_icons_layout.addWidget(new_scroll) + finally: + page.setVisible(was_page_visible) + + if new_scroll is not None: + _sections = getattr(new_scroll, "_icon_group_sections", []) + if _sections: + QTimer.singleShot(0, lambda: [s._relayout_icon_grid() for s in _sections]) + + if saved_scroll > 0 and new_scroll is not None: + QTimer.singleShot(0, lambda: new_scroll.verticalScrollBar().setValue(saved_scroll)) + + def changeEvent(self, event: QEvent) -> None: + super().changeEvent(event) + if ( + event.type() == QEvent.Type.WindowStateChange + and self.isMinimized() + and QSystemTrayIcon.isSystemTrayAvailable() + ): + event.ignore() + QTimer.singleShot(0, self._hide_to_tray) + + def _hide_to_tray(self) -> None: + """Hide window and switch to Accessory policy on macOS (no Dock icon). + Window must be hidden before changing policy — macOS rejects Accessory + while a visible window exists.""" + self.hide() + if sys.platform == "darwin": + from utils.macos_activation import set_policy_accessory + set_policy_accessory() + + def closeEvent(self, event) -> None: + from utils.ui_prefs import load_ui_preferences + prefs = load_ui_preferences() + if prefs.get("close_to_tray", True) and QSystemTrayIcon.isSystemTrayAvailable(): + event.ignore() + self._hide_to_tray() + else: + event.accept() + + def bring_to_front(self) -> None: + import sys + if sys.platform == "darwin": + from utils.macos_activation import set_policy_regular + set_policy_regular() + self.showNormal() + self.raise_() + self.activateWindow() + + +def _debug_log_extra_top_level_widgets(context: str) -> None: + """Log unexpected Qt top-level surfaces (NETNEIGHBOR_DEBUG_TOPLEVEL=1 or ``--qt-diag-toplevels``).""" + if not os.environ.get("NETNEIGHBOR_DEBUG_TOPLEVEL"): + return + app = QApplication.instance() + if app is None: + _LOG.info("TLW diag [%s]: no QApplication", context) + return + extras: list[str] = [] + for w in app.topLevelWidgets(): + if not w.isWindow(): + continue + mo = w.metaObject() + cn = mo.className() if mo is not None else type(w).__name__ + if cn == "NetNeighborMainWindow": + continue + extras.append(f"{cn}(title={w.windowTitle()!r},visible={w.isVisible()})") + + qwin_parts: list[str] = [] + try: + from PySide6.QtGui import QGuiApplication + + ga = QGuiApplication.instance() + if ga is not None: + for qw in ga.topLevelWindows(): + if qw is None: + continue + qwin_parts.append(f"{type(qw).__name__}(title={qw.title()!r},vis={qw.isVisible()})") + except Exception as e: + qwin_parts.append(f"") + + _LOG.info( + "TLW diag [%s]: QWidget_windows_extras=%s | QGuiApplication.topLevelWindows=%s", + context, + len(extras), + len(qwin_parts), + ) + if extras: + _LOG.info("TLW diag [%s] QWidget extras: %s", context, " | ".join(extras)) + if qwin_parts: + _LOG.info("TLW diag [%s] QWindows: %s", context, " | ".join(qwin_parts)) + + +def _disabled_title_action(parent: QMainWindow, text: str) -> QAction: + """Section label in menu (non-clickable).""" + a = QAction(text, parent) + a.setEnabled(False) + return a + + +def _format_last_seen(last_seen: datetime | None) -> str: + """Return a human-readable 'Last seen: X ago' string, or '' if seen very recently.""" + if last_seen is None: + return "" + try: + now = datetime.now(timezone.utc) + if last_seen.tzinfo is None: + last_seen = last_seen.replace(tzinfo=timezone.utc) + delta_s = (now - last_seen).total_seconds() + if delta_s < 120: + return "" # seen in the last 2 min → no label needed + if delta_s < 3600: + mins = int(delta_s // 60) + return _("Last seen: {n} min ago").format(n=mins) + if delta_s < 86400: + hrs = int(delta_s // 3600) + return _("Last seen: {n} h ago").format(n=hrs) + days = int(delta_s // 86400) + return _("Last seen: {n} d ago").format(n=days) + except Exception: + return "" + + +def _device_snapshot_ui_fingerprint(devices: Iterable[Device]) -> tuple: + """Stable fingerprint of fields that affect the Qt table and icon labels (not raw metadata noise).""" + rows: list[tuple] = [] + for d in sorted(devices, key=lambda x: x.key): + md = d.metadata if isinstance(d.metadata, dict) else {} + rows.append( + ( + d.key, + (d.source or "").strip().lower(), + (d.name or "").strip(), + (d.ip or "").strip(), + int(d.port or 0), + (d.type or "unknown").strip().lower(), + bool(d.online), + (md.get("user_location") or "").strip(), + ) + ) + return (len(rows), tuple(rows)) + + +def _ordered_bundles( + bundles: list[DeviceBundle], + icon_sort_mode: str, + *, + no_location_label: str, +) -> list[DeviceBundle]: + rows = list(bundles) + if icon_sort_mode == "appearance": + return rows + if icon_sort_mode == "sorted": + return sorted( + rows, + key=lambda b: (b.primary.category.lower(), b.primary.type.lower(), b.primary.name.lower()), + ) + if icon_sort_mode == "location": + return sorted( + rows, + key=lambda b: ( + bundle_location_label(b, no_location_label=no_location_label).lower(), + b.primary.category.lower(), + b.primary.name.lower(), + ), + ) + return rows + + +def _safe_str(value: object) -> str: + s = str(value) if value is not None else "" + return s.strip() or "-" diff --git a/app/ui/no_focus_item_delegate.py b/app/ui/no_focus_item_delegate.py new file mode 100644 index 00000000..ab53d83a --- /dev/null +++ b/app/ui/no_focus_item_delegate.py @@ -0,0 +1,46 @@ +# File no_focus_item_delegate.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Item delegate that skips the platform focus frame (inner border on selected cells).""" + +from __future__ import annotations + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QApplication, QListWidget, QStyledItemDelegate, QStyle, QStyleOptionViewItem + + +class NoFocusItemDelegate(QStyledItemDelegate): + """Paint like the default delegate but without ``State_HasFocus`` (no focus rectangle).""" + + def __init__(self, parent=None, *, elide_none: bool = False) -> None: + super().__init__(parent) + self._elide_none = elide_none + + def initStyleOption(self, option: QStyleOptionViewItem, index): # type: ignore[override] + super().initStyleOption(option, index) + # super() calls view->initViewItemOption() which resets textElideMode to ElideRight + # and resets features based on QListWidget.wordWrap(). Set our overrides AFTER. + w = self.parent() + if isinstance(w, QListWidget): + # WrapText must be set for Qt to respect explicit \n characters in item text. + # Without it QCommonStyle adds TextSingleLine which strips newlines, collapsing + # relayout_icon_mode_list's explicit \\n breaks into a single clipped line. + text = index.data(Qt.ItemDataRole.DisplayRole) + has_newlines = isinstance(text, str) and "\n" in text + if w.wordWrap() or has_newlines: + option.features |= QStyleOptionViewItem.ViewItemFeature.WrapText + if self._elide_none: + option.textElideMode = Qt.TextElideMode.ElideNone + + def paint(self, painter, option, index) -> None: + opt = QStyleOptionViewItem(option) + self.initStyleOption(opt, index) + opt.state &= ~QStyle.StateFlag.State_HasFocus + opt.state &= ~QStyle.StateFlag.State_Selected + # Call drawControl directly instead of super().paint() to avoid the + # second initStyleOption() call inside QStyledItemDelegate::paint that + # would re-read view state and overwrite our WrapText / ElideNone overrides. + widget = opt.widget + style = widget.style() if widget is not None else QApplication.style() + style.drawControl(QStyle.ControlElement.CE_ItemViewItem, opt, painter, widget) diff --git a/app/ui/notifications_history_dialog.py b/app/ui/notifications_history_dialog.py new file mode 100644 index 00000000..10bc6a36 --- /dev/null +++ b/app/ui/notifications_history_dialog.py @@ -0,0 +1,92 @@ +# File notifications_history_dialog.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Notifications history dialog — shows past online/offline transitions.""" + +from __future__ import annotations + +from collections.abc import Callable +from gettext import gettext as _ + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import ( + QAbstractItemView, + QDialog, + QDialogButtonBox, + QHBoxLayout, + QPushButton, + QTableWidget, + QTableWidgetItem, + QVBoxLayout, + QWidget, +) + + +class NotificationsHistoryDialog(QDialog): + def __init__( + self, + parent: QWidget | None, + log: list[tuple[str, str, str]], + on_clear: Callable[[], None], + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Notifications history")) + self.setModal(True) + self.resize(680, 420) + + self._on_clear = on_clear + + layout = QVBoxLayout(self) + layout.setContentsMargins(12, 12, 12, 12) + layout.setSpacing(8) + + self._table = QTableWidget(len(log), 3) + self._table.setHorizontalHeaderLabels( + [_("Date / Time"), _("Device"), _("Status")] + ) + self._table.horizontalHeader().setStretchLastSection(True) + self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + self._table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self._table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self._table.verticalHeader().setVisible(False) + self._table.setAlternatingRowColors(True) + + for r, (dt, name, status) in enumerate(log): + self._table.setItem(r, 0, QTableWidgetItem(dt)) + self._table.setItem(r, 1, QTableWidgetItem(name)) + status_item = QTableWidgetItem(status) + status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + self._table.setItem(r, 2, status_item) + + self._table.resizeColumnsToContents() + self._table.clearSelection() + self._table.setCurrentIndex(self._table.model().index(-1, -1)) + layout.addWidget(self._table) + + btn_bar = QHBoxLayout() + clear_btn = QPushButton(_("Clear")) + clear_btn.clicked.connect(self._do_clear) + btn_bar.addWidget(clear_btn) + btn_bar.addStretch(1) + + close_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + close_box.rejected.connect(self.reject) + close_btn = close_box.button(QDialogButtonBox.StandardButton.Close) + if close_btn: + close_btn.setText(_("Close")) + btn_bar.addWidget(close_box) + + layout.addLayout(btn_bar) + + def _do_clear(self) -> None: + self._table.setRowCount(0) + self._on_clear() + + +def show_notifications_history_dialog( + parent: QWidget | None, + log: list[tuple[str, str, str]], + on_clear: Callable[[], None], +) -> None: + NotificationsHistoryDialog(parent, log, on_clear).exec() diff --git a/app/ui/preferences_dialog.py b/app/ui/preferences_dialog.py new file mode 100644 index 00000000..f9ca99b1 --- /dev/null +++ b/app/ui/preferences_dialog.py @@ -0,0 +1,766 @@ +# File preferences_dialog.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Preferences dialog — General, Notifications, Locations, Types, Applications.""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Callable +from gettext import gettext as _ + +from PySide6.QtCore import Qt +from PySide6.QtGui import QPixmap +from PySide6.QtWidgets import ( + QAbstractItemView, + QButtonGroup, + QCheckBox, + QComboBox, + QDialog, + QDialogButtonBox, + QGridLayout, + QGroupBox, + QHBoxLayout, + QHeaderView, + QInputDialog, + QLabel, + QLineEdit, + QMessageBox, + QPushButton, + QRadioButton, + QScrollArea, + QSizePolicy, + QTabWidget, + QTreeWidget, + QTreeWidgetItem, + QListWidget, + QVBoxLayout, + QWidget, +) + +from utils.connect_launcher import default_connect_command_templates, normalize_connect_templates +from utils.location_label import normalize_location_options +from utils.session_autostart import apply_autostart_pref, autostart_enabled_on_disk +from utils.ui_prefs import load_ui_preferences, save_ui_preferences + +from ui.preset_editors import ( + _TypeEntryDialog, + _LIST_QSS, + _TREE_QSS, + _SCHEME_ROWS, + _default_location_presets, + _default_type_options, +) + + +class PreferencesDialog(QDialog): + """Modal preferences with tabs: General, Notifications, Locations, Types, Applications.""" + + _THEME_QSS = ( + "QPushButton#nnThemeL, QPushButton#nnThemeM, QPushButton#nnThemeR {" + " background: palette(button); color: palette(text);" + " border: 1px solid palette(mid); border-right: none; border-radius: 0px;" + " padding: 6px 0px; font-size: 14px;" + "}" + "QPushButton#nnThemeL {" + " border-top-left-radius: 4px; border-bottom-left-radius: 4px;" + "}" + "QPushButton#nnThemeR {" + " border-right: 1px solid palette(mid);" + " border-top-right-radius: 4px; border-bottom-right-radius: 4px;" + "}" + "QPushButton#nnThemeL:checked, QPushButton#nnThemeM:checked, QPushButton#nnThemeR:checked {" + " background: palette(highlight); color: palette(highlighted-text);" + " border-color: palette(highlight);" + "}" + "QPushButton#nnThemeL:hover:!checked, QPushButton#nnThemeM:hover:!checked," + "QPushButton#nnThemeR:hover:!checked {" + " background: palette(alternate-base);" + "}" + ) + + def __init__( + self, + parent: QWidget | None = None, + *, + on_location_presets_saved: Callable[[list[str], bool], None] | None = None, + on_type_presets_saved: Callable[[list[tuple[str, str]]], None] | None = None, + on_connect_templates_saved: Callable[[dict[str, str], str], None] | None = None, + on_clear_icon_cache: Callable[[], None] | None = None, + on_icon_pack_changed: Callable[[str], None] | None = None, + on_restart: Callable[[], None] | None = None, + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Preferences")) + self.setModal(True) + self.resize(580, 520) + self._on_location_presets_saved = on_location_presets_saved + self._on_type_presets_saved = on_type_presets_saved + self._on_connect_templates_saved = on_connect_templates_saved + self._on_clear_icon_cache = on_clear_icon_cache + self._on_icon_pack_changed = on_icon_pack_changed + self._on_restart = on_restart + self._icon_packs: list = [] + self._icon_folder_opened: bool = False + + self._prefs = load_ui_preferences() + self._original_theme = str(self._prefs.get("theme", "auto")) + + tabs = QTabWidget() + tabs.addTab(self._build_general_tab(), _("General")) + tabs.addTab(self._build_notifications_tab(), _("Notifications")) + tabs.addTab(self._build_locations_tab(), _("Locations")) + tabs.addTab(self._build_types_tab(), _("Types")) + tabs.addTab(self._build_applications_tab(), _("Applications")) + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self._accept_save) + buttons.rejected.connect(self._cancel) + + layout = QVBoxLayout(self) + layout.addWidget(tabs) + layout.addWidget(buttons) + + self._load_widgets() + + # ------------------------------------------------------------------ + # Tab builders + # ------------------------------------------------------------------ + + def _build_general_tab(self) -> QWidget: + page = QWidget() + outer = QVBoxLayout(page) + + theme_box = QGroupBox(_("Theme")) + theme_inner = QWidget() + theme_inner.setStyleSheet(self._THEME_QSS) + tl = QHBoxLayout(theme_inner) + tl.setContentsMargins(0, 0, 0, 0) + tl.setSpacing(0) + self._btn_theme_light = QPushButton("☀ " + _("Light")) + self._btn_theme_auto = QPushButton("⊙ " + _("Auto")) + self._btn_theme_dark = QPushButton("☾ " + _("Dark")) + self._btn_theme_light.setObjectName("nnThemeL") + self._btn_theme_auto.setObjectName("nnThemeM") + self._btn_theme_dark.setObjectName("nnThemeR") + self._theme_group = QButtonGroup(self) + self._theme_group.setExclusive(True) + self._theme_group.addButton(self._btn_theme_light, 0) + self._theme_group.addButton(self._btn_theme_auto, 1) + self._theme_group.addButton(self._btn_theme_dark, 2) + for btn in (self._btn_theme_light, self._btn_theme_auto, self._btn_theme_dark): + btn.setCheckable(True) + btn.setMinimumHeight(34) + btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + tl.addWidget(btn) + self._theme_group.idToggled.connect(self._on_theme_toggled) + QVBoxLayout(theme_box).addWidget(theme_inner) + + icon_pack_box = QGroupBox(_("Icon pack")) + ip_outer = QVBoxLayout(icon_pack_box) + ip_top = QHBoxLayout() + self._icon_pack_combo = QComboBox() + self._icon_pack_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self._icon_pack_combo.currentIndexChanged.connect(self._on_icon_pack_combo_changed) + btn_open_packs = QPushButton(_("Open folder…")) + btn_open_packs.setFixedWidth(110) + btn_open_packs.clicked.connect(self._on_open_icon_packs_folder) + ip_top.addWidget(self._icon_pack_combo) + ip_top.addWidget(btn_open_packs) + self._icon_pack_scroll = QScrollArea() + self._icon_pack_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn) + self._icon_pack_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self._icon_pack_scroll.setWidgetResizable(True) + self._icon_pack_scroll.setFixedHeight(72) + self._icon_pack_scroll.setStyleSheet( + "QScrollArea { border: 1px solid palette(mid); border-radius: 4px; background: palette(base); }" + ) + self._icon_pack_strip_widget = QWidget() + self._icon_pack_strip_layout = QHBoxLayout(self._icon_pack_strip_widget) + self._icon_pack_strip_layout.setContentsMargins(4, 4, 4, 4) + self._icon_pack_strip_layout.setSpacing(4) + self._icon_pack_scroll.setWidget(self._icon_pack_strip_widget) + ip_outer.addLayout(ip_top) + ip_outer.addWidget(self._icon_pack_scroll) + + session = QGroupBox(_("Session")) + sl = QVBoxLayout(session) + self._close_to_tray = QCheckBox(_("Close to system tray / panel instead of exiting")) + self._start_minimized = QCheckBox(_("Start minimized to tray")) + self._start_at_login = QCheckBox(_("Start NetNeighbor when logging in")) + sl.addWidget(self._close_to_tray) + sl.addWidget(self._start_minimized) + sl.addWidget(self._start_at_login) + + maintenance = QGroupBox(_("Maintenance")) + ml = QVBoxLayout(maintenance) + self._btn_clear_icon_cache = QPushButton(_("Reset all application data…")) + self._btn_clear_icon_cache.setMaximumWidth(240) + self._btn_clear_icon_cache.clicked.connect(self._on_clear_icon_cache_clicked) + ml.addWidget(self._btn_clear_icon_cache) + + outer.addWidget(theme_box) + outer.addWidget(icon_pack_box) + outer.addWidget(session) + outer.addWidget(maintenance) + outer.addStretch(1) + return page + + def _build_notifications_tab(self) -> QWidget: + page = QWidget() + layout = QVBoxLayout(page) + + group = QGroupBox(_("Desktop notifications")) + gl = QVBoxLayout(group) + self._notif_group = QButtonGroup(self) + self._notif_off = QRadioButton(_("Notifications off")) + self._notif_monitored = QRadioButton(_("Monitored devices only")) + self._notif_all = QRadioButton(_("All devices")) + self._notif_group.addButton(self._notif_off, 0) + self._notif_group.addButton(self._notif_monitored, 1) + self._notif_group.addButton(self._notif_all, 2) + gl.addWidget(self._notif_off) + gl.addWidget(self._notif_monitored) + gl.addWidget(self._notif_all) + + note = QLabel( + _( + "Notification delivery depends on the OS and session. " + "Tray-backed behaviour (close to tray, minimized start) will align " + "once the system tray is implemented." + ) + ) + note.setWordWrap(True) + note.setStyleSheet("color: palette(mid);") + + layout.addWidget(group) + layout.addWidget(note) + layout.addStretch(1) + return page + + def _build_locations_tab(self) -> QWidget: + page = QWidget() + layout = QVBoxLayout(page) + + intro = QLabel(_("Manage location presets shown in the right-click menu.")) + intro.setWordWrap(True) + + self._loc_auto_add = QCheckBox( + _("Automatically add locations discovered on the network to this list") + ) + + self._loc_list = QListWidget() + self._loc_list.setStyleSheet(_LIST_QSS) + + btn_add = QPushButton(_("Add")) + self._loc_btn_rename = QPushButton(_("Rename")) + self._loc_btn_remove = QPushButton(_("Remove")) + btn_clear = QPushButton(_("Clear all")) + btn_add.clicked.connect(self._loc_on_add) + self._loc_btn_rename.clicked.connect(self._loc_on_rename) + self._loc_btn_remove.clicked.connect(self._loc_on_remove) + btn_clear.clicked.connect(self._loc_on_clear) + self._loc_list.currentRowChanged.connect(self._loc_update_buttons) + + ctrl = QHBoxLayout() + ctrl.addWidget(btn_add) + ctrl.addWidget(self._loc_btn_rename) + ctrl.addWidget(self._loc_btn_remove) + ctrl.addWidget(btn_clear) + ctrl.addStretch(1) + + layout.addWidget(intro) + layout.addSpacing(4) + layout.addWidget(self._loc_auto_add) + layout.addWidget(self._loc_list, 1) + layout.addLayout(ctrl) + return page + + def _build_types_tab(self) -> QWidget: + page = QWidget() + layout = QVBoxLayout(page) + + intro = QLabel(_("Manage device type presets shown in the right-click menu.")) + intro.setWordWrap(True) + + self._typ_tree = QTreeWidget() + self._typ_tree.setColumnCount(2) + self._typ_tree.setHeaderLabels([_("Label"), _("Type ID")]) + self._typ_tree.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + self._typ_tree.header().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + self._typ_tree.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self._typ_tree.setRootIsDecorated(False) + self._typ_tree.setAllColumnsShowFocus(True) + self._typ_tree.setStyleSheet(_TREE_QSS) + self._typ_tree.currentItemChanged.connect( + lambda cur, _prev: self._typ_update_buttons(cur is not None) + ) + + btn_add = QPushButton(_("Add")) + self._typ_btn_edit = QPushButton(_("Edit")) + self._typ_btn_remove = QPushButton(_("Remove")) + btn_restore = QPushButton(_("Restore defaults")) + btn_add.clicked.connect(self._typ_on_add) + self._typ_btn_edit.clicked.connect(self._typ_on_edit) + self._typ_btn_remove.clicked.connect(self._typ_on_remove) + btn_restore.clicked.connect(self._typ_on_restore) + + ctrl = QHBoxLayout() + ctrl.addWidget(btn_add) + ctrl.addWidget(self._typ_btn_edit) + ctrl.addWidget(self._typ_btn_remove) + ctrl.addStretch(1) + ctrl.addWidget(btn_restore) + + layout.addWidget(intro) + layout.addWidget(self._typ_tree, 1) + layout.addLayout(ctrl) + return page + + def _build_applications_tab(self) -> QWidget: + page = QWidget() + layout = QVBoxLayout(page) + + intro = QLabel( + _("Command templates for opening device connections. Leave empty to use the system default.") + ) + intro.setWordWrap(True) + + defaults = default_connect_command_templates() + grid = QGridLayout() + grid.setColumnStretch(1, 1) + grid.setHorizontalSpacing(8) + grid.setVerticalSpacing(6) + + self._app_entries: dict[str, QLineEdit] = {} + for i, (scheme, title) in enumerate(_SCHEME_ROWS): + lbl = QLabel(title + ":") + lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + ent = QLineEdit() + ent.setPlaceholderText(_("Empty = system default")) + reset_btn = QPushButton(_("Reset")) + reset_btn.setFixedWidth(64) + default_val = defaults.get(scheme, "") + reset_btn.clicked.connect( + lambda _checked=False, e=ent, v=default_val: e.setText(v) + ) + grid.addWidget(lbl, i, 0) + grid.addWidget(ent, i, 1) + grid.addWidget(reset_btn, i, 2) + self._app_entries[scheme] = ent + + custom_row = len(_SCHEME_ROWS) + custom_lbl = QLabel(_("Custom:")) + custom_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + self._app_custom_edit = QLineEdit() + self._app_custom_edit.setPlaceholderText(_("Empty = disabled")) + clear_btn = QPushButton(_("Clear")) + clear_btn.setFixedWidth(64) + clear_btn.clicked.connect(lambda: self._app_custom_edit.clear()) + grid.addWidget(custom_lbl, custom_row, 0) + grid.addWidget(self._app_custom_edit, custom_row, 1) + grid.addWidget(clear_btn, custom_row, 2) + + hint = QLabel( + " ".join([ + "{url} " + _("full address"), + "{ip} " + _("device IP"), + "{port} " + _("service port"), + "{name} " + _("device name"), + "{type} " + _("device type"), + ]) + ) + hint.setTextFormat(Qt.TextFormat.RichText) + hint.setWordWrap(True) + hint.setStyleSheet("color: palette(mid); font-size: smaller;") + + layout.addWidget(intro) + layout.addSpacing(4) + layout.addLayout(grid) + layout.addWidget(hint) + layout.addStretch(1) + return page + + def _on_clear_icon_cache_clicked(self) -> None: + box = QMessageBox(self) + box.setIcon(QMessageBox.Icon.Warning) + box.setWindowTitle(_("Reset all application data?")) + box.setText( + _( + "All preferences, cached icons, discovery data and logs will be " + "permanently deleted:\n" + "• ~/.config/netneighbor\n" + "• ~/.cache/netneighbor\n\n" + "NetNeighbor will use default settings on next start.\n" + "This action cannot be undone." + ) + ) + box.setStandardButtons( + QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel + ) + box.setDefaultButton(QMessageBox.StandardButton.Cancel) + if box.exec() != QMessageBox.StandardButton.Ok: + return + if self._on_clear_icon_cache is not None: + self._on_clear_icon_cache() + self.reject() + if self._on_restart is not None: + self._on_restart() + + # ------------------------------------------------------------------ + # Load / save + # ------------------------------------------------------------------ + + def _load_widgets(self) -> None: + # Theme + theme_pref = str(self._prefs.get("theme", "auto")) + if theme_pref == "light": + self._btn_theme_light.setChecked(True) + elif theme_pref == "dark": + self._btn_theme_dark.setChecked(True) + else: + self._btn_theme_auto.setChecked(True) + + # Icon pack + from utils.icon_packs import load_available_packs, BUILTIN_PACK_ID + self._icon_packs = load_available_packs() + current_pack_id = str(self._prefs.get("icon_pack", BUILTIN_PACK_ID)) + self._icon_pack_combo.blockSignals(True) + for pack in self._icon_packs: + self._icon_pack_combo.addItem(pack.name, pack.pack_id) + select_idx = 0 + for i in range(self._icon_pack_combo.count()): + if self._icon_pack_combo.itemData(i) == current_pack_id: + select_idx = i + break + self._icon_pack_combo.setCurrentIndex(select_idx) + self._icon_pack_combo.blockSignals(False) + self._update_icon_pack_preview(self._icon_pack_combo.itemData(select_idx) or BUILTIN_PACK_ID) + + # Session + self._close_to_tray.setChecked(bool(self._prefs.get("close_to_tray", True))) + self._start_minimized.setChecked(bool(self._prefs.get("start_minimized_to_tray", False))) + self._start_at_login.setChecked( + bool(self._prefs.get("start_at_login", autostart_enabled_on_disk())) + ) + + # Notifications + mode = str(self._prefs.get("notification_mode", "off")) + if mode == "monitored": + self._notif_monitored.setChecked(True) + elif mode == "all": + self._notif_all.setChecked(True) + else: + self._notif_off.setChecked(True) + + # Locations + raw_locs = self._prefs.get("location_options") + initial_locs = normalize_location_options( + [str(v).strip() for v in raw_locs if isinstance(v, str) and str(v).strip()] + ) if isinstance(raw_locs, list) else [] + for opt in (initial_locs or _default_location_presets()): + self._loc_list.addItem(opt) + self._loc_auto_add.setChecked(bool(self._prefs.get("auto_add_discovered_locations", False))) + self._loc_list.clearSelection() + self._loc_update_buttons(-1) + + # Types + raw_types = self._prefs.get("type_options") + initial_types: list[tuple[str, str]] = [] + if isinstance(raw_types, list): + for entry in raw_types: + if isinstance(entry, dict): + lbl = entry.get("label") + slg = entry.get("slug") + if isinstance(lbl, str) and isinstance(slg, str) and slg.strip(): + initial_types.append((lbl, slg.strip().lower())) + for label, slug in (initial_types or _default_type_options()): + QTreeWidgetItem(self._typ_tree, [label, slug]) + self._typ_tree.clearSelection() + self._typ_tree.setCurrentItem(None) + self._typ_update_buttons(False) + + # Applications + templates = normalize_connect_templates(self._prefs.get("connect_command_templates")) + custom = str(self._prefs.get("custom_command_template", "") or "") + for scheme, ent in self._app_entries.items(): + ent.setText(templates.get(scheme, "")) + self._app_custom_edit.setText(custom) + + def _accept_save(self) -> None: + prefs = dict(self._prefs) + + # Theme + tid = self._theme_group.checkedId() + theme_val = "light" if tid == 0 else "dark" if tid == 2 else "auto" + prefs["theme"] = theme_val + + # Icon pack + pack_idx = self._icon_pack_combo.currentIndex() + new_pack_id = self._icon_pack_combo.itemData(pack_idx) if pack_idx >= 0 else "" + from utils.icon_packs import BUILTIN_PACK_ID + if not new_pack_id: + new_pack_id = BUILTIN_PACK_ID + old_pack_id = str(prefs.get("icon_pack", BUILTIN_PACK_ID)) + prefs["icon_pack"] = new_pack_id + + # Session + prefs["close_to_tray"] = self._close_to_tray.isChecked() + prefs["start_minimized_to_tray"] = self._start_minimized.isChecked() + prefs["start_at_login"] = self._start_at_login.isChecked() + + # Notifications + if self._notif_monitored.isChecked(): + prefs["notification_mode"] = "monitored" + elif self._notif_all.isChecked(): + prefs["notification_mode"] = "all" + else: + prefs["notification_mode"] = "off" + + # Locations + loc_options = normalize_location_options( + [self._loc_list.item(i).text() for i in range(self._loc_list.count())] + ) + auto_add = self._loc_auto_add.isChecked() + prefs["location_options"] = loc_options + prefs["auto_add_discovered_locations"] = auto_add + + # Types + type_options: list[tuple[str, str]] = [] + for i in range(self._typ_tree.topLevelItemCount()): + item = self._typ_tree.topLevelItem(i) + lbl = item.text(0).strip() + slg = item.text(1).strip().lower() + if lbl and slg: + type_options.append((lbl, slg)) + prefs["type_options"] = [{"label": lbl, "slug": slg} for lbl, slg in type_options] + + # Applications + templates = {scheme: ent.text().strip() for scheme, ent in self._app_entries.items()} + custom = self._app_custom_edit.text().strip() + prefs["connect_command_templates"] = templates + prefs["custom_command_template"] = custom + + save_ui_preferences(prefs) + apply_autostart_pref(bool(prefs.get("start_at_login"))) + self._apply_theme(theme_val) + + if self._on_location_presets_saved: + self._on_location_presets_saved(loc_options, auto_add) + if self._on_type_presets_saved: + self._on_type_presets_saved(type_options) + if self._on_connect_templates_saved: + self._on_connect_templates_saved(templates, custom) + if self._on_icon_pack_changed and new_pack_id != old_pack_id: + self._on_icon_pack_changed(new_pack_id) + + self.accept() + + # ------------------------------------------------------------------ + # Icon pack tab actions + # ------------------------------------------------------------------ + + def _on_icon_pack_combo_changed(self, index: int) -> None: + pack_id = self._icon_pack_combo.itemData(index) + if pack_id: + self._update_icon_pack_preview(pack_id) + + def _update_icon_pack_preview(self, pack_id: str) -> None: + # Clear previous strip + while self._icon_pack_strip_layout.count(): + item = self._icon_pack_strip_layout.takeAt(0) + if item.widget(): + item.widget().deleteLater() + + pack = next((p for p in self._icon_packs if p.pack_id == pack_id), None) + if pack is None: + return + + from utils.icon_packs import find_icon_in_pack, scan_pack_sizes + ICON_PX = 48 + sizes = scan_pack_sizes(pack.root) + if not sizes: + # Built-in: use ui.icons sizes + from ui.icons import bundled_freedesktop_png_side_sizes + sizes = bundled_freedesktop_png_side_sizes() + if not sizes: + return + best_sz = min(sizes, key=lambda s: (abs(s - ICON_PX), s)) + + # Collect all icon files at best_sz + icon_files: list[str] = [] + for dir_name in (f"{best_sz}x{best_sz}", str(best_sz)): + size_dir = pack.root / dir_name + if size_dir.is_dir(): + icon_files = sorted(str(p) for p in size_dir.glob("*.png")) + break + + for icon_path in icon_files: + pix = QPixmap(icon_path) + if pix.isNull(): + continue + pix = pix.scaled( + ICON_PX, ICON_PX, + Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + lbl = QLabel() + lbl.setPixmap(pix) + lbl.setFixedSize(ICON_PX + 2, ICON_PX + 2) + lbl.setAlignment(Qt.AlignmentFlag.AlignCenter) + self._icon_pack_strip_layout.addWidget(lbl) + self._icon_pack_strip_layout.addStretch(1) + + def _on_open_icon_packs_folder(self) -> None: + from utils.icon_packs import user_icon_packs_dir + import subprocess + folder = user_icon_packs_dir() + try: + folder.mkdir(parents=True, exist_ok=True) + if sys.platform == "win32": + os.startfile(str(folder)) # noqa: S606 + elif sys.platform == "darwin": + subprocess.Popen(["open", str(folder)]) + else: + subprocess.Popen(["xdg-open", str(folder)]) + except OSError: + from PySide6.QtCore import QUrl + from PySide6.QtGui import QDesktopServices + QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder))) + self._icon_folder_opened = True + + def changeEvent(self, event: object) -> None: + from PySide6.QtCore import QEvent + super().changeEvent(event) # type: ignore[arg-type] + if ( + isinstance(event, QEvent) + and event.type() == QEvent.Type.ActivationChange + and self.isActiveWindow() + and self._icon_folder_opened + ): + self._icon_folder_opened = False + self._refresh_icon_pack_list() + + def _refresh_icon_pack_list(self) -> None: + from utils.icon_packs import load_available_packs, BUILTIN_PACK_ID + current_id = self._icon_pack_combo.currentData() or BUILTIN_PACK_ID + self._icon_packs = load_available_packs() + self._icon_pack_combo.blockSignals(True) + self._icon_pack_combo.clear() + for pack in self._icon_packs: + self._icon_pack_combo.addItem(pack.name, pack.pack_id) + select_idx = 0 + for i in range(self._icon_pack_combo.count()): + if self._icon_pack_combo.itemData(i) == current_id: + select_idx = i + break + self._icon_pack_combo.setCurrentIndex(select_idx) + self._icon_pack_combo.blockSignals(False) + self._update_icon_pack_preview(self._icon_pack_combo.itemData(select_idx) or BUILTIN_PACK_ID) + + def _on_theme_toggled(self, button_id: int, checked: bool) -> None: + if not checked: + return + theme = "light" if button_id == 0 else "dark" if button_id == 2 else "auto" + self._apply_theme(theme) + + def _cancel(self) -> None: + self._apply_theme(self._original_theme) + self.reject() + + def _apply_theme(self, theme: str) -> None: + from PySide6.QtWidgets import QApplication + from ui.app_theme import apply_color_scheme + app = QApplication.instance() + if app is None: + return + if theme == "light": + apply_color_scheme(app, Qt.ColorScheme.Light) + elif theme == "dark": + apply_color_scheme(app, Qt.ColorScheme.Dark) + else: + apply_color_scheme(app, None) + + # ------------------------------------------------------------------ + # Locations tab actions + # ------------------------------------------------------------------ + + def _loc_update_buttons(self, row: int) -> None: + has = row >= 0 + self._loc_btn_rename.setEnabled(has) + self._loc_btn_remove.setEnabled(has) + + def _loc_on_add(self) -> None: + text, ok = QInputDialog.getText(self, _("Add location preset"), _("Location name:")) + text = text.strip() + existing = [self._loc_list.item(i).text() for i in range(self._loc_list.count())] + if not ok or not text or text in existing: + return + self._loc_list.addItem(text) + + def _loc_on_rename(self) -> None: + item = self._loc_list.currentItem() + if item is None: + return + old = item.text() + text, ok = QInputDialog.getText(self, _("Rename location preset"), _("New name:"), text=old) + text = text.strip() + existing = [self._loc_list.item(i).text() for i in range(self._loc_list.count())] + if not ok or not text or text == old or text in existing: + return + item.setText(text) + + def _loc_on_remove(self) -> None: + row = self._loc_list.currentRow() + if row >= 0: + self._loc_list.takeItem(row) + self._loc_update_buttons(self._loc_list.currentRow()) + + def _loc_on_clear(self) -> None: + self._loc_list.clear() + self._loc_update_buttons(-1) + + # ------------------------------------------------------------------ + # Types tab actions + # ------------------------------------------------------------------ + + def _typ_update_buttons(self, has: bool) -> None: + self._typ_btn_edit.setEnabled(has) + self._typ_btn_remove.setEnabled(has) + + def _typ_on_add(self) -> None: + dlg = _TypeEntryDialog(self, title=_("Add type preset")) + if dlg.exec() != QDialog.DialogCode.Accepted: + return + label, slug = dlg.result_entry() + if label and slug: + QTreeWidgetItem(self._typ_tree, [label, slug]) + + def _typ_on_edit(self) -> None: + item = self._typ_tree.currentItem() + if item is None: + return + dlg = _TypeEntryDialog(self, title=_("Edit type preset"), label=item.text(0), slug=item.text(1)) + if dlg.exec() != QDialog.DialogCode.Accepted: + return + label, slug = dlg.result_entry() + if label and slug: + item.setText(0, label) + item.setText(1, slug) + + def _typ_on_remove(self) -> None: + item = self._typ_tree.currentItem() + if item is not None: + self._typ_tree.takeTopLevelItem(self._typ_tree.indexOfTopLevelItem(item)) + + def _typ_on_restore(self) -> None: + self._typ_tree.clear() + for label, slug in _default_type_options(): + QTreeWidgetItem(self._typ_tree, [label, slug]) + self._typ_tree.clearSelection() + self._typ_tree.setCurrentItem(None) + self._typ_update_buttons(False) diff --git a/app/ui/preset_editors.py b/app/ui/preset_editors.py new file mode 100644 index 00000000..ece99809 --- /dev/null +++ b/app/ui/preset_editors.py @@ -0,0 +1,459 @@ +# File preset_editors.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Modal editors for Location presets, Type presets, and External applications.""" + +from __future__ import annotations + +from gettext import gettext as _ + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import ( + QAbstractItemView, + QCheckBox, + QDialog, + QDialogButtonBox, + QGridLayout, + QHBoxLayout, + QHeaderView, + QInputDialog, + QLabel, + QLineEdit, + QListWidget, + QPushButton, + QTreeWidget, + QTreeWidgetItem, + QVBoxLayout, +) + +_LIST_QSS = ( + "QListWidget { background-color: palette(base); outline: none; }" + "QListWidget::item { padding: 4px 6px; border: 1px solid transparent; }" + "QListWidget::item:hover { background-color: palette(alternate-base); }" + "QListWidget::item:selected," + "QListWidget::item:selected:active," + "QListWidget::item:selected:!active { background-color: palette(highlight); color: palette(highlighted-text); }" + "QListWidget::item:selected:hover { background-color: palette(highlight); color: palette(highlighted-text); }" +) + +_TREE_QSS = ( + "QTreeWidget { background-color: palette(base); outline: none; show-decoration-selected: 1; }" + "QTreeWidget::item { padding: 4px 6px; }" + "QTreeWidget::item:hover { background-color: palette(alternate-base); }" + "QTreeWidget::item:selected," + "QTreeWidget::item:selected:active," + "QTreeWidget::item:selected:!active { background-color: palette(highlight); color: palette(highlighted-text); }" + "QTreeWidget::item:selected:hover { background-color: palette(highlight); color: palette(highlighted-text); }" +) + +from utils.connect_launcher import default_connect_command_templates +from utils.location_label import normalize_location_options + +_SCHEME_ROWS: list[tuple[str, str]] = [ + ("http", "HTTP"), + ("https", "HTTPS"), + ("smb", "SMB"), + ("ftp", "FTP"), + ("ssh", "SSH"), + ("telnet", "Telnet"), + ("sftp", "SFTP"), + ("spotify", "Spotify"), +] + + +def _default_location_presets() -> list[str]: + return normalize_location_options([ + _("Office"), _("Room"), _("Living room"), + _("Kitchen"), _("Workshop"), _("Garage"), + ]) + + +def _default_type_options() -> list[tuple[str, str]]: + return [ + (_("NAS"), "nas"), + (_("Server"), "server"), + (_("Rack server"), "rackserver"), + (_("Computer"), "computer"), + (_("Desktop computer"), "desktop"), + (_("Mini PC"), "minipc"), + (_("All-in-one computer"), "allinone"), + (_("Laptop"), "laptop"), + (_("Smartphone"), "smartphone"), + (_("Router"), "router"), + (_("Media server"), "mediaserver"), + (_("Printer"), "printer"), + (_("Multifunction printer"), "multifunction_printer"), + (_("Printer (network / IPP)"), "networkprinter"), + (_("SmartSpeaker"), "smartspeaker"), + (_("SmartTV"), "smarttv"), + (_("SmartDevice"), "smartdevice"), + (_("Camera"), "camera"), + (_("HomeAppliance"), "homeappliance"), + (_("CNC"), "cnc"), + (_("3D printer"), "3dprinter"), + ] + + +# --------------------------------------------------------------------------- +# Location presets +# --------------------------------------------------------------------------- + +class LocationPresetsDialog(QDialog): + """List editor for room / location preset strings.""" + + def __init__( + self, + parent, + *, + initial_options: list[str], + auto_add: bool, + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("Location presets")) + self.resize(440, 400) + + intro = QLabel(_("Manage location presets shown in the right-click menu.")) + intro.setWordWrap(True) + + self._auto_add_chk = QCheckBox( + _("Automatically add locations discovered on the network to this list") + ) + self._auto_add_chk.setChecked(auto_add) + + self._list = QListWidget() + self._list.setStyleSheet(_LIST_QSS) + for opt in (initial_options or _default_location_presets()): + self._list.addItem(opt) + self._list.clearSelection() + + btn_add = QPushButton(_("Add")) + self._btn_rename = QPushButton(_("Rename")) + self._btn_remove = QPushButton(_("Remove")) + btn_clear = QPushButton(_("Clear all")) + btn_add.clicked.connect(self._on_add) + self._btn_rename.clicked.connect(self._on_rename) + self._btn_remove.clicked.connect(self._on_remove) + btn_clear.clicked.connect(self._on_clear) + + self._list.currentRowChanged.connect(self._update_buttons) + self._update_buttons(-1) + + ctrl = QHBoxLayout() + ctrl.addWidget(btn_add) + ctrl.addWidget(self._btn_rename) + ctrl.addWidget(self._btn_remove) + ctrl.addWidget(btn_clear) + ctrl.addStretch(1) + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + + layout = QVBoxLayout(self) + layout.addWidget(intro) + layout.addSpacing(4) + layout.addWidget(self._auto_add_chk) + layout.addWidget(self._list, 1) + layout.addLayout(ctrl) + layout.addWidget(buttons) + + # ------------------------------------------------------------------ + + def _update_buttons(self, row: int) -> None: + has = row >= 0 + self._btn_rename.setEnabled(has) + self._btn_remove.setEnabled(has) + + def _on_add(self) -> None: + text, ok = QInputDialog.getText(self, _("Add location preset"), _("Location name:")) + text = text.strip() + if not ok or not text or text in self._existing_values(): + return + self._list.addItem(text) + + def _on_rename(self) -> None: + item = self._list.currentItem() + if item is None: + return + old = item.text() + text, ok = QInputDialog.getText( + self, _("Rename location preset"), _("New name:"), text=old + ) + text = text.strip() + if not ok or not text or text == old or text in self._existing_values(): + return + item.setText(text) + + def _on_remove(self) -> None: + row = self._list.currentRow() + if row >= 0: + self._list.takeItem(row) + self._update_buttons(self._list.currentRow()) + + def _on_clear(self) -> None: + self._list.clear() + self._update_buttons(-1) + + def _existing_values(self) -> list[str]: + return [self._list.item(i).text() for i in range(self._list.count())] + + # ------------------------------------------------------------------ + + def result_options(self) -> list[str]: + return normalize_location_options(self._existing_values()) + + def result_auto_add(self) -> bool: + return self._auto_add_chk.isChecked() + + +# --------------------------------------------------------------------------- +# Type presets +# --------------------------------------------------------------------------- + +class _TypeEntryDialog(QDialog): + """Small form to enter / edit a (label, slug) pair.""" + + def __init__(self, parent, *, title: str, label: str = "", slug: str = "") -> None: + super().__init__(parent) + self.setWindowTitle(title) + self.setFixedWidth(340) + + self._label_edit = QLineEdit(label) + self._slug_edit = QLineEdit(slug) + + grid = QGridLayout() + grid.setColumnStretch(1, 1) + grid.addWidget(QLabel(_("Label:")), 0, 0) + grid.addWidget(self._label_edit, 0, 1) + grid.addWidget(QLabel(_("Type ID:")), 1, 0) + grid.addWidget(self._slug_edit, 1, 1) + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + + layout = QVBoxLayout(self) + layout.addLayout(grid) + layout.addWidget(buttons) + + def result_entry(self) -> tuple[str, str]: + return self._label_edit.text().strip(), self._slug_edit.text().strip().lower() + + +class TypePresetsDialog(QDialog): + """Two-column editor for device type presets (label + slug).""" + + def __init__(self, parent, *, initial_options: list[tuple[str, str]]) -> None: + super().__init__(parent) + self.setWindowTitle(_("Type presets")) + self.resize(480, 420) + + intro = QLabel(_("Manage device type presets shown in the right-click menu.")) + intro.setWordWrap(True) + + self._tree = QTreeWidget() + self._tree.setColumnCount(2) + self._tree.setHeaderLabels([_("Label"), _("Type ID")]) + self._tree.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + self._tree.header().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + self._tree.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self._tree.setRootIsDecorated(False) + self._tree.setAllColumnsShowFocus(True) + self._tree.setStyleSheet(_TREE_QSS) + + for label, slug in (initial_options or _default_type_options()): + self._append_row(label, slug) + self._tree.clearSelection() + self._tree.setCurrentItem(None) + + btn_add = QPushButton(_("Add")) + self._btn_edit = QPushButton(_("Edit")) + self._btn_remove = QPushButton(_("Remove")) + btn_restore = QPushButton(_("Restore defaults")) + btn_add.clicked.connect(self._on_add) + self._btn_edit.clicked.connect(self._on_edit) + self._btn_remove.clicked.connect(self._on_remove) + btn_restore.clicked.connect(self._on_restore) + + self._tree.currentItemChanged.connect( + lambda cur, _prev: self._update_buttons(cur is not None) + ) + self._update_buttons(False) + + ctrl = QHBoxLayout() + ctrl.addWidget(btn_add) + ctrl.addWidget(self._btn_edit) + ctrl.addWidget(self._btn_remove) + ctrl.addStretch(1) + ctrl.addWidget(btn_restore) + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + + layout = QVBoxLayout(self) + layout.addWidget(intro) + layout.addWidget(self._tree, 1) + layout.addLayout(ctrl) + layout.addWidget(buttons) + + # ------------------------------------------------------------------ + + def _update_buttons(self, has: bool) -> None: + self._btn_edit.setEnabled(has) + self._btn_remove.setEnabled(has) + + def _append_row(self, label: str, slug: str) -> None: + QTreeWidgetItem(self._tree, [label, slug]) + + def _on_add(self) -> None: + dlg = _TypeEntryDialog(self, title=_("Add type preset")) + if dlg.exec() != QDialog.DialogCode.Accepted: + return + label, slug = dlg.result_entry() + if label and slug: + self._append_row(label, slug) + + def _on_edit(self) -> None: + item = self._tree.currentItem() + if item is None: + return + dlg = _TypeEntryDialog( + self, + title=_("Edit type preset"), + label=item.text(0), + slug=item.text(1), + ) + if dlg.exec() != QDialog.DialogCode.Accepted: + return + label, slug = dlg.result_entry() + if label and slug: + item.setText(0, label) + item.setText(1, slug) + + def _on_remove(self) -> None: + item = self._tree.currentItem() + if item is not None: + idx = self._tree.indexOfTopLevelItem(item) + self._tree.takeTopLevelItem(idx) + + def _on_restore(self) -> None: + self._tree.clear() + for label, slug in _default_type_options(): + self._append_row(label, slug) + self._tree.clearSelection() + self._tree.setCurrentItem(None) + self._update_buttons(False) + + # ------------------------------------------------------------------ + + def result_options(self) -> list[tuple[str, str]]: + out: list[tuple[str, str]] = [] + for i in range(self._tree.topLevelItemCount()): + item = self._tree.topLevelItem(i) + label = item.text(0).strip() + slug = item.text(1).strip().lower() + if label and slug: + out.append((label, slug)) + return out + + +# --------------------------------------------------------------------------- +# External applications +# --------------------------------------------------------------------------- + +class ExternalApplicationsDialog(QDialog): + """Per-scheme command template editor + global custom command.""" + + def __init__( + self, + parent, + *, + initial_templates: dict[str, str], + initial_custom: str, + ) -> None: + super().__init__(parent) + self.setWindowTitle(_("External applications")) + self.resize(620, 360) + + intro = QLabel( + _("Command templates for opening device connections. Leave empty to use the system default.") + ) + intro.setWordWrap(True) + + defaults = default_connect_command_templates() + grid = QGridLayout() + grid.setColumnStretch(1, 1) + grid.setHorizontalSpacing(8) + grid.setVerticalSpacing(6) + + self._entries: dict[str, QLineEdit] = {} + for i, (scheme, title) in enumerate(_SCHEME_ROWS): + lbl = QLabel(title + ":") + lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + ent = QLineEdit(initial_templates.get(scheme, "")) + ent.setPlaceholderText(_("Empty = system default")) + reset_btn = QPushButton(_("Reset")) + reset_btn.setFixedWidth(64) + default_val = defaults.get(scheme, "") + reset_btn.clicked.connect( + lambda _checked=False, e=ent, v=default_val: e.setText(v) + ) + grid.addWidget(lbl, i, 0) + grid.addWidget(ent, i, 1) + grid.addWidget(reset_btn, i, 2) + self._entries[scheme] = ent + + custom_row = len(_SCHEME_ROWS) + custom_lbl = QLabel(_("Custom:")) + custom_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + self._custom_edit = QLineEdit(initial_custom) + self._custom_edit.setPlaceholderText(_("Empty = disabled")) + clear_btn = QPushButton(_("Clear")) + clear_btn.setFixedWidth(64) + clear_btn.clicked.connect(lambda: self._custom_edit.clear()) + grid.addWidget(custom_lbl, custom_row, 0) + grid.addWidget(self._custom_edit, custom_row, 1) + grid.addWidget(clear_btn, custom_row, 2) + + hint = QLabel( + " ".join([ + "{url} " + _("full address"), + "{ip} " + _("device IP"), + "{port} " + _("service port"), + "{name} " + _("device name"), + "{type} " + _("device type"), + ]) + ) + hint.setTextFormat(Qt.TextFormat.RichText) + hint.setWordWrap(True) + hint.setStyleSheet("color: palette(mid); font-size: smaller;") + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel + ) + buttons.accepted.connect(self.accept) + buttons.rejected.connect(self.reject) + + layout = QVBoxLayout(self) + layout.addWidget(intro) + layout.addSpacing(4) + layout.addLayout(grid) + layout.addWidget(hint) + layout.addStretch(1) + layout.addWidget(buttons) + + # ------------------------------------------------------------------ + + def result_templates(self) -> dict[str, str]: + return {scheme: ent.text().strip() for scheme, ent in self._entries.items()} + + def result_custom(self) -> str: + return self._custom_edit.text().strip() diff --git a/app/ui/remote_icon_cache.py b/app/ui/remote_icon_cache.py new file mode 100644 index 00000000..ae89e1c4 --- /dev/null +++ b/app/ui/remote_icon_cache.py @@ -0,0 +1,394 @@ +# File remote_icon_cache.py for NetNeighbor version 2.0.1 +# Internal version : 2.0.1 date: 2026-05-26 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""In-memory Qt pixmaps for device-provided icons (HTTP fetch + GTK-compatible disk cache).""" + +from __future__ import annotations + +import logging +import threading +from collections.abc import Callable +from urllib.parse import urlparse + +from PySide6.QtCore import QObject, Qt, Signal +from PySide6.QtGui import QIcon, QImage, QPainter, QPixmap + +from model.device import Device +from utils.device_bundles import DeviceBundle +from utils.device_remote_icon import ( + iter_remote_icon_disk_keys, + load_remote_icon_payload_for_device, + persist_remote_icon_index_entry, + primary_fetch_pair_for_device, + save_remote_icon_payload, + urlopen_remote_icon, +) +from utils.icon_view_prefs import DEVICE_ICON_REFERENCE_PX + +_LOG = logging.getLogger("ui.remote_icon") + + +def _is_svg_payload(data: bytes) -> bool: + sample = data[:1024].lstrip().lower() + if not sample: + return False + if sample.startswith(b" QPixmap | None: + """Crop empty alpha margins (GTK ``_trim_transparent_borders`` parity).""" + image = pix.toImage().convertToFormat(QImage.Format.Format_ARGB32) + if image.isNull(): + return None + width = image.width() + height = image.height() + if width <= 0 or height <= 0: + return None + min_x = width + min_y = height + max_x = -1 + max_y = -1 + for y in range(height): + for x in range(width): + if (image.pixel(x, y) >> 24) & 0xFF > 8: + if x < min_x: + min_x = x + if y < min_y: + min_y = y + if x > max_x: + max_x = x + if y > max_y: + max_y = y + if max_x < min_x or max_y < min_y: + return None + crop_w = (max_x - min_x) + 1 + crop_h = (max_y - min_y) + 1 + if crop_w == width and crop_h == height: + return None + cropped = image.copy(min_x, min_y, crop_w, crop_h) + if cropped.isNull(): + return None + out = QPixmap.fromImage(cropped) + return out if not out.isNull() else None + + +def _normalize_device_pixmap(pix: QPixmap, size: int) -> QPixmap | None: + """Scale visible artwork so the tile's longest side matches ``size`` (height-fit heuristic). + + Device UPnP icons are often 48×48; grid presets may be ``large`` (96px) or ``xlarge``. + We still upscale smoothly so the device artwork appears instead of falling back to the + bundled type icon. + """ + if size <= 0: + return pix + source = pix + width = max(1, source.width()) + height = max(1, source.height()) + if (width > size and height < size) or (height > size and width < size): + return source + ratio = size / height + target_w = max(1, int(width * ratio)) + target_h = max(1, int(height * ratio)) + scaled = source.scaled( + target_w, + target_h, + Qt.AspectRatioMode.IgnoreAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + return scaled if not scaled.isNull() else source + + +def _render_svg_pixmap(data: bytes, target_size: int) -> QPixmap | None: + try: + from PySide6.QtSvg import QSvgRenderer + except ImportError: + return None + renderer = QSvgRenderer(data) + if not renderer.isValid(): + return None + side = target_size if target_size > 0 else DEVICE_ICON_REFERENCE_PX + pix = QPixmap(side, side) + pix.fill(Qt.GlobalColor.transparent) + painter = QPainter(pix) + renderer.render(painter) + painter.end() + if pix.isNull(): + return None + return pix + + +def pixmap_from_icon_bytes(data: bytes, target_size: int, *, min_native_size: int = 0) -> QPixmap | None: + """SVG at target size; raster trimmed and height-normalized like GTK. + + For raster images, pass ``min_native_size`` to reject images whose native + resolution is below the threshold (avoids blurry upscaling). + """ + if not data: + return None + if target_size <= 0: + target_size = DEVICE_ICON_REFERENCE_PX + if _is_svg_payload(data): + return _render_svg_pixmap(data, target_size) + + image = QImage.fromData(data) + if image.isNull(): + return None + pix = QPixmap.fromImage(image) + if pix.isNull(): + return None + if min_native_size > 0 and max(pix.width(), pix.height()) < min_native_size: + return None + normalized = _normalize_device_pixmap(pix, target_size) + return normalized + + +def qicon_from_icon_bytes(data: bytes, target_size: int, *, min_native_size: int = 0) -> QIcon | None: + """Build a multi-size ``QIcon`` for the given target size. + + Pass ``min_native_size`` to reject raster icons whose native resolution is + below the threshold (avoids blurry upscaling); SVGs are always accepted. + """ + if target_size <= 0: + target_size = DEVICE_ICON_REFERENCE_PX + + pix = pixmap_from_icon_bytes(data, target_size, min_native_size=min_native_size) + if pix is None or pix.isNull(): + return None + + icon = QIcon() + icon.addPixmap(pix) + if target_size != DEVICE_ICON_REFERENCE_PX: + ref_pix = pixmap_from_icon_bytes(data, DEVICE_ICON_REFERENCE_PX) + if ref_pix is not None and not ref_pix.isNull(): + icon.addPixmap(ref_pix) + return icon + + +class QtRemoteIconCache(QObject): + """Load SSDP/mDNS device icons from disk cache or background HTTP.""" + + icons_ready = Signal() + _fetch_result = Signal(object) # dict: cache_key, payload, sip, disk_keys + + def __init__(self, parent: QObject | None = None) -> None: + super().__init__(parent) + # Keyed by canonical icon URL only — never by IP: DHCP reuses addresses, and an + # IP-keyed map handed a previous occupant's icon to the host now holding that IP. + self._bytes_by_key: dict[str, bytes] = {} + self._fetching: set[str] = set() + self._failed: set[str] = set() + self._fetch_result.connect(self._handle_fetch_result) + + def clear(self) -> None: + self._bytes_by_key.clear() + self._failed.clear() + + def evict_for_ip(self, ip: str) -> None: + """Drop ALL in-memory icon state for a device IP so a rebuild re-fetches cleanly. + + Must mirror the disk purge (purge_remote_icon_for_ip): drop every URL→bytes entry and + failure mark whose URL host is this IP, so ``fetch_status_for_device`` does not keep + returning "ready" and the icon is re-fetched after a "Clear device". + """ + sip = str(ip).strip() + if not sip: + return + + def _host_matches(url_key: str) -> bool: + try: + return (urlparse(url_key).hostname or "").strip() == sip + except ValueError: + return False + + for key in [k for k in self._bytes_by_key if _host_matches(k)]: + self._bytes_by_key.pop(key, None) + for key in [k for k in self._failed if _host_matches(k)]: + self._failed.discard(key) + + def prefetch_from_index(self) -> None: + """Pre-warm in-memory cache from the on-disk icon index. + + Called once at startup so the first render finds all previously-fetched + icons in memory, avoiding per-device disk reads during tile painting. + """ + from utils.device_remote_icon import _load_index, _REMOTE_ICON_DISK_DIR + loaded = 0 + for _sip, row in _load_index().items(): + canon = row.get("canonical_url", "") + if not canon or canon in self._bytes_by_key: + continue + sha = row.get("payload_sha256", "") + if not isinstance(sha, str) or len(sha) != 64: + continue + path = _REMOTE_ICON_DISK_DIR / f"{sha}.payload" + try: + data = path.read_bytes() + except OSError: + continue + if data: + self._bytes_by_key[canon] = data + loaded += 1 + _LOG.debug("prefetch_from_index: %d icon(s) pre-loaded", loaded) + + def fetch_status_for_device(self, device: Device) -> str: + """Return 'ready', 'fetching', 'failed', or 'missing'.""" + for key in iter_remote_icon_disk_keys(device): + if key in self._bytes_by_key: + return "ready" + if load_remote_icon_payload_for_device(device): + return "ready" + pair = primary_fetch_pair_for_device(device) + if pair is None: + return "missing" + _, cache_key = pair + if cache_key in self._fetching: + return "fetching" + if cache_key in self._failed: + return "failed" + return "missing" + + def trigger_fetch_for_device(self, device: Device) -> None: + """Start (or retry after failure) a background fetch for this device's icon.""" + pair = primary_fetch_pair_for_device(device) + if pair is None: + _LOG.warning("trigger_fetch: no URL for device ip=%s source=%s", device.ip, device.source) + return + fetch_url, cache_key = pair + if cache_key in self._fetching: + _LOG.warning("trigger_fetch: already fetching key=%s url=%s", cache_key, fetch_url) + return + _LOG.warning("trigger_fetch: starting fetch url=%s key=%s", fetch_url, cache_key) + self._failed.discard(cache_key) + self._start_fetch(fetch_url, cache_key, device, None) + + def icon_for_bundle_device( + self, + bundle: DeviceBundle, + device: Device, + size: int, + *, + on_fetch_started: Callable[[], None] | None = None, + ) -> QIcon | None: + data = self._load_bytes(device, on_fetch_started=on_fetch_started) + if not data: + return None + display = size if size > 0 else DEVICE_ICON_REFERENCE_PX + min_size = (display * 3) // 4 + return qicon_from_icon_bytes(data, display, min_native_size=min_size) + + def bytes_for_device(self, device: Device) -> bytes | None: + """Return cached icon bytes (memory or disk) without triggering a network fetch.""" + for key in iter_remote_icon_disk_keys(device): + cached = self._bytes_by_key.get(key) + if cached: + return cached + return load_remote_icon_payload_for_device(device) + + def prefetch_bundle(self, bundle: DeviceBundle, size: int) -> None: + for dev in ( + bundle.ssdp_device, + bundle.wsdd_device, + bundle.wsd_device, + bundle.nmb_device, + bundle.mdns_device, + ): + if dev is None: + continue + if primary_fetch_pair_for_device(dev) is None: + continue + self._load_bytes(dev) + + def _load_bytes( + self, + device: Device, + *, + on_fetch_started: Callable[[], None] | None = None, + ) -> bytes | None: + for key in iter_remote_icon_disk_keys(device): + cached = self._bytes_by_key.get(key) + if cached: + return cached + + data = load_remote_icon_payload_for_device(device) + if data: + self._register_bytes(device, data, iter_remote_icon_disk_keys(device)) + return data + + pair = primary_fetch_pair_for_device(device) + if pair is None: + return None + fetch_url, cache_key = pair + if cache_key in self._fetching: + return None + if cache_key in self._failed: + return None + self._start_fetch(fetch_url, cache_key, device, on_fetch_started) + return None + + def _register_bytes( + self, device: Device, data: bytes, disk_keys: list[str] + ) -> None: + for key in disk_keys: + self._bytes_by_key[key] = data + pair = primary_fetch_pair_for_device(device) + if pair: + self._bytes_by_key.setdefault(pair[1], data) + + def _start_fetch( + self, + fetch_url: str, + cache_key: str, + device: Device, + on_fetch_started: Callable[[], None] | None, + ) -> None: + if cache_key in self._fetching: + return + self._fetching.add(cache_key) + if on_fetch_started is not None: + on_fetch_started() + sip = str(device.ip).strip() + disk_keys = list(iter_remote_icon_disk_keys(device)) + + def _worker() -> None: + payload: bytes | None = None + _LOG.warning("icon fetch thread started url=%s", fetch_url) + try: + with urlopen_remote_icon(fetch_url) as response: + payload = response.read() + if payload: + _LOG.warning("icon fetch OK url=%s bytes=%d", fetch_url, len(payload)) + save_remote_icon_payload(cache_key, payload) + else: + _LOG.warning("icon fetch returned empty payload url=%s", fetch_url) + except Exception as exc: + _LOG.warning("icon fetch FAILED url=%s: %s", fetch_url, exc) + + _LOG.warning("icon fetch emitting _fetch_result for key=%s success=%s", cache_key, bool(payload)) + self._fetch_result.emit({ + "cache_key": cache_key, + "payload": payload or b"", + "sip": sip, + "disk_keys": disk_keys, + }) + + threading.Thread(target=_worker, daemon=True).start() + + def _handle_fetch_result(self, result: dict) -> None: + cache_key = result["cache_key"] + payload = result["payload"] + sip = result["sip"] + disk_keys = result["disk_keys"] + self._fetching.discard(cache_key) + if payload: + for key in disk_keys: + self._bytes_by_key[key] = payload + self._bytes_by_key.setdefault(cache_key, payload) + if sip: + persist_remote_icon_index_entry(sip, cache_key) + else: + self._failed.add(cache_key) + _LOG.warning("icon _handle_fetch_result: success=%s key=%s", bool(payload), cache_key) + self.icons_ready.emit() diff --git a/app/ui/scheduler.py b/app/ui/scheduler.py new file mode 100644 index 00000000..741bfb77 --- /dev/null +++ b/app/ui/scheduler.py @@ -0,0 +1,24 @@ +# File scheduler.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Marshal callables from discovery threads onto the GUI main thread (PySide6).""" + +from __future__ import annotations + +from PySide6.QtCore import QObject, Signal, Slot + + +class MainThreadScheduler(QObject): + """Queue plain callables to run on the thread that owns this QObject (typically the GUI thread).""" + + invoke = Signal(object) + + def __init__(self, parent: QObject | None = None) -> None: + super().__init__(parent) + self.invoke.connect(self._dispatch) + + @Slot(object) + def _dispatch(self, fn: object) -> None: + if callable(fn): + fn() diff --git a/app/ui/systray.py b/app/ui/systray.py new file mode 100644 index 00000000..d7769aef --- /dev/null +++ b/app/ui/systray.py @@ -0,0 +1,67 @@ +# File systray.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""System-tray icon and context menu for NetNeighbor.""" + +from __future__ import annotations + +from gettext import gettext as _ + +from PySide6.QtGui import QIcon +from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon + + +class NetNeighborTray(QSystemTrayIcon): + """System-tray icon with Show/Hide and Quit actions. + + Pass the main window as *window*; the tray toggles its visibility on + left-click and keeps the Show/Hide label in sync with the window state. + """ + + def __init__(self, icon: QIcon, window, parent=None) -> None: + super().__init__(icon, parent) + self._window = window + self.setToolTip("NetNeighbor") + self._menu = QMenu() + self._action_show_hide = self._menu.addAction("") + self._menu.addSeparator() + self._action_quit = self._menu.addAction(_("Quit")) + self.setContextMenu(self._menu) + self._sync_show_hide_label() + self._menu.aboutToShow.connect(self._sync_show_hide_label) + self._action_show_hide.triggered.connect(self._toggle_window) + self._action_quit.triggered.connect(self._quit) + self.activated.connect(self._on_activated) + + # ── public API ───────────────────────────────────────────────────────────── + + def notify_window_visibility_changed(self) -> None: + """Call whenever the window is shown or hidden to keep the label in sync.""" + self._sync_show_hide_label() + + # ── internals ────────────────────────────────────────────────────────────── + + def _sync_show_hide_label(self) -> None: + if self._window.isVisible(): + self._action_show_hide.setText(_("Hide window")) + else: + self._action_show_hide.setText(_("Show window")) + + def _toggle_window(self) -> None: + if self._window.isVisible(): + self._window._hide_to_tray() + else: + self._window.bring_to_front() + self._sync_show_hide_label() + + def _on_activated(self, reason: QSystemTrayIcon.ActivationReason) -> None: + if reason == QSystemTrayIcon.ActivationReason.Trigger: + self._toggle_window() + elif reason == QSystemTrayIcon.ActivationReason.DoubleClick: + self._window.bring_to_front() + self._sync_show_hide_label() + + def _quit(self) -> None: + self.hide() + QApplication.quit() diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 00000000..7553517e --- /dev/null +++ b/app/utils/__init__.py @@ -0,0 +1,5 @@ +# File __init__.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Utilities package.""" diff --git a/app/utils/about_content.py b/app/utils/about_content.py new file mode 100644 index 00000000..06d47bda --- /dev/null +++ b/app/utils/about_content.py @@ -0,0 +1,101 @@ +# File about_content.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Shared About / Credits / License text.""" + +from __future__ import annotations + +import html +from gettext import gettext as _ + +GITHUB_PROJECT_URL = "https://github.com/luc-github/NetNeighbor" +LGPL3_LICENSE_URL = "https://www.gnu.org/licenses/lgpl-3.0.html" + + +def about_program_name() -> str: + return "NetNeighbor" + + +def about_comments() -> str: + return _("Discover and monitor devices on your local network.") + + +def about_copyright_line() -> str: + return "Copyright © Luc LEBOSSE" + + +def about_website_label() -> str: + return _("GitHub Project") + + +def about_warranty_line() -> str: + return _("This program comes with absolutely no warranty.") + + +def about_license_notice_html() -> str: + """“See the … for details.” with the license name linked to LGPL-3.0.""" + link_text = _("GNU Lesser General Public License version 3 or later") + return ( + f"{html.escape(_('See the'))} " + f'' + f"{html.escape(link_text)} " + f"{html.escape(_('for details.'))}" + ) + + +def python_library_credit_entries() -> list[tuple[str, str, str]]: + """(name, description, url) for Credits sections.""" + return [ + ( + "PySide6", + _("Qt for Python bindings"), + "https://doc.qt.io/qtforpython/", + ), + ( + "zeroconf", + _("mDNS/DNS-SD discovery"), + "https://github.com/python-zeroconf/python-zeroconf", + ), + ( + "WSDiscovery", + _("WS-Discovery (Windows devices)"), + "https://github.com/andreikop/python-ws-discovery", + ), + ] + + +def icon_credit_entries() -> list[tuple[str, str | None]]: + """(description, optional url) for the Icons credits section.""" + from utils.icon_attribution import icon_credit_lines_for_ui + + entries: list[tuple[str, str | None]] = [ + (line, None) for line in icon_credit_lines_for_ui() + ] + entries.append((_("App logo under assets/icons: Luc LEBOSSE"), None)) + return entries + + +def credits_html() -> str: + """Rich credits body with clickable links (About dialog Credits page).""" + parts: list[str] = [] + + parts.append(f"

{html.escape(_('Python libraries'))}

    ") + for name, desc, url in python_library_credit_entries(): + link = ( + f'{html.escape(name)}' + ) + parts.append(f"
  • {link} — {html.escape(desc)}
  • ") + parts.append("
") + + parts.append(f"

{html.escape(_('Icons'))}

    ") + for desc, url in icon_credit_entries(): + if url: + parts.append( + f'
  • {html.escape(desc)}
  • ' + ) + else: + parts.append(f"
  • {html.escape(desc)}
  • ") + parts.append("
") + + return "\n".join(parts) diff --git a/app/utils/app_logging.py b/app/utils/app_logging.py new file mode 100644 index 00000000..7c93c418 --- /dev/null +++ b/app/utils/app_logging.py @@ -0,0 +1,226 @@ +# File app_logging.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Shared file + console logging setup (GTK and Qt entrypoints).""" + +from __future__ import annotations + +import json +import logging +import os +from logging.handlers import RotatingFileHandler +from pathlib import Path + +_ROOT = Path(__file__).resolve().parent.parent +_SHIPPED_LOGGING_JSON = _ROOT / "config" / "logging.json" + +_LOG_LEVEL_OFF = 100 # above CRITICAL (50): suppress all standard levels + +# Cap the log file so a long DEBUG session can't grow it without bound. +# 25 MB × 5 files ≈ 125 MB worst case, then the oldest is discarded. +_LOG_MAX_BYTES = 25 * 1024 * 1024 +_LOG_BACKUP_COUNT = 5 + +# Exact stock ``logging.json`` from older releases (no ``app_qt`` key) — useless log file. +_LEGACY_SILENT_STOCK_FILE: dict[str, str] = { + "default": "NONE", + "app": "NONE", + "ui": "NONE", + "device_list": "NONE", + "ssdp": "NONE", + "mdns": "NONE", + "wsd": "NONE", + "wsdd": "NONE", + "nmb": "NONE", +} + + +def _is_legacy_all_silent_user_config(parsed: dict[str, object]) -> bool: + """True when the file is only the old all-NONE template (optional ``app_qt`` also NONE).""" + if not isinstance(parsed, dict) or not parsed: + return False + stock_keys = frozenset(_LEGACY_SILENT_STOCK_FILE) + keys = frozenset(str(k).strip() for k in parsed) + if keys not in (stock_keys, stock_keys | {"app_qt"}): + return False + off = frozenset({"NONE", "OFF", "DISABLED", "SILENT", ""}) + return all(str(v).strip().upper() in off for v in parsed.values()) + + +def _to_level(level_name: str, fallback: int) -> int: + normalized = str(level_name).strip().upper() + if normalized in {"NONE", "OFF", "DISABLED", "SILENT"}: + return _LOG_LEVEL_OFF + resolved = getattr(logging, normalized, None) + if isinstance(resolved, int): + return resolved + return fallback + + +def _fallback_logging_defaults() -> dict[str, str]: + """Built-in fallback when ``config/logging.json`` is missing or invalid.""" + return { + "default": "INFO", + "app": "INFO", + "app_qt": "INFO", + "ui": "WARNING", + "device_list": "WARNING", + "ssdp": "INFO", + "mdns": "INFO", + "wsd": "WARNING", + "wsdd": "WARNING", + "nmb": "WARNING", + } + + +def _shipped_logging_defaults() -> dict[str, str]: + """Defaults from ``config/logging.json`` (shipped with the app).""" + fallback = _fallback_logging_defaults() + if not _SHIPPED_LOGGING_JSON.is_file(): + return dict(fallback) + try: + parsed = json.loads(_SHIPPED_LOGGING_JSON.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return dict(fallback) + if not isinstance(parsed, dict): + return dict(fallback) + merged = dict(fallback) + for key, value in parsed.items(): + if isinstance(key, str) and isinstance(value, str) and value.strip(): + merged[key.strip()] = value.strip() + return merged + + +class _FlushingFileHandler(RotatingFileHandler): + """Size-capped, rotating log handler that flushes each line for live tailing.""" + + def emit(self, record: logging.LogRecord) -> None: + super().emit(record) + self.flush() + + +def load_logging_config() -> dict: + config_dir = Path.home() / ".config" / "netneighbor" + config_path = config_dir / "logging.json" + defaults = _shipped_logging_defaults() + try: + config_dir.mkdir(parents=True, exist_ok=True) + if not config_path.exists(): + if _SHIPPED_LOGGING_JSON.is_file(): + shipped_text = _SHIPPED_LOGGING_JSON.read_text(encoding="utf-8") + config_path.write_text(shipped_text, encoding="utf-8") + else: + config_path.write_text(json.dumps(defaults, indent=2, sort_keys=True), encoding="utf-8") + return dict(defaults) + parsed_raw = json.loads(config_path.read_text(encoding="utf-8")) + if not isinstance(parsed_raw, dict): + return dict(defaults) + parsed = parsed_raw + if _is_legacy_all_silent_user_config(parsed): + upgraded = dict(defaults) + config_path.write_text(json.dumps(upgraded, indent=2, sort_keys=True), encoding="utf-8") + return upgraded + merged = dict(defaults) + for key in defaults: + if key in parsed and isinstance(parsed[key], str): + merged[key] = parsed[key].strip() + return merged + except (OSError, json.JSONDecodeError): + return dict(defaults) + + +def apply_named_log_levels(config: dict) -> None: + app_level = _to_level(str(config.get("app", config.get("default", "INFO"))), logging.INFO) + app_qt_level = _to_level( + str(config.get("app_qt", config.get("app", config.get("default", "INFO")))), + logging.INFO, + ) + ssdp_level = _to_level(str(config.get("ssdp", config.get("default", "INFO"))), logging.INFO) + mdns_level = _to_level(str(config.get("mdns", config.get("default", "INFO"))), logging.INFO) + wsd_level = _to_level(str(config.get("wsd", config.get("default", "INFO"))), logging.INFO) + wsdd_level = _to_level(str(config.get("wsdd", config.get("default", "INFO"))), logging.INFO) + nmb_level = _to_level(str(config.get("nmb", config.get("default", "INFO"))), logging.INFO) + device_list_level = _to_level(str(config.get("device_list", config.get("default", "INFO"))), logging.INFO) + ui_level = _to_level(str(config.get("ui", config.get("ui_qt", config.get("default", "INFO")))), logging.INFO) + + for logger_name in ("app", "utils", "discovery.manager", "model"): + logging.getLogger(logger_name).setLevel(app_level) + logging.getLogger("app_qt").setLevel(app_qt_level) + logging.getLogger("ui").setLevel(ui_level) + logging.getLogger("discovery.ssdp").setLevel(ssdp_level) + logging.getLogger("discovery.mdns").setLevel(mdns_level) + logging.getLogger("discovery.wsd").setLevel(wsd_level) + logging.getLogger("discovery.wsdd_client").setLevel(wsdd_level) + logging.getLogger("discovery.netbios").setLevel(nmb_level) + logging.getLogger("discovery.manager.ssdp").setLevel(ssdp_level) + logging.getLogger("discovery.manager.mdns").setLevel(mdns_level) + logging.getLogger("discovery.manager.wsd").setLevel(wsd_level) + logging.getLogger("discovery.manager.wsdd").setLevel(wsdd_level) + logging.getLogger("discovery.manager.nmb").setLevel(nmb_level) + logging.getLogger("ui.device_list").setLevel(device_list_level) + + +def _apply_netneighbor_debug_ui_env(*, log_name: str) -> None: + """Raise loggers used for Qt / discovery UI troubleshooting when env is set.""" + dbg_ui = str(os.getenv("NETNEIGHBOR_DEBUG_UI", "")).strip().lower() + if dbg_ui not in ("1", "true", "yes", "on", "debug"): + return + for name in ("ui", "discovery.netbios"): + logging.getLogger(name).setLevel(logging.DEBUG) + logging.getLogger(log_name).info( + "NETNEIGHBOR_DEBUG_UI: DEBUG for loggers ui, discovery.netbios" + ) + + +def setup_logging(*, log_name: str = "app") -> None: + """Configure root logging once; respects ``NETNEIGHBOR_LOG_LEVEL`` and ``logging.json``.""" + env_level_name = os.getenv("NETNEIGHBOR_LOG_LEVEL") + config = load_logging_config() + default_level_name = str(config.get("default", "INFO")).upper() + if env_level_name: + default_level_name = env_level_name.upper() + level = _to_level(default_level_name, logging.INFO) + log_dir = Path.home() / ".cache" / "netneighbor" + log_dir.mkdir(parents=True, exist_ok=True) + log_file = log_dir / "netneighbor.log" + + root_logger = logging.getLogger() + if root_logger.handlers: + root_logger.setLevel(level) + apply_named_log_levels(config) + _apply_netneighbor_debug_ui_env(log_name=log_name) + return + + formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(name)s | %(message)s") + file_handler = _FlushingFileHandler( + log_file, + maxBytes=_LOG_MAX_BYTES, + backupCount=_LOG_BACKUP_COUNT, + encoding="utf-8", + ) + file_handler.setFormatter(formatter) + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + + root_logger.setLevel(level) + root_logger.addHandler(file_handler) + root_logger.addHandler(stream_handler) + apply_named_log_levels(config) + _apply_netneighbor_debug_ui_env(log_name=log_name) + logging.getLogger(log_name).info("Logging initialized at %s (%s)", default_level_name, log_file) + + +def close_file_log_handlers() -> None: + """Detach and close root file handlers so the log file can be deleted (Windows keeps it locked). + + Used before "Reset all application data"; later records still reach the stream handler. + """ + root_logger = logging.getLogger() + for handler in list(root_logger.handlers): + if isinstance(handler, logging.FileHandler): + root_logger.removeHandler(handler) + try: + handler.close() + except Exception: + pass diff --git a/app/utils/app_version.py b/app/utils/app_version.py new file mode 100644 index 00000000..40cc5400 --- /dev/null +++ b/app/utils/app_version.py @@ -0,0 +1,40 @@ +# File app_version.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Application release version: single source in repository root ``VERSION``.""" + +import sys +from pathlib import Path + + +def _candidate_paths() -> list[Path]: + """Possible locations of ``VERSION`` depending on how the app is run. + + - PyInstaller bundle (Windows/macOS): ``VERSION`` sits in ``sys._MEIPASS``. + - Sources / .deb / AppImage / tarball: ``VERSION`` sits next to ``app/``, + i.e. one level above the directory containing ``utils/``. + """ + here = Path(__file__).resolve().parent # .../app/utils + paths: list[Path] = [] + meipass = getattr(sys, "_MEIPASS", None) + if meipass: + paths.append(Path(meipass) / "VERSION") + paths.append(here.parent / "VERSION") # bundle root (PyInstaller) or app/ + paths.append(here.parent.parent / "VERSION") # project root (sources, Linux packages) + return paths + + +def get_app_version(default: str = "0.0.0") -> str: + """Return the first non-empty, non-comment line from ``VERSION`` at project root.""" + for path in _candidate_paths(): + try: + raw = path.read_text(encoding="utf-8") + except OSError: + continue + for line in raw.splitlines(): + s = line.strip() + if not s or s.startswith("#"): + continue + return s + return default diff --git a/app/utils/browser.py b/app/utils/browser.py new file mode 100644 index 00000000..91cc8db1 --- /dev/null +++ b/app/utils/browser.py @@ -0,0 +1,124 @@ +# File browser.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Browser utility to open device URLs.""" + +import logging +import os +import shutil +import subprocess +import sys +import threading +import webbrowser +from urllib.parse import urlparse + +_LOG = logging.getLogger(__name__) + +try: + import win32netcon + import win32wnet + _HAS_WIN32WN = True +except ImportError: + _HAS_WIN32WN = False + +_BROWSER_SCHEMES = {"http", "https", ""} + +# Schemes that need a file manager rather than a web browser or xdg-open. +# xdg-open silently fails for smb:// on many Linux desktops (Cinnamon, GNOME, etc.). +_FILE_MANAGER_SCHEMES = {"smb", "ftp", "sftp", "nfs", "dav", "davs"} +_FILE_MANAGERS = ["nemo", "nautilus", "dolphin", "thunar", "pcmanfm"] + + +def _win32_smb_worker(unc: str) -> None: + """Background thread: connect via WNet then open explorer.""" + if _HAS_WIN32WN: + try: + try: + win32wnet.WNetCancelConnection2(unc, 0, True) + except Exception: + pass + flags = win32netcon.CONNECT_INTERACTIVE | win32netcon.CONNECT_PROMPT + win32wnet.WNetAddConnection2( + win32netcon.RESOURCETYPE_DISK, + None, + unc, + None, + "", + "", + flags, + ) + _LOG.debug("WNetAddConnection2 ok: %r", unc) + subprocess.Popen(["explorer.exe", unc]) # noqa: S603,S607 + return + except Exception as exc: + if getattr(exc, "winerror", None) == 1223: + return # User cancelled — not an error. + _LOG.warning("WNetAddConnection2 failed (%s): %r", exc, unc) + # Fallback: no pywin32 or WNet failed — open directly (no credential prompt). + try: + subprocess.Popen(["explorer.exe", unc]) # noqa: S603,S607 + except OSError as exc: + _LOG.warning("explorer.exe also failed: %s", exc) + + +def _win32_open_smb(unc: str) -> bool: + """Spawn a background thread to open *unc*, keeping the UI responsive.""" + threading.Thread(target=_win32_smb_worker, args=(unc,), daemon=True).start() + return True + + +def open_url(url: str) -> bool: + if not url: + return False + scheme = urlparse(url).scheme.lower() + + if sys.platform == "win32": + # On Windows, os.startfile opens the default handler (browser for + # http/https) without ever spawning a console window. webbrowser.open + # may fall back to a generic controller that runs `cmd /c start`, + # which flashes an ephemeral terminal in the frozen app — avoid it. + if scheme == "smb": + parsed = urlparse(url) + path = parsed.path.replace("/", "\\") + unc = f"\\\\{parsed.netloc}{path}" + return _win32_open_smb(unc) + if scheme in ("ftp", "sftp"): + # The default ftp:// handler on modern Windows is the web browser, + # which dropped FTP support — force Explorer's FTP client instead. + # explorer.exe is a GUI app, so no console window flashes. + try: + subprocess.Popen(["explorer.exe", url]) # noqa: S603,S607 + return True + except OSError: + return webbrowser.open(url) + try: + os.startfile(url) # noqa: S606 — URL validated above + return True + except OSError: + return webbrowser.open(url) + + if scheme in _BROWSER_SCHEMES: + return webbrowser.open(url) + + if sys.platform == "darwin": + try: + subprocess.Popen(["open", url]) + return True + except OSError: + return webbrowser.open(url) + + # Linux: prefer a known file manager, fall back to xdg-open. + if scheme in _FILE_MANAGER_SCHEMES: + for fm in _FILE_MANAGERS: + if shutil.which(fm): + try: + subprocess.Popen([fm, url], close_fds=True) + return True + except OSError: + continue + try: + subprocess.Popen(["xdg-open", url], close_fds=True) + return True + except FileNotFoundError: + return webbrowser.open(url) diff --git a/app/utils/config_integrity.py b/app/utils/config_integrity.py new file mode 100644 index 00000000..930ba774 --- /dev/null +++ b/app/utils/config_integrity.py @@ -0,0 +1,56 @@ +# File config_integrity.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Startup integrity check for the bundled, non-defaultable config files. + +These JSON files ship inside the application bundle and are the *single source of truth* for +device classification (no Python fallback duplicates them anymore). If one is missing or +unparseable the installation is corrupt — the app surfaces a "reinstall" dialog and exits +rather than silently running with no rules. +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path + +_LOG = logging.getLogger(__name__) + +_CONFIG_DIR = Path(__file__).resolve().parent.parent / "config" + +# Bundled data files that have no meaningful runtime default. Tunables with code defaults +# (discovery.json, logging.json, …) are intentionally NOT listed — their absence is normal. +REQUIRED_CONFIG_FILES: tuple[str, ...] = ( + "device_types.json", + "ssdp_rules.json", + "mdns_rules.json", + "wsd_rules.json", +) + + +def check_bundled_config_integrity() -> list[str]: + """Return a list of human-readable problems for missing/corrupt required config files. + + Empty list ⇒ healthy install. Each entry is like ``"ssdp_rules.json: missing"``. + """ + problems: list[str] = [] + for name in REQUIRED_CONFIG_FILES: + path = _CONFIG_DIR / name + if not path.is_file(): + problems.append(f"{name}: missing") + continue + try: + data = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + problems.append(f"{name}: invalid JSON ({exc.msg}, line {exc.lineno})") + continue + except OSError as exc: + problems.append(f"{name}: unreadable ({exc})") + continue + if not isinstance(data, dict): + problems.append(f"{name}: not a JSON object") + if problems: + _LOG.error("Bundled config integrity check failed: %s", problems) + return problems diff --git a/app/utils/connect_launcher.py b/app/utils/connect_launcher.py new file mode 100644 index 00000000..7b7d849e --- /dev/null +++ b/app/utils/connect_launcher.py @@ -0,0 +1,271 @@ +# File connect_launcher.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Launch resolved connect URIs: system default (empty template) or per-scheme command from preferences.""" + +from __future__ import annotations + +import json +import logging +import sys +from collections.abc import Callable +from pathlib import Path +from urllib.parse import urlparse + +from utils.browser import open_url +from utils.custom_command import build_argv_from_template, spawn_custom_command_detached + +_LOG = logging.getLogger(__name__) +_SCHEME_ORDER = ("http", "https", "smb", "ftp", "ssh", "telnet", "sftp", "spotify") + +# Pseudo-template for the "spotify" scheme: open the Spotify desktop app when installed, +# otherwise the web player (utils.spotify_launch). Same on every OS. +_LOCAL_SPOTIFY_TEMPLATE = "localspotify:" +_SCHEME_DEFAULT_PORT = {"ssh": 22, "sftp": 22, "telnet": 23, "ftp": 21, "http": 80, "https": 443} + +_SKIP_JSON_KEYS = frozenset({"version", "comment", "schema"}) + +# Windows-native pseudo-schemes: resolved to their real scheme and opened via +# open_url() (ShellExecute/os.startfile) instead of spawning a console process. +_LOCAL_PSEUDO_SCHEMES: dict[str, str] = { + "localsmb": "smb", + "localhttps": "https", + "localhttp": "http", + "localsftp": "sftp", + "localftp": "ftp", +} + +_HARDCODED_DEFAULTS_BY_OS: dict[str, dict[str, str]] = { + "linux": { + "http": "xdg-open {url}", + "https": "xdg-open {url}", + "smb": "nemo smb://{ip}", + "ftp": "nemo ftp://{ip}", + "ssh": "x-terminal-emulator -e ssh -p {port} {ip}", + "telnet": "x-terminal-emulator -e nc {ip} {port}", + "sftp": "nemo sftp://{ip}", + "spotify": _LOCAL_SPOTIFY_TEMPLATE, + }, + "darwin": { + "http": "open {url}", + "https": "open {url}", + "smb": "open smb://{ip}", + "ftp": "open ftp://{ip}", + "ssh": "open ssh://{ip}:{port}", + "telnet": "open telnet://{ip}:{port}", + "sftp": "open sftp://{ip}", + "spotify": _LOCAL_SPOTIFY_TEMPLATE, + }, + "win32": { + # "{url}" alone opens the full discovered URL (port + path) with the + # system default handler via ShellExecute (no console flash). + "http": "{url}", + "https": "{url}", + "smb": "localsmb://{ip}", + "ftp": "localftp://{ip}", + "ssh": "cmd.exe /k ssh -p {port} {ip}", + "telnet": "cmd.exe /k telnet {ip} {port}", + "sftp": "localsftp://{ip}", + "spotify": _LOCAL_SPOTIFY_TEMPLATE, + }, +} + + +def _get_hardcoded_defaults() -> dict[str, str]: + key = _platform_branch_key() + out = dict(_HARDCODED_DEFAULTS_BY_OS.get("linux", {})) + if key != "linux": + out.update(_HARDCODED_DEFAULTS_BY_OS.get(key, {})) + return out + + +def _platform_branch_key() -> str: + p = sys.platform + if p == "win32": + return "win32" + if p == "darwin": + return "darwin" + return "linux" + + +def _coerce_scheme_map(obj: object) -> dict[str, str]: + if not isinstance(obj, dict): + return {} + out: dict[str, str] = {} + for k, v in obj.items(): + if not isinstance(k, str) or k in _SKIP_JSON_KEYS: + continue + if isinstance(v, str) and v.strip(): + out[k] = v + return out + + +def _json_has_os_branches(data: dict) -> bool: + for k in ("linux", "darwin", "win32"): + v = data.get(k) + if isinstance(v, dict) and v: + return True + return False + + +def _merge_templates_from_json_doc(data: dict) -> dict[str, str]: + """Extract scheme→template from either per-OS branches or legacy flat mapping.""" + if _json_has_os_branches(data): + merged: dict[str, str] = {} + linux_b = data.get("linux") + if isinstance(linux_b, dict): + merged.update(_coerce_scheme_map(linux_b)) + plat_key = _platform_branch_key() + if plat_key != "linux": + plat = data.get(plat_key) + if isinstance(plat, dict): + for k, v in plat.items(): + if not isinstance(k, str) or k in _SKIP_JSON_KEYS: + continue + if isinstance(v, str): + if v.strip(): + merged[k] = v + else: + # Explicit empty in platform branch clears the linux default. + merged.pop(k, None) + return merged + return _coerce_scheme_map(data) + + +def _load_json_defaults() -> dict[str, str]: + json_path = Path(__file__).resolve().parent.parent / "config" / "default_commands.json" + try: + with json_path.open(encoding="utf-8") as fh: + data = json.load(fh) + except Exception: + _LOG.debug("Could not load %s; using hardcoded defaults", json_path) + return {} + if not isinstance(data, dict): + return {} + return _merge_templates_from_json_doc(data) + + +def default_connect_command_templates() -> dict[str, str]: + defaults = _get_hardcoded_defaults() + defaults.update(_load_json_defaults()) + return defaults + + +# Former HTTP(S) defaults that dropped the discovered port and path (opened :80 / :443 root). +# A saved preference still equal to one of them is upgraded to the current default. +_LEGACY_URL_DROPPING_DEFAULTS: frozenset[str] = frozenset({ + "localhttp://{ip}", + "localhttps://{ip}", + "xdg-open http://{ip}", + "xdg-open https://{ip}", + "open http://{ip}", + "open https://{ip}", +}) + + +def normalize_connect_templates(raw: object) -> dict[str, str]: + out = default_connect_command_templates() + if isinstance(raw, dict): + for k in out: + v = raw.get(k) + if isinstance(v, str): + if k in ("http", "https") and v.strip() in _LEGACY_URL_DROPPING_DEFAULTS: + continue # keep the new default + out[k] = v + return out + + +def launch_connect_for_uri( + uri: str, + templates: dict[str, str], + *, + ip: str, + port: int, + name: str, + type_: str, + category: str, + device_cmd_override: str = "", + on_spawn_error: Callable[[str], None] | None = None, +) -> str | None: + """ + Open *uri* with the desktop default, or run the template for ``urlparse(uri).scheme``. + + If *device_cmd_override* is set it takes priority over the scheme template from *templates*. + ``{ip}`` and ``{port}`` in the template are resolved from the URI itself when present + (this transparently respects per-device endpoint overrides). + + Returns a **user-visible error** when the template is set but invalid; ``None`` on success + (including spawn scheduled). Spawn failures invoke *on_spawn_error* asynchronously. + """ + u = (uri or "").strip() + if not u: + return None + + parsed = urlparse(u) + scheme = parsed.scheme.lower() + if not scheme: + open_url(u) + return None + + # Prefer ip/port embedded in the URI (handles endpoint overrides automatically). + effective_ip = parsed.hostname or ip + effective_port = parsed.port if parsed.port is not None else port + if effective_port == 0: + effective_port = _SCHEME_DEFAULT_PORT.get(scheme, 0) + + # Per-device command override > scheme template > open_url fallback. + tmpl = (device_cmd_override or "").strip() + if not tmpl: + tmpl = ((templates.get(scheme) if isinstance(templates, dict) else None) or "").strip() + if not tmpl: + _LOG.debug("open: no template for scheme=%s → system default url=%s", scheme, u) + open_url(u) + return None + + # "{url}" alone: open the full resolved URI (port + path) with the system default + # handler (ShellExecute on Windows → no console flash). + if tmpl == "{url}": + _LOG.debug("open: {url} template → system default url=%s", u) + open_url(u) + return None + + low = tmpl.lower() + if low.startswith(_LOCAL_SPOTIFY_TEMPLATE): + from utils.spotify_launch import open_spotify + + _LOG.debug("open: localspotify: template → Spotify app or web player") + if not open_spotify(): + return _("Could not open Spotify.") + return None + + # local* pseudo-schemes (localsmb/localhttp/localhttps) route through + # open_url() so Windows opens them via ShellExecute/os.startfile — no + # console window flash — while still honouring {ip}/{port} overrides. + for pseudo, real in _LOCAL_PSEUDO_SCHEMES.items(): + if low.startswith(pseudo + ":"): + local_url = ( + tmpl + .replace("{ip}", str(effective_ip)) + .replace("{port}", str(effective_port)) + .replace(pseudo + "://", real + "://", 1) + ) + _LOG.debug("open: %s pseudo-scheme → %s", pseudo, local_url) + open_url(local_url) + return None + + argv = build_argv_from_template( + tmpl, + ip=effective_ip, + port=effective_port, + name=name, + type_=type_, + category=category, + url=u, + ) + if argv is None: + return _("Invalid command template for this protocol.") + + _LOG.debug("open: scheme=%s template=%r argv=%s", scheme, tmpl, argv) + spawn_custom_command_detached(argv, on_error=on_spawn_error or (lambda _s: None)) + return None diff --git a/app/utils/custom_command.py b/app/utils/custom_command.py new file mode 100644 index 00000000..5b081510 --- /dev/null +++ b/app/utils/custom_command.py @@ -0,0 +1,107 @@ +# File custom_command.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""User-defined external command per device (placeholders: {ip}, {port}, {name}, {type}, {category}, {url}).""" + +from __future__ import annotations + +import logging +import re +import shlex +import subprocess +import sys +import threading +from collections.abc import Callable + +from utils.scheduling import ScheduleMainFn + +_LOG = logging.getLogger(__name__) + +_PLACEHOLDER_RE = re.compile(r"\{([a-z_]+)\}") +# {ip_raw} is kept as a silent alias for {ip} for backwards compatibility +# with any saved preferences — it is no longer shown in the UI. +_KNOWN = frozenset({"ip", "ip_raw", "port", "name", "type", "category", "url"}) + + +def build_argv_from_template( + template: str, + *, + ip: str, + port: int, + name: str, + type_: str, + category: str, + url: str = "", +) -> list[str] | None: + """ + Substitute placeholders then split the result into argv. + + Values are shell-quoted before substitution so that ``shlex.split`` can + correctly reassemble tokens containing spaces (e.g. device names). + ``{ip_raw}`` is a silent alias for ``{ip}`` kept for backwards compat. + """ + raw = (template or "").strip() + if not raw: + return None + + for m in _PLACEHOLDER_RE.finditer(raw): + key = m.group(1) + if key not in _KNOWN: + _LOG.warning("custom command: unknown placeholder {%s}", key) + return None + + values = { + "ip": ip, + "ip_raw": ip, + "port": str(int(port)), + "name": name, + "type": type_, + "category": category, + "url": url, + } + substituted = raw + # ip_raw is substituted raw (no shlex quoting) — keep for UNC path compat. + substituted = substituted.replace("{ip_raw}", values["ip_raw"]) + for key in ("ip", "port", "name", "type", "category", "url"): + substituted = substituted.replace("{" + key + "}", shlex.quote(str(values[key]))) + + if "{" in substituted: + _LOG.warning("custom command: unreplaced placeholders remain") + return None + + try: + argv = shlex.split(substituted, posix=True) + except ValueError as e: + _LOG.warning("custom command: shlex failed: %s", e) + return None + return argv or None + + +def spawn_custom_command_detached( + argv: list[str], + *, + on_error: Callable[[str], None], + schedule_on_main: ScheduleMainFn | None = None, +) -> None: + """Run *argv* in a background thread; marshal ``on_error`` to the UI thread when *schedule_on_main* is set.""" + + def _run() -> None: + _LOG.debug("spawn: %s", argv) + try: + if sys.platform == "win32": + subprocess.Popen(argv, creationflags=subprocess.CREATE_NEW_CONSOLE) + else: + subprocess.Popen(argv, close_fds=True, start_new_session=True) + except OSError as e: + _LOG.warning("custom command spawn failed: %s", e) + + def _fail() -> None: + on_error(str(e)) + + if schedule_on_main is not None: + schedule_on_main(_fail) + else: + _fail() + + threading.Thread(target=_run, daemon=True).start() diff --git a/utils/details_payload.py b/app/utils/details_payload.py similarity index 91% rename from utils/details_payload.py rename to app/utils/details_payload.py index 278fa1cd..4b29f84a 100644 --- a/utils/details_payload.py +++ b/app/utils/details_payload.py @@ -1,5 +1,5 @@ -# File details_payload.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File details_payload.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Build protocol detail payloads from normalized metadata.""" @@ -20,6 +20,29 @@ from utils.neighbor_mac import lookup_ipv4_for_mac, lookup_mac_from_neighbor_cache +def _pretty_xml(raw: str) -> str: + """Re-indent SSDP descriptor XML for display, regardless of how the device sent it. + + Some devices return the whole descriptor on a single line (e.g. ESP3D), others pre-indent it + (e.g. Sonos). Inter-element whitespace is collapsed first so minidom produces consistent + indentation in both cases; namespaces/prefixes are preserved. Falls back to the trimmed + original if the payload is not well-formed XML. + """ + text = raw.strip() + try: + import xml.dom.minidom as _minidom + + collapsed = re.sub(r">\s+<", "><", text) + pretty = _minidom.parseString(collapsed).toprettyxml(indent=" ") + lines = [ln for ln in pretty.splitlines() if ln.strip()] + # Drop the synthetic declaration minidom adds when the source had none. + if lines and lines[0].startswith(" int | None: try: p = int(value) @@ -119,8 +142,15 @@ def format_device_type_for_details(device: Device) -> str: "cnc": _("CNC"), "3dprinter": _("3D printer"), "nas": _("NAS"), + "server": _("Server"), + "rackserver": _("Rack server"), + "desktop": _("Desktop computer"), + "minipc": _("Mini PC"), + "allinone": _("All-in-one computer"), + "laptop": _("Laptop"), + "smartphone": _("Smartphone"), "computer": _("Computer"), - "esp32": _("ESP3D / firmware"), + "esp32": _("ESP3D Device"), "scanner": _("Scanner"), } if t in known: @@ -283,7 +313,7 @@ def build_ssdp_payload(device: Device) -> tuple[ ] xml_location = metadata.get("location") xml_location_norm = xml_location if isinstance(xml_location, str) else None - raw_xml = xml_data if isinstance(xml_data, str) and xml_data.strip() else None + raw_xml = _pretty_xml(xml_data) if isinstance(xml_data, str) and xml_data.strip() else None troubleshooting_fields: list[tuple[str, str]] = [ (_("Serial number"), _value_or_unavailable(xml_fields.get("serialNumber"))), ( @@ -309,6 +339,16 @@ def _detail_field_usable(text: object) -> bool: return bool(stripped and stripped != "unavailable") +def detail_field_value_visible(value: object) -> bool: + """True if a details row should be shown in the UI.""" + return _detail_field_usable(value) + + +def filter_visible_detail_fields(fields: list[tuple[str, str]]) -> list[tuple[str, str]]: + """Drop empty or ``unavailable`` rows (GTK details dialog behaviour).""" + return [(k, v) for k, v in fields if detail_field_value_visible(v)] + + def _txt_pairs_from_service_dict(svc: dict[str, Any]) -> list[tuple[str, str]]: pairs_raw = svc.get("txt_records") pairs: list[tuple[str, str]] = [] @@ -641,6 +681,13 @@ def _norm_key(key: str) -> str: continue mdns_for_merge.append((key, value)) + # Build a value-lookup dict for SSDP fields (first occurrence wins, keys already normalised above). + ssdp_val_by_key: dict[str, str] = {} + for _k, _v in ssdp_fields: + nk0 = _norm_key(_k) + if nk0 not in ssdp_val_by_key: + ssdp_val_by_key[nk0] = _v + prefer_ssdp_only = {"ip", "port", "ports", "location", "last seen"} out: list[tuple[str, str]] = list(ssdp_fields) for key, value in mdns_for_merge: @@ -648,6 +695,10 @@ def _norm_key(key: str) -> str: if nk in prefer_ssdp_only and nk in ssdp_keys: continue if nk in ssdp_keys: + # Same key and same value → SSDP already covers it; skip the mDNS duplicate. + ssdp_val = ssdp_val_by_key.get(nk, "") + if (ssdp_val or "").strip().lower() == (value or "").strip().lower(): + continue out.append((f"{key} (mDNS)", value)) else: out.append((key, value)) diff --git a/app/utils/device_bundles.py b/app/utils/device_bundles.py new file mode 100644 index 00000000..9f380546 --- /dev/null +++ b/app/utils/device_bundles.py @@ -0,0 +1,476 @@ +# File device_bundles.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Merge discovery rows by host (same logic as ``ui/device_list``; no GTK imports).""" + +from __future__ import annotations + +import ipaddress +import logging +import re +from collections.abc import Sequence +from dataclasses import dataclass + +from model.device import Device +from utils.discovery_config import ( + information_precedence_rank, + information_precedence_role_for_device_source, +) +from utils.discovery_identity import upnp_identity_from_udn, upnp_identity_from_usn, uuid_urn_if_present +from utils.location_label import is_plausible_room_location +from utils.neighbor_mac import lookup_mac_from_neighbor_cache + +_LOG = logging.getLogger(__name__) +# Child of "discovery.ssdp": follows the "ssdp" level of ~/.config/netneighbor/logging.json. +_SSDP_CHOICE_LOG = logging.getLogger("discovery.ssdp.bundle_choice") +# Last logged (kept, ignored) descriptor pair per IP — log only when the choice changes. +_last_ssdp_choice_by_ip: dict[str, tuple[str, str]] = {} + +_SOURCE_PRIMARY_TIEBREAK = {"ssdp": 0, "wsdd": 1, "wsd": 2, "nmb": 3, "mdns": 4} +_PRIMARY_RANK_SLACK_FOR_NAME = 2 + +_WSD_SYNTHETIC_DISPLAY_RE = re.compile( + r"^ws[d]?[\s\-·∙]+[0-9a-f]{6,}$", + re.IGNORECASE, +) + + +def weak_bundle_display_name(device: Device | None) -> bool: + """True if the row label is too generic to prefer over another protocol's hostname.""" + if device is None: + return True + n = (getattr(device, "name", None) or "").strip() + if not n: + return True + low = n.lower() + if low == "wsd host": + return True + if low.startswith("wsd ·") or low.startswith("wsd \u00b7"): + return True + if _WSD_SYNTHETIC_DISPLAY_RE.match(n.strip()): + return True + if len(n) <= 1: + return True + try: + ipaddress.ip_address(n.strip("[]")) + return True + except ValueError: + pass + return False + + +def bundle_row_debug_line( + dev: Device, + *, + rank: int, + role: str, + tie: int, + weak: bool, +) -> str: + return ( + f"{dev.source}@{dev.ip}:{dev.port} name={dev.name!r} role={role} " + f"precedence_index={rank} tiebreak={tie} weak_name={weak}" + ) + + +@dataclass(slots=True) +class DeviceBundle: + ip: str + port: int + primary: Device + ssdp_device: Device | None = None + mdns_device: Device | None = None + wsd_device: Device | None = None + wsdd_device: Device | None = None + nmb_device: Device | None = None + + @property + def name(self) -> str: + return self.primary.name + + @property + def category(self) -> str: + return self.primary.category + + @property + def type(self) -> str: + return self.primary.type + + @property + def icon(self) -> str | None: + return self.primary.icon + + @property + def online(self) -> bool: + return any(device.online for device in self.devices) + + @property + def monitored(self) -> bool: + return any(getattr(device, "monitored", False) for device in self.devices) + + @property + def hidden(self) -> bool: + return any(getattr(device, "hidden", False) for device in self.devices) + + @property + def devices(self) -> list[Device]: + unique: dict[str, Device] = {} + for device in (self.mdns_device, self.ssdp_device, self.wsdd_device, self.wsd_device, self.nmb_device, self.primary): + if device is not None: + unique[device.key] = device + return list(unique.values()) + + +def bundle_location_label(bundle: DeviceBundle, *, no_location_label: str) -> str: + for device in bundle.devices: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + location = metadata.get("user_location") + if isinstance(location, str) and location.strip(): + s = location.strip() + if is_plausible_room_location(s): + return s + return no_location_label + + +def protocol_row_preference_rank(device: Device | None, information_precedence: Sequence[str]) -> int: + if device is None: + return 99 + role = information_precedence_role_for_device_source(device.source or "") + return information_precedence_rank(list(information_precedence), role) + + +def normalize_mac_for_bundle_merge(raw: str) -> str: + t = (raw or "").strip().lower().replace("-", ":") + parts = t.split(":") + if len(parts) != 6: + return "" + if not all(len(p) == 2 and all(c in "0123456789abcdef" for c in p) for p in parts): + return "" + return ":".join(parts) + + +def extract_mac(metadata: dict) -> str: + if not isinstance(metadata, dict): + return "" + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} + candidates = [ + xml_fields.get("mac"), + metadata.get("mac"), + metadata.get("mac_address"), + metadata.get("MAC"), + metadata.get("macAddress"), + txt_fields.get("mac"), + txt_fields.get("macaddress"), + txt_fields.get("mac_address"), + ] + for value in candidates: + if isinstance(value, str) and value.strip(): + return value.strip().lower() + return "" + + +def extract_uid(metadata: dict) -> str: + if not isinstance(metadata, dict): + return "" + xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} + txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} + + usn = metadata.get("usn") + if isinstance(usn, str) and usn.strip(): + return upnp_identity_from_usn(usn) + + wsd_epr = metadata.get("wsd_epr") + if isinstance(wsd_epr, str) and wsd_epr.strip(): + u = uuid_urn_if_present(wsd_epr) + if u: + return u + wsdd_uri = metadata.get("wsdd_uri") + if isinstance(wsdd_uri, str) and wsdd_uri.strip(): + u = uuid_urn_if_present(wsdd_uri) + if u: + return u + + udn_raw = xml_fields.get("UDN") + if isinstance(udn_raw, str) and udn_raw.strip(): + hit = upnp_identity_from_udn(udn_raw) + if hit: + return hit + + candidates = [ + xml_fields.get("UDN"), + metadata.get("udn"), + txt_fields.get("uuid"), + txt_fields.get("udn"), + txt_fields.get("id"), + txt_fields.get("deviceid"), + txt_fields.get("device_id"), + txt_fields.get("serial"), + txt_fields.get("serialnumber"), + ] + for value in candidates: + if isinstance(value, str) and value.strip(): + return value.strip().lower() + return "" + + +def mac_for_bundle_merge(device: Device, metadata: dict) -> str: + m = extract_mac(metadata) + n = normalize_mac_for_bundle_merge(m) if m else "" + if n: + return n + hit = lookup_mac_from_neighbor_cache(str(getattr(device, "ip", "") or "").strip()) + return normalize_mac_for_bundle_merge(hit) if hit else "" + + +def device_host_bundle_keys(device: Device) -> list[str]: + if device.source not in {"mdns", "ssdp", "wsd", "wsdd", "nmb"}: + return [] + metadata = device.metadata if isinstance(device.metadata, dict) else {} + ordered: list[str] = [] + mac = mac_for_bundle_merge(device, metadata) + if mac: + ordered.append(f"mac:{mac}") + uid = extract_uid(metadata) + if uid: + ordered.append(f"uid:{uid}") + ip = str(device.ip).strip() + if ip and ip != "0.0.0.0": + ordered.append(f"ip:{ip}") + seen: set[str] = set() + deduped: list[str] = [] + for key in ordered: + if key not in seen: + seen.add(key) + deduped.append(key) + return deduped + + +def choose_bundle_primary(bundle: DeviceBundle, information_precedence: Sequence[str]) -> Device: + candidates: list[Device] = [] + for d in (bundle.ssdp_device, bundle.wsdd_device, bundle.wsd_device, bundle.nmb_device, bundle.mdns_device): + if d is not None: + candidates.append(d) + if not candidates: + return bundle.primary + if len(candidates) == 1: + return candidates[0] + + def _sort_key(d: Device) -> tuple[int, int]: + src = (d.source or "").strip().lower() + return ( + protocol_row_preference_rank(d, information_precedence), + _SOURCE_PRIMARY_TIEBREAK.get(src, 9), + ) + + ordered = sorted(candidates, key=_sort_key) + top = ordered[0] + + if bundle.nmb_device is not None and not weak_bundle_display_name(bundle.nmb_device): + if top.source in {"wsd", "wsdd"} and weak_bundle_display_name(top): + return bundle.nmb_device + + best_rank = protocol_row_preference_rank(ordered[0], information_precedence) + slack = _PRIMARY_RANK_SLACK_FOR_NAME + for d in ordered: + dr = protocol_row_preference_rank(d, information_precedence) + if dr > best_rank + slack: + break + if not weak_bundle_display_name(d): + return d + return ordered[0] + + +def _descriptor_richness(dev: Device | None) -> tuple[int, int, int]: + """Rank a device by how much descriptor data it carries (raw XML, iconURL, xml_fields). + + The icon ranks before the field count: a host can serve a vendor descriptor (with an icon, + e.g. Sharp DIAL :8008) and a bare SoC placeholder one (e.g. "Mediatek_MTXXXX" tvdevice) with + a similar number of fields; the placeholder is re-announced more often and must not win ties. + """ + if dev is None: + return (0, 0, 0) + md = dev.metadata if isinstance(dev.metadata, dict) else {} + xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} + has_xml = 1 if isinstance(md.get("xml"), str) and md.get("xml").strip() else 0 + icon = xf.get("iconURL") + has_icon = 1 if isinstance(icon, str) and icon.strip() else 0 + return (has_xml, has_icon, len(xf)) + + +def _richer_descriptor_device(existing: Device | None, candidate: Device) -> Device: + """Pick the richer of two same-source devices that map to one bundle. + + A host can expose several SSDP responses for the same identity — e.g. Sonos returns an + enriched root descriptor AND a bare "SSDP Device" (XML pending). Whichever is processed last + must not blank out the descriptor: keep the one carrying real XML / xml_fields / iconURL so the + SSDP detail tab and device icon survive. Ties favour the newer (candidate) for freshness. + """ + if existing is None: + return candidate + kept = candidate if _descriptor_richness(candidate) >= _descriptor_richness(existing) else existing + ignored = existing if kept is candidate else candidate + if kept.source == "ssdp": + _log_ssdp_descriptor_choice(kept, ignored) + return kept + + +def _ssdp_descriptor_label(dev: Device) -> str: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + return str(md.get("location") or dev.url or f"{dev.ip}:{dev.port}").strip() + + +def _log_ssdp_descriptor_choice(kept: Device, ignored: Device) -> None: + """DEBUG trace of the SSDP descriptor set aside when one host exposes several (e.g. DIAL + tvdevice).""" + if not _SSDP_CHOICE_LOG.isEnabledFor(logging.DEBUG): + return + kept_loc = _ssdp_descriptor_label(kept) + ignored_loc = _ssdp_descriptor_label(ignored) + if kept_loc == ignored_loc: + return + ip = str(kept.ip).strip() + pair = (kept_loc, ignored_loc) + if _last_ssdp_choice_by_ip.get(ip) == pair: + return + _last_ssdp_choice_by_ip[ip] = pair + + def _desc(dev: Device) -> str: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} + return ( + f"LOCATION={_ssdp_descriptor_label(dev)} USN={md.get('usn', '')} " + f"friendlyName={xf.get('friendlyName', '')!r} manufacturer={xf.get('manufacturer', '')!r} " + f"modelName={xf.get('modelName', '')!r} icon={xf.get('iconURL', '')!r} " + f"richness(xml,icon,fields)={_descriptor_richness(dev)}" + ) + + ignored_md = ignored.metadata if isinstance(ignored.metadata, dict) else {} + ignored_xml = ignored_md.get("xml") if isinstance(ignored_md.get("xml"), str) else "" + _SSDP_CHOICE_LOG.debug( + "SSDP descriptor choice for %s\n kept: %s\n ignored: %s\nignored XML:\n%s", + ip, + _desc(kept), + _desc(ignored), + ignored_xml.strip() or "(none: XML not fetched yet)", + ) + + +def build_device_bundles( + devices: list[Device], + information_precedence: Sequence[str], +) -> list[DeviceBundle]: + bundles_by_id: dict[str, DeviceBundle] = {} + host_to_bundle_id: dict[str, str] = {} + order: list[str] = [] + for device in devices: + bundle_id = f"endpoint:{device.ip}:{device.port}" + bundle_keys = device_host_bundle_keys(device) + for key in bundle_keys: + existing = host_to_bundle_id.get(key) + if existing is not None: + bundle_id = existing + break + bundle = bundles_by_id.get(bundle_id) + if bundle is None: + bundle = DeviceBundle(ip=device.ip, port=device.port, primary=device) + bundles_by_id[bundle_id] = bundle + order.append(bundle_id) + + if device.source == "mdns": + bundle.mdns_device = _richer_descriptor_device(bundle.mdns_device, device) + elif device.source == "ssdp": + bundle.ssdp_device = _richer_descriptor_device(bundle.ssdp_device, device) + elif device.source == "wsd": + bundle.wsd_device = device + elif device.source == "wsdd": + bundle.wsdd_device = device + elif device.source == "nmb": + bundle.nmb_device = device + bundle.primary = choose_bundle_primary(bundle, information_precedence) + + _LOG.debug( + "bundle_merge attach source=%s endpoint=%s:%s merge_keys=%s name=%r", + device.source, + device.ip, + device.port, + bundle_keys, + device.name, + ) + + for key in bundle_keys: + host_to_bundle_id[key] = bundle_id + ordered = [bundles_by_id[key] for key in order] + for bundle in ordered: + bundle.ip = bundle.primary.ip + bundle.port = int(bundle.primary.port) + return ordered + + +def bundle_remote_icon_hint(dev: Device | None) -> str: + """Token that changes when a device's remote-icon source appears. + + Captures both attachment (None vs present) and descriptor enrichment: a row first attached + generic (e.g. SSDP fast-emit, XML pending) gains ``iconURL`` only once its descriptor is + parsed. If the fingerprint tracked only ``device is not None``, that late enrichment would not + flip it — so the bundle would not re-render and the remote icon would never be fetched (it + stays the generic type icon). Including the icon URL here closes that gap. + """ + if dev is None: + return "" + md = dev.metadata if isinstance(dev.metadata, dict) else {} + xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} + icon = xf.get("iconURL") or md.get("iconURL") or "" + return f"{1 if xf else 0}:{str(icon).strip()}" + + +def bundle_snapshot_ui_fingerprint(bundles: Sequence[DeviceBundle]) -> tuple: + """Fingerprint of merged bundles (protocol attachment + primary row) for Qt UI refresh.""" + rows: list[tuple] = [] + for b in sorted(bundles, key=lambda x: (str(x.ip), int(x.port or 0), x.primary.key)): + p = b.primary + rows.append( + ( + str(b.ip).strip(), + int(b.port or 0), + p.key, + (p.source or "").strip().lower(), + (p.name or "").strip(), + (p.type or "unknown").strip().lower(), + bool(p.online), + bundle_remote_icon_hint(b.ssdp_device), + bundle_remote_icon_hint(b.mdns_device), + bundle_remote_icon_hint(b.wsd_device), + bundle_remote_icon_hint(b.wsdd_device), + bundle_remote_icon_hint(b.nmb_device), + ) + ) + return tuple(rows) + + +def apply_bundle_category_filter( + bundles: list[DeviceBundle], + filter_key: str | None, + *, + no_location_label: str, +) -> list[DeviceBundle]: + if not filter_key: + return list(bundles) + if isinstance(filter_key, str) and filter_key.startswith("location:"): + location_value = filter_key.split(":", 1)[1] + if location_value == "__none__": + return [ + b for b in bundles if bundle_location_label(b, no_location_label=no_location_label) == no_location_label + ] + return [ + b for b in bundles if bundle_location_label(b, no_location_label=no_location_label) == location_value + ] + cf = filter_key + out: list[DeviceBundle] = [] + for bundle in bundles: + slug = (bundle.primary.type or "unknown").strip().lower() + if slug == cf.strip().lower(): + out.append(bundle) + elif bundle.category == cf: + out.append(bundle) + return out diff --git a/app/utils/device_details_view.py b/app/utils/device_details_view.py new file mode 100644 index 00000000..d359d0b1 --- /dev/null +++ b/app/utils/device_details_view.py @@ -0,0 +1,195 @@ +# File device_details_view.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Build device details view-model from a merged ``DeviceBundle`` (GTK/Qt shared).""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from model.device import Device +from utils.details_payload import ( + build_mdns_payload, + build_ssdp_payload, + build_wsd_family_detail_fields, + collect_link_local_ipv6, + dedupe_last_seen_in_fields, + filter_visible_detail_fields, + format_device_ip_for_details, + format_device_type_for_details, + merge_ssdp_mdns_detail_fields, + strip_detail_fields_covered_by_overview, + with_aggregate_ports_field, +) +from utils.device_bundles import DeviceBundle, bundle_location_label + + +def effective_ssdp_device(bundle: DeviceBundle) -> Device | None: + if bundle.ssdp_device is not None: + return bundle.ssdp_device + mdns = bundle.mdns_device + if mdns is None or not isinstance(mdns.metadata, dict): + return None + mdns_meta = mdns.metadata + xml_fields = mdns_meta.get("xml_fields") + if not isinstance(xml_fields, dict) or not xml_fields: + return None + if not any( + isinstance(xml_fields.get(k), str) and xml_fields.get(k).strip() + for k in ( + "friendlyName", + "deviceType", + "UDN", + "modelName", + "manufacturer", + "services_description", + ) + ): + return None + synth_meta = dict(mdns_meta) + synth_meta["xml_fields"] = dict(xml_fields) + return Device( + name=mdns.name, + ip=mdns.ip, + port=mdns.port, + type=mdns.type, + category=mdns.category, + source="ssdp", + url=mdns.url, + metadata=synth_meta, + last_seen=mdns.last_seen, + online=mdns.online, + monitored=mdns.monitored, + icon=mdns.icon, + ) + + +@dataclass(slots=True) +class DeviceDetailsViewModel: + title: str + overview: dict[str, str] + fields: list[tuple[str, str]] + services_records: list[tuple[str, str, str]] | None = None + mdns_service_sections: list[dict[str, Any]] | None = None + raw_content: str | None = None + raw_xml_location: str | None = None + details_field_rule_map: dict[str, str] = field(default_factory=dict) + endpoint_source: str = "" + endpoint_ip: str = "" + endpoint_port: int = 0 + url_override: str | None = None + custom_command: str | None = None + device_commands: list[dict] | None = None + + +def _metadata_str(devices: list[Device], key: str) -> str | None: + for dev in devices: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + val = md.get(key) + if isinstance(val, str) and val.strip(): + return val.strip() + return None + + +def build_device_details_view_model( + bundle: DeviceBundle, + *, + no_location_label: str, +) -> DeviceDetailsViewModel: + ipv6 = collect_link_local_ipv6( + bundle.wsdd_device, + bundle.wsd_device, + bundle.mdns_device, + effective_ssdp_device(bundle), + bundle.nmb_device, + ) + overview = { + "name": bundle.name or "", + "ip": format_device_ip_for_details(bundle.primary), + "location": bundle_location_label(bundle, no_location_label=no_location_label), + "type": format_device_type_for_details(bundle.primary), + "ipv6_link_local": ipv6 or "", + } + ssdp = effective_ssdp_device(bundle) + mdns = bundle.mdns_device + raw_xml: str | None = None + xml_location: str | None = None + services_list: list[tuple[str, str, str]] | None = None + troubleshooting_fields: list[tuple[str, str]] | None = None + mdns_sections: list[dict[str, Any]] | None = None + details_field_rule_map: dict[str, str] = {} + + if ssdp is not None and mdns is not None: + f_ssdp, raw_xml, services_list, troubleshooting_fields, xml_location = build_ssdp_payload(ssdp) + f_mdns, mdns_sections = build_mdns_payload(mdns) + fields = with_aggregate_ports_field( + merge_ssdp_mdns_detail_fields(f_ssdp, f_mdns), ssdp, mdns + ) + details_field_rule_map = { + "Friendly name": "xml:friendlyName", + "Information": "meta:information", + "Hostname (mDNS)": "meta:hostname", + "Server (mDNS)": "meta:server", + } + elif ssdp is not None: + fields, raw_xml, services_list, troubleshooting_fields, xml_location = build_ssdp_payload(ssdp) + fields = with_aggregate_ports_field(fields, ssdp) + details_field_rule_map = { + "Friendly name": "xml:friendlyName", + "Information": "meta:information", + "Model": "xml:modelName", + "Manufacturer": "xml:manufacturer", + } + elif mdns is not None: + fields, mdns_sections = build_mdns_payload(mdns) + fields = with_aggregate_ports_field(fields, mdns) + details_field_rule_map = { + "Hostname": "meta:hostname", + "Server": "meta:server", + "Information": "meta:information", + } + else: + fields = build_wsd_family_detail_fields( + bundle.wsdd_device, + bundle.wsd_device, + bundle.nmb_device, + ) + details_field_rule_map = {} + + if troubleshooting_fields: + fields.extend(troubleshooting_fields) + + fields = filter_visible_detail_fields( + dedupe_last_seen_in_fields( + strip_detail_fields_covered_by_overview(fields, overview) + ) + ) + + devices = bundle.devices + return DeviceDetailsViewModel( + title=f"{bundle.name}", + overview=overview, + fields=fields, + services_records=services_list, + mdns_service_sections=mdns_sections, + raw_content=raw_xml, + raw_xml_location=xml_location, + details_field_rule_map=details_field_rule_map, + endpoint_source=bundle.primary.source, + endpoint_ip=bundle.primary.ip, + endpoint_port=int(bundle.primary.port), + url_override=_metadata_str(devices, "url_override"), + custom_command=_metadata_str(devices, "custom_command"), + device_commands=_metadata_list_dict(devices, "device_commands"), + ) + + +def _metadata_list_dict(devices: list[Device], key: str) -> list[dict] | None: + for dev in devices: + md = dev.metadata if isinstance(dev.metadata, dict) else {} + cmds = md.get(key) + if isinstance(cmds, list) and cmds: + return [c for c in cmds if isinstance(c, dict)] + return None diff --git a/app/utils/device_remote_icon.py b/app/utils/device_remote_icon.py new file mode 100644 index 00000000..37b2d0b7 --- /dev/null +++ b/app/utils/device_remote_icon.py @@ -0,0 +1,567 @@ +# File device_remote_icon.py for NetNeighbor version 2.0.1 +# Internal version : 2.0.1 date: 2026-05-26 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Device-provided icon URLs and local cache index (shared GTK/Qt, no UI deps).""" + +from __future__ import annotations + +import hashlib +import ipaddress +import json +import os +import ssl +from datetime import datetime, timezone +from pathlib import Path +from urllib.parse import urlparse, urlunparse +from urllib.request import urlopen + +from model.device import Device +from utils.device_bundles import DeviceBundle + + +def _netneighbor_cache_dir() -> Path: + return Path.home() / ".cache" / "netneighbor" + + +_CACHE_BASE = _netneighbor_cache_dir() +_REMOTE_ICON_DISK_DIR = _CACHE_BASE / "remote_icons" +_REMOTE_ICON_INDEX_PATH = _CACHE_BASE / "remote_icon_index.json" +_index_cache: dict[str, dict[str, str]] | None = None + + +def _load_index() -> dict[str, dict[str, str]]: + global _index_cache + if _index_cache is not None: + return _index_cache + out: dict[str, dict[str, str]] = {} + try: + if _REMOTE_ICON_INDEX_PATH.is_file(): + data = json.loads(_REMOTE_ICON_INDEX_PATH.read_text(encoding="utf-8")) + if isinstance(data, dict) and int(data.get("version", 0)) >= 2: + hosts = data.get("hosts") + if isinstance(hosts, dict): + for sip, row in hosts.items(): + if isinstance(sip, str) and isinstance(row, dict): + canon = row.get("canonical_url") + sha = row.get("payload_sha256") + if ( + isinstance(canon, str) + and canon.strip() + and isinstance(sha, str) + and sha.strip() + ): + out[sip.strip()] = { + "canonical_url": canon.strip(), + "payload_sha256": sha.strip(), + } + except (OSError, json.JSONDecodeError, TypeError, ValueError): + pass + _index_cache = out + return out + + +def _normalize_icon_url(ref: str, ip: str, port: int) -> str: + ref = ref.strip() + if ref.startswith(("http://", "https://")): + return rewrite_remote_icon_url_to_device_ip(ref, ip) + try: + p = int(port) if port else 80 + except (TypeError, ValueError): + p = 80 + sip = str(ip).strip() + if not sip or sip in {"0.0.0.0", "::"}: + sip = "127.0.0.1" + base = f"http://{sip}:{p}" + if ref.startswith("/"): + return base + ref + return f"{base}/{ref.lstrip('/')}" + + +_MDNS_ICON_TXT_KEYS = frozenset( + {"representation", "icon", "iconurl", "apple-touch-icon", "favicon"} +) +_MDNS_IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg") + + +_GOOGLECAST_HTTP_PORT = 8008 + + +def _mdns_preferred_icon_base_port(metadata: dict, fallback_port: int) -> int: + """Base port for relative mDNS icon paths. + + - ``_http._tcp`` port when present (Sonos and similar serve icons there). + - Google Cast (``_googlecast._tcp``): TXT ``ic=/setup/icon.png`` is served by the Cast + HTTP server on :8008 (the DIAL ``URLBase``); the advertised :8009 is the TLS Cast + channel and never answers HTTP (verified on Sharp AQUOS Google TV). + """ + if not isinstance(metadata, dict): + return fallback_port + services = metadata.get("services") + if not isinstance(services, list): + services = [] + is_googlecast = "_googlecast._tcp" in str(metadata.get("service", "")).lower() + for svc in services: + if not isinstance(svc, dict): + continue + name = str(svc.get("service", "")).lower() + if "_googlecast._tcp" in name: + is_googlecast = True + if "_http._tcp" not in name: + continue + try: + candidate = int(svc.get("port", 0) or 0) + except (TypeError, ValueError): + continue + if candidate > 0: + return candidate + if is_googlecast: + return _GOOGLECAST_HTTP_PORT + try: + return int(fallback_port) if fallback_port else 80 + except (TypeError, ValueError): + return 80 + + +def _mdns_txt_value_is_image_path(val: str) -> bool: + """True when a TXT value points at a PNG/JPEG (URL or path), as in V1.""" + v = val.strip() + if not v or len(v) > 2048: + return False + lower = v.lower() + path_part = lower.split("?", 1)[0].split("#", 1)[0] + if not any(path_part.endswith(ext) for ext in _MDNS_IMAGE_SUFFIXES): + return False + if lower.startswith(("http://", "https://")): + return True + return "/" in v or v.startswith((".", "\\")) + + +def _mdns_icon_urls(metadata: dict, ip: str, port: int) -> list[str]: + """Collect device icon URLs from mDNS metadata and per-service TXT (GTK / V1 parity).""" + urls: list[str] = [] + seen: set[str] = set() + base_port = _mdns_preferred_icon_base_port(metadata, port) + + def _push(raw_val: str) -> None: + u = _normalize_icon_url(raw_val.strip(), ip, base_port) + if u not in seen: + seen.add(u) + urls.append(u) + + for key in ("icon", "apple-touch-icon", "favicon"): + raw = metadata.get(key) + if isinstance(raw, str) and raw.strip(): + _push(raw) + + def _scan_txt(txt: dict) -> None: + if not isinstance(txt, dict): + return + for key, val in txt.items(): + if not isinstance(val, str) or not val.strip(): + continue + key_l = str(key).strip().lower() + if key_l in _MDNS_ICON_TXT_KEYS or _mdns_txt_value_is_image_path(val): + _push(val) + + services = metadata.get("services") + if isinstance(services, list): + for svc in services: + if not isinstance(svc, dict): + continue + for key in ("icon", "apple-touch-icon"): + raw = svc.get(key) + if isinstance(raw, str) and raw.strip(): + _push(raw) + _scan_txt(svc.get("txt")) + + txt_top = metadata.get("txt") + if isinstance(txt_top, dict): + _scan_txt(txt_top) + + return urls + + +def canonical_remote_icon_url(icon_url: str) -> str: + """Stable cache key: normalized scheme, host, port, path (GTK-compatible).""" + u = icon_url.strip() + try: + p = urlparse(u) + except ValueError: + return u + if not p.scheme or not p.hostname: + return u + scheme = (p.scheme or "").lower() + host_txt = (p.hostname or "").lower().rstrip(".") + port = p.port + + host_literal = host_txt + try: + parsed_ip = ipaddress.ip_address(host_txt) + if isinstance(parsed_ip, ipaddress.IPv6Address): + host_literal = f"[{parsed_ip.compressed}]" + except ValueError: + host_literal = host_txt + + omit_default = (scheme == "http" and port in {None, 80}) or ( + scheme == "https" and port in {None, 443} + ) + if omit_default: + netloc_final = host_literal + elif port is not None: + netloc_final = f"{host_literal}:{port}" + else: + netloc_final = host_literal + + path = p.path.strip() if p.path else "" + if not path: + path = "/" + query = (p.query or "").strip() + return urlunparse((scheme, netloc_final, path, "", query, "")) + + +def _should_rewrite_icon_hostname_to_lan_ip(hostname: str) -> bool: + """Replace any non-literal host with the device IP (avoids mDNS / DNS timeouts).""" + h = (hostname or "").strip().lower().rstrip(".") + if not h: + return False + try: + ipaddress.ip_address(h.strip("[]")) + return False + except ValueError: + return True + + +def rewrite_remote_icon_url_to_device_ip(url: str, ip: str) -> str: + ip_stripped = str(ip).strip() + if not ip_stripped or ip_stripped in {"0.0.0.0", "::"}: + return url.strip() + try: + p = urlparse(url.strip()) + except ValueError: + return url.strip() + if p.scheme.lower() not in {"http", "https"} or not p.netloc: + return url.strip() + host = p.hostname + if not host or not _should_rewrite_icon_hostname_to_lan_ip(host): + return url.strip() + try: + dev_ip = ipaddress.ip_address(ip_stripped) + except ValueError: + return url.strip() + port = p.port + if isinstance(dev_ip, ipaddress.IPv6Address): + netloc = f"[{ip_stripped}]" + if port is not None: + netloc += f":{port}" + else: + netloc = ip_stripped + if port is not None: + netloc += f":{port}" + path = p.path or "/" + return urlunparse((p.scheme.lower(), netloc, path, "", p.query, "")) + + +def remote_icon_digest(icon_url: str) -> str: + return hashlib.sha256(icon_url.encode("utf-8")).hexdigest() + + +def remote_icon_payload_path(cache_key: str) -> Path: + return _REMOTE_ICON_DISK_DIR / f"{remote_icon_digest(cache_key)}.payload" + + +def primary_fetch_pair_for_device(device: Device) -> tuple[str, str] | None: + """Returns ``(fetch_url, disk_cache_key)`` for the preferred device icon.""" + raw = remote_icon_url_for_device(device) + if not isinstance(raw, str) or not raw.strip(): + return None + sip = str(device.ip).strip() + fetch_url = rewrite_remote_icon_url_to_device_ip(raw.strip(), sip).strip() + if not fetch_url: + return None + cache_key = canonical_remote_icon_url(fetch_url) + if not cache_key: + return None + return fetch_url, cache_key + + +def _expand_cached_remote_icon_aliases(canonical_key: str) -> list[str]: + out: list[str] = [] + seen: set[str] = set() + ck = (canonical_key or "").strip() + if not ck: + return out + + def add(u: str) -> None: + if u and u not in seen: + seen.add(u) + out.append(u) + + add(ck) + try: + p = urlparse(ck) + except ValueError: + return out + scheme = (p.scheme or "").lower() + host_txt = (p.hostname or "") + if not host_txt: + return out + port = p.port + path = p.path or "/" + query = p.query or "" + + try: + parsed_ip = ipaddress.ip_address(host_txt.strip("[]")) + if isinstance(parsed_ip, ipaddress.IPv6Address): + host_literal = f"[{parsed_ip.compressed}]" + else: + host_literal = host_txt + except ValueError: + host_literal = host_txt + + def build(netloc_piece: str) -> str: + return urlunparse((scheme, netloc_piece, path, "", query, "")) + + if scheme == "http" and port in {None, 80}: + add(build(f"{host_literal}:80")) + elif scheme == "https" and port in {None, 443}: + add(build(f"{host_literal}:443")) + return out + + +def iter_remote_icon_disk_keys(device: Device) -> list[str]: + keys: list[str] = [] + seen: set[str] = set() + sip = str(device.ip).strip() + + def push_logical_url(candidate: str) -> None: + if not isinstance(candidate, str) or not candidate.strip(): + return + base = canonical_remote_icon_url(candidate.strip()) + for alias in _expand_cached_remote_icon_aliases(base): + if alias not in seen: + seen.add(alias) + keys.append(alias) + + # Keys derive only from the icon URL the device announces *now*. The per-IP index + # is not consulted: DHCP reuses addresses, so an IP-only lookup would hand a + # previous occupant's icon (e.g. a Sonos) to whatever host now holds that IP. + raw = remote_icon_url_for_device(device) + if raw: + push_logical_url(rewrite_remote_icon_url_to_device_ip(raw, sip)) + push_logical_url(raw) + return keys + + +def load_remote_icon_payload_bytes(cache_key: str) -> bytes | None: + path = remote_icon_payload_path(cache_key) + if path.is_file(): + try: + return path.read_bytes() + except OSError: + pass + return None + + +def _rmdir_contents(path: Path) -> None: + """Delete all files and subdirectories inside *path* (keep the directory itself).""" + import shutil + try: + if not path.is_dir(): + return + for item in path.iterdir(): + try: + if item.is_dir(): + shutil.rmtree(item, ignore_errors=True) + else: + item.unlink() + except OSError: + pass + except OSError: + pass + + +def clear_all_app_data() -> None: + """Delete all files in ~/.cache/netneighbor and ~/.config/netneighbor.""" + global _index_cache + _index_cache = None + _rmdir_contents(Path.home() / ".cache" / "netneighbor") + _rmdir_contents(Path.home() / ".config" / "netneighbor") + + +def load_remote_icon_payload_for_device(device: Device) -> bytes | None: + keys = iter_remote_icon_disk_keys(device) + if not keys: + # The device announces no icon URL: never borrow one through its IP. + return None + sip = str(device.ip).strip() + row = _load_index().get(sip) + # Only trust the per-IP index row when it records the URL this device announces. + if row and row.get("canonical_url") in keys: + sha = row.get("payload_sha256") + if isinstance(sha, str) and len(sha) == 64: + sl = sha.lower() + if all(c in "0123456789abcdef" for c in sl): + path = _REMOTE_ICON_DISK_DIR / f"{sl}.payload" + if path.is_file(): + try: + return path.read_bytes() + except OSError: + pass + for key in keys: + data = load_remote_icon_payload_bytes(key) + if data: + return data + return None + + +def save_remote_icon_payload(cache_key: str, data: bytes) -> None: + if not data: + return + path = remote_icon_payload_path(cache_key) + tmp = path.with_name(path.name + ".tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + tmp.write_bytes(data) + os.replace(tmp, path) + except OSError: + try: + if tmp.is_file(): + tmp.unlink() + except OSError: + pass + + +def persist_remote_icon_index_entry(sip: str, canonical_url: str) -> None: + if not sip or not isinstance(canonical_url, str) or not canonical_url.strip(): + return + canon = canonical_remote_icon_url(canonical_url.strip()) + sha = remote_icon_digest(canon) + hosts = dict(_load_index()) + prev = hosts.get(sip.strip()) + if prev and prev.get("canonical_url") == canon and prev.get("payload_sha256") == sha: + return + hosts[sip.strip()] = {"canonical_url": canon, "payload_sha256": sha} + global _index_cache + _index_cache = hosts + try: + _REMOTE_ICON_INDEX_PATH.parent.mkdir(parents=True, exist_ok=True) + blob = { + "version": 2, + "hosts": dict(sorted(hosts.items())), + "updated_at": datetime.now(timezone.utc).isoformat(), + } + tmp = _REMOTE_ICON_INDEX_PATH.with_suffix(".tmp") + tmp.write_text(json.dumps(blob, indent=2, sort_keys=True), encoding="utf-8") + os.replace(tmp, _REMOTE_ICON_INDEX_PATH) + except OSError: + pass + + +def purge_remote_icon_for_ip(ip: str) -> None: + """Remove the cached remote icon for *ip* from both the index and disk.""" + global _index_cache + sip = str(ip).strip() + if not sip or sip in {"0.0.0.0", "::"}: + return + hosts = dict(_load_index()) + row = hosts.pop(sip, None) + if row is None: + return + _index_cache = hosts + try: + _REMOTE_ICON_INDEX_PATH.parent.mkdir(parents=True, exist_ok=True) + blob = { + "version": 2, + "hosts": dict(sorted(hosts.items())), + "updated_at": datetime.now(timezone.utc).isoformat(), + } + tmp = _REMOTE_ICON_INDEX_PATH.with_suffix(".tmp") + tmp.write_text(json.dumps(blob, indent=2, sort_keys=True), encoding="utf-8") + os.replace(tmp, _REMOTE_ICON_INDEX_PATH) + except OSError: + pass + sha = row.get("payload_sha256", "") + if isinstance(sha, str) and sha.strip(): + still_used = any(r.get("payload_sha256") == sha for r in hosts.values()) + if not still_used: + payload_path = _REMOTE_ICON_DISK_DIR / f"{sha}.payload" + try: + payload_path.unlink(missing_ok=True) + except OSError: + pass + + +def urlopen_remote_icon(url: str): + parsed = urlparse(url) + scheme = (parsed.scheme or "").lower() + host = (parsed.hostname or "").lower().rstrip(".") + ctx = None + if scheme == "https": + allow_insecure = host.endswith(".local") or host.endswith(".lan") + if not allow_insecure and host: + try: + allow_insecure = ipaddress.ip_address(host).is_private + except ValueError: + pass + if allow_insecure: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + try: + ctx.set_ciphers("DEFAULT:@SECLEVEL=0") + except ssl.SSLError: + pass + timeout = 4.5 if scheme == "https" else 2.0 + if ctx is not None: + return urlopen(url, timeout=timeout, context=ctx) + return urlopen(url, timeout=timeout) + + +def remote_icon_url_for_device(device: Device) -> str | None: + metadata = device.metadata if isinstance(device.metadata, dict) else {} + if device.source == "ssdp": + xml_fields = metadata.get("xml_fields") + if not isinstance(xml_fields, dict): + return None + icon_url = xml_fields.get("iconURL") + if isinstance(icon_url, str) and icon_url.strip(): + return _normalize_icon_url( + icon_url.strip(), device.ip, device.port or 80 + ) + if device.source == "mdns": + for url in _mdns_icon_urls(metadata, device.ip, device.port): + if url: + return url + return None + + +def bundle_has_device_icon_source(bundle: DeviceBundle) -> bool: + for dev in ( + bundle.ssdp_device, + bundle.wsdd_device, + bundle.wsd_device, + bundle.nmb_device, + bundle.mdns_device, + ): + if dev is None: + continue + if remote_icon_url_for_device(dev): + return True + return False + + +def bundle_provided_icon_display(bundle: DeviceBundle) -> str | None: + for dev in ( + bundle.ssdp_device, + bundle.wsdd_device, + bundle.wsd_device, + bundle.nmb_device, + bundle.mdns_device, + ): + if dev is None: + continue + url = remote_icon_url_for_device(dev) + if url: + return url + return None diff --git a/app/utils/discovery_cache.py b/app/utils/discovery_cache.py new file mode 100644 index 00000000..ceb24ff3 --- /dev/null +++ b/app/utils/discovery_cache.py @@ -0,0 +1,186 @@ +# File discovery_cache.py for NetNeighbor version 2.0.1 +# Internal version : 2.0.1 date: 2026-05-26 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Persistence helpers for volatile discovery cache data.""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +_CACHE_DIR = Path.home() / ".cache" / "netneighbor" +_CACHE_FILE = _CACHE_DIR / "discovery-cache.json" + +# Maximum age of a cache entry before it is purged from disk. +# Must be >= the per-protocol write TTL (ssdp.py: _PROFILE_CACHE_DISK_TTL_SECONDS = 24 h) +# so that entries written by one session are still readable the next day. +CACHE_MAX_AGE_HOURS: int = 48 + + +def _parse_iso(value: str | None) -> datetime | None: + if not isinstance(value, str): + return None + try: + dt = datetime.fromisoformat(value) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt + except ValueError: + return None + + +def _is_stale(updated_at_raw: str | None, threshold: datetime) -> bool: + """Return True if the entry's updated_at is older than *threshold*.""" + dt = _parse_iso(updated_at_raw) + if dt is None: + return False # no parseable timestamp → keep (safer than silently dropping) + return dt < threshold + + +def _purge_stale_section(section: Any, threshold: datetime) -> Any: + """Remove entries with an updated_at older than *threshold* from a cache section dict.""" + if not isinstance(section, dict): + return section + entries = section.get("entries") + if not isinstance(entries, dict): + return section + kept = { + k: v + for k, v in entries.items() + if not (isinstance(v, dict) and _is_stale(v.get("updated_at"), threshold)) + } + if len(kept) == len(entries): + return section + result = dict(section) + result["entries"] = kept + return result + + +def load_discovery_cache() -> dict[str, Any]: + try: + content = _CACHE_FILE.read_text(encoding="utf-8") + data = json.loads(content) + if isinstance(data, dict): + return data + except (OSError, json.JSONDecodeError): + return {} + return {} + + +def save_wsd_device_cache(device_key: str, row: dict[str, Any]) -> None: + """Persist a WSD device row so restarts can pre-populate it immediately.""" + entry = dict(row) + entry["updated_at"] = datetime.now(timezone.utc).isoformat() + save_discovery_cache({"wsd_device_cache": {"entries": {device_key: entry}}}) + + +def save_nmb_name_cache(ip: str, name: str, mac: str | None = None) -> None: + """Persist an NMB/DNS-resolved hostname so restarts can pre-populate it immediately.""" + now = datetime.now(timezone.utc).isoformat() + entry: dict[str, Any] = {"name": name, "updated_at": now} + if mac: + entry["mac"] = mac + save_discovery_cache({"nmb_name_cache": {"entries": {ip: entry}}}) + + +def _host_from_urls(row: dict) -> str | None: + """Extract a hostname/IP from SSDP profile-cache URLs.""" + urls: list[str] = [] + loc = row.get("ssdp_location") + if isinstance(loc, str) and loc.strip(): + urls.append(loc.strip()) + url = row.get("url") + if isinstance(url, str) and url.strip(): + urls.append(url.strip()) + xf = row.get("xml_fields") + if isinstance(xf, dict): + pres = xf.get("presentationURL") + if isinstance(pres, str) and pres.strip(): + urls.append(pres.strip()) + for u in urls: + try: + host = urlparse(u).hostname + except ValueError: + continue + if host: + return str(host).strip() + return None + + +def purge_device_from_discovery_cache(ips: set[str]) -> None: + """Remove all cache entries that belong to any of the given IP addresses.""" + if not ips: + return + try: + existing = load_discovery_cache() + if not existing: + return + changed = False + for section_name, section in existing.items(): + if not isinstance(section, dict): + continue + entries = section.get("entries") + if not isinstance(entries, dict): + continue + to_remove: set[str] = set() + for key, val in entries.items(): + if key in ips: + # nmb_name_cache: key is the IP itself + to_remove.add(key) + elif isinstance(val, dict) and str(val.get("ip", "") or "").strip() in ips: + # wsd_device_cache: key is device key, val has an "ip" field + to_remove.add(key) + elif section_name == "ssdp_profile_cache" and isinstance(val, dict): + # ssdp_profile_cache: keys are UUIDs/USNs; resolve IP from URLs. + host = _host_from_urls(val) + if host and host in ips: + to_remove.add(key) + if to_remove: + for key in to_remove: + del entries[key] + changed = True + if changed: + _CACHE_DIR.mkdir(parents=True, exist_ok=True) + _CACHE_FILE.write_text( + json.dumps(existing, indent=2, sort_keys=True), encoding="utf-8" + ) + except OSError: + return + + +def save_discovery_cache( + cache_data: dict[str, Any], + max_age_hours: int = CACHE_MAX_AGE_HOURS, +) -> None: + """Merge *cache_data* into the on-disk cache and purge entries older than *max_age_hours*.""" + try: + _CACHE_DIR.mkdir(parents=True, exist_ok=True) + existing: dict[str, Any] = {} + try: + if _CACHE_FILE.exists(): + parsed = json.loads(_CACHE_FILE.read_text(encoding="utf-8")) + if isinstance(parsed, dict): + existing = parsed + except (OSError, json.JSONDecodeError): + existing = {} + + merged = dict(existing) + merged.update(cache_data) + + # Purge stale entries from every section that holds an "entries" sub-dict. + # This removes entries that were once written but have not been refreshed + # within the retention window — they survive the merge but should not stay forever. + threshold = datetime.now(timezone.utc) - timedelta(hours=max_age_hours) + for key in list(merged.keys()): + merged[key] = _purge_stale_section(merged[key], threshold) + + _CACHE_FILE.write_text( + json.dumps(merged, indent=2, sort_keys=True), encoding="utf-8" + ) + except OSError: + # Keep UI responsive even if cache path is unavailable. + return diff --git a/app/utils/discovery_config.py b/app/utils/discovery_config.py new file mode 100644 index 00000000..2dc00ab7 --- /dev/null +++ b/app/utils/discovery_config.py @@ -0,0 +1,769 @@ +# File discovery_config.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Load discovery protocol toggles from user config.""" + +from __future__ import annotations + +import copy +import ipaddress +import json +from pathlib import Path +from typing import Any, Sequence + +_ROOT = Path(__file__).resolve().parent.parent +_SHIPPED_DISCOVERY_JSON = _ROOT / "config" / "discovery.json" + +_DEFAULT_STARTUP_REFRESH = [5, 15, 30, 60, 120, 300, 600] + +# mDNS: enumeration and per-service resolution (see discovery/mdns.py). +_DEFAULT_MDNS_QUERY = { + "enumeration_timeout_seconds": 2.5, + "enumeration_interval_seconds": 240, + "service_info_timeout_ms": 2500, +} +# SSDP: periodic M-SEARCH cadence and MX (max wait, seconds) in each M-SEARCH (discovery/ssdp.py). +_DEFAULT_SSDP_QUERY = { + "interval_seconds": 60, + "mx_seconds": 5, + # Minimum seconds between HTTP GETs for descriptor URLs with the same host IP (or same hostname); + # avoids duplicate fetches when anticipatory + SSDP LOCATION arrive close together. 0 = off. + "descriptor_http_min_interval_seconds": 5.0, + # Optional IPv4 list: send unicast M-SEARCH to each :1900 (helps when UDP 1900 is not bound / NOTIFY missed). + "msearch_directed_ips": [], +} +# WSD: WS-Discovery probe interval and per-probe wait (discovery/wsd.py); requires PyPI ``WSDiscovery``. +_DEFAULT_WSD_QUERY = { + "interval_seconds": 90, + "timeout_seconds": 8.0, +} +# NetBIOS: periodic ``nmblookup`` (discovery/netbios.py); requires Samba ``nmblookup`` on PATH. +_DEFAULT_NMB_QUERY = { + "interval_seconds": 60, + "timeout_seconds": 10, + # ``-S`` requests node status so hostnames are real (plain ``*`` only yields ``*<00>`` per IP). + "argv": ["-S", "*"], + # Optional explicit IPs for ``nmblookup -A`` when broadcast browse misses PCs (same subnet). + "directed_ips": [], +} +# wsdd: poll local `wsdd` control socket (``-l``) in discovery mode (``-D``); see ``discovery/wsdd_client.py``. +_DEFAULT_WSDD_QUERY = { + "listen": "", + "interval_seconds": 60.0, + "socket_timeout_seconds": 4.0, + "probe_each_poll": True, +} + +# Cross-protocol ordering for the same host — canonical ladder is ``merge.information_precedence`` +# in discovery.json (verified keys only; must list all roles exactly once to customize order). +# +# Semantics: **first role in the list = strongest** when picking which protocol row drives name/type for a +# bundled host; **last role = weakest** among merge roles. This only affects merge/display, not how fast or +# whether a probe finds a device (discovery “weight” is separate: timeouts, firewalls, ``protocol_order`` ties). +# +# Roles: user_override (prefs), ssdp_live (UPnP), wsdd_live (local wsdd daemon cache), wsd_live (WS-Discovery), +# nmb_live (NetBIOS/nmblookup), ssdp_profile_cache (disk on mDNS), mdns (service inference). +# ``protocol_order``: live protocol ``source`` ids (``ssdp``, ``wsd``, ``nmb``, ``mdns``, …) for UI tie-breaks. +_ALLOWED_MERGE_INFORMATION_ROLES = frozenset( + {"user_override", "ssdp_live", "wsdd_live", "wsd_live", "nmb_live", "ssdp_profile_cache", "mdns"} +) +_LEGACY_INFORMATION_ROLES = frozenset({"user_override", "ssdp_live", "ssdp_profile_cache", "mdns"}) +_LEGACY_WITH_WSD_ONLY = frozenset( + {"user_override", "ssdp_live", "wsd_live", "ssdp_profile_cache", "mdns"} +) +# Saved configs from before ``wsdd_live`` existed (six roles, no ``wsdd_live``). +_LEGACY_MERGE_ROLES_WITHOUT_WSDD_CLIENT = frozenset( + {"user_override", "ssdp_live", "wsd_live", "nmb_live", "ssdp_profile_cache", "mdns"} +) +_DEFAULT_MERGE = { + "protocol_order": ["ssdp", "wsd", "wsdd", "nmb", "mdns"], + # Strongest → weakest for merged list/detail primary row (same machine, several protocols). + "information_precedence": [ + "user_override", + "ssdp_live", + "ssdp_profile_cache", + "mdns", + "nmb_live", + "wsdd_live", + "wsd_live", # weakest merge role by default: generic WSD label loses to SSDP/mDNS/nmb/wsdd above + ], + "show_ip_in_device_list": True, +} + + +def category_for_device_type(device_type: str, fallback: str | None = None) -> str: + """Return the translated category label for a device type slug. + + Single source of truth shared by all discovery modules (manager, mdns, ssdp, wsd). + ``fallback`` is returned when the type is not in the table; defaults to ``"Unknown Devices"``. + """ + return { + "router": _("Routers & Gateways"), + "mediaserver": _("Media Servers"), + "scanner": _("Printers"), + "printer": _("Printers"), + "networkprinter": _("Printers"), + "multifunction_printer": _("Printers"), + "smartspeaker": _("Smart Speakers"), + "smarttv": _("Smart TVs"), + "smartdevice": _("Smart Devices"), + "camera": _("Cameras"), + "homeappliance": _("Home Appliances"), + "cnc": _("CNC Machines"), + "3dprinter": _("3D Printers"), + "nas": _("NAS / File Servers"), + "server": _("Servers"), + "rackserver": _("Servers"), + "desktop": _("Computers"), + "minipc": _("Computers"), + "allinone": _("Computers"), + "laptop": _("Computers"), + "smartphone": _("Phones & Tablets"), + "computer": _("Computers"), + "esp32": _("ESP3D Devices"), + "http": _("Unknown Devices"), + "https": _("Unknown Devices"), + "unknown": _("Unknown Devices"), + }.get(device_type, fallback if fallback is not None else _("Unknown Devices")) + + +def _ensure_nmb_before_wsd(roles: list[str]) -> list[str]: + """Prefer NetBIOS / ``nmblookup`` names (neighborhood) over generic WSD labels for the same host.""" + if "nmb_live" not in roles or "wsd_live" not in roles: + return list(roles) + out = list(roles) + i_wsd = out.index("wsd_live") + i_nmb = out.index("nmb_live") + if i_nmb < i_wsd: + return out + out.remove("nmb_live") + out.insert(i_wsd, "nmb_live") + return out + + +def normalize_information_precedence_list(src: object) -> list[str]: + """Return a validated ``information_precedence`` list or defaults. + + Custom order must list each merge role exactly once; otherwise defaults apply. + Older lists without ``wsd_live`` / ``nmb_live`` are migrated by inserting those roles after + ``ssdp_live`` / ``wsd_live``. + """ + default = list(_DEFAULT_MERGE["information_precedence"]) + if not isinstance(src, list): + return default + cleaned: list[str] = [] + seen: set[str] = set() + for item in src: + if not isinstance(item, str): + continue + s = item.strip().lower() + if s in _ALLOWED_MERGE_INFORMATION_ROLES and s not in seen: + cleaned.append(s) + seen.add(s) + if seen == _ALLOWED_MERGE_INFORMATION_ROLES: + return _ensure_nmb_before_wsd(cleaned) + + if seen == _LEGACY_MERGE_ROLES_WITHOUT_WSDD_CLIENT: + migrated = list(cleaned) + if "wsd_live" in migrated: + migrated.insert(migrated.index("wsd_live"), "wsdd_live") + else: + migrated.append("wsdd_live") + return _ensure_nmb_before_wsd(migrated) + + migrated = list(cleaned) + cur = seen + if cur == _LEGACY_INFORMATION_ROLES: + tmp: list[str] = [] + for role in migrated: + tmp.append(role) + if role == "ssdp_live": + tmp.append("wsd_live") + migrated = tmp + cur = frozenset(migrated) + if cur == _LEGACY_WITH_WSD_ONLY: + tmp = [] + for role in migrated: + tmp.append(role) + if role == "wsd_live": + tmp.append("nmb_live") + migrated = tmp + cur = frozenset(migrated) + if cur == _ALLOWED_MERGE_INFORMATION_ROLES: + return _ensure_nmb_before_wsd(migrated) + return default + + +def information_precedence_rank(order: Sequence[str], role: str) -> int: + """Return index of ``role`` in ``order``. Lower value = stronger merge precedence; last roles are weakest.""" + r = (role or "").strip().lower() + for i, x in enumerate(order): + if str(x).strip().lower() == r: + return i + return len(order) + + +def information_precedence_role_for_device_source(source: str) -> str: + """Map :attr:`~model.device.Device.source` to a merge ``information_precedence`` role.""" + s = (source or "").strip().lower() + if s == "ssdp": + return "ssdp_live" + if s == "wsd": + return "wsd_live" + if s == "wsdd": + return "wsdd_live" + if s == "nmb": + return "nmb_live" + if s == "mdns": + return "mdns" + return s + + +def _default_nested() -> dict[str, Any]: + return { + "mdns": { + "enabled": True, + "rules": True, + "query": dict(_DEFAULT_MDNS_QUERY), + }, + "ssdp": { + "enabled": True, + "rules": True, + "query": dict(_DEFAULT_SSDP_QUERY), + }, + "wsd": { + "enabled": True, + "query": dict(_DEFAULT_WSD_QUERY), + }, + "nmb": { + "enabled": True, + "query": dict(_DEFAULT_NMB_QUERY), + }, + "wsdd": { + "enabled": True, + "query": dict(_DEFAULT_WSDD_QUERY), + }, + "merge": dict(_DEFAULT_MERGE), + "startup_refresh_seconds": list(_DEFAULT_STARTUP_REFRESH), + } + + +def _coerce_bool(value: object, default: bool) -> bool: + if value is None: + return default + if isinstance(value, bool): + return value + if isinstance(value, (int, float)) and not isinstance(value, bool): + return int(value) != 0 + if isinstance(value, str): + v = value.strip().lower() + if v in ("1", "true", "yes", "on"): + return True + if v in ("0", "false", "no", "off", ""): + return False + return default + + +def _parse_startup_refresh(value: object) -> list[int] | None: + if value is None: + return None + if isinstance(value, list): + cleaned: list[int] = [] + for item in value: + try: + delay = int(item) + except (TypeError, ValueError): + continue + if 1 <= delay <= 86400 and delay not in cleaned: + cleaned.append(delay) + return cleaned or None + if isinstance(value, str): + parts = value.replace(",", " ").split() + cleaned = [] + for part in parts: + try: + delay = int(part) + except ValueError: + continue + if 1 <= delay <= 86400 and delay not in cleaned: + cleaned.append(delay) + return cleaned or None + try: + delay = int(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return None + if 1 <= delay <= 86400: + return [delay] + return None + + +def _clamp_int(value: object, default: int, low: int, high: int) -> int: + try: + v = int(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return default + return max(low, min(high, v)) + + +def _clamp_float(value: object, default: float, low: float, high: float) -> float: + try: + v = float(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return default + return max(low, min(high, v)) + + +def _merge_query_into(out_proto: dict[str, Any], parsed_block: object, protocol: str) -> None: + if not isinstance(parsed_block, dict): + return + pq = parsed_block.get("query") + if not isinstance(pq, dict): + return + base_q = out_proto.setdefault("query", {}) + if protocol == "mdns": + if "enumeration_timeout_seconds" in pq: + base_q["enumeration_timeout_seconds"] = _clamp_float( + pq.get("enumeration_timeout_seconds"), + float(_DEFAULT_MDNS_QUERY["enumeration_timeout_seconds"]), + 2.0, + 3.0, + ) + if "enumeration_interval_seconds" in pq: + base_q["enumeration_interval_seconds"] = _clamp_int( + pq.get("enumeration_interval_seconds"), + int(_DEFAULT_MDNS_QUERY["enumeration_interval_seconds"]), + 30, + 86400, + ) + if "service_info_timeout_ms" in pq: + base_q["service_info_timeout_ms"] = _clamp_int( + pq.get("service_info_timeout_ms"), + int(_DEFAULT_MDNS_QUERY["service_info_timeout_ms"]), + 2000, + 3000, + ) + elif protocol == "ssdp": + if "interval_seconds" in pq: + base_q["interval_seconds"] = _clamp_int( + pq.get("interval_seconds"), + int(_DEFAULT_SSDP_QUERY["interval_seconds"]), + 10, + 3600, + ) + if "mx_seconds" in pq: + base_q["mx_seconds"] = _clamp_int( + pq.get("mx_seconds"), + int(_DEFAULT_SSDP_QUERY["mx_seconds"]), + 5, + 6, + ) + if "descriptor_http_min_interval_seconds" in pq: + v = _clamp_float( + pq.get("descriptor_http_min_interval_seconds"), + float(_DEFAULT_SSDP_QUERY["descriptor_http_min_interval_seconds"]), + 0.0, + 120.0, + ) + base_q["descriptor_http_min_interval_seconds"] = v + if "msearch_directed_ips" in pq: + raw_ips = pq.get("msearch_directed_ips") + ips: list[str] = [] + if isinstance(raw_ips, list): + for x in raw_ips: + if not isinstance(x, str) or not x.strip(): + continue + s = x.strip() + try: + addr = ipaddress.ip_address(s) + except ValueError: + continue + if isinstance(addr, ipaddress.IPv4Address): + ips.append(addr.compressed) + base_q["msearch_directed_ips"] = ips + elif protocol == "wsd": + if "interval_seconds" in pq: + base_q["interval_seconds"] = _clamp_float( + pq.get("interval_seconds"), + float(_DEFAULT_WSD_QUERY["interval_seconds"]), + 15.0, + 3600.0, + ) + if "timeout_seconds" in pq: + base_q["timeout_seconds"] = _clamp_float( + pq.get("timeout_seconds"), + float(_DEFAULT_WSD_QUERY["timeout_seconds"]), + 2.0, + 60.0, + ) + elif protocol == "wsdd": + if "interval_seconds" in pq: + base_q["interval_seconds"] = _clamp_float( + pq.get("interval_seconds"), + float(_DEFAULT_WSDD_QUERY["interval_seconds"]), + 15.0, + 3600.0, + ) + if "socket_timeout_seconds" in pq: + base_q["socket_timeout_seconds"] = _clamp_float( + pq.get("socket_timeout_seconds"), + float(_DEFAULT_WSDD_QUERY["socket_timeout_seconds"]), + 1.0, + 60.0, + ) + if "listen" in pq and isinstance(pq.get("listen"), str): + base_q["listen"] = pq.get("listen", "").strip() + if "probe_each_poll" in pq: + base_q["probe_each_poll"] = _coerce_bool(pq.get("probe_each_poll"), bool(_DEFAULT_WSDD_QUERY["probe_each_poll"])) + elif protocol == "nmb": + if "interval_seconds" in pq: + base_q["interval_seconds"] = _clamp_float( + pq.get("interval_seconds"), + float(_DEFAULT_NMB_QUERY["interval_seconds"]), + 60.0, + 3600.0, + ) + if "timeout_seconds" in pq: + base_q["timeout_seconds"] = _clamp_float( + pq.get("timeout_seconds"), + float(_DEFAULT_NMB_QUERY["timeout_seconds"]), + 5.0, + 120.0, + ) + if "argv" in pq and isinstance(pq.get("argv"), list): + av = [str(x) for x in pq["argv"] if isinstance(x, str) and str(x).strip()] + if av: + base_q["argv"] = av + if "directed_ips" in pq and isinstance(pq.get("directed_ips"), list): + ips: list[str] = [] + for x in pq["directed_ips"]: + if isinstance(x, str) and x.strip(): + ips.append(x.strip()) + base_q["directed_ips"] = ips[:64] + + +def _normalize_mdns_block(src: object) -> dict[str, Any]: + out = copy.deepcopy(_default_nested()["mdns"]) + if not isinstance(src, dict): + return out + if "enabled" in src: + out["enabled"] = _coerce_bool(src.get("enabled"), out["enabled"]) + if "rules" in src: + out["rules"] = _coerce_bool(src.get("rules"), out["rules"]) + _merge_query_into(out, src, "mdns") + return out + + +def _normalize_ssdp_block(src: object) -> dict[str, Any]: + out = copy.deepcopy(_default_nested()["ssdp"]) + if not isinstance(src, dict): + return out + if "enabled" in src: + out["enabled"] = _coerce_bool(src.get("enabled"), out["enabled"]) + if "rules" in src: + out["rules"] = _coerce_bool(src.get("rules"), out["rules"]) + _merge_query_into(out, src, "ssdp") + return out + + +def _normalize_wsd_block(src: object) -> dict[str, Any]: + out = copy.deepcopy(_default_nested()["wsd"]) + if not isinstance(src, dict): + return out + if "enabled" in src: + out["enabled"] = _coerce_bool(src.get("enabled"), out["enabled"]) + _merge_query_into(out, src, "wsd") + return out + + +def _normalize_nmb_block(src: object) -> dict[str, Any]: + out = copy.deepcopy(_default_nested()["nmb"]) + if not isinstance(src, dict): + return out + if "enabled" in src: + out["enabled"] = _coerce_bool(src.get("enabled"), out["enabled"]) + _merge_query_into(out, src, "nmb") + q = out.get("query") if isinstance(out.get("query"), dict) else {} + av = q.get("argv") + if isinstance(av, list) and len(av) == 1 and str(av[0]).strip() == "*": + q["argv"] = ["-S", "*"] + return out + + +def _normalize_wsdd_block(src: object) -> dict[str, Any]: + out = copy.deepcopy(_default_nested()["wsdd"]) + if not isinstance(src, dict): + return out + if "enabled" in src: + out["enabled"] = _coerce_bool(src.get("enabled"), out["enabled"]) + _merge_query_into(out, src, "wsdd") + return out + + +def _normalize_startup_refresh(value: object) -> list[int]: + cleaned = _parse_startup_refresh(value) + if cleaned: + return cleaned + return list(_DEFAULT_STARTUP_REFRESH) + + +def _normalize_merge(src: object) -> dict[str, Any]: + out = copy.deepcopy(_DEFAULT_MERGE) + if not isinstance(src, dict): + return out + po = src.get("protocol_order") + if isinstance(po, list): + cleaned: list[str] = [] + seen: set[str] = set() + for item in po: + if not isinstance(item, str): + continue + s = item.strip().lower() + if not s or s in seen: + continue + seen.add(s) + cleaned.append(s) + if cleaned: + out["protocol_order"] = cleaned + out["information_precedence"] = normalize_information_precedence_list(src.get("information_precedence")) + if "show_ip_in_device_list" in src: + out["show_ip_in_device_list"] = _coerce_bool(src.get("show_ip_in_device_list"), bool(out.get("show_ip_in_device_list", True))) + return out + + +def _disk_repr(cfg: dict[str, Any]) -> dict[str, Any]: + """Human-friendly JSON: booleans as true/false, startup as comma-separated string at root.""" + mdns = cfg.get("mdns") if isinstance(cfg.get("mdns"), dict) else {} + ssdp = cfg.get("ssdp") if isinstance(cfg.get("ssdp"), dict) else {} + wsd = cfg.get("wsd") if isinstance(cfg.get("wsd"), dict) else {} + nmb = cfg.get("nmb") if isinstance(cfg.get("nmb"), dict) else {} + wsdd = cfg.get("wsdd") if isinstance(cfg.get("wsdd"), dict) else {} + mq = mdns.get("query") if isinstance(mdns.get("query"), dict) else {} + sq = ssdp.get("query") if isinstance(ssdp.get("query"), dict) else {} + wq = wsd.get("query") if isinstance(wsd.get("query"), dict) else {} + nq = nmb.get("query") if isinstance(nmb.get("query"), dict) else {} + wx = wsdd.get("query") if isinstance(wsdd.get("query"), dict) else {} + merge = cfg.get("merge") if isinstance(cfg.get("merge"), dict) else {} + po = merge.get("protocol_order") if isinstance(merge.get("protocol_order"), list) else _DEFAULT_MERGE["protocol_order"] + protocol_order_out = [str(x).strip().lower() for x in po if isinstance(x, str) and str(x).strip()] + ip_out = normalize_information_precedence_list(merge.get("information_precedence")) + show_ip = bool(merge.get("show_ip_in_device_list", True)) + delays = cfg.get("startup_refresh_seconds") + if not isinstance(delays, list): + delays = list(_DEFAULT_STARTUP_REFRESH) + startup_str = ", ".join(str(int(x)) for x in delays) + out: dict[str, Any] = { + "mdns": { + "enabled": bool(mdns.get("enabled", True)), + "rules": bool(mdns.get("rules", True)), + "query": { + "enumeration_timeout_seconds": float( + mq.get("enumeration_timeout_seconds", _DEFAULT_MDNS_QUERY["enumeration_timeout_seconds"]) + ), + "enumeration_interval_seconds": int( + mq.get("enumeration_interval_seconds", _DEFAULT_MDNS_QUERY["enumeration_interval_seconds"]) + ), + "service_info_timeout_ms": int( + mq.get("service_info_timeout_ms", _DEFAULT_MDNS_QUERY["service_info_timeout_ms"]) + ), + }, + }, + "ssdp": { + "enabled": bool(ssdp.get("enabled", True)), + "rules": bool(ssdp.get("rules", True)), + "query": { + "interval_seconds": int(sq.get("interval_seconds", _DEFAULT_SSDP_QUERY["interval_seconds"])), + "mx_seconds": int(sq.get("mx_seconds", _DEFAULT_SSDP_QUERY["mx_seconds"])), + "descriptor_http_min_interval_seconds": float( + sq.get( + "descriptor_http_min_interval_seconds", + _DEFAULT_SSDP_QUERY["descriptor_http_min_interval_seconds"], + ) + ), + "msearch_directed_ips": list( + sq.get("msearch_directed_ips", _DEFAULT_SSDP_QUERY["msearch_directed_ips"]) + or [] + ), + }, + }, + "wsd": { + "enabled": bool(wsd.get("enabled", True)), + "query": { + "interval_seconds": float(wq.get("interval_seconds", _DEFAULT_WSD_QUERY["interval_seconds"])), + "timeout_seconds": float(wq.get("timeout_seconds", _DEFAULT_WSD_QUERY["timeout_seconds"])), + }, + }, + "nmb": { + "enabled": bool(nmb.get("enabled", True)), + "query": { + "interval_seconds": float( + nq.get("interval_seconds", _DEFAULT_NMB_QUERY["interval_seconds"]) + ), + "timeout_seconds": float( + nq.get("timeout_seconds", _DEFAULT_NMB_QUERY["timeout_seconds"]) + ), + **( + {"argv": list(nq["argv"])} + if isinstance(nq.get("argv"), list) and nq.get("argv") + else {} + ), + **( + {"directed_ips": [str(x).strip() for x in nq["directed_ips"] if str(x).strip()]} + if isinstance(nq.get("directed_ips"), list) and nq.get("directed_ips") + else {} + ), + }, + }, + "wsdd": { + "enabled": bool(wsdd.get("enabled", False)), + "query": { + "listen": str(wx.get("listen", _DEFAULT_WSDD_QUERY["listen"]) or "").strip(), + "interval_seconds": float(wx.get("interval_seconds", _DEFAULT_WSDD_QUERY["interval_seconds"])), + "socket_timeout_seconds": float( + wx.get("socket_timeout_seconds", _DEFAULT_WSDD_QUERY["socket_timeout_seconds"]) + ), + "probe_each_poll": bool(wx.get("probe_each_poll", _DEFAULT_WSDD_QUERY["probe_each_poll"])), + }, + }, + "merge": { + "protocol_order": protocol_order_out or list(_DEFAULT_MERGE["protocol_order"]), + "information_precedence": ip_out, + "show_ip_in_device_list": show_ip, + }, + "startup_refresh_seconds": startup_str, + } + return out + + +def _normalize_discovery_document(parsed: dict[str, Any]) -> dict[str, Any]: + return { + "mdns": _normalize_mdns_block(parsed.get("mdns")), + "ssdp": _normalize_ssdp_block(parsed.get("ssdp")), + "wsd": _normalize_wsd_block(parsed.get("wsd")), + "nmb": _normalize_nmb_block(parsed.get("nmb")), + "wsdd": _normalize_wsdd_block(parsed.get("wsdd")), + "merge": _normalize_merge(parsed.get("merge")), + "startup_refresh_seconds": _normalize_startup_refresh(parsed.get("startup_refresh_seconds")), + } + + +def load_discovery_protocol_config() -> dict[str, object]: + """Return discovery settings from ~/.config/netneighbor/discovery.json. + + Shipped defaults live in ``config/discovery.json`` and are copied on first run when the user file + is missing. Expected shape: top-level ``mdns`` / ``ssdp`` / ``wsd`` objects (``wsd`` has ``enabled`` + and optional ``query``: ``interval_seconds``, ``timeout_seconds``), optional ``merge.protocol_order`` + (ordered ``source`` ids: ``ssdp``, ``wsd``, ``mdns``, …), optional ``merge.information_precedence`` + (roles ``user_override``, ``ssdp_live``, ``wsd_live``, ``ssdp_profile_cache``, ``mdns``), and root + ``startup_refresh_seconds``. Use ``"mdns": { "enabled": false }`` to disable mDNS (SSDP-only + experiments); file lives at ``~/.config/netneighbor/discovery.json`` (under the user home on + all OS, e.g. ``%USERPROFILE%/.config/netneighbor/discovery.json`` on Windows). Malformed or missing file + yields defaults; defaults are written only when the file does not exist. + + The default ``merge.information_precedence`` places ``user_override`` first (strongest); the manager + applies user type/name/location prefs after composing discovery rows so they override protocol hints. + """ + cfg_dir = Path.home() / ".config" / "netneighbor" + cfg_path = cfg_dir / "discovery.json" + defaults = _default_nested() + try: + cfg_dir.mkdir(parents=True, exist_ok=True) + if not cfg_path.exists(): + if _SHIPPED_DISCOVERY_JSON.is_file(): + shipped_text = _SHIPPED_DISCOVERY_JSON.read_text(encoding="utf-8") + cfg_path.write_text( + shipped_text if shipped_text.endswith("\n") else shipped_text + "\n", + encoding="utf-8", + ) + parsed_raw = json.loads(shipped_text) + else: + cfg_path.write_text(json.dumps(_disk_repr(defaults), indent=2, sort_keys=True) + "\n", encoding="utf-8") + return copy.deepcopy(defaults) + if not isinstance(parsed_raw, dict): + return copy.deepcopy(defaults) + return _normalize_discovery_document(parsed_raw) + + parsed_raw = json.loads(cfg_path.read_text(encoding="utf-8")) + if not isinstance(parsed_raw, dict): + return copy.deepcopy(defaults) + + return _normalize_discovery_document(parsed_raw) + except (OSError, json.JSONDecodeError): + return copy.deepcopy(defaults) + + +def discovery_manager_kwargs(proto_cfg: dict[str, object]) -> dict[str, object]: + """Build keyword arguments for ``discovery.manager.DiscoveryManager`` from merged protocol config.""" + mdns_cfg = proto_cfg.get("mdns") + ssdp_cfg = proto_cfg.get("ssdp") + wsd_cfg = proto_cfg.get("wsd") + nmb_cfg = proto_cfg.get("nmb") + wsdd_cfg = proto_cfg.get("wsdd") + if not isinstance(mdns_cfg, dict): + mdns_cfg = {} + if not isinstance(ssdp_cfg, dict): + ssdp_cfg = {} + if not isinstance(wsd_cfg, dict): + wsd_cfg = {} + if not isinstance(nmb_cfg, dict): + nmb_cfg = {} + if not isinstance(wsdd_cfg, dict): + wsdd_cfg = {} + mdns_q = mdns_cfg.get("query") if isinstance(mdns_cfg.get("query"), dict) else {} + ssdp_q = ssdp_cfg.get("query") if isinstance(ssdp_cfg.get("query"), dict) else {} + wsd_q = wsd_cfg.get("query") if isinstance(wsd_cfg.get("query"), dict) else {} + nmb_q = nmb_cfg.get("query") if isinstance(nmb_cfg.get("query"), dict) else {} + wx_q = wsdd_cfg.get("query") if isinstance(wsdd_cfg.get("query"), dict) else {} + merge_cfg = proto_cfg.get("merge") if isinstance(proto_cfg.get("merge"), dict) else {} + protocol_order = merge_cfg.get("protocol_order") + order_list: list[str] | None = None + if isinstance(protocol_order, list) and protocol_order: + order_list = [str(x).strip().lower() for x in protocol_order if isinstance(x, str) and str(x).strip()] + order_list = list(dict.fromkeys(order_list)) + ipc = merge_cfg.get("information_precedence") + information_precedence = normalize_information_precedence_list(ipc if isinstance(ipc, list) else None) + wsdd_listen = wx_q.get("listen") if isinstance(wx_q.get("listen"), str) else "" + wsdd_listen = str(wsdd_listen).strip() + enable_wsdd_socket = bool(wsdd_cfg.get("enabled", False)) and bool(wsdd_listen) + + ssdp_msearch_directed_ips: list[str] = [] + raw_directed = ssdp_q.get("msearch_directed_ips") + if isinstance(raw_directed, list): + for x in raw_directed: + if not isinstance(x, str) or not x.strip(): + continue + try: + addr = ipaddress.ip_address(x.strip()) + except ValueError: + continue + if isinstance(addr, ipaddress.IPv4Address): + ssdp_msearch_directed_ips.append(addr.compressed) + + return { + "enable_ssdp": bool(ssdp_cfg.get("enabled", True)), + "enable_mdns": bool(mdns_cfg.get("enabled", True)), + "enable_ssdp_rules": bool(ssdp_cfg.get("rules", True)), + "enable_mdns_rules": bool(mdns_cfg.get("rules", True)), + "ssdp_query_interval_seconds": ssdp_q.get("interval_seconds"), + "ssdp_mx_seconds": ssdp_q.get("mx_seconds"), + "ssdp_descriptor_http_min_interval_seconds": ssdp_q.get("descriptor_http_min_interval_seconds"), + "ssdp_msearch_directed_ips": ssdp_msearch_directed_ips, + "mdns_enumeration_timeout_seconds": mdns_q.get("enumeration_timeout_seconds"), + "mdns_enumeration_interval_seconds": mdns_q.get("enumeration_interval_seconds"), + "mdns_service_info_timeout_ms": mdns_q.get("service_info_timeout_ms"), + "enable_wsd": bool(wsd_cfg.get("enabled", True)), + "wsd_interval_seconds": wsd_q.get("interval_seconds"), + "wsd_timeout_seconds": wsd_q.get("timeout_seconds"), + "enable_wsdd_socket": enable_wsdd_socket, + "wsdd_listen": wsdd_listen or None, + "wsdd_interval_seconds": wx_q.get("interval_seconds"), + "wsdd_socket_timeout_seconds": wx_q.get("socket_timeout_seconds"), + "wsdd_probe_each_poll": bool(wx_q.get("probe_each_poll", True)), + "enable_nmb": bool(nmb_cfg.get("enabled", True)), + "nmb_interval_seconds": nmb_q.get("interval_seconds"), + "nmb_timeout_seconds": nmb_q.get("timeout_seconds"), + "nmb_argv": nmb_q.get("argv") if isinstance(nmb_q.get("argv"), list) else None, + "nmb_directed_ips": nmb_q.get("directed_ips") if isinstance(nmb_q.get("directed_ips"), list) else None, + "protocol_merge_order": order_list, + "information_precedence": information_precedence, + } diff --git a/app/utils/discovery_identity.py b/app/utils/discovery_identity.py new file mode 100644 index 00000000..c161989c --- /dev/null +++ b/app/utils/discovery_identity.py @@ -0,0 +1,89 @@ +# File discovery_identity.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Shared identity hints for cross-protocol device matching (bundle keys, merge).""" + +from __future__ import annotations + +import ipaddress +import re + +_UUID_IN_TEXT = re.compile( + r"(?:urn:uuid:|uuid:)?([0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12})", + re.IGNORECASE, +) +# Sonos advertises ZonePlayer / MediaServer / MediaRenderer as separate USN suffixes on one speaker. +_RINCON_MONITORED_UID = re.compile( + r"^(uuid:rincon_[0-9a-f]+)(?:_mr|_ms)$", + re.IGNORECASE, +) + + +def uuid_urn_if_present(text: str) -> str: + """Return ``urn:uuid:…`` (lowercase) if a UUID appears in WSD EPR, wsdd URI, USN, etc.""" + if not isinstance(text, str) or not text.strip(): + return "" + m = _UUID_IN_TEXT.search(text.strip()) + if not m: + return "" + return f"urn:uuid:{m.group(1).lower()}" + + +def upnp_identity_from_usn(usn: str) -> str: + """Stable UPnP row id for bundle merge: USN prefix before ``::`` only. + + Scanning the **full** USN with :func:`uuid_urn_if_present` wrongly picks embedded schema UUIDs + (e.g. ``00000000-0000-1000-8000-00805f9b34fb``) that are **identical** on many ZonePlayers, + collapsing different speakers into one bundle so the UI IP label flips as rows overwrite. + """ + if not isinstance(usn, str) or not usn.strip(): + return "" + head = usn.strip().split("::", 1)[0].strip() + if not head: + return "" + u = uuid_urn_if_present(head) + if u: + return u + return head.lower() + + +def normalize_monitored_uid(uid: str) -> str: + """One follow/monitor identity per physical Sonos (strip ``_MR`` / ``_MS`` service USNs).""" + if not isinstance(uid, str) or not uid.strip(): + return "" + u = uid.strip().lower() + m = _RINCON_MONITORED_UID.match(u) + if m: + return m.group(1) + return u + + +def normalize_monitored_name(name: str) -> str: + """Display-name token for follow prefs (skip IPs and placeholder labels).""" + if not isinstance(name, str) or not name.strip(): + return "" + collapsed = " ".join(name.strip().split()).lower() + if not collapsed or collapsed in {"unknown", "wsd host"}: + return "" + try: + ipaddress.ip_address(collapsed.strip("[]")) + return "" + except ValueError: + pass + if collapsed.startswith("mdns device "): + return "" + return collapsed + + +def upnp_identity_from_udn(udn: str) -> str: + """Same rule as :func:`upnp_identity_from_usn` for device ``UDN`` fields (may embed ``::``).""" + if not isinstance(udn, str) or not udn.strip(): + return "" + head = udn.strip().split("::", 1)[0].strip() + if not head: + return "" + u = uuid_urn_if_present(head) + if u: + return u + return head.lower() diff --git a/app/utils/double_click_open.py b/app/utils/double_click_open.py new file mode 100644 index 00000000..de021188 --- /dev/null +++ b/app/utils/double_click_open.py @@ -0,0 +1,463 @@ +# File double_click_open.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Resolve LAN « Open » targets for double-click / Open menu (HTTP(S) from URLs and mDNS, then SMB → …).""" + +from __future__ import annotations + +import ipaddress +import logging +from urllib.parse import urlparse + +from model.device import Device + +_LOG = logging.getLogger(__name__) + +# DNS-SD / mDNS service type substrings (after normalization, lowercase). +_HTTPS = ("_https._tcp",) +_HTTP = ("_http._tcp",) +_SMB = ("_smb._tcp", "_microsoft-ds._tcp") +_FTP = ("_ftp._tcp",) +_SSH = ("_ssh._tcp",) +_TELNET = ("_telnet._tcp",) +_SPOTIFY = ("_spotify-connect._tcp",) + +# Double-click priority order. Spotify comes last: it only wins the double-click when the +# device has nothing else to open (a Sonos with no web UI, a phone or PC running Spotify). +_DCLICK_SCHEME_ORDER = ("http", "smb", "ssh", "ftp", "sftp", "telnet", "spotify") + +# Spotify Connect is not a LAN endpoint: the detected target just opens the local Spotify app +# (or the web player, see the ``localspotify:`` launch template) and the user picks the speaker. +_SPOTIFY_URI = "spotify:" + +_SCHEME_LABELS: dict[str, str] = { + "https": "HTTPS", + "http": "HTTP", + "smb": "SMB", + "ftp": "FTP", + "ssh": "SSH", + "sftp": "SFTP", + "telnet": "Telnet", + "spotify": "Spotify", +} + +_SCHEME_DEFAULT_PORTS: dict[str, int] = { + "http": 80, "https": 443, "smb": 445, "ftp": 21, + "ssh": 22, "sftp": 22, "telnet": 23, +} + + +def _split_zone(bundle_ip: str) -> tuple[str, str | None]: + ip = (bundle_ip or "").strip() + if "%" not in ip: + return ip, None + base, zone = ip.split("%", 1) + return base.strip() or ip, zone.strip() or None + + +def format_host_for_uri(bundle_ip: str, _devices: list[Device]) -> str: + """Format IP or hostname for smb://, ftp://, ssh://, etc.""" + ip, _zone = _split_zone(bundle_ip) + try: + addr = ipaddress.ip_address(ip.split("%", 1)[0]) + except ValueError: + return ip + if isinstance(addr, ipaddress.IPv6Address): + return f"[{addr.compressed}]" + return addr.exploded + + +def _first_url_with_scheme(devices: list[Device], scheme: str) -> str | None: + low = scheme.lower() + for dev in devices: + raw = getattr(dev, "url", None) + if not isinstance(raw, str) or not raw.strip(): + continue + u = raw.strip() + if urlparse(u).scheme.lower() == low: + return u + return None + + +def _collect_https_http_urls(devices: list[Device]) -> tuple[list[str], list[str]]: + https_u: list[str] = [] + http_u: list[str] = [] + for dev in devices: + # WSD/wsdd URLs are protocol endpoints (port 5357), not web interfaces. + if (getattr(dev, "source", "") or "").strip().lower() in {"wsd", "wsdd"}: + continue + raw = getattr(dev, "url", None) + if not isinstance(raw, str) or not raw.strip(): + continue + u = raw.strip() + scheme = urlparse(u).scheme.lower() + if scheme == "https": + https_u.append(u) + elif scheme == "http": + http_u.append(u) + return https_u, http_u + + +def _url_override_from_devices(devices: list[Device]) -> str | None: + for dev in devices: + md = getattr(dev, "metadata", None) + if isinstance(md, dict): + v = md.get("url_override") + if isinstance(v, str) and v.strip(): + return v.strip() + return None + + +def _device_commands_from_devices(devices: list[Device]) -> list[dict]: + """Return per-device command list from metadata (first device that has one).""" + for dev in devices: + md = getattr(dev, "metadata", None) + if isinstance(md, dict): + cmds = md.get("device_commands") + if isinstance(cmds, list) and cmds: + return cmds + return [] + + +def _expand_command_placeholders( + scheme: str, + template: str, + ep_port: int, + host: str, + devices: list[Device], + services: list[dict], +) -> str | None: + """Expand ``{url} {ip} {port} {name} {type} {category}`` in a device_commands field. + + ``{url}`` is the auto-detected URI for *scheme* (port + path), or one built from the + host and port when nothing was detected. The result is a full URI when it contains + ``://``; otherwise ``scheme://`` is prepended (``{ip}:8080/admin`` → ``http://…``). + """ + detected = _detected_uri_for_scheme(scheme, devices, services, host) or "" + det_port = urlparse(detected).port if detected else None + default_port = _SCHEME_DEFAULT_PORTS.get(scheme, 0) + port = ep_port or det_port or default_port + if not detected: + detected = f"{scheme}://{host}" if not port or port == default_port else f"{scheme}://{host}:{port}" + if scheme in ("http", "https", "smb", "ftp"): + detected += "/" + primary = devices[0] if devices else None + values = { + "{url}": detected, + "{ip_raw}": host, + "{ip}": host, + "{port}": str(port) if port else "", + "{name}": str(getattr(primary, "name", "") or ""), + "{type}": str(getattr(primary, "type", "") or ""), + "{category}": str(getattr(primary, "category", "") or ""), + } + out = template + for k, v in values.items(): + out = out.replace(k, v) + out = out.strip() + if not out or any(c.isspace() for c in out): + _LOG.debug("device command %r is not a host/URL template → ignored", template) + return None + if "://" in out: + return out + if ep_port and urlparse(f"{scheme}://{out}").port is None: + head, sep, tail = out.partition("/") + out = f"{head}:{ep_port}{sep}{tail}" + return f"{scheme}://{out}" + + +def _build_uri_from_command( + scheme: str, + cmd: dict, + fallback_ip: str, + devices: list[Device] | None = None, + services: list[dict] | None = None, +) -> str | None: + """Build a URI for *scheme* from a device_commands entry. + + The IP/Host field may be a bare host, or a template using placeholders + (``{url}``, ``http://{ip}:8080/admin``, ``{ip}/setup``…). + """ + ep_ip = str(cmd.get("ip", "")).strip() + ep_port = int(cmd.get("port", 0) or 0) + if "{" in ep_ip and "}" in ep_ip: + return _expand_command_placeholders( + scheme, ep_ip, ep_port, fallback_ip, devices or [], services or [] + ) + eff_ip = ep_ip if ep_ip else fallback_ip + if not eff_ip: + return None + default_port = _SCHEME_DEFAULT_PORTS.get(scheme, 0) + if ":" in eff_ip and not eff_ip.startswith("["): + eff_ip = f"[{eff_ip}]" + if scheme in ("http", "https", "smb", "ftp"): + if ep_port and ep_port != default_port: + return f"{scheme}://{eff_ip}:{ep_port}/" + return f"{scheme}://{eff_ip}/" + elif scheme in ("ssh", "sftp"): + if ep_port and ep_port != default_port: + return f"{scheme}://{eff_ip}:{ep_port}" + return f"{scheme}://{eff_ip}" + elif scheme == "telnet": + if ep_port and ep_port != default_port: + return f"telnet://{eff_ip}:{ep_port}" + return f"telnet://{eff_ip}" + if ep_port: + return f"{scheme}://{eff_ip}:{ep_port}" + return f"{scheme}://{eff_ip}" + + +def _merged_mdns_services(devices: list[Device]) -> list[dict]: + seen_keys: set[str] = set() + result: list[dict] = [] + for dev in devices: + if getattr(dev, "source", None) != "mdns": + continue + md = getattr(dev, "metadata", None) + if not isinstance(md, dict): + continue + svcs = md.get("services") + if not isinstance(svcs, list): + continue + for s in svcs: + if not isinstance(s, dict): + continue + key = str(s.get("service", "")).lower() + if key and key not in seen_keys: + seen_keys.add(key) + result.append(s) + return result + + +def _service_match(services: list[dict], needles: tuple[str, ...]) -> dict | None: + for svc in services: + name = str(svc.get("service", "")).lower() + if any(n in name for n in needles): + return svc + return None + + +def _port(svc: dict | None, default: int) -> int: + if svc is None: + return default + p = int(svc.get("port", 0) or 0) + return p if p > 0 else default + + +def mdns_http_path(txt: object) -> str: + """Web path from a DNS-SD ``_http._tcp`` / ``_https._tcp`` TXT ``path=`` key (RFC 6763 convention). + + Returns ``"/"`` when absent or unusable; always starts with ``/``. + """ + if not isinstance(txt, dict): + return "/" + raw = "" + for k, v in txt.items(): + if str(k).strip().lower() == "path": + raw = v.strip() if isinstance(v, str) else str(v or "").strip() + break + if not raw or "://" in raw or any(c.isspace() for c in raw): + return "/" + return raw if raw.startswith("/") else f"/{raw}" + + +def _mdns_http_url(svc: dict | None, *, https: bool, host: str) -> str | None: + if svc is None: + return None + default = 443 if https else 80 + p = _port(svc, default) + scheme = "https" if https else "http" + path = mdns_http_path(svc.get("txt")) + if p == default: + return f"{scheme}://{host}{path}" + return f"{scheme}://{host}:{p}{path}" + + +def _disabled_schemes(device_cmds: list[dict]) -> frozenset[str]: + """Schemes whose auto-detected entry the user hid (``mode: disabled``).""" + return frozenset( + str(c.get("scheme", "")).strip().lower() + for c in device_cmds + if isinstance(c, dict) and str(c.get("mode", "")).strip().lower() == "disabled" + ) + + +_MDNS_NEEDLES = { + "http": _HTTP, "https": _HTTPS, + "smb": _SMB, "ftp": _FTP, "ssh": _SSH, "telnet": _TELNET, + "spotify": _SPOTIFY, +} + + +def _detected_uri_for_scheme( + scheme: str, + devices: list[Device], + services: list[dict], + host: str, +) -> str | None: + """Return the auto-discovered URI for *scheme*, or None.""" + if scheme == "spotify": + return _SPOTIFY_URI if _service_match(services, _SPOTIFY) is not None else None + if scheme in ("http", "https"): + https_u, http_u = _collect_https_http_urls(devices) + if scheme == "https" and https_u: + return https_u[0] + if scheme == "http" and http_u: + return http_u[0] + needles = _MDNS_NEEDLES.get(scheme) + if needles: + svc = _service_match(services, needles) + return _mdns_http_url(svc, https=(scheme == "https"), host=host) + return None + + found = _first_url_with_scheme(devices, scheme) + if found: + return found + + needles = _MDNS_NEEDLES.get(scheme) + if needles: + svc = _service_match(services, needles) + if svc is not None: + dp = _SCHEME_DEFAULT_PORTS.get(scheme, 0) + p = _port(svc, dp) + if scheme in ("smb", "ftp"): + return f"{scheme}://{host}/" if p == dp else f"{scheme}://{host}:{p}/" + else: + return f"{scheme}://{host}" if p == dp else f"{scheme}://{host}:{p}" + return None + + +def _command_label(scheme: str, cmd: dict) -> str: + """Human-readable label for a device_commands entry.""" + base = _SCHEME_LABELS.get(scheme, scheme.upper()) + lbl = str(cmd.get("label", "")).strip() + mode = str(cmd.get("mode", "override")).strip().lower() + if lbl: + return f"{base} ({lbl})" + if mode == "override": + return f"{base} (override)" + return base + + +def resolve_connect_target( + *, + bundle_ip: str, + primary_type: str, + devices: list[Device], +) -> str | None: + """ + Return the best URI for double-click, following the priority: + http → smb → ssh → ftp → sftp → telnet → spotify + For each scheme: override > detected default > first additional. + Falls back to legacy url_override, then computer→smb heuristic. + """ + if not devices: + return None + + # Legacy url_override takes absolute priority (backward compat) + url_override = _url_override_from_devices(devices) + if url_override: + return url_override + + host = format_host_for_uri(bundle_ip, devices) + services = _merged_mdns_services(devices) + device_cmds = _device_commands_from_devices(devices) + disabled = _disabled_schemes(device_cmds) + + for scheme in _DCLICK_SCHEME_ORDER: + # 1. Override for this scheme + override = next( + (c for c in device_cmds if c.get("scheme") == scheme and c.get("mode") == "override"), + None, + ) + if override is not None: + u = _build_uri_from_command(scheme, override, host, devices, services) + if u: + return u + + # 2. Auto-detected default (unless the user disabled it for this device) + detected = ( + None if scheme in disabled + else _detected_uri_for_scheme(scheme, devices, services, host) + ) + if detected: + _LOG.debug("resolve_connect: detected scheme=%s uri=%s", scheme, detected) + return detected + + # 3. First additional for this scheme + additional = next( + (c for c in device_cmds if c.get("scheme") == scheme and c.get("mode") == "additional"), + None, + ) + if additional is not None: + u = _build_uri_from_command(scheme, additional, host, devices, services) + if u: + return u + + _LOG.debug("resolve_connect: no target found for ip=%s type=%s", bundle_ip, primary_type) + return None + + +def resolve_all_connect_targets( + *, + bundle_ip: str, + primary_type: str, + devices: list[Device], +) -> list[tuple[str, str]]: + """Return ALL available connection targets as (label, uri) pairs, in priority order. + + Label format: + - Auto-detected: "HTTP", "SMB", … + - Override entry: "HTTP (override)" or "HTTP (label)" if labelled + - Additional: "SSH (Admin)", "HTTP (Caméra 2)", … + """ + if not devices: + return [] + + result: list[tuple[str, str]] = [] + seen_uris: set[str] = set() + host = format_host_for_uri(bundle_ip, devices) + services = _merged_mdns_services(devices) + device_cmds = _device_commands_from_devices(devices) + disabled = _disabled_schemes(device_cmds) + + def _add(label: str, uri: str) -> None: + if uri and uri not in seen_uris: + seen_uris.add(uri) + result.append((label, uri)) + + # Legacy url_override (backward compat, shown as HTTP override) + url_override = _url_override_from_devices(devices) + if url_override: + from urllib.parse import urlparse as _up + s = _up(url_override).scheme.lower() + _add(f"{_SCHEME_LABELS.get(s, s.upper())} (override)", url_override) + + for scheme in _DCLICK_SCHEME_ORDER: + base = _SCHEME_LABELS.get(scheme, scheme.upper()) + + # Override entry + override = next( + (c for c in device_cmds if c.get("scheme") == scheme and c.get("mode") == "override"), + None, + ) + if override is not None: + u = _build_uri_from_command(scheme, override, host, devices, services) + if u: + _add(_command_label(scheme, override), u) + + # Auto-detected (hidden when the user disabled it for this device) + if scheme not in disabled: + detected = _detected_uri_for_scheme(scheme, devices, services, host) + if detected: + _add(base, detected) + + # All additionals for this scheme + for cmd in device_cmds: + if cmd.get("scheme") == scheme and cmd.get("mode") == "additional": + u = _build_uri_from_command(scheme, cmd, host, devices, services) + if u: + _add(_command_label(scheme, cmd), u) + + return result diff --git a/app/utils/icon_attribution.py b/app/utils/icon_attribution.py new file mode 100644 index 00000000..7d7d1883 --- /dev/null +++ b/app/utils/icon_attribution.py @@ -0,0 +1,21 @@ +# File icon_attribution.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Short attribution lines for device icons (About dialogs).""" + +from __future__ import annotations + +ICON_CREDIT_LINES_EN: tuple[str, ...] = ( + "Device-type icons: bundled under assets/icons/netneighbor; per-device overrides in ~/.config/netneighbor/custom_icons/.", +) + + +def icon_credit_lines_for_ui() -> tuple[str, ...]: + """Bullet lines for About dialogs (GTK Credits / Qt About body).""" + return ICON_CREDIT_LINES_EN + + +def icon_credits_paragraph() -> str: + """Single paragraph for Qt ``QMessageBox.about`` or similar.""" + return "\n".join(ICON_CREDIT_LINES_EN) diff --git a/app/utils/icon_packs.py b/app/utils/icon_packs.py new file mode 100644 index 00000000..63b0499e --- /dev/null +++ b/app/utils/icon_packs.py @@ -0,0 +1,246 @@ +# File icon_packs.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Icon pack discovery and resolution. + +User-installed packs live in ``~/.config/netneighbor_icon_packs/{pack_id}/``, +a directory intentionally outside ``~/.config/netneighbor/`` so that +*Reset all application data* does not wipe them. + +Each pack directory may optionally contain ``iconpack.json`` and ``preview.png``. +Icons are stored under ``{N}x{N}/`` **or** flat ``{N}/`` sub-directories so both +naming conventions are supported. +""" + +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass, field +from pathlib import Path + +_LOG = logging.getLogger("utils.icon_packs") + +BUILTIN_PACK_ID = "builtin" + +# Module-level cache — call invalidate_icon_pack_cache() after saving prefs. +_active_pack_id_cache: str | None = None + + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- + +def user_icon_packs_dir() -> Path: + """``~/.config/netneighbor_icon_packs`` — survives *Reset all application data*.""" + return Path.home() / ".config" / "netneighbor_icon_packs" + + +def _builtin_pack_root() -> Path: + return Path(__file__).resolve().parent.parent / "assets" / "icons" / "netneighbor" + + +def _assets_dir() -> Path: + return Path(__file__).resolve().parent.parent / "assets" + + +# --------------------------------------------------------------------------- +# Data model +# --------------------------------------------------------------------------- + +@dataclass +class IconPackInfo: + pack_id: str + name: str + owner: str = "" + version: str = "" + date: str = "" + resolutions: str = "" + repository: str = "" + license: str = "" + root: Path = field(default_factory=Path) + preview_path: Path | None = None + + +# --------------------------------------------------------------------------- +# Size helpers (supports both {N}x{N}/ and flat {N}/ naming) +# --------------------------------------------------------------------------- + +def scan_pack_sizes(pack_root: Path) -> tuple[int, ...]: + """Sorted distinct icon sizes available in ``pack_root``. + + Supports both ``{N}x{N}/`` and flat ``{N}/`` directory naming. + """ + sizes: set[int] = set() + try: + for p in pack_root.iterdir(): + if not p.is_dir(): + continue + name = p.name + if "x" in name: + a, _, b = name.partition("x") + if a.isdigit() and b.isdigit() and a == b: + n = int(a) + if 1 <= n <= 4096: + sizes.add(n) + elif name.isdigit(): + n = int(name) + if 1 <= n <= 4096: + sizes.add(n) + except OSError: + pass + return tuple(sorted(sizes)) + + +def find_icon_in_pack(pack_root: Path, sz: int, stem: str) -> Path | None: + """Return path to ``{stem}.png`` at size ``sz`` in ``pack_root``, or ``None``. + + Checks ``{N}x{N}/`` first, then flat ``{N}/``. + """ + for dir_name in (f"{sz}x{sz}", str(sz)): + p = pack_root / dir_name / f"{stem}.png" + if p.is_file(): + return p + return None + + +# --------------------------------------------------------------------------- +# Pack discovery +# --------------------------------------------------------------------------- + +def _find_meta_file(directory: Path) -> Path | None: + """Return ``iconpack.json`` in ``directory`` if it exists, else ``None``.""" + p = directory / "iconpack.json" + return p if p.is_file() else None + + +def _parse_meta_text(text: str) -> dict | None: + """Parse JSON or Python-dict-literal metadata (single-quote files are accepted).""" + try: + result = json.loads(text) + if isinstance(result, dict): + return result + except Exception: + pass + try: + import ast + result = ast.literal_eval(text.strip()) + if isinstance(result, dict): + return result + except Exception: + pass + return None + + +def _load_pack_meta(meta_path: Path, pack_id: str, root: Path) -> IconPackInfo | None: + try: + raw = _parse_meta_text(meta_path.read_text(encoding="utf-8")) + except Exception: + return None + if raw is None: + return None + name = str(raw.get("name", pack_id)).strip() or pack_id + return IconPackInfo( + pack_id=pack_id, + name=name, + owner=str(raw.get("owner", "")), + version=str(raw.get("version", "")), + date=str(raw.get("date", "")), + resolutions=str(raw.get("resolutions", "")), + repository=str(raw.get("repository", "")), + license=str(raw.get("license", "")), + root=root, + ) + + +def load_available_packs() -> list[IconPackInfo]: + """Return all available icon packs: built-in first, then user-installed (sorted by name).""" + packs: list[IconPackInfo] = [] + + # Built-in pack + assets = _assets_dir() + builtin_root = _builtin_pack_root() + meta_path = _find_meta_file(assets) + if meta_path is not None: + info = _load_pack_meta(meta_path, BUILTIN_PACK_ID, builtin_root) + if info is not None: + # Preview: check pack root first, then assets/ + for preview_candidate in (builtin_root / "preview.png", assets / "iconpack_preview.png"): + if preview_candidate.is_file(): + info.preview_path = preview_candidate + break + packs.append(info) + if not packs: + from gettext import gettext as _ + packs.append(IconPackInfo( + pack_id=BUILTIN_PACK_ID, + name=_("NetNeighbor (built-in)"), + root=builtin_root, + )) + + # User-installed packs (iconpack.json is optional) + udir = user_icon_packs_dir() + if udir.is_dir(): + user_packs: list[IconPackInfo] = [] + try: + for subdir in sorted(udir.iterdir()): + if not subdir.is_dir(): + continue + meta = _find_meta_file(subdir) + if meta is not None: + info = _load_pack_meta(meta, subdir.name, subdir) + if info is None: + continue + else: + info = IconPackInfo(pack_id=subdir.name, name=subdir.name, root=subdir) + preview = subdir / "preview.png" + info.preview_path = preview if preview.is_file() else None + user_packs.append(info) + except OSError: + pass + user_packs.sort(key=lambda p: p.name.lower()) + packs.extend(user_packs) + + return packs + + +# --------------------------------------------------------------------------- +# Active pack resolution (cached) +# --------------------------------------------------------------------------- + +def active_icon_pack_id() -> str: + """Active icon pack ID from ``ui_prefs.json`` (cached). + + Call :func:`invalidate_icon_pack_cache` after saving a new value to prefs. + """ + global _active_pack_id_cache + if _active_pack_id_cache is not None: + return _active_pack_id_cache + try: + from utils.ui_prefs import load_ui_preferences + prefs = load_ui_preferences() + val = prefs.get("icon_pack", BUILTIN_PACK_ID) + result = str(val).strip() if isinstance(val, str) and val.strip() else BUILTIN_PACK_ID + except Exception: + result = BUILTIN_PACK_ID + _active_pack_id_cache = result + return result + + +def invalidate_icon_pack_cache() -> None: + """Invalidate the cached active pack ID (call after saving prefs).""" + global _active_pack_id_cache + _active_pack_id_cache = None + + +def active_icon_pack_root() -> Path: + """Root directory for the active icon pack (falls back to built-in if not found).""" + pack_id = active_icon_pack_id() + if not pack_id or pack_id == BUILTIN_PACK_ID: + return _builtin_pack_root() + candidate = user_icon_packs_dir() / pack_id + if candidate.is_dir(): + return candidate + _LOG.warning("Icon pack '%s' not found, falling back to built-in", pack_id) + return _builtin_pack_root() diff --git a/app/utils/icon_view_prefs.py b/app/utils/icon_view_prefs.py new file mode 100644 index 00000000..39f7d409 --- /dev/null +++ b/app/utils/icon_view_prefs.py @@ -0,0 +1,38 @@ +# File icon_view_prefs.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Icon grid size presets (Explorer-like) for the Qt UI.""" + +from __future__ import annotations + +from PySide6.QtCore import QSize + +# Logical preset keys stored in ``ui_prefs.json`` under ``icon_size_preset``. +# Values are the **logical** side length (px at 100 % UI scaling) used for ``QListWidget`` icon +# cells. ``QIcon`` pixmaps are chosen to match ``setIconSize`` (bundled multi-resolution pack). +ICON_SIZE_PRESET_PIXELS: dict[str, int] = { + "small": 16, + "medium": 48, + "large": 96, + "xlarge": 256, +} + +DEFAULT_ICON_SIZE_PRESET = "medium" + +# Reference edge length for device-provided icons and bundled pickers (medium preset). +DEVICE_ICON_REFERENCE_PX = ICON_SIZE_PRESET_PIXELS[DEFAULT_ICON_SIZE_PRESET] + + +def normalize_icon_size_preset(raw: object) -> str: + if isinstance(raw, str) and raw in ICON_SIZE_PRESET_PIXELS: + return raw + return DEFAULT_ICON_SIZE_PRESET + + +def icon_size_preset_to_qsize(preset: str) -> QSize: + px = ICON_SIZE_PRESET_PIXELS.get( + normalize_icon_size_preset(preset), + ICON_SIZE_PRESET_PIXELS[DEFAULT_ICON_SIZE_PRESET], + ) + return QSize(px, px) diff --git a/app/utils/local_host.py b/app/utils/local_host.py new file mode 100644 index 00000000..e391ad01 --- /dev/null +++ b/app/utils/local_host.py @@ -0,0 +1,145 @@ +# File local_host.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-07-18 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Local machine addresses: enumerate them and rank candidate IPs for multi-homed hosts. + +The machine running NetNeighbor is a special discovery case (see docs/reference/MDNS.md, +"Multi-homed hosts and the local machine"): + +- A Windows host commonly holds several IPv4 addresses at once — the real LAN NIC (DHCP), + VirtualBox / Hyper-V host-only switches (192.168.56.1, ...), and APIPA 169.254.x + fallbacks on disconnected adapters. mDNS advertises ALL of them in one service record, + and zeroconf's address ordering is not stable between resolutions. +- Windows never answers WSD probes sent from the machine itself (verified empirically: + fdrespub running, Private profile — remote hosts respond, the local stack does not), + and NetBIOS browsing does not return the local host either. So the only rows the app + ever sees for its own machine are incidental mDNS adverts (e.g. Spotify's + _spotify-connect._tcp) that carry no "computer" identity. + +Hence the two helpers here: pick one stable routable address out of a multi-address +record, and recognise "this IP belongs to the machine NetNeighbor runs on". +""" + +from __future__ import annotations + +import ipaddress +import socket +import threading +import time + +# Host-only / hypervisor switch subnets: real neighbours never live there, and the +# addresses only exist on the machines hosting the hypervisor. Shared with SSDP +# multicast interface selection (ssdp.py). +VIRTUAL_HOST_SUBNETS: tuple[ipaddress.IPv4Network, ...] = ( + ipaddress.ip_network("192.168.56.0/24"), # VirtualBox host-only + ipaddress.ip_network("192.168.53.0/24"), # common Hyper-V / third-party virtual NIC + ipaddress.ip_network("192.168.122.0/24"), # libvirt virbr0 + ipaddress.ip_network("192.168.137.0/24"), # Windows ICS / hotspot host +) + +_LOCAL_IP_CACHE_TTL_S = 60.0 +_local_ip_cache: tuple[float, frozenset[str]] | None = None +_local_ip_lock = threading.Lock() + + +def address_preference_rank(ip_s: str) -> int: + """Lower is better. Routable LAN IPv4 first, virtual-switch IPv4 next, then routable + IPv6, then link-local (APIPA / fe80), loopback and garbage last.""" + try: + addr = ipaddress.ip_address(str(ip_s).strip().strip("[]")) + except ValueError: + return 9 + if addr.is_loopback or addr.is_multicast or addr.is_unspecified: + return 8 + if isinstance(addr, ipaddress.IPv4Address): + if addr.is_link_local: + return 4 + if any(addr in net for net in VIRTUAL_HOST_SUBNETS): + return 1 + return 0 + if addr.is_link_local: + return 5 + return 2 + + +def choose_best_address(addresses: list[str]) -> str: + """Deterministic best address from a (possibly reordered) mDNS address list. + + zeroconf returns a host's A/AAAA records in unstable order; taking the first entry + makes the same host flap between its LAN, virtual-switch and APIPA addresses across + resolutions — each flap materialising as a distinct device row. Ranking + a full + sort keeps the choice identical for any permutation of the same address set. + """ + candidates: list[tuple[int, bytes, str]] = [] + for value in addresses: + text = str(value).strip() + if not text: + continue + rank = address_preference_rank(text) + if rank >= 8: + continue + try: + sort_key = ipaddress.ip_address(text.strip("[]")).packed + except ValueError: + sort_key = text.encode() + candidates.append((rank, sort_key, text)) + if not candidates: + return "" + candidates.sort(key=lambda item: (item[0], item[1])) + return candidates[0][2] + + +def local_ip_addresses() -> frozenset[str]: + """This machine's non-loopback IP addresses (cached; DHCP renewals refresh within a minute).""" + global _local_ip_cache + now = time.monotonic() + with _local_ip_lock: + if _local_ip_cache is not None and now - _local_ip_cache[0] <= _LOCAL_IP_CACHE_TTL_S: + return _local_ip_cache[1] + found: set[str] = set() + try: + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.connect(("203.0.113.1", 9)) + ip = probe.getsockname()[0] + if ip: + found.add(ip) + finally: + probe.close() + except OSError: + pass + try: + for res in socket.getaddrinfo(socket.gethostname(), None, proto=socket.IPPROTO_TCP): + ip = str(res[4][0]).split("%", 1)[0] + if ip: + found.add(ip) + except OSError: + pass + normalized: set[str] = set() + for ip in found: + try: + addr = ipaddress.ip_address(ip) + except ValueError: + continue + if addr.is_loopback or addr.is_unspecified: + continue + normalized.add(addr.compressed) + result = frozenset(normalized) + with _local_ip_lock: + _local_ip_cache = (now, result) + return result + + +def is_local_host_ip(ip_s: str) -> bool: + """True when this IP belongs to the machine NetNeighbor is running on.""" + text = str(ip_s).strip().strip("[]") + if not text: + return False + try: + addr = ipaddress.ip_address(text) + except ValueError: + return False + if addr.is_loopback: + return True + return addr.compressed in local_ip_addresses() diff --git a/app/utils/location_label.py b/app/utils/location_label.py new file mode 100644 index 00000000..34ffc9e9 --- /dev/null +++ b/app/utils/location_label.py @@ -0,0 +1,55 @@ +# File location_label.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Room / location labels: reject mistaken SSDP LOCATION or UPnP descriptor URLs.""" + + +def is_plausible_room_location(value: str | None) -> bool: + if not isinstance(value, str): + return False + s = value.strip() + if not s: + return False + low = s.lower() + if low.startswith(("http://", "https://")): + return False + if "description.xml" in low: + return False + if "://" in s: + return False + return True + + +def normalize_location_options(options: list[str]) -> list[str]: + """Drop empty/invalid entries and case-insensitive duplicates. + + Keeps insertion order while preferring the earliest value, so + user-configured options are never replaced by later (discovered) ones. + Translations are deliberately NOT handled: "office" and "bureau" are two + distinct locations and both stay in the list. + """ + normalized: list[str] = [] + seen: set[str] = set() + for raw in options: + value = str(raw).strip() if isinstance(raw, str) else "" + if not value or not is_plausible_room_location(value): + continue + key = value.casefold() + if key in seen: + continue + seen.add(key) + normalized.append(value) + return normalized + + +def location_options_with_current(options: list[str], current: str | None) -> list[str]: + """Return *options* plus the device's current location label.""" + result = list(options) + value = current.strip() if isinstance(current, str) else "" + if not value or not is_plausible_room_location(value): + return result + if any(value.casefold() == opt.casefold() for opt in result): + return result + result.append(value) + return result diff --git a/app/utils/macos_activation.py b/app/utils/macos_activation.py new file mode 100644 index 00000000..d4f3b226 --- /dev/null +++ b/app/utils/macos_activation.py @@ -0,0 +1,21 @@ +# File macos_activation.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-24 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""macOS NSApplication activation-policy helpers — stubs only. + +Dynamic policy switching (Accessory ↔ Regular) was tested but found to +interfere with QSystemTrayIcon availability on macOS 11 Big Sur when called +before the system tray is initialised. These are no-ops until a reliable +sequencing solution is found. +""" + +from __future__ import annotations + + +def set_policy_regular() -> None: + pass + + +def set_policy_accessory() -> None: + pass diff --git a/app/utils/mdns_rules.py b/app/utils/mdns_rules.py new file mode 100644 index 00000000..d7123ac6 --- /dev/null +++ b/app/utils/mdns_rules.py @@ -0,0 +1,192 @@ +# File mdns_rules.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Load configurable mDNS heuristic rules (`config/mdns_rules.json`).""" + +from __future__ import annotations + +import json +import logging +import re +from functools import lru_cache +from pathlib import Path + +from utils.user_config_overlay import merge_mdns_rules_overlays + +_LOG = logging.getLogger(__name__) +_RULES_PATH = Path(__file__).resolve().parent.parent / "config" / "mdns_rules.json" + + +# The bundled config/mdns_rules.json is the single source of truth for the rules. This empty +# skeleton is only a graceful degraded fallback if that file is missing/corrupt — startup runs +# utils.config_integrity, which shows a "corrupted installation" dialog in that case, so the +# fallback below should never be reached in a healthy install. +_EMPTY_RULES: dict = {"summary_from_txt": [], "type_rules": []} + + +def _normalized_rule_dict(raw: object) -> dict: + """Coerce a payload into a well-formed rules dict (missing keys filled with empty lists).""" + if isinstance(raw, dict): + merged = dict(_EMPTY_RULES) + merged.update(raw) + if not isinstance(merged.get("summary_from_txt"), list): + merged["summary_from_txt"] = [] + if not isinstance(merged.get("type_rules"), list): + merged["type_rules"] = [] + return merged + return dict(_EMPTY_RULES) + + +def load_mdns_rules() -> dict: + """Return rules from config/mdns_rules.json (single source); user overlay merged from ~/.config. + + A missing/corrupt bundled file degrades to empty rules — startup integrity check surfaces the + "corrupted installation" message to the user (see utils.config_integrity). + """ + try: + data = json.loads(_RULES_PATH.read_text(encoding="utf-8")) + except FileNotFoundError: + _LOG.warning("mDNS rules file missing at %s — degraded (no rules)", _RULES_PATH) + data = dict(_EMPTY_RULES) + except (json.JSONDecodeError, OSError) as exc: + _LOG.warning("Invalid mDNS rules file %s: %s — degraded (no rules)", _RULES_PATH, exc) + data = dict(_EMPTY_RULES) + merged = merge_mdns_rules_overlays(_normalized_rule_dict(data)) + return _normalized_rule_dict(merged) + + +@lru_cache(maxsize=1) +def cached_mdns_rules() -> dict: + """Rules loaded once per process (edit file + restart app to pick up changes).""" + return load_mdns_rules() + + +def reload_mdns_rules_for_tests() -> None: + cached_mdns_rules.cache_clear() + + +def summary_field_labels_norm(rules: dict | None = None) -> frozenset[str]: + """Normalized detail labels emitted from summary_from_txt (for SSDP+mDNS merge).""" + r = rules if isinstance(rules, dict) else cached_mdns_rules() + norms: list[str] = [] + seq = r.get("summary_from_txt") or [] + if isinstance(seq, list): + for row in seq: + if isinstance(row, dict): + lbl = row.get("label") + if isinstance(lbl, str) and lbl.strip(): + norms.append(lbl.strip().lower()) + return frozenset(norms) + + +def _norm_txt_key_lookup(key: str) -> str: + return str(key).strip().lower() + + +def collect_first_txt_field(metadata: dict, key_candidates: list[str]) -> str: + """First non-empty value across top-level TXT and each service TXT, keyed by aliases (case-insensitive).""" + + lookup_order: list[str] = [] + seen: set[str] = set() + for k in key_candidates: + nk = _norm_txt_key_lookup(k) + if nk not in seen: + seen.add(nk) + lookup_order.append(nk) + + def _consume_txt_dict(txt_blob: dict) -> str | None: + if not isinstance(txt_blob, dict): + return None + for lk in lookup_order: + for kk, vv in txt_blob.items(): + if _norm_txt_key_lookup(kk) != lk: + continue + s = vv.strip() if isinstance(vv, str) else str(vv).strip() + if s: + return s + return None + + txt_top = metadata.get("txt") + got = _consume_txt_dict(txt_top) if isinstance(txt_top, dict) else None + if got: + return got + + services = metadata.get("services") + if isinstance(services, list): + for svc in services: + if not isinstance(svc, dict): + continue + stxt = svc.get("txt") + got_inner = _consume_txt_dict(stxt) if isinstance(stxt, dict) else None + if got_inner: + return got_inner + return "" + + +def summary_rows_from_rules(metadata: dict, rules: dict | None = None) -> list[tuple[str, str]]: + """Produce (detail label, raw value) rows for the first-tab mDNS summary from rules.""" + r = rules if isinstance(rules, dict) else cached_mdns_rules() + rows: list[tuple[str, str]] = [] + seq = r.get("summary_from_txt") or [] + if not isinstance(seq, list): + return rows + for row in seq: + if not isinstance(row, dict): + continue + label = row.get("label") + keys_raw = row.get("keys") + if not isinstance(label, str) or not label.strip(): + continue + keys: list[str] = [] + if isinstance(keys_raw, list): + for k in keys_raw: + if isinstance(k, str) and k.strip(): + keys.append(k.strip()) + if not keys: + continue + value = collect_first_txt_field(metadata, keys) + if value: + rows.append((label.strip(), value)) + return rows + + +@lru_cache(maxsize=256) +def _compiled_rule_pattern(pattern: str) -> re.Pattern[str] | None: + try: + return re.compile(pattern) + except re.error as exc: + _LOG.warning("Invalid mDNS rule regex %r: %s — ignored", pattern, exc) + return None + + +def evaluate_type_rules(haystack_lower: str, current_type: str, rules: dict | None = None) -> str: + """Evaluate type_rules in order (first match wins); haystack already lowercased. + + A rule matches when any ``contains_any`` substring or any ``matches_any`` regular + expression (``re.search``, written in lowercase) is found in the haystack. + """ + r = rules if isinstance(rules, dict) else cached_mdns_rules() + seq = r.get("type_rules") or [] + if not isinstance(seq, list): + return current_type + for entry in seq: + if not isinstance(entry, dict): + continue + target = entry.get("type") + if not isinstance(target, str) or not target.strip(): + continue + needles = entry.get("contains_any") + if isinstance(needles, list): + lowered_needles = [str(n).lower() for n in needles if isinstance(n, str) and str(n).strip()] + if any(n in haystack_lower for n in lowered_needles): + return target.strip().lower() + patterns = entry.get("matches_any") + if isinstance(patterns, list): + for p in patterns: + if not isinstance(p, str) or not p.strip(): + continue + rx = _compiled_rule_pattern(p) + if rx is not None and rx.search(haystack_lower): + return target.strip().lower() + return current_type diff --git a/app/utils/neighbor_mac.py b/app/utils/neighbor_mac.py new file mode 100644 index 00000000..c815e15c --- /dev/null +++ b/app/utils/neighbor_mac.py @@ -0,0 +1,623 @@ +# File neighbor_mac.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Resolve MAC from kernel neighbor caches (ARP / IPv6 ND) — no privileged probe. + +Reads ``/proc/net/arp`` and ``ip neigh show``. Entries appear after recent LAN traffic; +this does not send new packets (no ping / gratuitous ARP). +""" + +from __future__ import annotations + +import ipaddress +import logging +import re +import subprocess +import sys +import threading +from collections.abc import Callable +from pathlib import Path + +_LOG = logging.getLogger(__name__) + +# Neighbour tables are read for every device on every list rebuild, from the UI thread and +# from several worker threads (ping, NetBIOS, discovery). Each table is therefore cached +# and refreshed *single-flight*: one refresh at a time, concurrent callers wait for it and +# reuse its result. Without the lock, every caller that saw an expired cache spawned its +# own ``arp -a`` — on Windows that piled up hundreds of hidden arp.exe/conhost.exe and +# exhausted the desktop heap. +_TABLE_TTL_S = 2.0 + + +class _SingleFlightCache: + def __init__(self, loader: Callable[[], object], ttl_s: float = _TABLE_TTL_S) -> None: + self._loader = loader + self._ttl_s = ttl_s + self._lock = threading.Lock() + self._stamp = 0.0 + self._value: object = None + + def get(self): + with self._lock: + now = _monotonic() + if self._value is not None and now - self._stamp < self._ttl_s: + return self._value + try: + value = self._loader() + except Exception: # never let a failed refresh re-trigger on every call + _LOG.debug("neighbour table refresh failed", exc_info=True) + value = None + # Cache failures too (as an empty table) so a broken tool is not re-run per call. + self._value = value if value is not None else "" + self._stamp = _monotonic() + return self._value + +# macOS ``arp -an`` line: ``? (192.168.1.1) at aa:bb:cc:dd:ee:ff on en0 ...`` +_DARWIN_ARP_RE = re.compile( + r"\(([^)]+)\)\s+at\s+([0-9a-fA-F]{1,2}(?::[0-9a-fA-F]{1,2}){5})\b" +) + +_LLADDR_RE = re.compile(r"\blladdr\s+([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})\b") + + +def _monotonic() -> float: + try: + import time + + return time.monotonic() + except Exception: + return 0.0 + + +def _load_proc_arp_text() -> str: + try: + return Path("/proc/net/arp").read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + + +_PROC_ARP_CACHE = _SingleFlightCache(_load_proc_arp_text) + + +def _read_proc_arp_text_cached() -> str: + return _PROC_ARP_CACHE.get() + + +_NEIGH_FULL_CACHE = _SingleFlightCache(lambda: _run_ip_neigh(["neigh", "show"])) + + +def _ip_neigh_show_all_cached() -> str: + return _NEIGH_FULL_CACHE.get() + + +def _norm_mac(s: str) -> str | None: + t = (s or "").strip().lower() + if t.count("-") == 5 and ":" not in t: + t = t.replace("-", ":") + if len(t) == 17 and t.count(":") == 5: + parts = t.split(":") + if all(len(p) == 2 and all(c in "0123456789abcdef" for c in p) for p in parts): + return ":".join(parts) + return None + + +def _ip_matches(neighbor_col: str, want_raw: str) -> bool: + na = neighbor_col.split("%", 1)[0].strip() + wb = want_raw.split("%", 1)[0].strip() + try: + return ipaddress.ip_address(na) == ipaddress.ip_address(wb) + except ValueError: + return na == wb + + +def _mac_from_proc_arp(ipv4: str) -> str | None: + text = _read_proc_arp_text_cached() + if not text: + return None + target = ipv4.strip() + for line in text.splitlines()[1:]: + parts = line.split() + if len(parts) < 4: + continue + if parts[0] != target: + continue + hw = parts[3] + if hw == "00:00:00:00:00:00": + continue + m = _norm_mac(hw) + if m: + return m + return None + + +def _parse_ip_neigh_stdout(stdout: str, want_ip: str) -> str | None: + want_ip = want_ip.strip() + if not want_ip: + return None + for line in stdout.splitlines(): + line = line.strip() + if not line: + continue + parts = line.split() + if not parts: + continue + if not _ip_matches(parts[0], want_ip): + continue + mo = _LLADDR_RE.search(line) + if mo: + got = _norm_mac(mo.group(1)) + if got: + return got + return None + + +def _run_ip_neigh(args: list[str]) -> str: + if sys.platform == "win32" or sys.platform == "darwin": + return "" + try: + proc = subprocess.run( + ["ip", *args], + capture_output=True, + text=True, + timeout=3, + ) + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as e: + _LOG.debug("ip neigh failed: %s", e) + return "" + if proc.returncode != 0: + return "" + return proc.stdout or "" + + +def _load_win_arp_text() -> str: + """Fallback only: ``arp -a`` (used when the native neighbour API is unavailable).""" + _cflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) + try: + proc = subprocess.run( + ["arp", "-a"], + capture_output=True, + text=True, + timeout=4, + encoding="utf-8", + errors="replace", + creationflags=_cflags, + ) + text = proc.stdout or "" if proc.returncode == 0 else "" + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as e: + _LOG.debug("arp -a failed: %s", e) + text = "" + return text + + +_WIN_ARP_TEXT_CACHE = _SingleFlightCache(_load_win_arp_text) + + +def _win_arp_table_cached() -> str: + return _WIN_ARP_TEXT_CACHE.get() + + +def _load_win_ipv6_neigh_text() -> str: + """Fallback only: ``netsh interface ipv6 show neighbors``.""" + _cflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) + try: + proc = subprocess.run( + ["netsh", "interface", "ipv6", "show", "neighbors"], + capture_output=True, + text=True, + timeout=5, + encoding="utf-8", + errors="replace", + creationflags=_cflags, + ) + text = proc.stdout or "" if proc.returncode == 0 else "" + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as e: + _LOG.debug("netsh ipv6 neigh failed: %s", e) + text = "" + return text + + +_WIN_IPV6_TEXT_CACHE = _SingleFlightCache(_load_win_ipv6_neigh_text) + + +def _win_ipv6_neigh_cached() -> str: + return _WIN_IPV6_TEXT_CACHE.get() + + +def _load_win_native_neighbors() -> dict[str, str] | None: + """Read the IPv4+IPv6 neighbour table via ``GetIpNetTable2`` — no child process. + + Returns ``{ip_text: mac}`` (IPv6 without zone), or None when the API is unavailable + so callers fall back to ``arp -a`` / ``netsh``. + """ + if sys.platform != "win32": + return None + import ctypes + from ctypes import wintypes + + class _SockaddrInet(ctypes.Structure): # SOCKADDR_INET (28 bytes) + _fields_ = [("family", ctypes.c_ushort), ("data", ctypes.c_ubyte * 26)] + + class _MibIpnetRow2(ctypes.Structure): # MIB_IPNET_ROW2 (88 bytes) + _fields_ = [ + ("Address", _SockaddrInet), + ("InterfaceIndex", wintypes.ULONG), + ("InterfaceLuid", ctypes.c_ulonglong), + ("PhysicalAddress", ctypes.c_ubyte * 32), + ("PhysicalAddressLength", wintypes.ULONG), + ("State", ctypes.c_int), + ("Flags", ctypes.c_ubyte), + ("ReachabilityTime", wintypes.ULONG), + ] + + if ctypes.sizeof(_MibIpnetRow2) != 88: + return None + try: + iphlpapi = ctypes.WinDLL("iphlpapi.dll") + get_table = iphlpapi.GetIpNetTable2 + free_table = iphlpapi.FreeMibTable + except (OSError, AttributeError): + return None + get_table.argtypes = [ctypes.c_ushort, ctypes.POINTER(ctypes.c_void_p)] + get_table.restype = wintypes.ULONG + free_table.argtypes = [ctypes.c_void_p] + free_table.restype = None + + af_inet, af_inet6 = 2, 23 + nlns_incomplete = 1 # states 0 (unreachable) and 1 (incomplete) carry no usable MAC + table = ctypes.c_void_p() + if get_table(0, ctypes.byref(table)) != 0 or not table.value: # AF_UNSPEC + return None + out: dict[str, str] = {} + try: + count = wintypes.ULONG.from_address(table.value).value + # MIB_IPNET_TABLE2: ULONG NumEntries, then rows aligned on 8 bytes. + rows = (_MibIpnetRow2 * count).from_address(table.value + 8) + for row in rows: + if row.State <= nlns_incomplete or row.PhysicalAddressLength != 6: + continue + hw = bytes(row.PhysicalAddress[:6]) + if hw in (b"\x00" * 6, b"\xff" * 6): + continue + data = bytes(row.Address.data) + if row.Address.family == af_inet: + ip_txt = str(ipaddress.IPv4Address(data[2:6])) + elif row.Address.family == af_inet6: + ip_txt = str(ipaddress.IPv6Address(data[6:22])) + else: + continue + out.setdefault(ip_txt, ":".join(f"{b:02x}" for b in hw)) + finally: + free_table(table) + return out + + +_WIN_NATIVE_UNAVAILABLE = object() +def _load_win_native_or_marker() -> object: + got = _load_win_native_neighbors() + return _WIN_NATIVE_UNAVAILABLE if got is None else got # an empty table is still valid + + +_WIN_NATIVE_CACHE = _SingleFlightCache(_load_win_native_or_marker) + + +def _win_native_neighbors() -> dict[str, str] | None: + got = _WIN_NATIVE_CACHE.get() + return got if isinstance(got, dict) else None + + +def _mac_from_windows_ipv6_neigh(ipv6_raw: str) -> str | None: + """Resolve MAC for an IPv6 address (native table, else ``netsh``).""" + native = _win_native_neighbors() + if native is not None: + try: + return native.get(str(ipaddress.ip_address(ipv6_raw.split("%", 1)[0].strip()))) + except ValueError: + return None + text = _win_ipv6_neigh_cached() + if not text: + return None + want_base = ipv6_raw.split("%", 1)[0].strip() + try: + want_addr = ipaddress.ip_address(want_base) + except ValueError: + return None + for line in text.splitlines(): + parts = line.split() + if len(parts) < 2: + continue + col_ip = parts[0].split("%", 1)[0].strip() + try: + col_addr = ipaddress.ip_address(col_ip) + except ValueError: + continue + if col_addr != want_addr: + continue + for col in parts[1:]: + m = _norm_mac(col) + if m and m != "00:00:00:00:00:00": + return m + return None + + +def _mac_from_windows_arp(ipv4: str) -> str | None: + """Read ``arp -a`` on Windows (no extra packets; entry appears after LAN traffic).""" + if sys.platform != "win32": + return None + target = ipv4.strip() + if not target: + return None + native = _win_native_neighbors() + if native is not None: + return native.get(target) + for line in _win_arp_table_cached().splitlines(): + parts = line.split() + if len(parts) < 2: + continue + if parts[0] != target: + continue + m = _norm_mac(parts[1]) + if m and m != "00:00:00:00:00:00": + return m + return None + + +def _load_darwin_arp_text() -> str: + try: + proc = subprocess.run( + ["arp", "-an"], + capture_output=True, text=True, timeout=4, + encoding="utf-8", errors="replace", + ) + text = proc.stdout or "" if proc.returncode == 0 else "" + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as e: + _LOG.debug("arp -an failed: %s", e) + text = "" + return text + + +_DARWIN_ARP_CACHE = _SingleFlightCache(_load_darwin_arp_text) + + +def _darwin_arp_table_cached() -> str: + return _DARWIN_ARP_CACHE.get() + + +def _load_darwin_ndp_text() -> str: + try: + proc = subprocess.run( + ["ndp", "-an"], + capture_output=True, text=True, timeout=4, + encoding="utf-8", errors="replace", + ) + text = proc.stdout or "" if proc.returncode == 0 else "" + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as e: + _LOG.debug("ndp -an failed: %s", e) + text = "" + return text + + +_DARWIN_NDP_CACHE = _SingleFlightCache(_load_darwin_ndp_text) + + +def _darwin_ndp_table_cached() -> str: + return _DARWIN_NDP_CACHE.get() + + +def _mac_from_darwin_arp(ipv4: str) -> str | None: + target = ipv4.strip() + for line in _darwin_arp_table_cached().splitlines(): + m = _DARWIN_ARP_RE.search(line) + if not m: + continue + try: + if ipaddress.ip_address(m.group(1).strip()) != ipaddress.ip_address(target): + continue + except ValueError: + continue + mac = _norm_mac(m.group(2)) + if mac and mac != "00:00:00:00:00:00": + return mac + return None + + +def _mac_from_darwin_ndp(ipv6_raw: str) -> str | None: + want_base = ipv6_raw.split("%", 1)[0].strip() + try: + want_addr = ipaddress.ip_address(want_base) + except ValueError: + return None + for line in _darwin_ndp_table_cached().splitlines(): + parts = line.split() + if len(parts) < 2: + continue + col_ip = parts[0].split("%", 1)[0].strip() + try: + col_addr = ipaddress.ip_address(col_ip) + except ValueError: + continue + if col_addr != want_addr: + continue + mac = _norm_mac(parts[1]) + if mac and mac != "00:00:00:00:00:00": + return mac + return None + + +def _ipv4_addrs_for_mac_from_darwin_arp(mac_norm: str) -> set[str]: + out: set[str] = set() + for line in _darwin_arp_table_cached().splitlines(): + m = _DARWIN_ARP_RE.search(line) + if not m or _norm_mac(m.group(2)) != mac_norm: + continue + ip_tok = m.group(1).strip() + try: + a = ipaddress.ip_address(ip_tok) + except ValueError: + continue + if isinstance(a, ipaddress.IPv4Address): + out.add(str(a)) + return out + + +def lookup_mac_from_neighbor_cache(ip_raw: str | None) -> str | None: + """Return MAC from OS neighbor/ARP tables if known (Linux ``ip neigh`` / ``/proc/net/arp``, Windows ``arp -a``, macOS ``arp``/``ndp``).""" + if not ip_raw: + return None + if sys.platform == "win32": + try: + base = str(ip_raw).strip().split("%", 1)[0].strip() + if not base: + return None + parsed = ipaddress.ip_address(base) + if isinstance(parsed, ipaddress.IPv4Address): + return _mac_from_windows_arp(base) + return _mac_from_windows_ipv6_neigh(str(ip_raw).strip()) + except ValueError: + pass + return None + if sys.platform == "darwin": + try: + base = str(ip_raw).strip().split("%", 1)[0].strip() + if not base: + return None + parsed = ipaddress.ip_address(base) + if isinstance(parsed, ipaddress.IPv4Address): + return _mac_from_darwin_arp(base) + return _mac_from_darwin_ndp(str(ip_raw).strip()) + except ValueError: + pass + return None + raw = str(ip_raw).strip() + base = raw.split("%", 1)[0].strip() + if not base: + return None + try: + parsed = ipaddress.ip_address(base) + except ValueError: + return None + + if isinstance(parsed, ipaddress.IPv4Address): + hit = _mac_from_proc_arp(base) + if hit: + return hit + # Shared cached table only — no per-IP ``ip neigh show `` spawn per lookup. + out = _ip_neigh_show_all_cached() + return _parse_ip_neigh_stdout(out, base) + + out = _ip_neigh_show_all_cached() + hit = _parse_ip_neigh_stdout(out, raw) + if hit: + return hit + return _parse_ip_neigh_stdout(out, base) + + +def _ipv4_addrs_for_mac_from_win_arp(mac_norm: str) -> set[str]: + """Find IPv4 addresses for a MAC in the Windows neighbour table.""" + out: set[str] = set() + native = _win_native_neighbors() + if native is not None: + for ip_txt, mac in native.items(): + if mac == mac_norm and ":" not in ip_txt: + out.add(ip_txt) + return out + for line in _win_arp_table_cached().splitlines(): + parts = line.split() + if len(parts) < 2: + continue + m = _norm_mac(parts[1]) + if m != mac_norm: + continue + ip_tok = parts[0].strip() + try: + a = ipaddress.ip_address(ip_tok) + except ValueError: + continue + if isinstance(a, ipaddress.IPv4Address): + out.add(str(a)) + return out + + +def _ipv4_addrs_for_mac_from_proc_arp(mac_norm: str) -> set[str]: + out: set[str] = set() + text = _read_proc_arp_text_cached() + for line in text.splitlines()[1:]: + parts = line.split() + if len(parts) < 4: + continue + hw = _norm_mac(parts[3]) + if hw != mac_norm: + continue + ip_tok = parts[0].strip() + try: + a = ipaddress.ip_address(ip_tok) + except ValueError: + continue + if isinstance(a, ipaddress.IPv4Address): + out.add(str(a)) + return out + + +def _ipv4_addrs_for_mac_from_neigh_show(mac_norm: str) -> set[str]: + out: set[str] = set() + stdout = _ip_neigh_show_all_cached() + for line in stdout.splitlines(): + line = line.strip() + if not line: + continue + mo = _LLADDR_RE.search(line) + if not mo or _norm_mac(mo.group(1)) != mac_norm: + continue + parts = line.split() + if not parts: + continue + try: + a = ipaddress.ip_address(parts[0].split("%", 1)[0]) + except ValueError: + continue + if isinstance(a, ipaddress.IPv4Address): + out.add(str(a)) + return out + + +def _pick_preferred_ipv4(candidates: list[str]) -> str | None: + v4s: list[ipaddress.IPv4Address] = [] + for c in candidates: + try: + a = ipaddress.ip_address(c.strip()) + if isinstance(a, ipaddress.IPv4Address): + v4s.append(a) + except ValueError: + continue + if not v4s: + return None + + def sort_key(a: ipaddress.IPv4Address) -> tuple[int, int]: + if a.is_private: + return (0, int(a)) + if a.is_global: + return (1, int(a)) + return (2, int(a)) + + v4s.sort(key=sort_key) + return str(v4s[0]) + + +def lookup_ipv4_for_mac(mac_raw: str | None) -> str | None: + """Pick a LAN IPv4 for this MAC from kernel ARP / neighbor tables. + + Complements :func:`lookup_mac_from_neighbor_cache`: when discovery only shows IPv6 but the + neighbor cache already has an IPv4 for the same ``lladdr``, return it (still no extra packets). + """ + m = _norm_mac(mac_raw or "") + if not m: + return None + if sys.platform == "win32": + s = _ipv4_addrs_for_mac_from_win_arp(m) + elif sys.platform == "darwin": + s = _ipv4_addrs_for_mac_from_darwin_arp(m) + else: + s = _ipv4_addrs_for_mac_from_proc_arp(m) | _ipv4_addrs_for_mac_from_neigh_show(m) + if not s: + return None + return _pick_preferred_ipv4(list(s)) diff --git a/app/utils/notifications.py b/app/utils/notifications.py new file mode 100644 index 00000000..a18df39f --- /dev/null +++ b/app/utils/notifications.py @@ -0,0 +1,20 @@ +# File notifications.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Desktop notification helpers (best-effort, Linux only via notify-send).""" + +from __future__ import annotations + + +def send_notification(app_name: str, title: str, message: str) -> None: + try: + import subprocess + subprocess.run( + ["notify-send", "--app-name", app_name, title, message], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + except Exception: + pass diff --git a/app/utils/qt_device_icons.py b/app/utils/qt_device_icons.py new file mode 100644 index 00000000..708b52d7 --- /dev/null +++ b/app/utils/qt_device_icons.py @@ -0,0 +1,118 @@ +# File qt_device_icons.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Per-device-type icons: active icon pack + ``assets/icons/netneighbor`` built-in fallback. + +No system theme, no Windows Shell stock, no ``QStyle`` fallbacks — assets only, then +``assets/icons/unknown.png`` if present. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from PySide6.QtCore import QSize +from PySide6.QtGui import QIcon + +if TYPE_CHECKING: + from PySide6.QtWidgets import QStyle, QWidget + +from utils.icon_view_prefs import ( + DEVICE_ICON_REFERENCE_PX, + ICON_SIZE_PRESET_PIXELS, + normalize_icon_size_preset, +) +from utils.type_icon_config import type_icon_basenames_for_slug + + +def _bundled_freedesktop_qicon( + basename: str, *, preferred_px: int = DEVICE_ICON_REFERENCE_PX +) -> QIcon | None: + """Build a multi-resolution ``QIcon`` — active icon pack first, built-in fallback. + + Supports both ``{N}x{N}/`` and flat ``{N}/`` directory naming in user packs. + """ + from ui.icons import bundled_freedesktop_png_side_sizes, _bundled_freedesktop_root + from utils.icon_packs import ( + BUILTIN_PACK_ID, + active_icon_pack_id, + active_icon_pack_root, + find_icon_in_pack, + scan_pack_sizes, + ) + + raw = str(basename).strip() + stem = Path(raw).name + if not stem or stem != raw: + return None + + builtin_root = _bundled_freedesktop_root() + pack_id = active_icon_pack_id() + pack_root = active_icon_pack_root() if pack_id != BUILTIN_PACK_ID else None + + builtin_sizes = bundled_freedesktop_png_side_sizes() + icon = QIcon() + registered: set[int] = set() + + # Sizes present in built-in: prefer pack version, fall back to built-in. + for sz in builtin_sizes: + p = find_icon_in_pack(pack_root, sz, stem) if pack_root is not None else None + if p is None: + p = find_icon_in_pack(builtin_root, sz, stem) + if p is None: + continue + icon.addFile(str(p), QSize(sz, sz)) + registered.add(sz) + + # Extra sizes only the active pack provides (e.g. 22, 128 not in built-in). + if pack_root is not None: + for sz in scan_pack_sizes(pack_root): + if sz in registered: + continue + p = find_icon_in_pack(pack_root, sz, stem) + if p is not None: + icon.addFile(str(p), QSize(sz, sz)) + registered.add(sz) + + if preferred_px not in registered and registered: + best = min(registered, key=lambda s: (abs(s - preferred_px), s)) + p = find_icon_in_pack(pack_root, best, stem) if pack_root is not None else None + if p is None: + p = find_icon_in_pack(builtin_root, best, stem) + if p is not None: + icon.addFile(str(p), QSize(preferred_px, preferred_px)) + + for root in ([pack_root] if pack_root is not None else []) + [builtin_root]: + for ext in (".svg", ".png"): + flat = root / f"{stem}{ext}" + if flat.is_file(): + icon.addFile(str(flat)) + + return None if icon.isNull() else icon + + +def qt_icon_for_device_type( + device_type: str | None, + style: "QStyle", + widget: "QWidget | None" = None, + *, + icon_size_preset: str = "medium", +) -> QIcon: + """Icon for a logical device type: only bundled assets (``config/icons.json`` order).""" + _ = style, widget # API stability with existing callers. + preset = normalize_icon_size_preset(icon_size_preset) + preferred_px = ICON_SIZE_PRESET_PIXELS.get(preset, DEVICE_ICON_REFERENCE_PX) + + from ui.icons import resolve_asset_icon_file + + for icon_name in type_icon_basenames_for_slug(device_type): + ic = _bundled_freedesktop_qicon(icon_name, preferred_px=preferred_px) + if ic is not None and not ic.isNull(): + return ic + + unk = resolve_asset_icon_file("unknown.png") + if unk is not None: + return QIcon(str(unk)) + return QIcon() diff --git a/app/utils/qt_single_instance.py b/app/utils/qt_single_instance.py new file mode 100644 index 00000000..5e36b850 --- /dev/null +++ b/app/utils/qt_single_instance.py @@ -0,0 +1,69 @@ +# File qt_single_instance.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Cross-platform single-instance for Qt via QLocalServer (Windows, Linux, macOS).""" + +from __future__ import annotations + +from collections.abc import Callable + +from PySide6.QtCore import QObject +from PySide6.QtNetwork import QLocalServer, QLocalSocket + +# Stable pipe name; must match across launches (aligned with GTK app id io.esp3d.netneighbor). +SINGLETON_SERVER_NAME = "NetNeighbor_io_esp3d_netneighbor_qt" + + +def send_activate_to_primary(server_name: str = SINGLETON_SERVER_NAME) -> bool: + """Try to connect to an already running instance and send ``ACTIVATE``. + + Returns ``True`` if a primary responded — the caller should exit without starting a second UI. + Must be called after ``Q(Core)Application`` exists. + """ + sock = QLocalSocket() + sock.connectToServer(server_name) + if not sock.waitForConnected(200): + return False + sock.write(b"ACTIVATE") + sock.flush() + sock.waitForBytesWritten(2000) + sock.disconnectFromServer() + return True + + +def create_activation_listener( + parent: QObject, + *, + server_name: str = SINGLETON_SERVER_NAME, + on_activate: Callable[[], None], +) -> QLocalServer | None: + """Listen for secondary-instance ``ACTIVATE`` messages and call *on_activate* on the GUI thread. + + Returns the server (keep a reference on the application object) or ``None`` if listen failed. + """ + QLocalServer.removeServer(server_name) + server = QLocalServer(parent) + + def _on_new_connection() -> None: + conn = server.nextPendingConnection() + if conn is None: + return + conn.waitForReadyRead(1500) + raw = bytes(conn.readAll()).decode("utf-8", errors="ignore").strip() + conn.disconnectFromServer() + conn.deleteLater() + if raw == "ACTIVATE": + on_activate() + + server.newConnection.connect(_on_new_connection) + + if server.listen(server_name): + return server + + # Stale lock from a crash — remove and retry once. + QLocalServer.removeServer(server_name) + if server.listen(server_name): + return server + + return None diff --git a/app/utils/scheduling.py b/app/utils/scheduling.py new file mode 100644 index 00000000..d7b343b1 --- /dev/null +++ b/app/utils/scheduling.py @@ -0,0 +1,11 @@ +# File scheduling.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Schedule callables onto the UI toolkit main loop.""" + +from __future__ import annotations + +from collections.abc import Callable + +ScheduleMainFn = Callable[[Callable[[], None]], None] diff --git a/app/utils/session_autostart.py b/app/utils/session_autostart.py new file mode 100644 index 00000000..7bc332c9 --- /dev/null +++ b/app/utils/session_autostart.py @@ -0,0 +1,259 @@ +# File session_autostart.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Session-login autostart: XDG .desktop (Linux) / LaunchAgents plist (macOS) / registry Run key (Windows).""" + +from __future__ import annotations + +import logging +import shutil +import sys +from pathlib import Path + +_LOG = logging.getLogger(__name__) + +_AUTOSTART_FILENAME = "io.esp3d.netneighbor.desktop" +_WIN_REG_VALUE = "NetNeighbor" +_WIN_RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run" +_MACOS_LAUNCHAGENT_LABEL = "io.esp3d.netneighbor" + +# ── helpers ──────────────────────────────────────────────────────────────────── + +def _is_windows() -> bool: + return sys.platform == "win32" + + +def _resolve_launch_command(*, minimized: bool = True) -> str: + """Return the full command used to launch NetNeighbor at login.""" + suffix = "--start-minimized-to-tray" if minimized else "" + if _is_windows(): + import sys as _sys + exe = Path(_sys.executable) + root = Path(__file__).resolve().parent.parent + main_py = root / "main.py" + if main_py.is_file(): + cmd = f'"{exe}" "{main_py}"' + else: + cmd = f'"{exe}"' + return f"{cmd} {suffix}".strip() if suffix else cmd + # Linux / macOS: prefer installed wrapper, fall back to python3 + main.py + w = shutil.which("netneighbor") + if w: + return f"{w} {suffix}".strip() if suffix else w + root = Path(__file__).resolve().parent.parent + main_py = root / "main.py" + if main_py.is_file(): + return f'python3 "{main_py}" {suffix}'.strip() + return f"netneighbor {suffix}".strip() + + +def _resolve_launch_argv(*, minimized: bool = True) -> list[str]: + """Return the argv list for the LaunchAgent ProgramArguments key (macOS).""" + suffix = "--start-minimized-to-tray" if minimized else None + # Frozen PyInstaller bundle: sys.executable IS the stable binary path + # (e.g. /Applications/NetNeighbor.app/Contents/MacOS/NetNeighbor). + # Do NOT reference main.py — it lives in a per-run _MEI temp dir. + if getattr(sys, "frozen", False): + argv = [sys.executable] + if suffix: + argv.append(suffix) + return argv + w = shutil.which("netneighbor") + if w: + argv = [w] + else: + root = Path(__file__).resolve().parent.parent + main_py = root / "main.py" + argv = [sys.executable, str(main_py)] if main_py.is_file() else [sys.executable] + if suffix: + argv.append(suffix) + return argv + + +# ── Windows registry ─────────────────────────────────────────────────────────── + +def _win_autostart_enabled() -> bool: + try: + import winreg + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _WIN_RUN_KEY) as key: + winreg.QueryValueEx(key, _WIN_REG_VALUE) + return True + except (FileNotFoundError, OSError): + return False + + +def _win_apply_autostart(enabled: bool) -> bool: + try: + import winreg + with winreg.OpenKey( + winreg.HKEY_CURRENT_USER, _WIN_RUN_KEY, access=winreg.KEY_SET_VALUE + ) as key: + if enabled: + cmd = _resolve_launch_command(minimized=True) + winreg.SetValueEx(key, _WIN_REG_VALUE, 0, winreg.REG_SZ, cmd) + _LOG.info("Autostart registered: %s", cmd) + else: + try: + winreg.DeleteValue(key, _WIN_REG_VALUE) + _LOG.info("Autostart removed from registry") + except FileNotFoundError: + pass + return True + except OSError as e: + _LOG.warning("Could not update autostart registry key: %s", e) + return False + + +# ── LaunchAgents plist (macOS) ──────────────────────────────────────────────── + +def _macos_plist_path() -> Path: + return Path.home() / "Library" / "LaunchAgents" / f"{_MACOS_LAUNCHAGENT_LABEL}.plist" + + +def _macos_autostart_enabled() -> bool: + return _macos_plist_path().is_file() + + +def _macos_launchctl(action: str, path: Path) -> None: + """Run launchctl load/unload for the given plist (best-effort, errors are logged).""" + import subprocess + import os + try: + if action == "load": + # macOS 11+: bootstrap; fall back to legacy load -w + uid = os.getuid() + r = subprocess.run( + ["launchctl", "bootstrap", f"gui/{uid}", str(path)], + capture_output=True, + ) + if r.returncode != 0: + subprocess.run(["launchctl", "load", "-w", str(path)], capture_output=True) + else: + uid = os.getuid() + r = subprocess.run( + ["launchctl", "bootout", f"gui/{uid}", str(path)], + capture_output=True, + ) + if r.returncode != 0: + subprocess.run(["launchctl", "unload", "-w", str(path)], capture_output=True) + except OSError as e: + _LOG.warning("launchctl %s failed: %s", action, e) + + +def _macos_apply_autostart(enabled: bool) -> bool: + path = _macos_plist_path() + if not enabled: + _macos_launchctl("unload", path) + try: + path.unlink(missing_ok=True) + except OSError as e: + _LOG.warning("Could not remove LaunchAgent plist %s: %s", path, e) + return not path.exists() + return True + + try: + path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + _LOG.warning("Could not create LaunchAgents directory: %s", e) + return False + + argv = _resolve_launch_argv(minimized=True) + args_xml = "\n".join(f" {a}" for a in argv) + plist = ( + '\n' + '\n' + '\n' + f" Label{_MACOS_LAUNCHAGENT_LABEL}\n" + f" ProgramArguments\n \n{args_xml}\n \n" + " RunAtLoad\n" + " KeepAlive\n" + " ProcessTypeBackground\n" + "\n" + ) + try: + path.write_text(plist, encoding="utf-8") + path.chmod(0o644) + _LOG.info("LaunchAgent written: %s", path) + except OSError as e: + _LOG.warning("Could not write LaunchAgent plist %s: %s", path, e) + return False + # Do NOT call launchctl bootstrap here — RunAtLoad=true would launch a second + # instance immediately while the app is already running. launchd picks up the + # plist automatically at next login. + return True + + +# ── XDG .desktop (Linux) ────────────────────────────────────────────────────── + +def _xdg_autostart_file_path() -> Path: + return Path.home() / ".config" / "autostart" / _AUTOSTART_FILENAME + + +def _xdg_autostart_enabled() -> bool: + return _xdg_autostart_file_path().is_file() + + +def _xdg_apply_autostart(enabled: bool) -> bool: + path = _xdg_autostart_file_path() + if not enabled: + try: + path.unlink(missing_ok=True) + except OSError as e: + _LOG.warning("Could not remove autostart file %s: %s", path, e) + return not path.exists() + return True + + try: + path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + _LOG.warning("Could not create autostart directory %s: %s", path.parent, e) + return False + + exec_line = _resolve_launch_command(minimized=True) + body = ( + "[Desktop Entry]\n" + "Type=Application\n" + "Version=1.0\n" + "Name=NetNeighbor\n" + "Comment=LAN discovery (SSDP/mDNS)\n" + f"Exec={exec_line}\n" + "Icon=io.esp3d.netneighbor\n" + "Terminal=false\n" + "Categories=Network;Utility;\n" + "X-GNOME-Autostart-enabled=true\n" + "StartupNotify=false\n" + ) + try: + path.write_text(body, encoding="utf-8") + path.chmod(0o644) + except OSError as e: + _LOG.warning("Could not write autostart file %s: %s", path, e) + return False + return True + + +# ── public API (platform-agnostic) ──────────────────────────────────────────── + +def autostart_file_path() -> Path: + """XDG path (Linux/macOS only — kept for backwards compat).""" + return _xdg_autostart_file_path() + + +def autostart_enabled_on_disk() -> bool: + """Return True if autostart is currently configured for this user.""" + if _is_windows(): + return _win_autostart_enabled() + if sys.platform == "darwin": + return _macos_autostart_enabled() + return _xdg_autostart_enabled() + + +def apply_autostart_pref(enabled: bool) -> bool: + """Enable or disable launch-at-login. Returns True on success.""" + if _is_windows(): + return _win_apply_autostart(enabled) + if sys.platform == "darwin": + return _macos_apply_autostart(enabled) + return _xdg_apply_autostart(enabled) diff --git a/app/utils/spotify_launch.py b/app/utils/spotify_launch.py new file mode 100644 index 00000000..a4c53f3e --- /dev/null +++ b/app/utils/spotify_launch.py @@ -0,0 +1,84 @@ +# File spotify_launch.py for NetNeighbor version 2.1.1 +# Internal version : 2.1.1 date: 2026-11-30 20:23 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Launcher behind the ``localspotify:`` template of the ``spotify`` connect scheme. + +Devices advertising Spotify Connect (``_spotify-connect._tcp``) get a « Spotify » open target +(utils.double_click_open). Nothing is sent to the device: the local Spotify app (or the web +player) is opened and the user picks the speaker from Spotify's own « Devices » menu. +Selecting the target directly would need the Spotify Web API (developer app + OAuth + Premium). +""" + +from __future__ import annotations + +import logging +import shutil +import sys +from pathlib import Path + +from utils.browser import open_url + +_LOG = logging.getLogger(__name__) + +_SPOTIFY_APP_URI = "spotify:" +_SPOTIFY_WEB_URL = "https://open.spotify.com" + + +def _win32_protocol_has_handler(protocol: str) -> bool: + """Ask the shell (``AssocQueryStringW``) whether *protocol* resolves to an application. + + A classic install answers ASSOCSTR_COMMAND; the Microsoft Store (AppX) Spotify has no + ``shell\\open\\command`` and only answers ASSOCSTR_APPID. An unknown protocol fails both. + """ + try: + import ctypes + from ctypes import wintypes + + query = ctypes.windll.shlwapi.AssocQueryStringW + query.argtypes = [ + wintypes.DWORD, wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPCWSTR, + wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), + ] + query.restype = ctypes.c_long + except (AttributeError, OSError): + return False + assocf_is_protocol = 0x1000 + for assocstr in (1, 21): # ASSOCSTR_COMMAND, ASSOCSTR_APPID + size = wintypes.DWORD(1024) + buf = ctypes.create_unicode_buffer(size.value) + if query(assocf_is_protocol, assocstr, protocol, None, buf, ctypes.byref(size)) == 0 and buf.value: + return True + return False + + +def _spotify_app_installed() -> bool: + """Best-effort check that a ``spotify:`` URI handler exists on this machine.""" + if sys.platform == "win32": + return _win32_protocol_has_handler("spotify") + if sys.platform == "darwin": + return any( + p.is_dir() + for p in (Path("/Applications/Spotify.app"), Path.home() / "Applications" / "Spotify.app") + ) + if shutil.which("spotify"): + return True + return any( + p.exists() + for p in ( + Path("/snap/bin/spotify"), + Path("/var/lib/flatpak/exports/bin/com.spotify.Client"), + Path.home() / ".local/share/flatpak/exports/bin/com.spotify.Client", + ) + ) + + +def open_spotify() -> bool: + """Open the Spotify desktop app when installed, otherwise the web player.""" + target = _SPOTIFY_APP_URI if _spotify_app_installed() else _SPOTIFY_WEB_URL + _LOG.info("Open Spotify -> %s", target) + if open_url(target): + return True + if target != _SPOTIFY_WEB_URL: + return open_url(_SPOTIFY_WEB_URL) + return False diff --git a/app/utils/tcp_probe.py b/app/utils/tcp_probe.py new file mode 100644 index 00000000..d9ae6e28 --- /dev/null +++ b/app/utils/tcp_probe.py @@ -0,0 +1,194 @@ +# File tcp_probe.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Non-blocking TCP reachability probe for cached devices.""" + +from __future__ import annotations + +import concurrent.futures +import logging +import socket +import subprocess +import sys +import threading +from collections.abc import Callable + +_logger = logging.getLogger(__name__) + +_DEFAULT_TIMEOUT_S: float = 1.5 +_DEFAULT_MAX_WORKERS: int = 8 + + +def probe_tcp(ip: str, port: int, timeout_s: float = _DEFAULT_TIMEOUT_S) -> bool: + """Return True if a TCP connection to ip:port can be established within timeout_s.""" + if not ip or port <= 0: + return False + try: + with socket.create_connection((ip, port), timeout=timeout_s): + return True + except OSError: + return False + + +def _win_icmp_ping_v4(ip: str, timeout_ms: int) -> bool | None: + """ICMP echo through ``IcmpSendEcho`` (iphlpapi) — no ping.exe / conhost.exe spawn. + + Returns None when the API is unavailable or *ip* is not IPv4 (caller falls back to + ``ping.exe``). A reply only counts when it comes from the target itself with status + IP_SUCCESS — a router's "destination host unreachable" is not a presence signal. + """ + import ctypes + import ipaddress + + try: + addr = ipaddress.ip_address(ip.split("%", 1)[0].strip()) + except ValueError: + return None + if not isinstance(addr, ipaddress.IPv4Address): + return None + try: + iphlpapi = ctypes.WinDLL("iphlpapi.dll") + create = iphlpapi.IcmpCreateFile + send = iphlpapi.IcmpSendEcho + close = iphlpapi.IcmpCloseHandle + except (OSError, AttributeError): + return None + create.restype = ctypes.c_void_p + create.argtypes = [] + send.restype = ctypes.c_uint32 + send.argtypes = [ + ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint16, + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, + ] + close.restype = ctypes.c_int + close.argtypes = [ctypes.c_void_p] + + handle = create() + if not handle or handle == ctypes.c_void_p(-1).value: + return None + try: + dest = int.from_bytes(addr.packed, "little") # IPAddr: network byte order in memory + payload = ctypes.create_string_buffer(b"netneighbor", 11) + reply = ctypes.create_string_buffer(512) # ICMP_ECHO_REPLY + echoed data + 8 + n = send(handle, dest, payload, 11, None, reply, ctypes.sizeof(reply), max(1, int(timeout_ms))) + if n == 0: + return False + raw = reply.raw + reply_addr = int.from_bytes(raw[0:4], "little") + status = int.from_bytes(raw[4:8], "little") + return status == 0 and reply_addr == dest + finally: + close(handle) + + +def ping_host(ip: str, timeout_s: float = 2.0) -> bool: + """Return True if host responds to ICMP ping (no root required on Linux/Windows).""" + if sys.platform == "win32": + try: + native = _win_icmp_ping_v4(ip, int(timeout_s * 1000)) + except Exception: + native = None + if native is not None: + return native + timeout_ms = str(int(timeout_s * 1000)) + timeout_s_int = str(max(1, int(timeout_s))) + # On Windows, CREATE_NO_WINDOW prevents a console window from flashing on + # screen for every ping (the subprocess would otherwise pop a brief cmd box). + creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if sys.platform == "win32" else 0 + if sys.platform == "win32": + cmd = ["ping", "-n", "1", "-w", timeout_ms, ip] + else: + cmd = ["ping", "-c", "1", "-W", timeout_s_int, ip] + try: + result = subprocess.run( + cmd, capture_output=True, text=True, timeout=timeout_s + 2, + creationflags=creationflags, + ) + except Exception: + return False + if result.returncode != 0: + return False + # Windows ``ping`` exits 0 even when a router/other host answers with + # "Destination host unreachable" (ICMP type 3) for an offline LAN target — + # it counts as Received=1, Lost=0. A genuine reply from the target itself + # always contains "TTL=", which the unreachable/timeout messages do not. + if sys.platform == "win32": + return "TTL=" in (result.stdout or "").upper() + return True + + +def ping_ips_background( + ips: list[str], + on_result: Callable[[str, bool], None], + *, + timeout_s: float = 2.0, + max_workers: int = 16, +) -> None: + """Ping all IPs concurrently; call on_result(ip, reachable) for each. + + Runs entirely in background daemon threads — never blocks the caller. + """ + if not ips: + return + + def _worker() -> None: + with concurrent.futures.ThreadPoolExecutor( + max_workers=min(max_workers, len(ips)), + thread_name_prefix="ping-probe", + ) as pool: + futures: dict[concurrent.futures.Future[bool], str] = { + pool.submit(ping_host, ip, timeout_s): ip + for ip in ips + } + for fut in concurrent.futures.as_completed(futures): + ip = futures[fut] + try: + reachable = fut.result() + except Exception: + reachable = False + try: + on_result(ip, reachable) + except Exception: + _logger.debug("ping-probe on_result error for %s", ip, exc_info=True) + + threading.Thread(target=_worker, name="ping-probe-pool", daemon=True).start() + + +def probe_devices_background( + targets: list[tuple[str, int]], + on_result: Callable[[str, int, bool], None], + *, + timeout_s: float = _DEFAULT_TIMEOUT_S, + max_workers: int = _DEFAULT_MAX_WORKERS, +) -> None: + """Probe all (ip, port) targets concurrently; call on_result(ip, port, reachable) for each. + + Runs entirely in background daemon threads — never blocks the caller. + """ + if not targets: + return + + def _worker() -> None: + with concurrent.futures.ThreadPoolExecutor( + max_workers=min(max_workers, len(targets)), + thread_name_prefix="tcp-probe", + ) as pool: + futures: dict[concurrent.futures.Future[bool], tuple[str, int]] = { + pool.submit(probe_tcp, ip, port, timeout_s): (ip, port) + for ip, port in targets + } + for fut in concurrent.futures.as_completed(futures): + ip, port = futures[fut] + try: + reachable = fut.result() + except Exception: + reachable = False + try: + on_result(ip, port, reachable) + except Exception: + _logger.debug( + "tcp-probe on_result error for %s:%s", ip, port, exc_info=True + ) + + threading.Thread(target=_worker, name="tcp-probe-pool", daemon=True).start() diff --git a/app/utils/type_icon_config.py b/app/utils/type_icon_config.py new file mode 100644 index 00000000..463a3aca --- /dev/null +++ b/app/utils/type_icon_config.py @@ -0,0 +1,131 @@ +# File type_icon_config.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Load per-type default icon basenames from ``config/icons.json`` (+ optional user overlay).""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +from typing import Any + +from utils.user_config_overlay import USER_ICONS_JSON, optional_user_json + +_LOG = logging.getLogger(__name__) + +_ROOT = Path(__file__).resolve().parent.parent +_SHIPPED_ICONS_JSON = _ROOT / "config" / "icons.json" + +_cache_map: dict[str, list[str]] | None = None +_cache_sig: tuple[float, float] | None = None + + +def _mtime(p: Path) -> float: + try: + return p.stat().st_mtime + except OSError: + return -1.0 + + +def _normalize_icon_basename(name: str) -> str: + """Strip optional trailing ``.png`` so JSON may use either ``printer`` or ``printer.png``.""" + t = name.strip() + if t.lower().endswith(".png"): + t = t[:-4].strip() + return t + + +def _parse_types_object(raw: dict[str, Any]) -> dict[str, list[str]]: + t = raw.get("types") + if not isinstance(t, dict): + return {} + out: dict[str, list[str]] = {} + for k, v in t.items(): + if not isinstance(k, str) or not k.strip(): + continue + slug = k.strip().lower() + if isinstance(v, list): + names = [str(x).strip() for x in v if isinstance(x, (str, int)) and str(x).strip()] + elif isinstance(v, str) and v.strip(): + names = [v.strip()] + else: + continue + names = [_normalize_icon_basename(x) for x in names] + names = [x for x in names if x] + if names: + out[slug] = names + return out + + +def _merge_type_maps(base: dict[str, list[str]], overlay: dict[str, Any] | None) -> dict[str, list[str]]: + if not overlay: + return base + ot = overlay.get("types") + if not isinstance(ot, dict): + return base + out = dict(base) + for k, v in ot.items(): + if not isinstance(k, str) or not k.strip(): + continue + slug = k.strip().lower() + if isinstance(v, list): + names = [str(x).strip() for x in v if isinstance(x, (str, int)) and str(x).strip()] + elif isinstance(v, str) and v.strip(): + names = [v.strip()] + else: + continue + names = [_normalize_icon_basename(x) for x in names] + names = [x for x in names if x] + if names: + out[slug] = names + return out + + +def _load_shipped_types() -> dict[str, list[str]]: + if not _SHIPPED_ICONS_JSON.is_file(): + _LOG.warning("Missing shipped type icons config %s", _SHIPPED_ICONS_JSON) + return {} + try: + data = json.loads(_SHIPPED_ICONS_JSON.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + _LOG.warning("Invalid shipped icons.json: %s", exc) + return {} + if not isinstance(data, dict): + return {} + return _parse_types_object(data) + + +def load_type_icon_basenames_by_slug(*, force_reload: bool = False) -> dict[str, list[str]]: + """Merged ``slug -> [basename, …]`` from ``config/icons.json`` and ``~/.config/netneighbor/icons.json``.""" + global _cache_map, _cache_sig + mt_ship = _mtime(_SHIPPED_ICONS_JSON) + mt_user = _mtime(USER_ICONS_JSON) + sig = (mt_ship, mt_user) + if not force_reload and _cache_map is not None and _cache_sig == sig: + return _cache_map + + shipped = _load_shipped_types() + user_doc = optional_user_json(USER_ICONS_JSON) + merged = _merge_type_maps(shipped, user_doc) + if "unknown" not in merged: + merged["unknown"] = ["computer", "network-workgroup", "network-server"] + + _cache_map = merged + _cache_sig = sig + return merged + + +def type_icon_basenames_for_slug(device_type_slug: str | None) -> list[str]: + """Ordered basenames for bundled icon lookup (falls back to ``unknown``).""" + m = load_type_icon_basenames_by_slug() + slug = (device_type_slug or "unknown").strip().lower() or "unknown" + if slug in m: + return list(m[slug]) + return list(m.get("unknown", ["computer", "network-workgroup", "network-server"])) + + +def device_type_icon_slugs() -> tuple[str, ...]: + """Stable sorted list of type slugs defined in the merged icon map.""" + return tuple(sorted(load_type_icon_basenames_by_slug().keys())) diff --git a/utils/ui_prefs.py b/app/utils/ui_prefs.py similarity index 90% rename from utils/ui_prefs.py rename to app/utils/ui_prefs.py index 7fe58593..70281ce6 100644 --- a/utils/ui_prefs.py +++ b/app/utils/ui_prefs.py @@ -1,5 +1,5 @@ -# File ui_prefs.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File ui_prefs.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Persistence helpers for UI preferences.""" diff --git a/utils/user_config_overlay.py b/app/utils/user_config_overlay.py similarity index 86% rename from utils/user_config_overlay.py rename to app/utils/user_config_overlay.py index fd557b44..9c28ce3a 100644 --- a/utils/user_config_overlay.py +++ b/app/utils/user_config_overlay.py @@ -1,5 +1,5 @@ -# File user_config_overlay.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 +# File user_config_overlay.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 # Owner: Luc LEBOSSE all copyrights # License: LGPL3 """Merge bundled discovery JSON with optional user overlays in ~/.config/netneighbor.""" @@ -15,8 +15,10 @@ USER_CONFIG_DIR = Path.home() / ".config" / "netneighbor" USER_DEVICE_TYPES_JSON = USER_CONFIG_DIR / "device_types.json" +USER_ICONS_JSON = USER_CONFIG_DIR / "icons.json" USER_SSDP_RULES_JSON = USER_CONFIG_DIR / "ssdp_rules.json" USER_MDNS_RULES_JSON = USER_CONFIG_DIR / "mdns_rules.json" +USER_WSD_RULES_JSON = USER_CONFIG_DIR / "wsd_rules.json" def optional_user_json(filepath: Path) -> dict[str, Any] | None: @@ -105,6 +107,32 @@ def merge_ssdp_rules_overlays(bundled: dict[str, Any]) -> dict[str, Any]: return out +def merge_wsd_rules_overlays(bundled: dict[str, Any]) -> dict[str, Any]: + """User ~/.config/netneighbor/wsd_rules.json: prepend qname_rules; override precedence/default if given.""" + + overlay = optional_user_json(USER_WSD_RULES_JSON) + if overlay is None or overlay == {}: + return bundled + + out = _deep_copy_json(bundled) + + qr_u = overlay.get("qname_rules") + if isinstance(qr_u, list): + base_qr = list(out.get("qname_rules") or []) + out["qname_rules"] = [r for r in qr_u if isinstance(r, dict)] + base_qr + + prec_u = overlay.get("precedence") + if isinstance(prec_u, list): + out["precedence"] = [t for t in prec_u if isinstance(t, str)] + + default_u = overlay.get("default") + if isinstance(default_u, str) and default_u.strip(): + out["default"] = default_u.strip() + + _LOG.debug("Merged WSD rules with user overlay %s", USER_WSD_RULES_JSON) + return out + + def _merge_summary_txt_rows(user_rows: list[Any], bundled_rows: list[Any]) -> list[dict[str, Any]]: """Merge summary_from_txt: labels from user rows first (order preserved); bundled-only labels follow.""" diff --git a/app/utils/wsd_rules.py b/app/utils/wsd_rules.py new file mode 100644 index 00000000..4999d26a --- /dev/null +++ b/app/utils/wsd_rules.py @@ -0,0 +1,142 @@ +# File wsd_rules.py for NetNeighbor version 2.0.0 +# Internal version : 2.0.0 date: 2026-05-19 00:00 +# Owner: Luc LEBOSSE all copyrights +# License: LGPL3 +"""Load configurable WSD QName classification rules (`config/wsd_rules.json`). + +WSD classifies a host from the DPWS service QNames it advertises (namespace + localname), +not from free text — so the rule schema matches on structured QName attributes rather than +substrings. See `config/wsd_rules.json` for the documented schema. +""" + +from __future__ import annotations + +import json +import logging +from functools import lru_cache +from pathlib import Path + +from utils.user_config_overlay import merge_wsd_rules_overlays + +_LOG = logging.getLogger(__name__) +_RULES_PATH = Path(__file__).resolve().parent.parent / "config" / "wsd_rules.json" + +# The bundled config/wsd_rules.json is the single source of truth. This empty skeleton is only a +# graceful degraded fallback if that file is missing/corrupt (startup utils.config_integrity then +# shows a "corrupted installation" dialog). "computer" stays the default so WSD hosts still appear. +_EMPTY_RULES: dict = {"qname_rules": [], "precedence": [], "default": "computer"} + +_PREDICATE_OPS = ("local_eq", "local_endswith", "local_contains_any", "ns_contains") + + +def _normalized_rule_dict(raw: object) -> dict: + """Coerce a payload into a well-formed rules dict (missing keys filled with safe empties).""" + if isinstance(raw, dict): + merged = dict(_EMPTY_RULES) + merged.update(raw) + if not isinstance(merged.get("qname_rules"), list): + merged["qname_rules"] = [] + if not isinstance(merged.get("precedence"), list): + merged["precedence"] = [] + if not isinstance(merged.get("default"), str) or not merged["default"].strip(): + merged["default"] = _EMPTY_RULES["default"] + return merged + return dict(_EMPTY_RULES) + + +def load_wsd_rules() -> dict: + """Return rules from config/wsd_rules.json (single source); user overlay merged from ~/.config. + + A missing/corrupt bundled file degrades to empty rules (default type ``computer``) — startup + integrity check surfaces the "corrupted installation" message (see utils.config_integrity). + """ + try: + data = json.loads(_RULES_PATH.read_text(encoding="utf-8")) + except FileNotFoundError: + _LOG.warning("WSD rules file missing at %s — degraded (no rules)", _RULES_PATH) + data = dict(_EMPTY_RULES) + except (json.JSONDecodeError, OSError) as exc: + _LOG.warning("Invalid WSD rules file %s: %s — degraded (no rules)", _RULES_PATH, exc) + data = dict(_EMPTY_RULES) + merged = merge_wsd_rules_overlays(_normalized_rule_dict(data)) + return _normalized_rule_dict(merged) + + +@lru_cache(maxsize=1) +def cached_wsd_rules() -> dict: + """Rules loaded once per process (edit file + restart app to pick up changes).""" + return load_wsd_rules() + + +def reload_wsd_rules_for_tests() -> None: + cached_wsd_rules.cache_clear() + + +def _predicate_matches(pred: dict, ns: str, local: str) -> bool: + """A predicate matches when every operator it declares matches (AND); empty predicate never matches.""" + if not isinstance(pred, dict) or not any(op in pred for op in _PREDICATE_OPS): + return False + local_eq = pred.get("local_eq") + if isinstance(local_eq, list): + if local not in {str(x).strip().lower() for x in local_eq if isinstance(x, str)}: + return False + local_endswith = pred.get("local_endswith") + if isinstance(local_endswith, list): + if not any(local.endswith(str(x).strip().lower()) for x in local_endswith if isinstance(x, str) and str(x).strip()): + return False + local_contains_any = pred.get("local_contains_any") + if isinstance(local_contains_any, list): + if not any(str(x).strip().lower() in local for x in local_contains_any if isinstance(x, str) and str(x).strip()): + return False + ns_contains = pred.get("ns_contains") + if isinstance(ns_contains, list): + if not any(str(x).strip().lower() in ns for x in ns_contains if isinstance(x, str) and str(x).strip()): + return False + return True + + +def _qname_attrs(qname: object) -> tuple[str, str] | None: + """Lowercased (namespace, localname) for a QName-like object, or None if unreadable.""" + try: + ns = (qname.getNamespace() or "").lower() # type: ignore[attr-defined] + local = (qname.getLocalname() or "").lower() # type: ignore[attr-defined] + except Exception: + return None + return ns, local + + +def infer_type_from_qnames(types, rules: dict | None = None) -> str: + """Classify a WSD host from its service QNames using the rules (precedence-ordered, first wins).""" + r = rules if isinstance(rules, dict) else cached_wsd_rules() + default = r.get("default") if isinstance(r.get("default"), str) and r.get("default") else "computer" + if not types: + return default + + qname_rules = r.get("qname_rules") + if not isinstance(qname_rules, list): + return default + + matched_types: set[str] = set() + for qname in types: + attrs = _qname_attrs(qname) + if attrs is None: + continue + ns, local = attrs + for rule in qname_rules: + if not isinstance(rule, dict): + continue + target = rule.get("type") + if not isinstance(target, str) or not target.strip() or target in matched_types: + continue + preds = rule.get("match_any") + if not isinstance(preds, list): + continue + if any(_predicate_matches(p, ns, local) for p in preds): + matched_types.add(target) + + precedence = r.get("precedence") + if isinstance(precedence, list): + for t in precedence: + if isinstance(t, str) and t in matched_types: + return t + return default diff --git a/assets/icons/.gitkeep b/assets/icons/.gitkeep deleted file mode 100644 index 8b137891..00000000 --- a/assets/icons/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/assets/icons/3dprinter.png b/assets/icons/3dprinter.png deleted file mode 100644 index 2dd51e07..00000000 Binary files a/assets/icons/3dprinter.png and /dev/null differ diff --git a/assets/icons/cnc.png b/assets/icons/cnc.png deleted file mode 100644 index f11350f2..00000000 Binary files a/assets/icons/cnc.png and /dev/null differ diff --git a/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg b/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg deleted file mode 120000 index c050a260..00000000 --- a/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg +++ /dev/null @@ -1 +0,0 @@ -../../../../svg/netneighbor-tray.svg \ No newline at end of file diff --git a/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg b/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg deleted file mode 120000 index d7b60097..00000000 --- a/assets/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg +++ /dev/null @@ -1 +0,0 @@ -../../../../svg/netneighbor_icon.svg \ No newline at end of file diff --git a/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg b/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg deleted file mode 120000 index 9ba0f327..00000000 --- a/assets/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg +++ /dev/null @@ -1 +0,0 @@ -../../../../svg/netneighbor-tray-symbolic.svg \ No newline at end of file diff --git a/config/default_commands.json b/config/default_commands.json deleted file mode 100644 index 444cfaef..00000000 --- a/config/default_commands.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "http": "xdg-open http://{ip}", - "https": "xdg-open https://{ip}", - "smb": "nemo smb://{ip}", - "ftp": "nemo ftp://{ip}", - "ssh": "x-terminal-emulator -e ssh -p {port} {ip}", - "telnet": "x-terminal-emulator -e nc {ip} {port}", - "sftp": "nemo sftp://{ip}" -} diff --git a/config/mdns_rules.json b/config/mdns_rules.json deleted file mode 100644 index 4082d682..00000000 --- a/config/mdns_rules.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "summary_from_txt": [ - { - "label": "Manufacturer", - "keys": ["mfg", "manufacturer", "make"] - }, - { - "label": "Model", - "keys": ["mdl", "model", "product"] - } - ], - "type_rules": [] -} diff --git a/config/ssdp_rules.json b/config/ssdp_rules.json deleted file mode 100644 index 88dd6c63..00000000 --- a/config/ssdp_rules.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "name_rules": { - "fallback_fields": [ - "friendlyName", - "displayName" - ], - "prefer_display_name_when_no_friendly_name": true - }, - "information_rules": { - "concat_fields": [ - "roomName", - "displayName" - ], - "separator": " / " - }, - "type_rules": [ - { - "contains_any": [ - "smartspeaker-audio", - "sonos" - ], - "type": "smartspeaker" - }, - { - "contains_any": [ - "dial-multiscreen", - "chromecast", - "googletv", - "android tv" - ], - "type": "smarttv" - }, - { - "contains_any": [ - "camera", - "onvif", - "ipcam", - "surveillance" - ], - "type": "camera" - }, - { - "contains_any": [ - "washer", - "dryer", - "refrigerator", - "oven", - "dishwasher", - "home appliance" - ], - "type": "homeappliance" - }, - { - "contains_any": [ - "cnc", - "laser cutter" - ], - "type": "cnc" - }, - { - "contains_any": [ - "3d printer", - "3dprinter", - "esp3d", - "ultimaker", - "prusa", - "bambu" - ], - "type": "3dprinter" - }, - { - "contains_any": [ - "iot", - "smart device", - "smartdevice" - ], - "type": "smartdevice" - }, - { - "contains_any": [ - "printer-network", - "ipp", - "ipps", - "airprint", - "network printer", - "print service", - "urn:schemas-upnp-org:device:printer" - ], - "type": "networkprinter" - }, - { - "contains_any": [ - "wifialliance", - "wfadevice", - "wfawlanconfig" - ], - "type": "router" - }, - { - "contains_any": [ - "synology", - "qnap", - "nas" - ], - "type": "nas" - } - ] -} diff --git a/discovery/__init__.py b/discovery/__init__.py deleted file mode 100644 index ec57b6a7..00000000 --- a/discovery/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# File __init__.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""Discovery protocol package.""" - -from .manager import DiscoveryManager, PresenceTransitionHook, PresenceTransitionKind - -__all__ = [ - "DiscoveryManager", - "PresenceTransitionHook", - "PresenceTransitionKind", -] diff --git a/discovery/manager.py b/discovery/manager.py deleted file mode 100644 index c22ef840..00000000 --- a/discovery/manager.py +++ /dev/null @@ -1,2729 +0,0 @@ -# File manager.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""Orchestrates all protocol providers and keeps a simple device cache.""" - -from collections.abc import Callable -from datetime import datetime, timedelta, timezone -import ipaddress -import logging -import threading -from urllib.parse import urljoin, urlparse, urlunparse -from typing import Literal - -from discovery.base import BaseDiscovery -from discovery.mdns import MDNSDiscovery -from discovery.ssdp import SSDPDiscovery -from discovery.netbios import NetbiosDiscovery -from discovery.wsdd_client import WsddSocketDiscovery -from discovery.wsd import WSDiscovery, is_synthetic_wsd_display_name -from model.device import Device -from utils.discovery_cache import load_discovery_cache -from utils.discovery_config import normalize_information_precedence_list -from utils.discovery_identity import uuid_urn_if_present -from utils.location_label import is_plausible_room_location - -AnticipatoryDescriptorSource = Literal["ssdp_profile_cache", "mdns_txt"] - -PresenceTransitionKind = Literal["online", "offline"] -PresenceTransitionHook = Callable[[Device, PresenceTransitionKind], None] -_IDENTITY_HOLD_SECONDS = 3.0 - - -def _descriptor_url_with_ip(descriptor_template: str, ip_s: str) -> str | None: - """Rebuild SSDP LOCATION-style URL with ``ip_s`` as host (same path/port/query as template).""" - t = (descriptor_template or "").strip() - if not t: - return None - try: - addr = ipaddress.ip_address(ip_s.strip()) - except ValueError: - return None - p = urlparse(t) - if not p.scheme or not p.netloc: - return None - port = p.port - if isinstance(addr, ipaddress.IPv6Address): - host = f"[{addr.compressed}]" - else: - host = addr.compressed - netloc = f"{host}:{port}" if port is not None else host - return urlunparse((p.scheme, netloc, p.path or "/", p.params, p.query, p.fragment)) - - -def _http_base_url_for_descriptor(ip_s: str, port: int, *, https: bool = False) -> str | None: - """Build ``http(s)://host[:port]/`` for resolving relative descriptor paths from mDNS TXT.""" - try: - addr = ipaddress.ip_address(ip_s.strip()) - except ValueError: - return None - scheme = "https" if https else "http" - default_port = 443 if https else 80 - if isinstance(addr, ipaddress.IPv6Address): - h = f"[{addr.compressed}]" - else: - h = addr.compressed - p = int(port) if port else 0 - if p > 0 and p != default_port: - netloc = f"{h}:{p}" - else: - netloc = h - return urlunparse((scheme, netloc, "/", "", "", "")) - - -def _normalize_mdns_relative_descriptor_path(raw: str) -> str | None: - s = (raw or "").strip() - if not s: - return None - if s.startswith(("http://", "https://")): - return s - low = s.lower() - if ".xml" not in low: - return None - if s.startswith("/"): - return s - # Some TXT records use ``description.xml`` without a leading slash. - return "/" + s.lstrip("/") - - -def _join_descriptor_base_and_path(base_url: str, absolute_path: str) -> str | None: - """Like URL concatenation but preserves non-default port (``urljoin`` strips it for absolute paths).""" - path = absolute_path if absolute_path.startswith("/") else f"/{absolute_path}" - try: - p = urlparse(base_url) - except ValueError: - return None - if not p.scheme or not p.netloc: - return None - return urlunparse((p.scheme, p.netloc, path, "", "", "")) - - -_VALID_COMMAND_SCHEMES = frozenset(("http", "https", "smb", "ftp", "ssh", "sftp", "telnet")) -_VALID_COMMAND_MODES = frozenset(("override", "additional")) - - -def _normalize_command_list(raw: object) -> list[dict]: - """Validate and normalize a list of per-device command dicts.""" - if not isinstance(raw, list): - return [] - result = [] - for c in raw: - if not isinstance(c, dict): - continue - scheme = str(c.get("scheme", "")).strip().lower() - if scheme not in _VALID_COMMAND_SCHEMES: - continue - mode = str(c.get("mode", "override")).strip().lower() - if mode not in _VALID_COMMAND_MODES: - mode = "override" - result.append({ - "scheme": scheme, - "ip": str(c.get("ip", "")).strip(), - "port": int(c.get("port", 0) or 0), - "mode": mode, - "label": str(c.get("label", "")).strip(), - }) - return result - - -class DiscoveryManager: - def __init__( - self, - demo_mode: bool = False, - enable_ssdp: bool = True, - enable_mdns: bool = True, - enable_ssdp_rules: bool = True, - enable_mdns_rules: bool = True, - ssdp_query_interval_seconds: int | None = None, - ssdp_mx_seconds: int | None = None, - ssdp_descriptor_http_min_interval_seconds: float | None = None, - mdns_enumeration_timeout_seconds: float | None = None, - mdns_enumeration_interval_seconds: int | None = None, - mdns_service_info_timeout_ms: int | None = None, - enable_wsd: bool = True, - wsd_interval_seconds: float | None = None, - wsd_timeout_seconds: float | None = None, - enable_wsdd_socket: bool = False, - wsdd_listen: str | None = None, - wsdd_interval_seconds: float | None = None, - wsdd_socket_timeout_seconds: float | None = None, - wsdd_probe_each_poll: bool = True, - enable_nmb: bool = True, - nmb_interval_seconds: float | None = None, - nmb_timeout_seconds: float | None = None, - nmb_argv: list[str] | None = None, - nmb_directed_ips: list[str] | None = None, - protocol_merge_order: list[str] | None = None, - information_precedence: list[str] | None = None, - ) -> None: - self._logger = logging.getLogger(__name__) - self._ssdp_logger = logging.getLogger(f"{__name__}.ssdp") - self._mdns_logger = logging.getLogger(f"{__name__}.mdns") - self._wsd_logger = logging.getLogger(f"{__name__}.wsd") - self._wsdd_logger = logging.getLogger(f"{__name__}.wsdd") - self._nmb_logger = logging.getLogger(f"{__name__}.nmb") - self._protocol_merge_order: list[str] = ( - list(protocol_merge_order) - if protocol_merge_order - else ["ssdp", "wsd", "wsdd", "nmb", "mdns"] - ) - self._information_precedence: list[str] = ( - list(information_precedence) - if information_precedence - else normalize_information_precedence_list(None) - ) - self._logger.debug("merge.information_precedence (manager) = %s", self._information_precedence) - protocols: list[BaseDiscovery] = [] - if enable_ssdp: - protocols.append( - SSDPDiscovery( - rules_enabled=enable_ssdp_rules, - query_interval_seconds=ssdp_query_interval_seconds, - mx_seconds=ssdp_mx_seconds, - descriptor_http_min_interval_seconds=ssdp_descriptor_http_min_interval_seconds, - ) - ) - if enable_mdns: - protocols.append( - MDNSDiscovery( - rules_enabled=enable_mdns_rules, - enumeration_timeout_seconds=mdns_enumeration_timeout_seconds, - enumeration_interval_seconds=mdns_enumeration_interval_seconds, - service_info_timeout_ms=mdns_service_info_timeout_ms, - ) - ) - if enable_wsd: - protocols.append( - WSDiscovery( - interval_seconds=wsd_interval_seconds, - timeout_seconds=wsd_timeout_seconds, - ) - ) - if enable_wsdd_socket and (wsdd_listen or "").strip(): - protocols.append( - WsddSocketDiscovery( - listen=(wsdd_listen or "").strip(), - interval_seconds=wsdd_interval_seconds, - socket_timeout_seconds=wsdd_socket_timeout_seconds, - probe_each_poll=wsdd_probe_each_poll, - ) - ) - if enable_nmb: - protocols.append( - NetbiosDiscovery( - interval_seconds=nmb_interval_seconds, - timeout_seconds=nmb_timeout_seconds, - argv=nmb_argv, - directed_ips=nmb_directed_ips, - ) - ) - self._protocols = protocols - self._ssdp_discovery: SSDPDiscovery | None = None - self._nmb_discovery: NetbiosDiscovery | None = None - for _p in protocols: - if isinstance(_p, SSDPDiscovery): - self._ssdp_discovery = _p - if isinstance(_p, NetbiosDiscovery): - self._nmb_discovery = _p - self._anticipatory_fetch_attempted: set[str] = set() - self._anticipatory_reentrant: set[str] = set() - self._devices: dict[str, Device] = {} - self._arrival_sequence = 0 - self._listeners: list[Callable[[list[Device]], None]] = [] - self._presence_hooks: list[PresenceTransitionHook] = [] - self._type_overrides: dict[str, str] = {} - self._name_overrides: dict[str, str] = {} - self._location_overrides: dict[str, str] = {} - self._url_overrides: dict[str, str] = {} - self._device_commands: dict[str, list[dict]] = {} # key → [{scheme,ip,port,mode,label}] - self._custom_command_overrides: dict[str, str] = {} # key → command template - self._field_mapping_rules: dict[str, dict[str, list[str]]] = {} - self._monitored_overrides: dict[str, bool] = {} - self._last_seen_overrides: dict[str, str] = {} - self._identity_pending: dict[str, tuple[datetime, Device]] = {} - self._ssdp_profile_cache_by_ip: dict[str, dict] = self._load_ssdp_profile_cache_by_ip() - self._demo_mode = demo_mode - self._location_prefs_need_reapply = False - self._location_prefs_dirty_callback: Callable[[], None] | None = None - - for protocol in self._protocols: - protocol.set_callback(self._on_protocol_event) - - def set_location_prefs_dirty_callback(self, callback: Callable[[], None] | None) -> None: - self._location_prefs_dirty_callback = callback - - def add_listener(self, callback: Callable[[list[Device]], None]) -> None: - self._listeners.append(callback) - callback(self.devices) - - def register_presence_transition_hook(self, hook: PresenceTransitionHook) -> None: - """Notify when a device becomes reachable or unreachable (same identity row). - - Fires only on transitions: newly online (including back from offline), or offline from - online. Silent for first-seen rows that are already offline (e.g. restored monitored - ghosts). Plugins should treat callbacks as potentially running on a discovery thread — - marshal to the UI thread before touching GTK. - - Reserved for future automation / plugins; core code does not register hooks today. - """ - self._presence_hooks.append(hook) - - def unregister_presence_transition_hook(self, hook: PresenceTransitionHook) -> None: - try: - self._presence_hooks.remove(hook) - except ValueError: - pass - - @property - def devices(self) -> list[Device]: - return sorted(self._devices.values(), key=lambda device: (device.category, device.name.lower())) - - def start(self) -> None: - self._logger.info("Starting discovery protocols: %s", [p.source for p in self._protocols]) - self._emit_cached_devices() - if not self._protocols: - self._logger.warning("No discovery protocols enabled (check ~/.config/netneighbor/discovery.json)") - return - for protocol in self._protocols: - protocol.start() - - def stop(self) -> None: - self._logger.info("Stopping discovery protocols") - for protocol in self._protocols: - protocol.stop() - self._identity_pending.clear() - - def refresh(self) -> None: - self._logger.debug("Manual refresh requested") - for protocol in self._protocols: - protocol.refresh() - - def _device_event_logger(self, source: str) -> logging.Logger: - if source == "ssdp": - return self._ssdp_logger - if source == "mdns": - return self._mdns_logger - if source == "wsd": - return self._wsd_logger - if source == "wsdd": - return self._wsdd_logger - if source == "nmb": - return self._nmb_logger - return self._logger - - def add_or_update_device(self, device: Device) -> None: - sip = str(device.ip).strip() - if sip in {"", "0.0.0.0"}: - self._device_event_logger(device.source).debug( - "Ignoring device with placeholder IP: source=%s name=%s port=%s online=%s", - device.source, - device.name, - device.port, - device.online, - ) - return - # Loopback addresses are always the local machine — never useful as - # network neighbours. Drop them unconditionally. - try: - if ipaddress.ip_address(sip).is_loopback: - self._device_event_logger(device.source).debug( - "Ignoring loopback device: source=%s ip=%s name=%s", - device.source, - sip, - device.name, - ) - return - except ValueError: - pass - if self._should_hold_for_stable_identity(device): - return - - override_key = self._make_override_key_for_device(device) - existing_seen = self._last_seen_overrides.get(override_key) - if not existing_seen: - existing_seen = self._last_seen_overrides.get(self._make_override_key(device.source, device.ip, device.port)) - if device.online: - now = datetime.now(timezone.utc) - device.last_seen = now - self._last_seen_overrides[override_key] = now.isoformat() - elif existing_seen: - try: - device.last_seen = datetime.fromisoformat(existing_seen) - except ValueError: - pass - - existing_key = device.key - existing = self._devices.get(existing_key) - if existing is None and device.source == "ssdp": - existing_key, existing = self._find_existing_ssdp_by_endpoint(device) - - self._hydrate_mdns_from_ssdp_profile_cache(device, existing) - self._hydrate_ssdp_from_profile_cache(device) - self._schedule_anticipatory_descriptor_fetch(device) - self._apply_field_mapping_rules(device) - self._apply_type_override(device) - self._apply_name_override(device) - self._apply_location_override(device) - self._apply_url_override(device) - self._apply_device_commands(device) - self._apply_custom_command_override(device) - self._apply_monitored_override(device) - - prev_online: bool | None = existing.online if existing is not None else None - - if existing is not None: - # Preserve user-follow choice across updates. - device.monitored = existing.monitored - if device.online is False and existing.last_seen: - device.last_seen = existing.last_seen - if device.source == "ssdp": - self._ssdp_logger.debug( - "SSDP merge candidate for %s:%s old_name=%s new_name=%s", - device.ip, - device.port, - existing.name, - device.name, - ) - device.metadata = self._merge_ssdp_metadata(existing.metadata, device.metadata, existing.name, device.name) - device.name = self._pick_ssdp_name(existing.name, device.name, existing.metadata, device.metadata) - device.icon = existing.icon or device.icon - if not device.url and existing.url: - device.url = existing.url - if existing_key != device.key and existing_key in self._devices: - del self._devices[existing_key] - existing_key = device.key - - if not isinstance(device.metadata, dict): - device.metadata = {} - existing_arrival = None - if isinstance(existing, Device) and isinstance(existing.metadata, dict): - candidate = existing.metadata.get("_arrival_index") - if isinstance(candidate, int): - existing_arrival = candidate - if existing_arrival is None: - self._arrival_sequence += 1 - existing_arrival = self._arrival_sequence - device.metadata["_arrival_index"] = existing_arrival - self._supplement_missing_user_location(device, existing) - self._devices[existing_key] = device - self._maybe_queue_nmb_probe_for_synthetic_wsd(device) - self._run_location_reapply_sweep() - device_log = self._device_event_logger(device.source) - device_log.info( - "Device %s: source=%s name=%s ip=%s port=%s type=%s category=%s online=%s", - "updated" if existing else "added", - device.source, - device.name, - device.ip, - device.port, - device.type, - device.category, - device.online, - ) - device_log.debug( - "Device %s: %s %s:%s [%s] online=%s category=%s", - "updated" if existing else "added", - device.source, - device.ip, - device.port, - device.name, - device.online, - device.category, - ) - uloc = device.metadata.get("user_location") if isinstance(device.metadata, dict) else None - device_log.debug( - "Device appearance: ip=%s port=%s type=%s icon=%s user_location=%r", - device.ip, - device.port, - device.type, - device.icon, - uloc, - ) - self._emit_presence_hooks_if_transition(device, prev_online, device.online) - self._notify() - - def _maybe_queue_nmb_probe_for_synthetic_wsd(self, device: Device) -> None: - """Queue ``nmblookup -A`` on the LAN IPv4 for synthetic WSD/wsdd labels. - - Broadcast browse often misses PCs; directed ``-A`` matches what you'd run manually. - If discovery only has IPv6 (e.g. link-local), resolve IPv4 from kernel neighbor/MAC - tables—same source as ``ip neigh``—then probe that address for the NetBIOS name. - """ - nmb = self._nmb_discovery - if nmb is None: - return - if (device.source or "").strip().lower() not in {"wsd", "wsdd"}: - return - if not device.online: - return - if (device.type or "").strip().lower() != "computer": - return - if not is_synthetic_wsd_display_name(device.name): - return - sip = str(device.ip).strip() - base = sip.split("%", 1)[0].strip() - if not base: - return - try: - a = ipaddress.ip_address(base) - except ValueError: - return - target_v4: str | None = None - if isinstance(a, ipaddress.IPv4Address): - if a.is_loopback or not a.is_private: - return - target_v4 = base - elif isinstance(a, ipaddress.IPv6Address): - from utils.details_payload import resolve_mac_for_device - from utils.neighbor_mac import lookup_ipv4_for_mac - - mac = resolve_mac_for_device(device) - if not mac: - return - target_v4 = lookup_ipv4_for_mac(mac) - if not target_v4: - return - else: - return - nmb.suggest_directed_ip(target_v4) - - def _load_ssdp_profile_cache_by_ip(self) -> dict[str, dict]: - out: dict[str, dict] = {} - cache_blob = load_discovery_cache() - raw = cache_blob.get("ssdp_profile_cache") - if not isinstance(raw, dict): - return out - entries = raw.get("entries") - if not isinstance(entries, dict): - return out - for _key, row in entries.items(): - if not isinstance(row, dict): - continue - candidate_urls: list[str] = [] - ssdp_loc = row.get("ssdp_location") - if isinstance(ssdp_loc, str) and ssdp_loc.strip(): - candidate_urls.append(ssdp_loc.strip()) - for u in (row.get("url"), (row.get("xml_fields") or {}).get("presentationURL")): - if isinstance(u, str) and u.strip(): - candidate_urls.append(u.strip()) - # Fallback from raw xml LOCATION URL if present in row. - if not candidate_urls: - raw_xml = row.get("raw_xml") - if isinstance(raw_xml, str) and "URLBase>" in raw_xml: - start = raw_xml.find("URLBase>") - end = raw_xml.find("") - if start >= 0 and end > start: - candidate_urls.append(raw_xml[start + 8 : end].strip()) - host = "" - for u in candidate_urls: - try: - p = urlparse(u) - except ValueError: - continue - if p.hostname: - host = str(p.hostname).strip() - break - if not host: - continue - out[host] = dict(row) - return out - - def _emit_cached_devices(self) -> None: - """Pre-populate the device store from the SSDP profile disk cache before protocols start. - - Iterates the cached SSDP profiles and emits each as a synthetic ``ssdp`` device so that - previously-seen devices appear in the UI immediately at startup — without waiting 5-15 s - for live discovery to respond. - - Cache entries older than 24 h are skipped (same TTL as the cache GC). Once live - protocol events arrive they overwrite these entries: a live SSDP row shares the same - Device key (``ssdp:udn:…`` when a UDN is present, else ``ssdp:{ip}:{port}``) and simply - replaces the pre-populated entry via the normal ``add_or_update_device`` pipeline. - """ - _CACHE_MAX_AGE_S = 86_400 # 24 h - now = datetime.now(timezone.utc) - emitted = 0 - for sip, row in self._ssdp_profile_cache_by_ip.items(): - if not isinstance(row, dict): - continue - # TTL guard — skip entries not updated in the last 24 h. - updated_raw = row.get("updated_at") - if isinstance(updated_raw, str): - try: - updated_dt = datetime.fromisoformat(updated_raw) - if (now - updated_dt).total_seconds() > _CACHE_MAX_AGE_S: - self._logger.debug("_emit_cached_devices: skipping stale entry ip=%s updated_at=%s", sip, updated_raw) - continue - except ValueError: - pass # malformed timestamp → include the entry rather than skip it - name = self._ssdp_profile_display_name(row) - if not name: - name = f"Device ({sip})" - device_type = row.get("type") or "unknown" - if not isinstance(device_type, str): - device_type = "unknown" - device_category = row.get("category") or self._category_for_type(device_type) - if not isinstance(device_category, str): - device_category = self._category_for_type(device_type) - # Derive port from ssdp_location URL (e.g. "http://192.168.1.103:8008/…"). - port = 0 - ssdp_loc = row.get("ssdp_location") - if isinstance(ssdp_loc, str) and ssdp_loc.strip(): - try: - parsed = urlparse(ssdp_loc.strip()) - if parsed.port: - port = parsed.port - except Exception: - pass - # Build metadata mirrors a lean SSDP device event so hydration / details work. - metadata: dict = {"from_ssdp_cache": True} - xml_fields = row.get("xml_fields") - if isinstance(xml_fields, dict): - metadata["xml_fields"] = dict(xml_fields) - raw_xml = row.get("raw_xml") - if isinstance(raw_xml, str) and raw_xml.strip(): - metadata["xml"] = raw_xml - if isinstance(ssdp_loc, str) and ssdp_loc.strip(): - metadata["location"] = ssdp_loc.strip() - url = row.get("url") - device = Device( - name=name, - ip=sip, - port=port, - type=device_type, - category=device_category, - source="ssdp", - url=url if isinstance(url, str) and url.strip() else None, - metadata=metadata, - online=True, - ) - self.add_or_update_device(device) - emitted += 1 - self._logger.info("_emit_cached_devices: pre-populated %d device(s) from SSDP profile cache", emitted) - - def _ssdp_profile_display_name(self, row: dict) -> str: - """Best-effort human label from persisted SSDP profile (disk cache).""" - n = row.get("name") - if isinstance(n, str) and n.strip(): - return n.strip() - xf = row.get("xml_fields") if isinstance(row.get("xml_fields"), dict) else {} - for key in ("friendlyName", "displayName"): - value = xf.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - return "" - - def _hydrate_mdns_from_ssdp_profile_cache(self, device: Device, prior_row: Device | None = None) -> None: - """Merge SSDP disk-cache hints onto an mDNS row. - - Precedence among inputs (see ``merge.information_precedence`` in ``~/.config/netneighbor/discovery.json``): - user prefs override SSDP live; SSDP live overrides this disk cache; this cache overrides plain mDNS - naming/type inference. - - **Rule 0** — user name / location prefs override everything (see - :meth:`_has_effective_name_override`, :meth:`_apply_name_override`). - **Rule 1** — persisted SSDP ``friendlyName`` / profile ``name`` overrides mDNS naming unless rule 0 applies. - """ - if device.source != "mdns": - return - sip = str(device.ip).strip() - if not sip: - return - row = self._ssdp_profile_cache_by_ip.get(sip) - if not isinstance(row, dict): - return - if not isinstance(device.metadata, dict): - device.metadata = {} - xml_fields = row.get("xml_fields") - if isinstance(xml_fields, dict): - md_xml = device.metadata.get("xml_fields") - if not isinstance(md_xml, dict): - md_xml = {} - for key, value in xml_fields.items(): - if key not in md_xml and value: - md_xml[key] = value - if md_xml: - device.metadata["xml_fields"] = md_xml - # Also carry over raw XML and SSDP location so the "Device data" tab - # appears in details even when there is no live SSDP device. - if not device.metadata.get("xml"): - raw_xml = row.get("raw_xml") - if isinstance(raw_xml, str) and raw_xml.strip(): - device.metadata["xml"] = raw_xml - if not device.metadata.get("location"): - ssdp_loc = row.get("ssdp_location") - if isinstance(ssdp_loc, str) and ssdp_loc.strip(): - device.metadata["location"] = ssdp_loc - cached_display = self._ssdp_profile_display_name(row) - if cached_display and not self._has_effective_name_override(device, prior_row): - # Rule 1 vs mDNS; skipped when rule 0 applies (see _has_effective_name_override). - device.name = cached_display - self._apply_ssdp_cache_type_to_mdns(device, row) - - def _hydrate_ssdp_from_profile_cache(self, device: Device) -> None: - """Pre-populate empty xml_fields on a live SSDP device from the disk profile cache. - - When the live XML fetch has not yet completed (or previously failed), the - cached xml_fields from a prior successful fetch are used as an immediate - starting point so the details panel is never blank. The live fetch result - will overwrite these values once it arrives (higher-precedence merge path). - """ - if device.source != "ssdp": - return - sip = str(device.ip).strip() - if not sip: - return - row = self._ssdp_profile_cache_by_ip.get(sip) - if not isinstance(row, dict): - return - if not isinstance(device.metadata, dict): - device.metadata = {} - cached_xml = row.get("xml_fields") - if not isinstance(cached_xml, dict) or not cached_xml: - return - md_xml = device.metadata.get("xml_fields") - if not isinstance(md_xml, dict): - md_xml = {} - for key, value in cached_xml.items(): - if key not in md_xml and value: - md_xml[key] = value - if md_xml: - device.metadata["xml_fields"] = md_xml - if not device.metadata.get("xml"): - raw_xml = row.get("raw_xml") - if isinstance(raw_xml, str) and raw_xml.strip(): - device.metadata["xml"] = raw_xml - if not device.metadata.get("location"): - ssdp_loc = row.get("ssdp_location") - if isinstance(ssdp_loc, str) and ssdp_loc.strip(): - device.metadata["location"] = ssdp_loc - - def _apply_ssdp_cache_type_to_mdns(self, device: Device, row: dict) -> None: - """Use SSDP profile-cache type hints after merging ``xml_fields`` (not only when mDNS type is unknown). - - Samba ``_smb._tcp`` is inferred as ``computer`` before UUID/MAC may arrive; disk cache may already - hold ``modelType: NAS`` or a richer ``type`` from a prior SSDP observation. - """ - md = device.metadata if isinstance(device.metadata, dict) else {} - xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} - mt = (xf.get("modelType") or "").strip().lower() - if mt == "nas": - device.type = "nas" - device.category = self._category_for_type("nas") - return - cached = row.get("type") - if not isinstance(cached, str) or not cached.strip(): - return - ct = cached.strip().lower() - cur = str(device.type or "").strip().lower() - if cur == "unknown": - device.type = ct - device.category = self._category_for_type(ct) - return - weak = {"unknown", "http", "https", "computer"} - if cur in weak and self._cross_protocol_type_rank(ct) > self._cross_protocol_type_rank(cur): - device.type = ct - device.category = self._category_for_type(ct) - - def _mdns_web_endpoint(self, md: dict, device: Device) -> tuple[int, bool]: - """HTTP(S) port from merged mDNS ``_http._tcp`` / ``_https._tcp`` rows.""" - services = md.get("services") if isinstance(md.get("services"), list) else [] - https_p = 0 - http_p = 0 - for svc in services: - if not isinstance(svc, dict): - continue - name = str(svc.get("service", "")).lower() - port = int(svc.get("port", 0) or 0) - if port <= 0: - continue - if "_https._tcp" in name: - https_p = https_p or port - if "_http._tcp" in name: - http_p = http_p or port - if https_p: - return (https_p, True) - if http_p: - return (http_p, False) - dp = int(device.port or 0) - if dp > 0: - return (dp, False) - return (80, False) - - def _collect_mdns_descriptor_candidates(self, md: dict, ip: str, fallback_port: int, fallback_https: bool) -> list[tuple[int, str]]: - scored: dict[str, int] = {} - - def push(url: str) -> None: - u = (url or "").strip() - if not u: - return - q = self._ssdp_location_quality_score(u) - if q < 2: - return - prev = scored.get(u) - if prev is None or q > prev: - scored[u] = q - - def push_relative(path_fragment: str, port: int, https: bool) -> None: - norm = _normalize_mdns_relative_descriptor_path(path_fragment) - if not norm: - return - if norm.startswith(("http://", "https://")): - push(norm) - return - base = _http_base_url_for_descriptor(ip, port, https=https) - if not base: - return - full = _join_descriptor_base_and_path(base, norm) - if full: - push(full) - - agg_port, agg_https = int(fallback_port or 0), fallback_https - if agg_port <= 0: - agg_port = 80 - - combined = md.get("txt") if isinstance(md.get("txt"), dict) else {} - if isinstance(combined, dict): - for _key, val in combined.items(): - if not isinstance(val, str): - continue - v = val.strip() - if v.startswith(("http://", "https://")): - push(v) - for pk in ("path", "rp", "description_path", "descriptor_path", "device_description"): - raw = combined.get(pk) - if isinstance(raw, str) and raw.strip(): - push_relative(raw, agg_port, agg_https) - for _key, val in combined.items(): - if not isinstance(val, str): - continue - v = val.strip() - if ".xml" not in v.lower(): - continue - if v.startswith(("http://", "https://")): - continue - lk = str(_key).lower() - if lk in {"path", "rp", "description_path", "descriptor_path", "device_description"}: - continue - push_relative(v, agg_port, agg_https) - - services = md.get("services") if isinstance(md.get("services"), list) else [] - for svc in services: - if not isinstance(svc, dict): - continue - stxt = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} - if not stxt: - continue - sn = str(svc.get("service", "")).lower() - sport = int(svc.get("port", 0) or 0) - if sport <= 0: - sport = agg_port - if "_https._tcp" in sn: - svc_https = True - elif "_http._tcp" in sn: - svc_https = False - else: - svc_https = agg_https - - for _key, val in stxt.items(): - if not isinstance(val, str): - continue - v = val.strip() - if v.startswith(("http://", "https://")): - push(v) - for pk in ("path", "rp", "description_path", "descriptor_path", "device_description"): - raw = stxt.get(pk) - if isinstance(raw, str) and raw.strip(): - push_relative(raw, sport, svc_https) - for key, val in stxt.items(): - if not isinstance(val, str): - continue - v = val.strip() - if ".xml" not in v.lower(): - continue - if v.startswith(("http://", "https://")): - continue - lk = str(key).lower() - if lk in {"path", "rp", "description_path", "descriptor_path", "device_description"}: - continue - push_relative(v, sport, svc_https) - - return sorted(((q, u) for u, q in scored.items()), key=lambda t: t[0], reverse=True) - - def _best_mdns_descriptor_template(self, device: Device) -> str | None: - """Full descriptor URL if mDNS TXT advertises a UPnP XML path (often faster than waiting for SSDP).""" - if device.source != "mdns": - return None - md = device.metadata if isinstance(device.metadata, dict) else {} - sip = str(device.ip).strip() - if not sip: - return None - port, https = self._mdns_web_endpoint(md, device) - candidates = self._collect_mdns_descriptor_candidates(md, sip, port, https) - if not candidates: - return None - return candidates[0][1] - - def _resolve_anticipatory_descriptor_for_mdns( - self, device: Device, sip: str - ) -> tuple[str, AnticipatoryDescriptorSource] | None: - """Choose descriptor GET URL for anticipatory fetch — **one precedence chain**. - - The HTTP GET target is not ambiguous: we never blend SSDP cache with mDNS as competing URLs. - - 1. ``ssdp_profile_cache``: persisted SSDP ``LOCATION`` from disk profile cache (same path/query as - prior SSDP observation); host rewritten to ``sip``. - 2. ``mdns_txt``: only when (1) has no usable ``ssdp_location`` — TXT may advertise the descriptor - before SSDP has run / populated cache. - """ - self._ssdp_profile_cache_by_ip = self._load_ssdp_profile_cache_by_ip() - row = self._ssdp_profile_cache_by_ip.get(sip) - loc = row.get("ssdp_location") if isinstance(row, dict) else None - loc_s = loc.strip() if isinstance(loc, str) and loc.strip() else "" - if loc_s: - url_new = _descriptor_url_with_ip(loc_s, sip) - if url_new: - return (url_new, "ssdp_profile_cache") - mdns_tpl = self._best_mdns_descriptor_template(device) - if mdns_tpl: - url_new = _descriptor_url_with_ip(mdns_tpl, sip) - if url_new: - return (url_new, "mdns_txt") - return None - - def _schedule_anticipatory_descriptor_fetch(self, device: Device) -> None: - """Prefetch UPnP descriptor XML for mDNS hosts when we can build the URL early. - - Resolution uses :meth:`_resolve_anticipatory_descriptor_for_mdns` (single source-of-truth chain). - """ - if device.source != "mdns" or not device.online: - return - ssdp = self._ssdp_discovery - if ssdp is None: - return - k = device.key - if k in self._anticipatory_fetch_attempted: - return - sip = str(device.ip).strip() - if not sip or sip in {"0.0.0.0", "::"}: - return - - resolved = self._resolve_anticipatory_descriptor_for_mdns(device, sip) - if not resolved: - return - url_new, url_source = resolved - - self._anticipatory_fetch_attempted.add(k) - self._logger.debug( - "Anticipatory descriptor fetch scheduled ip=%s source=%s url=%s", - sip, - url_source, - url_new, - ) - - def worker() -> None: - try: - xml_fields, raw_xml = ssdp.fetch_descriptor_xml(url_new) - except Exception: - self._mdns_logger.debug("Anticipatory descriptor fetch failed for %s", url_new, exc_info=True) - return - if not xml_fields and not raw_xml: - return - - def apply_on_idle() -> bool: - self._apply_prefetched_descriptor( - k, - url_new, - xml_fields or {}, - raw_xml, - url_source=url_source, - ) - return False - - try: - from gi.repository import GLib - - GLib.idle_add(apply_on_idle) - except Exception: - self._apply_prefetched_descriptor( - k, - url_new, - xml_fields or {}, - raw_xml, - url_source=url_source, - ) - - threading.Thread(target=worker, name="NetNeighbor-anticipatory-xml", daemon=True).start() - - def _apply_prefetched_descriptor( - self, - device_key: str, - fetch_url: str, - xml_fields: dict, - raw_xml: str | None, - *, - url_source: AnticipatoryDescriptorSource, - ) -> None: - if device_key in self._anticipatory_reentrant: - return - existing = self._devices.get(device_key) - if existing is None or existing.source != "mdns": - return - self._anticipatory_reentrant.add(device_key) - try: - md = dict(existing.metadata) if isinstance(existing.metadata, dict) else {} - prev_xf = md.get("xml_fields") if isinstance(md.get("xml_fields"), dict) else {} - merged_xf = dict(prev_xf) - for fk, fv in xml_fields.items(): - if fv is None: - continue - if isinstance(fv, str) and not fv.strip(): - continue - merged_xf[fk] = fv.strip() if isinstance(fv, str) else fv - md["xml_fields"] = merged_xf - if raw_xml: - md["xml"] = raw_xml - md["anticipatory_descriptor_url"] = fetch_url - md["anticipatory_descriptor_source"] = url_source - name = existing.name - fn = merged_xf.get("friendlyName") or merged_xf.get("displayName") - if not self._has_effective_name_override(existing): - if isinstance(fn, str) and fn.strip() and self._is_generic_discovery_name(name): - name = fn.strip() - url = existing.url - if not url: - pu = merged_xf.get("presentationURL") - if isinstance(pu, str) and pu.strip(): - url = pu.strip() - icon = existing.icon - if not icon: - iu = merged_xf.get("iconURL") - if isinstance(iu, str) and iu.strip(): - icon = iu.strip() - updated = Device( - name=name, - ip=existing.ip, - port=existing.port, - type=existing.type, - category=existing.category, - source=existing.source, - url=url, - metadata=md, - last_seen=existing.last_seen, - online=existing.online, - monitored=existing.monitored, - icon=icon, - ) - self._apply_field_mapping_rules(updated) - self._apply_type_override(updated) - self._apply_name_override(updated) - self._apply_location_override(updated) - self._apply_url_override(updated) - self._apply_device_commands(updated) - self._apply_custom_command_override(updated) - self._apply_monitored_override(updated) - self._devices[device_key] = updated - self._run_location_reapply_sweep() - self._notify() - finally: - self._anticipatory_reentrant.discard(device_key) - - def _stable_identity_available(self, device: Device) -> bool: - metadata = device.metadata if isinstance(device.metadata, dict) else {} - return bool(self._extract_uid(metadata) or self._extract_mac(metadata)) - - def _pending_identity_key(self, device: Device) -> str: - return f"{(device.source or '').strip().lower()}:{str(device.ip).strip()}:{int(device.port)}" - - def _should_hold_for_stable_identity(self, device: Device) -> bool: - """Delay first appearance briefly until UID/MAC shows up, then release.""" - if device.source not in {"mdns", "ssdp"} or not bool(device.online): - return False - if self._stable_identity_available(device): - pending_key = self._pending_identity_key(device) - if pending_key in self._identity_pending: - self._identity_pending.pop(pending_key, None) - self._device_event_logger(device.source).debug( - "identity_resolved ip=%s port=%s source=%s", - device.ip, - device.port, - device.source, - ) - return False - - now = datetime.now(timezone.utc) - pending_key = self._pending_identity_key(device) - first_seen, _prev = self._identity_pending.get(pending_key, (now, device)) - self._identity_pending[pending_key] = (first_seen, device) - if now - first_seen < timedelta(seconds=_IDENTITY_HOLD_SECONDS): - self._device_event_logger(device.source).debug( - "identity_pending ip=%s port=%s source=%s held_for_ms=%s", - device.ip, - device.port, - device.source, - int((now - first_seen).total_seconds() * 1000), - ) - return True - self._device_event_logger(device.source).debug( - "identity_pending_timeout ip=%s port=%s source=%s hold_s=%s", - device.ip, - device.port, - device.source, - _IDENTITY_HOLD_SECONDS, - ) - self._identity_pending.pop(pending_key, None) - return False - - def _emit_presence_hooks_if_transition(self, device: Device, prev_online: bool | None, now_online: bool) -> None: - # Skip first-seen already-offline rows (monitoring placeholders, etc.). - if now_online and prev_online is not True: - transition: PresenceTransitionKind = "online" - elif prev_online is True and not now_online: - transition = "offline" - else: - return - if not self._presence_hooks: - return - for hook in tuple(self._presence_hooks): - try: - hook(device, transition) - except Exception: - self._logger.exception("Presence transition hook failed (event=%s)", transition) - - def set_type_overrides(self, overrides: dict[str, str]) -> None: - normalized: dict[str, str] = {} - for key, value in overrides.items(): - if not isinstance(key, str) or not isinstance(value, str): - continue - value_norm = value.strip().lower() - if value_norm: - normalized[key] = value_norm - self._type_overrides = normalized - - def get_type_overrides(self) -> dict[str, str]: - return dict(self._type_overrides) - - def set_name_overrides(self, overrides: dict[str, str]) -> None: - normalized: dict[str, str] = {} - for key, value in overrides.items(): - if not isinstance(key, str) or not isinstance(value, str): - continue - value_norm = value.strip() - if value_norm: - normalized[key] = value_norm - self._name_overrides = normalized - - def get_name_overrides(self) -> dict[str, str]: - return dict(self._name_overrides) - - def set_url_overrides(self, overrides: dict[str, str]) -> None: - normalized: dict[str, str] = {} - for key, value in overrides.items(): - if not isinstance(key, str) or not isinstance(value, str): - continue - value_norm = value.strip() - if value_norm: - normalized[key] = value_norm - self._url_overrides = normalized - - def get_url_overrides(self) -> dict[str, str]: - return dict(self._url_overrides) - - def set_device_commands_overrides(self, overrides: object) -> None: - """Bulk-load per-device commands from persisted preferences. - Accepts new list format or legacy dict format (auto-migrated to override mode).""" - normalized: dict[str, list[dict]] = {} - if not isinstance(overrides, dict): - self._device_commands = normalized - return - for key, raw in overrides.items(): - if not isinstance(key, str): - continue - # Legacy format: {scheme: {ip, port}} → convert to list with mode=override - if isinstance(raw, dict): - raw = [ - {"scheme": s, "ip": ep.get("ip", ""), "port": ep.get("port", 0), - "mode": "override", "label": ""} - for s, ep in raw.items() if isinstance(ep, dict) - ] - if not isinstance(raw, list): - continue - valid = _normalize_command_list(raw) - if valid: - normalized[key] = valid - self._device_commands = normalized - - def get_device_commands_overrides(self) -> dict[str, list[dict]]: - return {k: [dict(c) for c in cmds] for k, cmds in self._device_commands.items()} - - def set_custom_command_overrides(self, overrides: dict[str, str]) -> None: - """Bulk-load per-device custom command overrides from persisted preferences.""" - normalized: dict[str, str] = {} - if isinstance(overrides, dict): - for key, cmd in overrides.items(): - if isinstance(key, str) and isinstance(cmd, str) and cmd.strip(): - normalized[key] = cmd.strip() - self._custom_command_overrides = normalized - - def get_custom_command_overrides(self) -> dict[str, str]: - return dict(self._custom_command_overrides) - - def set_location_overrides(self, overrides: dict[str, str]) -> None: - normalized: dict[str, str] = {} - for key, value in overrides.items(): - if not isinstance(key, str) or not isinstance(value, str): - continue - value_norm = value.strip() - if value_norm: - normalized[key] = value_norm - self._location_overrides = normalized - changed = False - for device in self._devices.values(): - before = "" - metadata = device.metadata if isinstance(device.metadata, dict) else {} - value = metadata.get("user_location") - if isinstance(value, str): - before = value - self._apply_location_override(device) - metadata_after = device.metadata if isinstance(device.metadata, dict) else {} - after_raw = metadata_after.get("user_location") - after = after_raw if isinstance(after_raw, str) else "" - if before != after: - changed = True - if self._run_location_reapply_sweep(): - changed = True - if changed: - self._notify() - - def get_location_overrides(self) -> dict[str, str]: - return dict(self._location_overrides) - - def set_field_mapping_rules(self, rules: dict[str, dict[str, list[str]]]) -> None: - normalized: dict[str, dict[str, list[str]]] = {} - for key, value in rules.items(): - if not isinstance(key, str) or not isinstance(value, dict): - continue - per_target: dict[str, list[str]] = {} - for target in ("name", "location", "information"): - raw = value.get(target) - if not isinstance(raw, list): - continue - cleaned = [str(x).strip() for x in raw if isinstance(x, str) and str(x).strip()] - if cleaned: - per_target[target] = list(dict.fromkeys(cleaned)) - if per_target: - normalized[key] = per_target - self._field_mapping_rules = normalized - changed = False - for device in self._devices.values(): - before_name = device.name - before_info = "" - before_loc = "" - md = device.metadata if isinstance(device.metadata, dict) else {} - if isinstance(md.get("information"), str): - before_info = md.get("information", "") - if isinstance(md.get("user_location"), str): - before_loc = md.get("user_location", "") - self._apply_field_mapping_rules(device) - self._apply_name_override(device) - self._apply_location_override(device) - md_after = device.metadata if isinstance(device.metadata, dict) else {} - after_info = md_after.get("information") if isinstance(md_after.get("information"), str) else "" - after_loc = md_after.get("user_location") if isinstance(md_after.get("user_location"), str) else "" - if device.name != before_name or after_info != before_info or after_loc != before_loc: - changed = True - if changed: - self._notify() - - def get_field_mapping_rules(self) -> dict[str, dict[str, list[str]]]: - out: dict[str, dict[str, list[str]]] = {} - for key, value in self._field_mapping_rules.items(): - out[key] = {target: list(paths) for target, paths in value.items()} - return out - - def set_monitored_overrides(self, overrides: dict[str, bool]) -> None: - normalized: dict[str, bool] = {} - for key, value in overrides.items(): - if isinstance(key, str): - normalized[key] = bool(value) - self._monitored_overrides = normalized - - def get_monitored_overrides(self) -> dict[str, bool]: - return dict(self._monitored_overrides) - - def set_last_seen_overrides(self, overrides: dict[str, str]) -> None: - normalized: dict[str, str] = {} - for key, value in overrides.items(): - if isinstance(key, str) and isinstance(value, str) and value.strip(): - normalized[key] = value.strip() - self._last_seen_overrides = normalized - - def get_last_seen_overrides(self) -> dict[str, str]: - return dict(self._last_seen_overrides) - - def restore_monitored_snapshots(self, snapshots: list[dict]) -> None: - if not isinstance(snapshots, list): - return - changed = False - for raw in snapshots: - if not isinstance(raw, dict): - continue - source = str(raw.get("source", "unknown")).strip().lower() - ip = str(raw.get("ip", "")).strip() - port_raw = raw.get("port", 0) - try: - port = int(port_raw) - except (TypeError, ValueError): - continue - if not ip or port <= 0: - continue - metadata = raw.get("metadata") - if not isinstance(metadata, dict): - metadata = {} - device = Device( - name=str(raw.get("name", "Unknown")) or "Unknown", - ip=ip, - port=port, - type=str(raw.get("type", "unknown")) or "unknown", - category=str(raw.get("category", "Unknown Devices")) or "Unknown Devices", - source=source or "unknown", - url=raw.get("url") if isinstance(raw.get("url"), str) else None, - metadata=metadata, - online=False, - monitored=True, - icon=raw.get("icon") if isinstance(raw.get("icon"), str) else None, - ) - seen_text = raw.get("last_seen") - if isinstance(seen_text, str) and seen_text.strip(): - try: - device.last_seen = datetime.fromisoformat(seen_text.strip()) - except ValueError: - pass - self._apply_type_override(device) - self._apply_monitored_override(device) - if not device.monitored: - continue - existing = self._devices.get(device.key) - if existing is not None and existing.online: - continue - self._devices[device.key] = device - changed = True - if changed: - self._notify() - - def set_device_type_override(self, source: str, ip: str, port: int, device_type: str | None) -> None: - changed = False - for old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - if device_type is None or not str(device_type).strip() or str(device_type).strip().lower() == "auto": - self._type_overrides.pop(preferred_key, None) - self._type_overrides.pop(endpoint_key, None) - else: - self._type_overrides.pop(endpoint_key, None) - self._type_overrides[preferred_key] = str(device_type).strip().lower() - self._apply_type_override(existing) - new_key = existing.key - if new_key != old_key: - self._devices.pop(old_key, None) - self._devices[new_key] = existing - changed = True - if changed: - self._notify() - - def set_device_name_override(self, source: str, ip: str, port: int, device_name: str | None) -> None: - changed = False - for _old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_name_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - if device_name is None or not str(device_name).strip(): - self._name_overrides.pop(preferred_key, None) - self._name_overrides.pop(endpoint_key, None) - existing.name = self._default_name_for_device(existing) - else: - self._name_overrides.pop(endpoint_key, None) - self._name_overrides[preferred_key] = str(device_name).strip() - self._apply_name_override(existing) - changed = True - if changed: - self._notify() - - def set_device_location_override(self, source: str, ip: str, port: int, location: str | None) -> None: - changed = False - for _old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_name_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - if location is None or not str(location).strip(): - self._location_overrides.pop(preferred_key, None) - self._location_overrides.pop(endpoint_key, None) - else: - self._location_overrides.pop(endpoint_key, None) - self._location_overrides[preferred_key] = str(location).strip() - self._apply_location_override(existing) - changed = True - if changed: - self._notify() - - def set_device_url_override(self, source: str, ip: str, port: int, url: str | None) -> None: - changed = False - for _old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_name_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - if url is None or not str(url).strip(): - self._url_overrides.pop(preferred_key, None) - self._url_overrides.pop(endpoint_key, None) - else: - self._url_overrides.pop(endpoint_key, None) - self._url_overrides[preferred_key] = str(url).strip() - self._apply_url_override(existing) - changed = True - if changed: - self._notify() - - def set_device_commands( - self, source: str, ip: str, port: int, commands: list[dict], - ) -> None: - """Replace all per-device commands for a specific device.""" - changed = False - for _old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_name_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - self._device_commands.pop(endpoint_key, None) - valid = _normalize_command_list(commands) if isinstance(commands, list) else [] - if valid: - self._device_commands[preferred_key] = valid - else: - self._device_commands.pop(preferred_key, None) - self._apply_device_commands(existing) - changed = True - if changed: - self._notify() - - def set_device_custom_command(self, source: str, ip: str, port: int, cmd: str | None) -> None: - """Set or clear a per-device custom command override.""" - changed = False - for _old_key, existing in list(self._devices.items()): - if existing.source != source or existing.ip != ip or existing.port != port: - continue - preferred_key = self._make_name_override_key_for_device(existing) - endpoint_key = self._make_override_key(source, ip, port) - if cmd is None or not str(cmd).strip(): - self._custom_command_overrides.pop(preferred_key, None) - self._custom_command_overrides.pop(endpoint_key, None) - else: - self._custom_command_overrides.pop(endpoint_key, None) - self._custom_command_overrides[preferred_key] = str(cmd).strip() - self._apply_custom_command_override(existing) - changed = True - if changed: - self._notify() - - def set_device_field_mapping_rule(self, source: str, ip: str, port: int, target: str, field_path: str) -> None: - target_norm = str(target).strip().lower() - path_norm = str(field_path).strip() - if target_norm not in {"name", "location", "information"} or not path_norm: - return - changed = False - ip_norm = str(ip).strip() - for _old_key, existing in list(self._devices.items()): - if str(existing.ip).strip() != ip_norm: - continue - preferred_key = self._make_name_override_key_for_device(existing) - rules = self._field_mapping_rules.get(preferred_key) - if not isinstance(rules, dict): - rules = {} - bucket = rules.get(target_norm) - if not isinstance(bucket, list): - bucket = [] - if path_norm in bucket: - continue - bucket.append(path_norm) - rules[target_norm] = bucket - self._field_mapping_rules[preferred_key] = rules - changed = True - self._apply_field_mapping_rules(existing) - self._apply_location_override(existing) - self._apply_name_override(existing) - if changed: - self._notify() - - def remove_device_field_mapping_rule( - self, source: str, ip: str, port: int, target: str, field_path: str | None = None - ) -> None: - target_norm = str(target).strip().lower() - if target_norm not in {"name", "location", "information"}: - return - field_norm = str(field_path).strip() if isinstance(field_path, str) else "" - changed = False - ip_norm = str(ip).strip() - for _old_key, existing in list(self._devices.items()): - if str(existing.ip).strip() != ip_norm: - continue - preferred_key = self._make_name_override_key_for_device(existing) - rules = self._field_mapping_rules.get(preferred_key) - if not isinstance(rules, dict): - continue - bucket = rules.get(target_norm) - if not isinstance(bucket, list) or not bucket: - continue - if field_norm: - new_bucket = [x for x in bucket if x != field_norm] - else: - new_bucket = [] - if new_bucket == bucket: - continue - if new_bucket: - rules[target_norm] = new_bucket - else: - rules.pop(target_norm, None) - if rules: - self._field_mapping_rules[preferred_key] = rules - else: - self._field_mapping_rules.pop(preferred_key, None) - changed = True - self._apply_field_mapping_rules(existing) - self._apply_location_override(existing) - self._apply_name_override(existing) - if changed: - self._notify() - - def get_device_field_mapping_rules(self, device: Device) -> dict[str, list[str]]: - out: dict[str, list[str]] = {} - ip_norm = str(device.ip).strip() - for row in self._devices.values(): - if str(row.ip).strip() != ip_norm: - continue - preferred_key = self._make_name_override_key_for_device(row) - value = self._field_mapping_rules.get(preferred_key) - if not isinstance(value, dict): - continue - for target, paths in value.items(): - if not isinstance(paths, list): - continue - bucket = out.get(target) - if not isinstance(bucket, list): - bucket = [] - for path in paths: - if isinstance(path, str) and path.strip() and path not in bucket: - bucket.append(path) - out[target] = bucket - return out - - def _merge_ssdp_metadata(self, old_meta: dict, new_meta: dict, old_name: str, new_name: str) -> dict: - old_meta = old_meta if isinstance(old_meta, dict) else {} - new_meta = new_meta if isinstance(new_meta, dict) else {} - merged = dict(old_meta) - merged.update(new_meta) - - old_xml_fields = old_meta.get("xml_fields") if isinstance(old_meta.get("xml_fields"), dict) else {} - new_xml_fields = new_meta.get("xml_fields") if isinstance(new_meta.get("xml_fields"), dict) else {} - old_rank = self._ssdp_profile_rank(old_xml_fields) - new_rank = self._ssdp_profile_rank(new_xml_fields) - preferred_xml_fields = old_xml_fields if old_rank >= new_rank else new_xml_fields - self._ssdp_logger.debug( - "SSDP profile rank old=%s new=%s selected=%s", - old_rank, - new_rank, - "old" if old_rank >= new_rank else "new", - ) - - merged_xml_fields = dict(old_xml_fields) - for key, value in new_xml_fields.items(): - if value is None: - continue - if isinstance(value, str): - value_norm = value.strip() - if not value_norm or value_norm.lower() == "unavailable": - continue - old_value = merged_xml_fields.get(key) - if not old_value: - merged_xml_fields[key] = value_norm - continue - # Keep richer data when two payloads disagree (e.g. Sonos speaker group vs full root description). - if len(value_norm) > len(str(old_value).strip()): - merged_xml_fields[key] = value_norm - else: - merged_xml_fields[key] = value - - # Strict preference for the richer/profile-ranked XML fields. - for strict_key in ("friendlyName", "deviceType", "iconURL", "icons_description"): - preferred_value = preferred_xml_fields.get(strict_key) - if isinstance(preferred_value, str) and preferred_value.strip(): - merged_xml_fields[strict_key] = preferred_value.strip() - - merged["xml_fields"] = merged_xml_fields - - # Track alternate names instead of overwriting main identity. - aliases = merged.get("alternate_names") - if not isinstance(aliases, list): - aliases = [] - for candidate in (old_name, new_name): - if not isinstance(candidate, str): - continue - value = candidate.strip() - if not value or value in aliases: - continue - aliases.append(value) - self._ssdp_logger.debug("SSDP alias tracked: %s", value) - merged["alternate_names"] = aliases - - # Keep last known information text when a partial payload does not provide it. - old_info = old_meta.get("information") - new_info = new_meta.get("information") - if isinstance(new_info, str) and new_info.strip(): - merged["information"] = new_info.strip() - elif isinstance(old_info, str) and old_info.strip(): - merged["information"] = old_info.strip() - - old_xml = old_meta.get("xml") - new_xml = new_meta.get("xml") - if isinstance(old_xml, str) and isinstance(new_xml, str): - if old_rank >= new_rank and len(old_xml.strip()) >= len(new_xml.strip()): - merged["xml"] = old_xml - self._ssdp_logger.debug("SSDP raw XML preserved from previous richer profile") - elif isinstance(old_xml, str) and not isinstance(new_xml, str): - merged["xml"] = old_xml - self._ssdp_logger.debug("SSDP raw XML preserved because new payload has no XML") - - merged["location"] = self._pick_better_ssdp_location( - old_meta.get("location"), - new_meta.get("location"), - old_rank, - new_rank, - ) - - return merged - - def _ssdp_location_quality_score(self, value: str) -> int: - s = (value or "").strip() - if not s: - return -1 - low = s.lower() - score = 0 - if low.startswith(("http://", "https://")): - score += 1 - if low.endswith(".xml"): - score += 1 - if any(x in low for x in ("device-desc.xml", "description.xml", "/ssdp/")): - score += 4 - if "/dd.xml" in low: - score -= 2 - try: - parsed = urlparse(s) - if parsed.port in {80, 443, 8008, 1400, 5000}: - score += 1 - except Exception: - pass - return score - - def _pick_better_ssdp_location(self, old_loc, new_loc, old_rank: int, new_rank: int) -> str | None: - old_s = old_loc.strip() if isinstance(old_loc, str) and old_loc.strip() else "" - new_s = new_loc.strip() if isinstance(new_loc, str) and new_loc.strip() else "" - if not old_s: - self._ssdp_logger.debug( - "SSDP XML location selected(new-only) old=%r new=%r old_rank=%s new_rank=%s", - old_s, - new_s, - old_rank, - new_rank, - ) - return new_s or None - if not new_s: - self._ssdp_logger.debug( - "SSDP XML location selected(old-only) old=%r new=%r old_rank=%s new_rank=%s", - old_s, - new_s, - old_rank, - new_rank, - ) - return old_s - old_q = self._ssdp_location_quality_score(old_s) - new_q = self._ssdp_location_quality_score(new_s) - # If one LOCATION looks clearly better, prefer it even if XML profile rank differs. - # This avoids sticky picks like random-port /dd.xml overriding DIAL device-desc.xml. - quality_gap = 3 - if new_q >= old_q + quality_gap: - self._ssdp_logger.debug( - "SSDP XML location selected(new-quality-gap) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", - old_s, - new_s, - old_rank, - new_rank, - old_q, - new_q, - ) - return new_s - if old_q >= new_q + quality_gap: - self._ssdp_logger.debug( - "SSDP XML location selected(old-quality-gap) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", - old_s, - new_s, - old_rank, - new_rank, - old_q, - new_q, - ) - return old_s - if new_rank > old_rank: - self._ssdp_logger.debug( - "SSDP XML location selected(new-better-rank) old=%r new=%r old_rank=%s new_rank=%s", - old_s, - new_s, - old_rank, - new_rank, - ) - return new_s - if old_rank > new_rank: - self._ssdp_logger.debug( - "SSDP XML location selected(old-better-rank) old=%r new=%r old_rank=%s new_rank=%s", - old_s, - new_s, - old_rank, - new_rank, - ) - return old_s - if new_q > old_q: - self._ssdp_logger.debug( - "SSDP XML location selected(new-better-quality) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", - old_s, - new_s, - old_rank, - new_rank, - old_q, - new_q, - ) - return new_s - # Keep previous location on tie for visual stability. - self._ssdp_logger.debug( - "SSDP XML location selected(old-stable) old=%r new=%r old_rank=%s new_rank=%s old_q=%s new_q=%s", - old_s, - new_s, - old_rank, - new_rank, - old_q, - new_q, - ) - return old_s - - def _ssdp_profile_rank(self, xml_fields: dict) -> int: - if not isinstance(xml_fields, dict): - return 0 - device_type = str(xml_fields.get("deviceType", "")).lower() - score = 0 - if "schemas-upnp-org" in device_type: - score += 4 - if "smartspeaker-audio" in device_type: - score -= 1 - if isinstance(xml_fields.get("iconURL"), str) and xml_fields.get("iconURL", "").strip(): - score += 1 - if isinstance(xml_fields.get("manufacturer"), str) and xml_fields.get("manufacturer", "").strip(): - score += 1 - if isinstance(xml_fields.get("modelName"), str) and xml_fields.get("modelName", "").strip(): - score += 1 - return score - - def _pick_ssdp_name(self, old_name: str, new_name: str, old_meta: dict, new_meta: dict) -> str: - old_name = old_name.strip() if isinstance(old_name, str) else "" - new_name = new_name.strip() if isinstance(new_name, str) else "" - if not old_name: - return new_name or "Unknown" - if not new_name: - return old_name - - if old_name.startswith(("SSDP Device ", "Router ", "Media Server ", "Printer ")) and not new_name.startswith( - ("SSDP Device ", "Router ", "Media Server ", "Printer ") - ): - return new_name - - old_fields = old_meta.get("xml_fields") if isinstance(old_meta, dict) and isinstance(old_meta.get("xml_fields"), dict) else {} - new_fields = new_meta.get("xml_fields") if isinstance(new_meta, dict) and isinstance(new_meta.get("xml_fields"), dict) else {} - if self._ssdp_profile_rank(new_fields) > self._ssdp_profile_rank(old_fields): - self._ssdp_logger.debug("SSDP name switched to newer profile name: %s", new_name) - return new_name - self._ssdp_logger.debug("SSDP name preserved from previous profile: %s", old_name) - return old_name - - def _find_existing_ssdp_by_endpoint(self, candidate: Device) -> tuple[str, Device] | tuple[None, None]: - candidate_mac = self._extract_mac(candidate.metadata) - for key, item in self._devices.items(): - if item.source != "ssdp": - continue - if item.ip != candidate.ip or item.port != candidate.port: - continue - existing_mac = self._extract_mac(item.metadata) - if candidate_mac and existing_mac and candidate_mac != existing_mac: - self._ssdp_logger.debug( - "SSDP endpoint match rejected due to MAC mismatch ip=%s port=%s old=%s new=%s", - candidate.ip, - candidate.port, - existing_mac, - candidate_mac, - ) - continue - if candidate_mac and not existing_mac: - self._ssdp_logger.debug( - "SSDP endpoint match accepted and upgraded with MAC ip=%s port=%s mac=%s", - candidate.ip, - candidate.port, - candidate_mac, - ) - if existing_mac and not candidate_mac: - self._ssdp_logger.debug( - "SSDP endpoint match accepted using existing MAC ip=%s port=%s mac=%s", - candidate.ip, - candidate.port, - existing_mac, - ) - return key, item - return key, item - return None, None - - def _find_existing_cross_protocol_by_identity(self, candidate: Device) -> tuple[str, Device] | tuple[None, None]: - """Find an existing row from another protocol for the same host identity.""" - candidate_host_key = self._make_override_key_for_device(candidate) - if not isinstance(candidate_host_key, str) or not candidate_host_key.startswith("host:"): - return None, None - for key, item in self._devices.items(): - if item.source == candidate.source: - continue - if self._make_override_key_for_device(item) != candidate_host_key: - continue - self._device_event_logger(candidate.source).debug( - "Cross-protocol dedup matched host=%s old=%s/%s:%s new=%s/%s:%s", - candidate_host_key, - item.source, - item.ip, - item.port, - candidate.source, - candidate.ip, - candidate.port, - ) - return key, item - return None, None - - def _cross_protocol_type_rank(self, device_type: str) -> int: - t = (device_type or "unknown").strip().lower() - return { - "unknown": 0, - "http": 12, - "https": 12, - "computer": 20, - "esp32": 22, - "router": 35, - "nas": 38, - "mediaserver": 34, - "smartspeaker": 40, - "networkprinter": 55, - "multifunction_printer": 56, - "printer": 55, - "scanner": 52, - "smarttv": 36, - "smartdevice": 28, - "camera": 30, - "homeappliance": 26, - "cnc": 30, - "3dprinter": 32, - }.get(t, 8) - - def _is_generic_discovery_name(self, name: str) -> bool: - s = (name or "").strip().lower() - if not s: - return True - prefixes = ("ssdp device ", "mdns device ", "router ", "media server ", "printer ") - return any(s.startswith(prefix) for prefix in prefixes) - - def _protocol_merge_rank(self, source: str) -> int: - """Lower rank = higher precedence (earlier in ``discovery.json`` ``merge.protocol_order``).""" - s = (source or "").strip().lower() - order = self._protocol_merge_order - try: - return order.index(s) - except ValueError: - return len(order) - - def _choose_cross_protocol_display_name(self, existing: Device, incoming: Device) -> str: - """Prefer a non-generic name; if both are specific or both generic, prefer stronger protocol.""" - eg = self._is_generic_discovery_name(existing.name) - ig = self._is_generic_discovery_name(incoming.name) - if not eg and ig: - return existing.name - if eg and not ig: - return incoming.name - ir = self._protocol_merge_rank(incoming.source) - er = self._protocol_merge_rank(existing.source) - if ir < er: - return incoming.name - if er < ir: - return existing.name - return existing.name - - def _merge_cross_protocol_device(self, existing: Device, incoming: Device) -> Device: - """Merge SSDP/mDNS rows that represent the same host.""" - old_meta = existing.metadata if isinstance(existing.metadata, dict) else {} - new_meta = incoming.metadata if isinstance(incoming.metadata, dict) else {} - merged_meta = dict(old_meta) - # Keep per-protocol metadata snapshots to avoid losing diagnostics/details payloads. - proto_meta = merged_meta.get("protocol_metadata") if isinstance(merged_meta.get("protocol_metadata"), dict) else {} - proto_meta = dict(proto_meta) - proto_meta[str(existing.source)] = dict(old_meta) - proto_meta[str(incoming.source)] = dict(new_meta) - merged_meta["protocol_metadata"] = proto_meta - seen_sources = merged_meta.get("seen_sources") if isinstance(merged_meta.get("seen_sources"), list) else [] - merged_meta["seen_sources"] = sorted({str(x) for x in [*seen_sources, existing.source, incoming.source] if str(x).strip()}) - if isinstance(new_meta.get("user_location"), str) and new_meta.get("user_location", "").strip(): - merged_meta["user_location"] = new_meta.get("user_location").strip() - - old_rank = self._cross_protocol_type_rank(existing.type) - new_rank = self._cross_protocol_type_rank(incoming.type) - chosen_type = incoming.type if new_rank > old_rank else existing.type - chosen_category = self._category_for_type(chosen_type) - chosen_name = self._choose_cross_protocol_display_name(existing, incoming) - chosen_icon = existing.icon - if (not chosen_icon and incoming.icon) or new_rank > old_rank: - chosen_icon = incoming.icon or chosen_icon - chosen_url = existing.url or incoming.url - chosen_last_seen = existing.last_seen if existing.last_seen >= incoming.last_seen else incoming.last_seen - chosen_online = bool(existing.online or incoming.online) - - self._logger.debug( - "Cross-protocol merge kept=%s/%s:%s merged=%s/%s:%s type=%s->%s", - existing.source, - existing.ip, - existing.port, - incoming.source, - incoming.ip, - incoming.port, - existing.type, - chosen_type, - ) - - return Device( - name=chosen_name, - ip=existing.ip, - port=existing.port, - type=chosen_type, - category=chosen_category, - source=existing.source, - url=chosen_url, - metadata=merged_meta, - last_seen=chosen_last_seen, - online=chosen_online, - monitored=bool(existing.monitored), - icon=chosen_icon, - ) - - def _extract_mac(self, metadata: dict) -> str: - if not isinstance(metadata, dict): - return "" - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - mac = ( - xml_fields.get("mac") - or metadata.get("mac") - or metadata.get("mac_address") - or metadata.get("MAC") - or metadata.get("macAddress") - ) - if isinstance(mac, str) and mac.strip(): - return mac.strip().lower() - - def _mac_from_txt(txt: dict) -> str: - if not isinstance(txt, dict): - return "" - for key in ("mac", "hardware-address", "hwaddr", "device-mac", "machine"): - raw = txt.get(key) - if isinstance(raw, str) and raw.strip(): - return raw.strip().lower() - return "" - - top = _mac_from_txt(metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {}) - if top: - return top - services = metadata.get("services") - if isinstance(services, list): - for svc in services: - if not isinstance(svc, dict): - continue - got = _mac_from_txt(svc.get("txt") if isinstance(svc.get("txt"), dict) else {}) - if got: - return got - return "" - - def _apply_type_override(self, device: Device) -> None: - override_type = self._find_override_value(self._type_overrides, device) - if not override_type: - return - device.type = override_type - device.category = self._category_for_type(override_type) - - def _apply_name_override(self, device: Device) -> None: - """Rule 0: apply saved name prefs last among the early pipeline (overrides rule 1 and mDNS).""" - override_name = self._find_name_override_value(device) - if not override_name: - return - device.name = override_name - - def _apply_url_override(self, device: Device) -> None: - override_url = self._find_override_value(self._url_overrides, device) - if not isinstance(device.metadata, dict): - device.metadata = {} - if isinstance(override_url, str) and override_url.strip(): - device.metadata["url_override"] = override_url.strip() - else: - device.metadata.pop("url_override", None) - - def _apply_device_commands(self, device: Device) -> None: - cmds = self._find_override_value(self._device_commands, device) - if not isinstance(device.metadata, dict): - device.metadata = {} - valid = _normalize_command_list(cmds) if isinstance(cmds, list) else [] - if valid: - device.metadata["device_commands"] = valid - else: - device.metadata.pop("device_commands", None) - - def _apply_custom_command_override(self, device: Device) -> None: - cmd = self._find_override_value(self._custom_command_overrides, device) - if not isinstance(device.metadata, dict): - device.metadata = {} - if isinstance(cmd, str) and cmd.strip(): - device.metadata["custom_command"] = cmd.strip() - else: - device.metadata.pop("custom_command", None) - - def _clip_loc_log(self, value: str) -> str: - return value if len(value) <= 120 else value[:117] + "..." - - def _store_location_preference_for_device(self, device: Device, location: str) -> bool: - """Write identity-based location prefs (same key rules as set_device_location_override).""" - loc = str(location).strip() - if not loc or not is_plausible_room_location(loc): - return False - preferred_key = self._make_name_override_key_for_device(device) - endpoint_key = self._make_override_key(device.source, device.ip, device.port) - if self._location_overrides.get(preferred_key) == loc: - return False - self._location_overrides.pop(endpoint_key, None) - self._location_overrides[preferred_key] = loc - self._location_prefs_need_reapply = True - return True - - def _consume_location_prefs_need_reapply(self) -> bool: - if not self._location_prefs_need_reapply: - return False - self._location_prefs_need_reapply = False - return True - - def _run_location_reapply_sweep(self) -> bool: - """Re-apply location rules to all cached devices after prefs mutation; persist if needed.""" - any_round = False - rounds = 0 - while self._consume_location_prefs_need_reapply() and rounds < 8: - rounds += 1 - any_round = True - for existing in list(self._devices.values()): - self._apply_location_override(existing) - if any_round and self._location_prefs_dirty_callback is not None: - try: - self._location_prefs_dirty_callback() - except Exception: - self._logger.exception("location_prefs_dirty_callback failed") - return any_round - - def _apply_location_override(self, device: Device) -> None: - if not isinstance(device.metadata, dict): - device.metadata = {} - dev_log = self._device_event_logger(device.source) - cached_raw = self._find_location_override_value(device) - discovered_raw = self._default_location_for_device(device) - c_norm = cached_raw.strip() if isinstance(cached_raw, str) and cached_raw.strip() else "" - d_norm = discovered_raw.strip() if isinstance(discovered_raw, str) and discovered_raw.strip() else "" - - chosen = "" - - if c_norm: - if d_norm and d_norm != c_norm and is_plausible_room_location(d_norm): - self._store_location_preference_for_device(device, d_norm) - chosen = d_norm - dev_log.debug( - "Location: discovery overrides cache ip=%s port=%s old=%r new=%r", - device.ip, - device.port, - self._clip_loc_log(c_norm), - self._clip_loc_log(d_norm), - ) - else: - chosen = c_norm - dev_log.debug( - "Location: prefs cache ip=%s port=%s value=%r", - device.ip, - device.port, - self._clip_loc_log(chosen), - ) - elif d_norm and is_plausible_room_location(d_norm): - self._store_location_preference_for_device(device, d_norm) - chosen = d_norm - dev_log.debug( - "Location: auto from discovery (persisted) ip=%s port=%s value=%r", - device.ip, - device.port, - self._clip_loc_log(chosen), - ) - else: - dev_log.debug( - "Location: empty ip=%s port=%s (no RoomName/xml_fields or TXT keys matched)", - device.ip, - device.port, - ) - - if chosen: - device.metadata["user_location"] = chosen - else: - device.metadata.pop("user_location", None) - - def _apply_field_mapping_rules(self, device: Device) -> None: - if not isinstance(device.metadata, dict): - device.metadata = {} - rules = self.get_device_field_mapping_rules(device) - if not rules: - return - for target, paths in rules.items(): - chosen = "" - for raw in paths: - value = self._mapped_value_for_field_path(device, raw) - if isinstance(value, str) and value.strip(): - chosen = value.strip() - break - if not chosen: - continue - if target == "name": - device.name = chosen - elif target == "location": - if is_plausible_room_location(chosen): - device.metadata["user_location"] = chosen - elif target == "information": - device.metadata["information"] = chosen - - def _mapped_value_for_field_path(self, device: Device, field_path: str) -> str: - metadata = device.metadata if isinstance(device.metadata, dict) else {} - raw = str(field_path or "").strip() - if ":" not in raw: - return "" - prefix, rest = raw.split(":", 1) - key = rest.strip() - if not key: - return "" - if prefix == "txt": - txt = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} - for rk, rv in txt.items(): - if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): - return rv - services = metadata.get("services") if isinstance(metadata.get("services"), list) else [] - for svc in services: - if not isinstance(svc, dict): - continue - st = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} - for rk, rv in st.items(): - if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): - return rv - return "" - if prefix == "xml": - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - for rk, rv in xml_fields.items(): - if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): - return rv - return "" - if prefix == "meta": - for rk, rv in metadata.items(): - if isinstance(rk, str) and str(rk).strip().lower() == key.lower() and isinstance(rv, str): - return rv - return "" - return "" - - def _apply_monitored_override(self, device: Device) -> None: - override_value = self._find_override_value(self._monitored_overrides, device) - if override_value is not None: - device.monitored = bool(override_value) - - def _find_override_value(self, store: dict, device: Device): - preferred_key = self._make_override_key_for_device(device) - if preferred_key in store: - return store[preferred_key] - endpoint_key = self._make_override_key(device.source, device.ip, device.port) - if endpoint_key in store: - return store[endpoint_key] - hit = self._prefs_entry_same_source_ipv4_any_port(store, device) - if hit is not None: - return hit - return self._prefs_entry_for_host_ip_fallback(store, device) - - def _find_name_override_value(self, device: Device) -> str | None: - preferred_key = self._make_name_override_key_for_device(device) - value = self._name_overrides.get(preferred_key) - if isinstance(value, str) and value.strip(): - return value.strip() - endpoint_key = self._make_override_key(device.source, device.ip, device.port) - value = self._name_overrides.get(endpoint_key) - if isinstance(value, str) and value.strip(): - return value.strip() - hit_ep = self._prefs_entry_same_source_ipv4_any_port(self._name_overrides, device) - if isinstance(hit_ep, str) and hit_ep.strip(): - return hit_ep.strip() - hit = self._prefs_entry_for_host_ip_fallback(self._name_overrides, device) - if isinstance(hit, str) and hit.strip(): - return hit.strip() - return None - - def _has_effective_name_override(self, device: Device, prior_row: Device | None = None) -> bool: - """Rule 0: user-renamed devices (prefs) beat SSDP cache, mDNS, and descriptor-derived names.""" - if self._find_name_override_value(device) is not None: - return True - if prior_row is not None and self._find_name_override_value(prior_row) is not None: - return True - return False - - def _find_location_override_value(self, device: Device) -> str | None: - preferred_key = self._make_name_override_key_for_device(device) - value = self._location_overrides.get(preferred_key) - if isinstance(value, str) and value.strip(): - return value.strip() - endpoint_key = self._make_override_key(device.source, device.ip, device.port) - value = self._location_overrides.get(endpoint_key) - if isinstance(value, str) and value.strip(): - return value.strip() - hit_ep = self._prefs_entry_same_source_ipv4_any_port(self._location_overrides, device) - if isinstance(hit_ep, str) and hit_ep.strip(): - return hit_ep.strip() - hit = self._prefs_entry_for_host_ip_fallback(self._location_overrides, device) - if isinstance(hit, str) and hit.strip(): - return hit.strip() - return None - - def _prefs_entry_for_host_ip_fallback(self, store: dict, device: Device): - """Prefs may use host:ip:… while identity later resolves to host:uid:… / host:mac:… (richer mDNS).""" - ip_only = str(device.ip).strip() - if not ip_only or ip_only == "0.0.0.0": - return None - host_ip_key = f"host:ip:{ip_only}" - if self._make_override_key_for_device(device) == host_ip_key: - return None - if host_ip_key in store: - return store[host_ip_key] - return None - - def _prefs_entry_same_source_ipv4_any_port(self, store: dict, device: Device): - """Match `mdns:192.168.1.10:8611` when aggregated row moves to `:631`, etc. (IPv4-only).""" - sip = str(device.ip).strip() - if sip in {"", "0.0.0.0"}: - return None - try: - if not isinstance(ipaddress.ip_address(sip), ipaddress.IPv4Address): - return None - except ValueError: - return None - prefix = f"{(device.source or '').strip().lower()}:{sip}:" - matches: list[str] = [] - for key in store: - if isinstance(key, str) and key.startswith(prefix): - tail = key[len(prefix) :] - if tail.isdigit(): - matches.append(key) - if not matches: - return None - - endpoint_exact = prefix + str(int(device.port)) - if endpoint_exact in store: - return store.get(endpoint_exact) - widest = max(matches, key=lambda k: int(k.rsplit(":", 1)[-1])) - return store.get(widest) - - def _supplement_missing_user_location(self, device: Device, prior_row: Device | None) -> None: - """Stabilise location when fresh payload lacks room info but cache already had one.""" - if device.source not in {"mdns", "ssdp"}: - return - if not isinstance(device.metadata, dict): - device.metadata = {} - cur = device.metadata.get("user_location") - if isinstance(cur, str) and cur.strip(): - return - sip = str(device.ip).strip() - if not sip or sip == "0.0.0.0": - return - if prior_row is not None and prior_row.source == device.source and prior_row.key == device.key: - dm = prior_row.metadata if isinstance(prior_row.metadata, dict) else {} - preserved = dm.get("user_location") - if isinstance(preserved, str) and preserved.strip(): - ps = preserved.strip() - if is_plausible_room_location(ps): - device.metadata["user_location"] = ps - self._device_event_logger(device.source).debug( - "Location: %s carry-over from prior row ip=%s value=%r", - device.source, - sip, - ps if len(ps) <= 120 else ps[:117] + "...", - ) - return - if device.source == "ssdp": - for row in self._devices.values(): - if row is prior_row: - continue - if row.source != "ssdp" or row.key == device.key: - continue - if str(row.ip).strip() != sip: - continue - dm = row.metadata if isinstance(row.metadata, dict) else {} - borrowed = dm.get("user_location") - if isinstance(borrowed, str) and borrowed.strip(): - bs = borrowed.strip() - if not is_plausible_room_location(bs): - continue - device.metadata["user_location"] = bs - self._ssdp_logger.debug( - "Location: SSDP borrowed same-ip ip=%s from key=%s value=%r", - sip, - row.key, - bs if len(bs) <= 120 else bs[:117] + "...", - ) - return - return - for row in self._devices.values(): - if row is prior_row: - continue - if row.source != "mdns" or row.key == device.key: - continue - if str(row.ip).strip() != sip: - continue - dm = row.metadata if isinstance(row.metadata, dict) else {} - borrowed = dm.get("user_location") - if isinstance(borrowed, str) and borrowed.strip(): - bs = borrowed.strip() - if not is_plausible_room_location(bs): - continue - device.metadata["user_location"] = bs - self._mdns_logger.debug( - "Location: mDNS borrowed same-ip ip=%s from key=%s value=%r", - sip, - row.key, - bs if len(bs) <= 120 else bs[:117] + "...", - ) - return - - def _make_override_key(self, source: str, ip: str, port: int) -> str: - return f"{source}:{ip}:{int(port)}" - - def _make_override_key_for_device(self, device: Device) -> str: - uid = self._extract_uid(device.metadata) - if uid: - return f"host:uid:{uid}" - mac = self._extract_mac(device.metadata) - if mac: - return f"host:mac:{mac}" - ip = str(device.ip).strip() - if ip and ip != "0.0.0.0": - return f"host:ip:{ip}" - return self._make_override_key(device.source, device.ip, device.port) - - def _make_name_override_key_for_device(self, device: Device) -> str: - return self._make_override_key_for_device(device) - - def _extract_uid(self, metadata: dict) -> str: - if not isinstance(metadata, dict): - return "" - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} - usn = metadata.get("usn") - if isinstance(usn, str) and usn.strip(): - u = uuid_urn_if_present(usn) - if u: - return u - return usn.strip().lower().split("::", 1)[0] - wsd_epr = metadata.get("wsd_epr") - if isinstance(wsd_epr, str) and wsd_epr.strip(): - u = uuid_urn_if_present(wsd_epr) - if u: - return u - wsdd_uri = metadata.get("wsdd_uri") - if isinstance(wsdd_uri, str) and wsdd_uri.strip(): - u = uuid_urn_if_present(wsdd_uri) - if u: - return u - udn_raw = xml_fields.get("UDN") - if isinstance(udn_raw, str) and udn_raw.strip(): - u = uuid_urn_if_present(udn_raw) - if u: - return u - candidates = [ - xml_fields.get("UDN"), - metadata.get("udn"), - txt_fields.get("uuid"), - txt_fields.get("udn"), - txt_fields.get("id"), - txt_fields.get("deviceid"), - txt_fields.get("device_id"), - txt_fields.get("serial"), - txt_fields.get("serialnumber"), - ] - for value in candidates: - if isinstance(value, str) and value.strip(): - return value.strip().lower() - return "" - - def _default_name_for_device(self, device: Device) -> str: - metadata = device.metadata if isinstance(device.metadata, dict) else {} - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} - ip = str(device.ip).strip() or "0.0.0.0" - - for key in ("friendlyName", "displayName"): - value = xml_fields.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - - if device.source == "mdns": - for key in ("name", "fn", "friendlyname", "friendly_name", "device"): - value = txt_fields.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - server_raw = metadata.get("server") - if isinstance(server_raw, str) and server_raw.strip(): - normalized = server_raw.strip().removesuffix(".local.").removesuffix(".local").strip(".") - if normalized: - base = normalized.replace("-", " ") - prod = "" - if isinstance(txt_fields, dict): - for tk, tv in txt_fields.items(): - if isinstance(tk, str) and tk.lower() == "product" and isinstance(tv, str) and tv.strip(): - prod = tv.strip() - break - if prod: - return f"{base} ({prod})" - return base - for key in ("model", "mdl", "md", "product"): - value = txt_fields.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - hostname = metadata.get("hostname") - if isinstance(hostname, str) and hostname.strip(): - normalized = hostname.strip().removesuffix(".local.").removesuffix(".local").strip(".") - if normalized: - return normalized.replace("-", " ") - return f"mDNS Device {ip}" - - if device.source == "ssdp": - server = str(metadata.get("server", "")) - st = str(metadata.get("st", "")) - server_low = server.lower() - st_low = st.lower() - if "router" in server_low or "wan" in st_low: - return f"Router {ip}" - if "mediaserver" in st_low or "dlna" in server_low: - return f"Media Server {ip}" - if "printer" in st_low: - return f"Printer {ip}" - return f"SSDP Device {ip}" - - return str(device.name).strip() or "Unknown" - - def _default_location_for_device(self, device: Device) -> str: - metadata = device.metadata if isinstance(device.metadata, dict) else {} - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - txt_fields = metadata.get("txt") if isinstance(metadata.get("txt"), dict) else {} - - # Sonos commonly exposes a room label in SSDP XML fields. - for value in (xml_fields.get("RoomName"), xml_fields.get("roomName"), metadata.get("RoomName"), metadata.get("roomName")): - if isinstance(value, str) and value.strip(): - s = value.strip() - if is_plausible_room_location(s): - return s - - def txt_by_key_ci(txt: dict, *wanted_lower: str) -> str: - index: dict[str, str] = {} - if isinstance(txt, dict): - for rk, rv in txt.items(): - if isinstance(rk, str) and isinstance(rv, str): - index[rk.lower()] = rv - for wl in wanted_lower: - cand = index.get(wl.lower()) - if isinstance(cand, str) and cand.strip(): - s = cand.strip() - if is_plausible_room_location(s): - return s - return "" - - loc = txt_by_key_ci( - txt_fields, - "roomname", - "room_name", - "room", - "location", - "locationname", - "location_name", - "zonename", - "zone_name", - "zone", - ) - if loc: - return loc - services = metadata.get("services") if isinstance(metadata.get("services"), list) else [] - for svc in services: - if not isinstance(svc, dict): - continue - st = svc.get("txt") if isinstance(svc.get("txt"), dict) else {} - loc = txt_by_key_ci(st, "roomname", "room_name", "room", "location", "locationname", "zonename", "zone") - if loc: - return loc - return "" - - def _category_for_type(self, device_type: str) -> str: - return { - "router": _("Routers & Gateways"), - "mediaserver": _("Media Servers"), - "printer": _("Printers"), - "networkprinter": _("Printers"), - "multifunction_printer": _("Printers"), - "smartspeaker": _("Smart Speakers"), - "smarttv": _("Smart TVs"), - "smartdevice": _("Smart Devices"), - "camera": _("Cameras"), - "homeappliance": _("Home Appliances"), - "cnc": _("CNC Machines"), - "3dprinter": _("3D Printers"), - "nas": _("NAS / File Servers"), - "computer": _("Computers"), - "esp32": _("ESP3D Devices"), - "unknown": _("Unknown Devices"), - }.get(device_type, _("Unknown Devices")) - - def set_device_monitored(self, device_key: str, monitored: bool) -> None: - device = self._devices.get(device_key) - if device is None: - return - if device.monitored == monitored: - return - device.monitored = monitored - self._monitored_overrides[self._make_override_key_for_device(device)] = monitored - self._notify() - - def _notify(self) -> None: - snapshot = self.devices - self._logger.debug("Publishing %d devices to %d listeners", len(snapshot), len(self._listeners)) - for listener in self._listeners: - listener(snapshot) - - def _on_protocol_event(self, event_type: str, payload: dict) -> None: - if event_type != "device": - self._logger.debug("Ignoring protocol event_type=%s", event_type) - return - - device = Device( - name=payload.get("name", "Unknown"), - ip=payload.get("ip", "0.0.0.0"), - port=int(payload.get("port", 0)), - type=payload.get("type", "unknown"), - category=payload.get("category", "Unknown Devices"), - source=payload.get("source", "unknown"), - url=payload.get("url"), - metadata=payload.get("metadata", {}), - online=bool(payload.get("online", True)), - icon=payload.get("icon"), - ) - self.add_or_update_device(device) - - def _load_demo_devices(self) -> None: - demo_devices = [ - Device( - name="ESP3D Printer Node", - ip="192.168.1.42", - port=80, - type="esp32", - category="ESP3D Devices", - source="mdns", - url="http://192.168.1.42:80/", - metadata={ - "hostname": "esp3d-printer.local.", - "server": "esp3d-printer.local.", - "interface": "wlan0", - "priority": 0, - "weight": 0, - "ttl": 120, - "services": [ - { - "service": "_esp3d._tcp.local.", - "port": 80, - "hostname": "esp3d-printer.local.", - "server": "esp3d-printer.local.", - }, - { - "service": "_arduino._tcp.local.", - "port": 81, - "hostname": "esp3d-printer.local.", - "server": "esp3d-printer.local.", - }, - ], - "txt": { - "board": "ESP32", - "fw": "ESP3D 3.0.2", - "path": "/", - "auth": "false", - }, - }, - online=True, - icon="esp32.png", - ), - Device( - name="Salon Media Server", - ip="192.168.1.15", - port=8200, - type="mediaserver", - category="Media Servers", - source="ssdp", - url="http://192.168.1.15:8200/", - metadata={ - "st": "urn:schemas-upnp-org:device:MediaServer:1", - "nt": "urn:schemas-upnp-org:device:MediaServer:1", - "usn": "uuid:media-server-01::urn:schemas-upnp-org:device:MediaServer:1", - "location": "http://192.168.1.15:8200/rootDesc.xml", - "server": "Linux/6.8 UPnP/1.1 ReadyMedia/1.3.2", - "cache_control": "max-age=1800", - "headers": { - "HOST": "239.255.255.250:1900", - "CACHE-CONTROL": "max-age=1800", - "LOCATION": "http://192.168.1.15:8200/rootDesc.xml", - "NT": "urn:schemas-upnp-org:device:MediaServer:1", - "NTS": "ssdp:alive", - "SERVER": "Linux/6.8 UPnP/1.1 ReadyMedia/1.3.2", - "USN": "uuid:media-server-01::urn:schemas-upnp-org:device:MediaServer:1", - }, - "xml_fields": { - "friendlyName": "Salon Media Server", - "deviceType": "urn:schemas-upnp-org:device:MediaServer:1", - "manufacturer": "ReadyMedia", - "manufacturerURL": "https://www.readymedia.org/", - "modelName": "MiniDLNA", - "modelURL": "https://www.readymedia.org/docs/", - "serialNumber": "RM-001-ABCD", - "UDN": "uuid:media-server-01", - "presentationURL": "http://192.168.1.15:8200/", - "services_description": "urn:schemas-upnp-org:service:ContentDirectory:1, urn:schemas-upnp-org:service:ConnectionManager:1", - "icons_description": "mimetype=image/png;width=48;height=48;url=/icons/icon48.png", - }, - "xml": """ - - 10 - http://192.168.1.15:8200/ - - urn:schemas-upnp-org:device:MediaServer:1 - Salon Media Server - ReadyMedia - MiniDLNA - uuid:media-server-01 - -""", - }, - online=True, - icon="mediaserver.png", - ), - Device( - name="Box Internet", - ip="192.168.1.1", - port=80, - type="router", - category="Routers & Gateways", - source="ssdp", - url="http://192.168.1.1:80/", - metadata={ - "st": "urn:schemas-upnp-org:device:WANDevice:1", - "nt": "urn:schemas-upnp-org:device:WANDevice:1", - "usn": "uuid:router-01::urn:schemas-upnp-org:device:WANDevice:1", - "location": "http://192.168.1.1:80/igd.xml", - "server": "Linux/5.15 UPnP/1.0 RouterOS/7.10", - "cache_control": "max-age=1200", - "headers": { - "HOST": "239.255.255.250:1900", - "CACHE-CONTROL": "max-age=1200", - "LOCATION": "http://192.168.1.1:80/igd.xml", - "NT": "urn:schemas-upnp-org:device:WANDevice:1", - "NTS": "ssdp:alive", - "SERVER": "Linux/5.15 UPnP/1.0 RouterOS/7.10", - "USN": "uuid:router-01::urn:schemas-upnp-org:device:WANDevice:1", - }, - "xml_fields": { - "friendlyName": "Box Internet", - "deviceType": "urn:schemas-upnp-org:device:WANDevice:1", - "manufacturer": "ISP Vendor", - "manufacturerURL": "unavailable", - "modelName": "Gateway X1", - "modelURL": "unavailable", - "serialNumber": "GWX1-7788", - "UDN": "uuid:router-01", - "presentationURL": "http://192.168.1.1/", - "services_description": "urn:schemas-upnp-org:service:WANIPConnection:1", - "icons_description": "unavailable", - }, - "xml": """ - - 10 - - urn:schemas-upnp-org:device:WANDevice:1 - Box Internet - ISP Vendor - Gateway X1 - uuid:router-01 - -""", - }, - online=True, - icon="router.png", - ), - Device( - name="NAS Atelier", - ip="192.168.1.20", - port=2049, - type="nas", - category="NAS / File Servers", - source="mdns", - url=None, - metadata={ - "hostname": "nas-atelier.local.", - "server": "nas-atelier.local.", - "interface": "eth0", - "priority": 0, - "weight": 0, - "ttl": 4500, - "services": [ - { - "service": "_nfs._tcp.local.", - "port": 2049, - "hostname": "nas-atelier.local.", - "server": "nas-atelier.local.", - }, - { - "service": "_mountd._tcp.local.", - "port": 32768, - "hostname": "nas-atelier.local.", - "server": "nas-atelier.local.", - }, - ], - "txt": { - "model": "DS224+", - "vendor": "Synology", - "path": "/volume1", - }, - }, - online=False, - icon="nas.png", - ), - ] - for device in demo_devices: - self._devices[device.key] = device - self._notify() diff --git a/discovery/mdns.py b/discovery/mdns.py deleted file mode 100644 index 16079f6d..00000000 --- a/discovery/mdns.py +++ /dev/null @@ -1,960 +0,0 @@ -# File mdns.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""mDNS discovery using zeroconf service browsing.""" - -from __future__ import annotations - -import json -import logging -from pathlib import Path -import socket -import threading - -from discovery.base import BaseDiscovery -from utils.mdns_rules import cached_mdns_rules, evaluate_type_rules -from utils.user_config_overlay import USER_DEVICE_TYPES_JSON, merge_device_types_trees, optional_user_json - -try: - from zeroconf import ServiceBrowser, ServiceListener, Zeroconf -except Exception: # pragma: no cover - dependency/runtime availability - ServiceBrowser = None - ServiceListener = object - Zeroconf = None - -try: - from zeroconf import ZeroconfServiceTypes -except Exception: # pragma: no cover - older zeroconf builds - ZeroconfServiceTypes = None - -try: - from gi.repository import GLib -except Exception: # pragma: no cover - GLib = None - -_ENUMERATION_TIMEOUT_S = 2.5 -_ENUMERATION_REFRESH_INTERVAL_S = 240 -# How long to retain a per-service record after remove_service() when the host -# is still alive via other services. In practice, genuine mid-session service -# removal (NAS disabling FTP, etc.) is extremely rare; almost all remove_service -# callbacks while a host is online are TTL re-announcement jitter or transient -# network hiccups. A refresh() restarts browsers and actively re-queries, so -# stale records that truly disappeared will be cleaned up on the next user- -# initiated reload even if this timer hasn't fired. Set long enough to survive -# the worst-case zeroconf re-query window (~4 × re-query intervals ≈ 2-3 min). -_SERVICE_REMOVE_GRACE_S = 180 - - -_TYPE_MAP_PATH = Path(__file__).resolve().parent.parent / "data" / "device_types.json" - - -class _MDNSListener(ServiceListener): - def __init__(self, discovery: "MDNSDiscovery") -> None: - self._discovery = discovery - - def add_service(self, zc, service_type: str, name: str) -> None: - self._discovery._on_service_change(zc, service_type, name, online=True) - - def update_service(self, zc, service_type: str, name: str) -> None: - self._discovery._on_service_change(zc, service_type, name, online=True) - - def remove_service(self, _zc, service_type: str, name: str) -> None: - self._discovery._on_service_remove(service_type, name) - - -class MDNSDiscovery(BaseDiscovery): - def __init__( - self, - rules_enabled: bool = True, - *, - enumeration_timeout_seconds: float | None = None, - enumeration_interval_seconds: int | None = None, - service_info_timeout_ms: int | None = None, - ) -> None: - super().__init__(source="mdns") - self._logger = logging.getLogger(__name__) - self._rules_enabled = bool(rules_enabled) - self._enumeration_timeout_s = ( - float(enumeration_timeout_seconds) - if enumeration_timeout_seconds is not None - else _ENUMERATION_TIMEOUT_S - ) - self._enumeration_interval_s = ( - int(enumeration_interval_seconds) - if enumeration_interval_seconds is not None - else _ENUMERATION_REFRESH_INTERVAL_S - ) - self._service_info_timeout_ms = ( - int(service_info_timeout_ms) if service_info_timeout_ms is not None else 2500 - ) - self._mdns_rules = cached_mdns_rules() if self._rules_enabled else {"type_rules": [], "summary_fields": []} - self._running = False - self._zeroconf = None - self._browsers: list[ServiceBrowser] = [] - self._browsers_started: set[str] = set() - self._listener = _MDNSListener(self) - self._seen_by_service: dict[tuple[str, str], dict] = {} - self._service_host_keys: dict[tuple[str, str], str] = {} - self._host_last_endpoint: dict[str, tuple[str, int]] = {} - self._type_map = self._load_mdns_type_map() - self._enumeration_timer_id: int | None = None - self._enumeration_busy = False - self._pending_remove_timers: dict[tuple[str, str], int] = {} - - def start(self) -> None: - if self._running: - return - self._running = True - if Zeroconf is None or ServiceBrowser is None: - self._logger.warning("mDNS discovery unavailable: zeroconf not installed") - return - try: - self._zeroconf = Zeroconf() - except Exception: - self._logger.exception("Failed to initialize zeroconf") - self._running = False - return - - self._browsers_started.clear() - for service_type in self._service_types_to_browse_from_config(): - self._ensure_browser(service_type) - self._kick_service_type_enumeration() - self._schedule_enumeration_timer() - if not self._browsers: - self._logger.warning("No mDNS service browser started") - - def stop(self) -> None: - if not self._running: - return - self._running = False - self._enumeration_busy = False - if GLib is not None and self._enumeration_timer_id is not None: - try: - GLib.source_remove(self._enumeration_timer_id) - except Exception: - pass - self._enumeration_timer_id = None - for key in list(self._pending_remove_timers): - self._cancel_grace_remove(key) - self._seen_by_service.clear() - self._host_last_endpoint.clear() - self._browsers.clear() - self._browsers_started.clear() - zc = self._zeroconf - self._zeroconf = None - if zc is not None: - try: - zc.close() - except Exception: - self._logger.debug("Error while closing zeroconf", exc_info=True) - - def refresh(self) -> None: - if not self._running or self._zeroconf is None: - return - # Cancel pending grace-remove timers before dropping the cache. - for key in list(self._pending_remove_timers): - self._cancel_grace_remove(key) - # Cancel running browsers. - for browser in self._browsers: - try: - if hasattr(browser, "cancel"): - browser.cancel() - except Exception: - pass - self._browsers.clear() - # Close and reopen the Zeroconf instance to clear its internal DNS cache. - # This ensures the subsequent PTR queries go out without "known answer" - # suppression headers (RFC 6762 §7.1), so devices that stopped announcing - # (e.g. a NAS whose TTL expired) will respond and re-populate the device list. - old_zc = self._zeroconf - self._zeroconf = None - if old_zc is not None: - try: - old_zc.close() - except Exception: - self._logger.debug("mDNS refresh: error closing zeroconf", exc_info=True) - try: - self._zeroconf = Zeroconf() - except Exception: - self._logger.exception("mDNS refresh: failed to reopen zeroconf") - return - self._logger.debug("mDNS refresh: zeroconf cache cleared, sending fresh PTR queries") - types_to_rebrowse = list(self._browsers_started) - self._browsers_started.clear() - for service_type in types_to_rebrowse: - self._ensure_browser(service_type) - self._kick_service_type_enumeration() - - def _service_types_to_browse_from_config(self) -> list[str]: - known_types = sorted(self._type_map.keys()) if self._type_map else [] - if not known_types: - known_types = ["_http._tcp"] - return [self._normalize_service_type(service) for service in known_types] - - def _ensure_browser(self, service_type: str) -> None: - if not self._running or self._zeroconf is None or ServiceBrowser is None: - return - normalized = self._normalize_service_type(service_type) - if normalized in self._browsers_started: - return - try: - browser = ServiceBrowser(self._zeroconf, normalized, self._listener) - self._browsers.append(browser) - self._browsers_started.add(normalized) - self._logger.debug("mDNS browser started for %s", normalized) - except Exception: - self._logger.exception("Failed to start mDNS browser for %s", normalized) - - def _restart_browsers(self) -> None: - """Cancel all running browsers and recreate them to force fresh PTR queries. - - A new ServiceBrowser sends an immediate PTR query for its type; devices - respond and trigger add_service callbacks — recovering any records that - zeroconf evicted from its cache without re-announcement. - - Pending grace-remove timers are also cancelled: the fresh PTR queries - will either confirm the service is gone (no add_service callback) or - restore it (add_service fires and refreshes the record). - """ - for key in list(self._pending_remove_timers): - self._cancel_grace_remove(key) - for browser in self._browsers: - try: - if hasattr(browser, "cancel"): - browser.cancel() - except Exception: - pass - self._browsers.clear() - types_to_rebrowse = list(self._browsers_started) - self._browsers_started.clear() - for service_type in types_to_rebrowse: - self._ensure_browser(service_type) - self._logger.debug("mDNS browsers restarted for %d type(s)", len(types_to_rebrowse)) - - def _enqueue_browsers_for_types(self, service_types: list[str]) -> None: - """Register browsers on the GTK main thread (callbacks must stay GUI-safe).""" - - def apply_pending() -> bool: - if not self._running or self._zeroconf is None: - return False - for service_type in service_types: - self._ensure_browser(service_type) - return False - - if GLib is not None: - GLib.idle_add(apply_pending) - else: - self._logger.warning("GLib not available; starting enumerated mDNS browsers inline (thread may be unsafe)") - apply_pending() - - def _kick_service_type_enumeration(self) -> None: - """DNS-SD: discover which service types are advertised on the LAN (beyond config file).""" - - if ZeroconfServiceTypes is None or not self._running: - return - if self._enumeration_busy: - self._logger.debug("mDNS enumeration skipped (already in progress)") - return - - self._enumeration_busy = True - - def worker() -> None: - try: - try: - found = ZeroconfServiceTypes.find(zc=None, timeout=self._enumeration_timeout_s) - except Exception: - self._logger.exception("mDNS service type enumeration failed") - return - - additions: list[str] = [] - seen: set[str] = set() - for raw in found: - if not isinstance(raw, str) or not raw.strip(): - continue - normalized = self._normalize_service_type(raw) - if normalized in seen: - continue - meta = "_services._dns-sd._udp" in normalized - # Avoid browsing the enumerator itself as a generic service catalogue. - if meta: - continue - seen.add(normalized) - additions.append(normalized) - - self._enqueue_browsers_for_types(additions) - self._logger.info("mDNS enumeration found %d service type(s)", len(additions)) - finally: - self._enumeration_busy = False - - threading.Thread(target=worker, name="NetNeighbor-mdns-enumerate", daemon=True).start() - - def _schedule_enumeration_timer(self) -> None: - if GLib is None: - return - - def on_timer() -> bool: - if not self._running or self._zeroconf is None: - self._enumeration_timer_id = None - return False - self._kick_service_type_enumeration() - return True - - if self._enumeration_timer_id is None: - self._enumeration_timer_id = GLib.timeout_add_seconds(self._enumeration_interval_s, on_timer) - - def _normalize_service_type(self, service: str) -> str: - value = (service or "").strip().lower() - if not value: - return "_http._tcp.local." - if value.endswith(".local."): - return value - if value.endswith(".local"): - return f"{value}." - return f"{value}.local." - - def _load_mdns_type_map(self) -> dict[str, dict]: - try: - parsed = json.loads(_TYPE_MAP_PATH.read_text(encoding="utf-8")) - if isinstance(parsed, dict): - overlay = optional_user_json(USER_DEVICE_TYPES_JSON) - if overlay is not None: - parsed = merge_device_types_trees(parsed, overlay) - self._logger.info("Merged device_types.json with user overlay %s", USER_DEVICE_TYPES_JSON) - mdns_map = parsed.get("mdns") if isinstance(parsed, dict) else {} - if isinstance(mdns_map, dict): - normalized: dict[str, dict] = {} - for key, value in mdns_map.items(): - if isinstance(key, str) and isinstance(value, dict): - normalized[key.strip().lower()] = value - return normalized - except (OSError, json.JSONDecodeError): - self._logger.exception("Failed to load mDNS type map from %s", _TYPE_MAP_PATH) - return {} - - def _on_service_change(self, zc, service_type: str, name: str, online: bool) -> None: - if not self._running: - return - # Service is re-announcing — cancel any pending grace-remove immediately so - # the UI never sees the record disappear if re-announcement arrives in time. - self._cancel_grace_remove((service_type, name)) - try: - info = zc.get_service_info(service_type, name, timeout=self._service_info_timeout_ms) - except Exception: - self._logger.debug("mDNS lookup failed for %s %s", service_type, name, exc_info=True) - return - if info is None: - self._logger.debug("mDNS service info unavailable for %s %s", service_type, name) - return - payload = self._build_payload(service_type, name, info, online=online) - key = (service_type, name) - self._seen_by_service[key] = payload - host_key = self._host_key_for_payload(payload, service_type, name) - self._service_host_keys[key] = host_key - aggregate = self._aggregate_payload_for_host(host_key, online=True) - previous_endpoint = self._host_last_endpoint.get(host_key) - current_endpoint = (str(aggregate.get("ip", "0.0.0.0")), int(aggregate.get("port", 0) or 0)) - if previous_endpoint and previous_endpoint != current_endpoint: - stale_payload = dict(aggregate) - stale_payload["ip"] = previous_endpoint[0] - stale_payload["port"] = previous_endpoint[1] - stale_payload["online"] = False - self._emit("device", stale_payload) - self._host_last_endpoint[host_key] = current_endpoint - self._emit("device", aggregate) - - def _on_service_remove(self, service_type: str, name: str) -> None: - if not self._running: - return - key = (service_type, name) - host_key = self._service_host_keys.get(key, "") - if host_key: - # Check if host is still alive via other services (excluding this key). - still_alive = any( - v == host_key for k, v in self._service_host_keys.items() if k != key - ) - if still_alive: - # Host is still up — delay the removal to absorb TTL re-announcement - # jitter. If add_service fires within the grace window the timer is - # cancelled and the UI never sees the record disappear. - self._schedule_grace_remove(key, host_key) - return - # Host going fully offline (or no known host) — apply immediately. - self._cancel_grace_remove(key) - self._apply_remove(key) - - def _schedule_grace_remove(self, key: tuple[str, str], host_key: str) -> None: - self._cancel_grace_remove(key) - if GLib is None: - self._apply_remove(key) - return - - def _fire() -> bool: - self._pending_remove_timers.pop(key, None) - if not self._running: - return False - self._apply_remove(key) - return False - - timer_id = GLib.timeout_add_seconds(_SERVICE_REMOVE_GRACE_S, _fire) - self._pending_remove_timers[key] = timer_id - self._logger.debug( - "mDNS grace remove scheduled for %s %s (host still alive, %ds delay)", - key[0], key[1], _SERVICE_REMOVE_GRACE_S, - ) - - def _cancel_grace_remove(self, key: tuple[str, str]) -> None: - timer_id = self._pending_remove_timers.pop(key, None) - if timer_id is not None and GLib is not None: - try: - GLib.source_remove(timer_id) - except Exception: - pass - - def _apply_remove(self, key: tuple[str, str]) -> None: - """Commit a service removal after the optional grace delay has elapsed.""" - self._seen_by_service.pop(key, None) - host_key = self._service_host_keys.pop(key, "") - if host_key: - still_online = any(value == host_key for value in self._service_host_keys.values()) - if still_online: - self._emit("device", self._aggregate_payload_for_host(host_key, online=True)) - return - self._host_last_endpoint.pop(host_key, None) - payload = self._aggregate_payload_for_host(host_key, online=False) - self._emit("device", payload) - return - service_type, name = key - payload = self._build_fallback_remove_payload(service_type, name) - self._emit("device", payload) - - def _build_payload(self, service_type: str, name: str, info, online: bool) -> dict: - service_key = self._service_key(service_type) - mapping = self._type_map.get(service_key, {}) - addresses = self._extract_addresses(info) - ip = addresses[0] if addresses else "0.0.0.0" - port = int(getattr(info, "port", 0) or 0) - hostname = getattr(info, "name", "") or name - server = getattr(info, "server", "") - priority = int(getattr(info, "priority", 0) or 0) - weight = int(getattr(info, "weight", 0) or 0) - txt, txt_records = self._txt_from_service_info(info) - instance_label = name.split("._", 1)[0].strip() if name else "" - - display_name = self._infer_display_name(name, txt, self._to_text(server)) - type_name = str(mapping.get("type", "unknown")).strip().lower() or "unknown" - type_name = self._infer_type_from_context(type_name, service_key, display_name, txt) - category = self._category_for_type( - type_name, - str(mapping.get("category", _("Unknown Devices"))) or _("Unknown Devices"), - ) - icon = mapping.get("icon") - if not isinstance(icon, str): - icon = self._icon_for_type(type_name) - - service_normalized = self._normalize_service_type(service_type) - metadata = { - "service": service_normalized, - "hostname": hostname, - "server": server, - "priority": priority, - "weight": weight, - "ttl": int(getattr(info, "host_ttl", 0) or getattr(info, "other_ttl", 0) or 0), - "services": [ - { - "service": service_normalized, - "port": port, - "hostname": hostname, - "server": server, - "instance": instance_label, - "txt": txt, - "txt_records": txt_records, - } - ], - "txt": txt, - } - return { - "name": display_name, - "ip": ip, - "port": port, - "type": type_name, - "category": category, - "source": "mdns", - "url": None, - "metadata": metadata, - "online": bool(online), - "icon": icon, - } - - def _build_fallback_remove_payload(self, service_type: str, name: str) -> dict: - service_key = self._service_key(service_type) - mapping = self._type_map.get(service_key, {}) - type_name = str(mapping.get("type", "unknown")).strip().lower() or "unknown" - type_name = self._infer_type_from_context(type_name, service_key, self._infer_display_name(name, {}), {}) - category = self._category_for_type( - type_name, - str(mapping.get("category", _("Unknown Devices"))) or _("Unknown Devices"), - ) - icon = mapping.get("icon") - if not isinstance(icon, str): - icon = self._icon_for_type(type_name) - return { - "name": self._infer_display_name(name, {}), - "ip": "0.0.0.0", - "port": int(mapping.get("default_port", 0) or 0), - "type": type_name, - "category": category, - "source": "mdns", - "url": None, - "metadata": {"service": self._normalize_service_type(service_type), "txt": {}, "services": []}, - "online": False, - "icon": icon, - } - - def _service_key(self, service_type: str) -> str: - value = self._normalize_service_type(service_type) - if value.endswith(".local."): - value = value[: -len(".local.")] - return value - - def _infer_type_from_service(self, service_key: str) -> str: - if "_esp3d._tcp" in service_key or "_arduino._tcp" in service_key: - return "esp32" - if "_smb._tcp" in service_key: - return "computer" - if "_printer._tcp" in service_key or "_ipp._tcp" in service_key or "_ipps._tcp" in service_key: - return "networkprinter" - if "_airplay._tcp" in service_key or "_raop._tcp" in service_key or "_companion-link._tcp" in service_key: - return "smartspeaker" - if "_ftp._tcp" in service_key or "_afpovertcp._tcp" in service_key or "_webdav._tcp" in service_key: - # NAS heuristic refines Synology/QNAP in TXT / name. - return "computer" - if "_scanner" in service_key or "_uscan" in service_key or "_uscans." in service_key: - return "scanner" - if "_http._tcp" in service_key or "_https._tcp" in service_key: - return "http" - return "unknown" - - def _infer_type_from_context( - self, - mapped_type: str, - service_key: str, - display_name: str, - txt: dict[str, str], - merged_services_line: str = "", - ) -> str: - base = mapped_type if mapped_type and mapped_type != "unknown" else self._infer_type_from_service(service_key) - # Collapse printer variants into one device type class. - if base == "printer": - base = "networkprinter" - - haystack_parts = [service_key, display_name, merged_services_line] - haystack_parts.extend([f"{k}={v}" for k, v in txt.items()]) - haystack = " ".join([part.lower() for part in haystack_parts if isinstance(part, str)]) - - if "fluidnc" in haystack: - return "cnc" - if "laserjet" in haystack: - return "networkprinter" - if "synology" in haystack or "qnap" in haystack or " nas " in f" {haystack} ": - return "nas" - if not self._rules_enabled: - return base - return evaluate_type_rules(haystack, base, self._mdns_rules) - - def _aggregate_type_rank(self, device_type: str) -> int: - """Higher = stronger signal for host-level aggregate type (icon + category).""" - t = (device_type or "unknown").strip().lower() - return { - "unknown": 0, - "http": 12, - "https": 12, - "computer": 20, - "esp32": 22, - "nas": 38, - "mediaserver": 34, - "smartspeaker": 40, - "networkprinter": 55, - "multifunction_printer": 56, - "printer": 55, - "scanner": 52, - }.get(t, 8) - - def _best_aggregate_mdns_type(self, seed: str, merged_services: list) -> str: - best = (seed or "unknown").strip().lower() - best_r = self._aggregate_type_rank(best) - for svc in merged_services: - if not isinstance(svc, dict): - continue - svc_key = str(svc.get("service", "")).lower() - cand = self._infer_type_from_service(svc_key) - cr = self._aggregate_type_rank(cand) - if cr > best_r: - best = cand - best_r = cr - return best - - def _merged_services_imply_multifunction_printer(self, merged_services: list) -> bool: - """Printer-class DNS-SD plus scanner / eSCL on the same host → multifunction.""" - parts: list[str] = [] - for svc in merged_services: - if not isinstance(svc, dict): - continue - parts.append(str(svc.get("service", "")).lower()) - line = " ".join(parts) - printer = any( - x in line - for x in ("_ipp._tcp", "_ipps._tcp", "_printer._tcp", "_pdl-datastream._tcp") - ) - scanner = any( - tok in line - for tok in ( - "_uscan._tcp", - "_uscans._tcp", - "_scanner._tcp", - "_scan._tcp", - "_escl._tcp", - ) - ) or ("scanner" in line and "._tcp" in line) - return bool(printer and scanner) - - def _dns_target_label_from_server(self, server: str) -> str: - """SRV / PTR target host (often ``thing.local``) without ``.local`` — good NAS / printer labels.""" - s = self._to_text(server).strip().strip(".") - if not s: - return "" - low = s.lower() - if low.endswith(".local"): - s = s[:-6].strip(".") - elif low.endswith(".local."): - s = s[:-7].strip(".") - return s.replace("-", " ").strip() if s else "" - - def _txt_product_value(self, txt: dict[str, str]) -> str: - """Non-empty ``product`` TXT field if present (case-insensitive key).""" - if not isinstance(txt, dict): - return "" - for raw_k, raw_v in txt.items(): - if not isinstance(raw_k, str) or raw_k.lower() != "product": - continue - if isinstance(raw_v, str) and raw_v.strip(): - return raw_v.strip() - return "" - - def _infer_display_name(self, service_instance: str, txt: dict[str, str], server: str = "") -> str: - # Order: friendly TXT first; Google Cast uses ``fn``. DNS target (without .local) before hardware - # ``model`` so NAS / printers show hostname when TXT advertises a bare model string. - for key in ("name", "fn", "friendlyname", "friendly_name", "device"): - value = txt.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - dns_label = self._dns_target_label_from_server(server) - if dns_label: - prod = self._txt_product_value(txt) - if prod: - return f"{dns_label} ({prod})" - return dns_label - for key in ("model", "mdl", "md", "product"): - value = txt.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - label = service_instance.split("._", 1)[0].strip() - return label or "mDNS Device" - - def _extract_addresses(self, info) -> list[str]: - addresses: list[str] = [] - parsed_addresses = getattr(info, "parsed_addresses", None) - if callable(parsed_addresses): - try: - values = parsed_addresses() - if isinstance(values, list): - addresses.extend([str(v) for v in values if v]) - except Exception: - pass - raw_addrs = getattr(info, "addresses", None) - if isinstance(raw_addrs, list): - for raw in raw_addrs: - if not isinstance(raw, (bytes, bytearray)): - continue - try: - if len(raw) == 4: - addresses.append(socket.inet_ntop(socket.AF_INET, raw)) - elif len(raw) == 16: - addresses.append(socket.inet_ntop(socket.AF_INET6, raw)) - except OSError: - continue - unique: list[str] = [] - for value in addresses: - if value not in unique: - unique.append(value) - return unique - - def _unpack_txt_bytes(self, text: bytes) -> list[tuple[str, str]]: - """Parse concatenated RFC 6763 TXT blobs; preserves order and duplicate keys. - - zeroconf's internal unpack keeps only the first occurrence per key — some devices expose - multiple strings or duplicated keys across the TXT compound. - """ - if not text: - return [] - pairs: list[tuple[str, str]] = [] - index = 0 - end = len(text) - while index < end: - length = text[index] - index += 1 - if length == 0: - continue - segment = text[index : index + length] - index += length - split = segment.split(b"=", 1) - key = self._to_text(split[0]).strip() - if not key and len(split) < 2: - continue - value = self._to_text(split[1]).strip() if len(split) > 1 else "" - pairs.append((key, value)) - return pairs - - def _txt_from_service_info(self, info) -> tuple[dict[str, str], list[tuple[str, str]]]: - """TXT as dict (last wins duplicate keys for heuristics) + ordered record list.""" - - pairs: list[tuple[str, str]] = [] - raw_text = getattr(info, "text", None) - if isinstance(raw_text, (bytes, bytearray)) and len(raw_text) > 0: - pairs = self._unpack_txt_bytes(bytes(raw_text)) - if not pairs: - props = getattr(info, "properties", None) - if isinstance(props, dict): - for raw_key, raw_value in props.items(): - key = self._to_text(raw_key).strip() - if not key: - continue - val = "" if raw_value is None else self._to_text(raw_value).strip() - pairs.append((key, val)) - merged: dict[str, str] = {} - for key, val in pairs: - if key: - merged[key] = val - return merged, pairs - - def _decode_properties(self, props) -> dict[str, str]: - if not isinstance(props, dict): - return {} - decoded: dict[str, str] = {} - for raw_key, raw_value in props.items(): - key = self._to_text(raw_key).strip() - if not key: - continue - decoded[key] = self._to_text(raw_value).strip() - return decoded - - def _to_text(self, value) -> str: - if isinstance(value, bytes): - return value.decode("utf-8", errors="replace") - return str(value) - - def _host_key_for_payload(self, payload: dict, service_type: str, name: str) -> str: - metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} - ip = str(payload.get("ip", "")).strip() - if ip and ip != "0.0.0.0": - return ip - for key in ("hostname", "server"): - value = metadata.get(key) - if isinstance(value, str) and value.strip(): - return value.strip().lower() - return f"{self._normalize_service_type(service_type)}::{name.strip().lower()}" - - def _aggregate_payload_for_host(self, host_key: str, online: bool) -> dict: - entries: list[dict] = [] - for key, value in self._seen_by_service.items(): - if self._service_host_keys.get(key) == host_key: - entries.append(value) - if not entries: - return { - "name": "mDNS Device", - "ip": "0.0.0.0", - "port": 0, - "type": "unknown", - "category": _("Unknown Devices"), - "source": "mdns", - "url": None, - "metadata": {"service": "_mdns._udp.local.", "txt": {}, "services": []}, - "online": bool(online), - "icon": self._icon_for_type("unknown"), - } - - def _score(entry: dict) -> tuple[int, int]: - metadata = entry.get("metadata") if isinstance(entry.get("metadata"), dict) else {} - service_text = str(metadata.get("service", "")).lower() - # Prefer print-related rows over bare _http so aggregate type/icon stay printer-like - # (avoids http → GTK "browser" flash before IPP TXT / device icon URL arrives). - if any( - x in service_text - for x in ("_ipp._tcp", "_ipps._tcp", "_printer._tcp", "_pdl-datastream._tcp") - ): - return (0, 0) - # Prefer playback / casting rows over bare _http (room TXT + artwork URLs). - if any( - x in service_text - for x in ( - "_airplay._tcp", - "_raop._tcp", - "_companion-link._tcp", - "_sonos._tcp", - "_spotify-connect._tcp", - "_googlecast._tcp", - ) - ): - return (1, 0) - if "_http._tcp" in service_text or "_https._tcp" in service_text: - return (2, 0) - if "_esp3d._tcp" in service_text: - return (3, 0) - return (4, int(entry.get("port", 0) or 0)) - - representative = sorted(entries, key=_score)[0] - rep_metadata = representative.get("metadata") if isinstance(representative.get("metadata"), dict) else {} - merged_services: list[dict] = [] - combined_txt: dict[str, str] = {} - for entry in entries: - metadata = entry.get("metadata") if isinstance(entry.get("metadata"), dict) else {} - entry_txt = metadata.get("txt") - if isinstance(entry_txt, dict): - combined_txt.update(entry_txt) - services_list = metadata.get("services") if isinstance(metadata.get("services"), list) else [] - for service in services_list: - if not isinstance(service, dict): - continue - normalized_service = str(service.get("service", "")).strip() - normalized_port = int(service.get("port", 0) or 0) - inst_norm = str(service.get("instance", "")).strip() - duplicate = any( - str(existing.get("service", "")).strip() == normalized_service - and int(existing.get("port", 0) or 0) == normalized_port - and str(existing.get("instance", "")).strip() == inst_norm - for existing in merged_services - ) - if not duplicate: - merged_services.append(dict(service)) - - http_port = None - for service in merged_services: - service_name = str(service.get("service", "")).lower() - if "_http._tcp" in service_name: - candidate = int(service.get("port", 0) or 0) - if candidate > 0: - http_port = candidate - break - - ip = str(representative.get("ip", "0.0.0.0")) - url = None - if http_port and ip and ip != "0.0.0.0": - url = f"http://{ip}:{http_port}/" - - merged_metadata = dict(rep_metadata) - merged_metadata["services"] = merged_services - if combined_txt: - merged_metadata["txt"] = combined_txt - - seed_type = str(representative.get("type", "unknown")).strip().lower() - services_line_for_infer = " ".join( - str(s.get("service", "")).lower() for s in merged_services if isinstance(s, dict) - ) - agg_type = self._infer_type_from_context( - seed_type, - str(rep_metadata.get("service", "")).lower(), - str(representative.get("name", "mDNS Device")), - combined_txt, - services_line_for_infer, - ) - agg_type = self._best_aggregate_mdns_type(agg_type, merged_services) - if self._merged_services_imply_multifunction_printer(merged_services): - agg_type = "multifunction_printer" - icon_out = representative.get("icon") - if not isinstance(icon_out, str) or not icon_out.strip(): - icon_out = self._icon_for_type(agg_type) - elif self._aggregate_type_rank(agg_type) > self._aggregate_type_rank(seed_type): - icon_out = self._icon_for_type(agg_type) - category = self._category_for_type(agg_type, representative.get("category", _("Unknown Devices"))) - - rep_svc = str(rep_metadata.get("service", "")) - self._logger.debug( - "mDNS aggregate host=%s ip=%s rows=%d rep_service=%r rep_port=%s seed_type=%s agg_type=%s icon=%s " - "merged_txt_keys=%d merged_services=%d", - host_key, - ip, - len(entries), - rep_svc, - representative.get("port"), - seed_type, - agg_type, - icon_out, - len(combined_txt), - len(merged_services), - ) - - return { - "name": representative.get("name", "mDNS Device"), - "ip": ip, - "port": int(representative.get("port", 0) or 0), - "type": agg_type, - "category": category, - "source": "mdns", - "url": url, - "metadata": merged_metadata, - "online": bool(online), - "icon": icon_out, - } - - def _build_url(self, mapping: dict, ip: str, port: int) -> str | None: - info_url = mapping.get("info_url") - if not isinstance(info_url, str) or not info_url.strip(): - return None - try: - return info_url.format(ip=ip, port=port) - except Exception: - return None - - def _category_for_type(self, device_type: str, fallback: str) -> str: - return { - "router": _("Routers & Gateways"), - "mediaserver": _("Media Servers"), - "scanner": _("Printers"), - "printer": _("Printers"), - "networkprinter": _("Printers"), - "multifunction_printer": _("Printers"), - "smartspeaker": _("Smart Speakers"), - "smarttv": _("Smart TVs"), - "smartdevice": _("Smart Devices"), - "camera": _("Cameras"), - "homeappliance": _("Home Appliances"), - "cnc": _("CNC Machines"), - "3dprinter": _("3D Printers"), - "nas": _("NAS / File Servers"), - "computer": _("Computers"), - "esp32": _("ESP3D Devices"), - "http": _("Unknown Devices"), - "unknown": _("Unknown Devices"), - }.get(device_type, fallback or _("Unknown Devices")) - - def _icon_for_type(self, device_type: str) -> str | None: - return { - "router": "router.png", - "mediaserver": "mediaserver.png", - "scanner": "printer.png", - "printer": "printer.png", - "networkprinter": "printer.png", - "multifunction_printer": "printer.png", - "smartspeaker": "smartspeaker.png", - "smarttv": "smarttv.png", - "smartdevice": "smartdevice.png", - "camera": "camera.png", - "homeappliance": "homeappliance.png", - "cnc": "cnc.png", - "3dprinter": "3dprinter.png", - "nas": "nas.png", - "computer": "computer.png", - "esp32": "esp32.png", - "http": "http.png", - "unknown": "unknown.png", - }.get(device_type) diff --git a/discovery/netbios.py b/discovery/netbios.py deleted file mode 100644 index f13a3d67..00000000 --- a/discovery/netbios.py +++ /dev/null @@ -1,375 +0,0 @@ -# File netbios.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""NetBIOS LAN discovery via Samba ``nmblookup`` (NMB broadcast / name query).""" - -from __future__ import annotations - -import concurrent.futures -import ipaddress -import logging -import re -import shutil -import subprocess -import threading -from collections import OrderedDict, defaultdict -from collections.abc import Sequence - -from discovery.base import BaseDiscovery - -_DEFAULT_INTERVAL_S = 180.0 -_DEFAULT_TIMEOUT_S = 15.0 - -# ``Looking up status of 192.168.1.10`` / IPv6 -_STATUS_OF_RE = re.compile(r"^Looking up status of\s+(\S+)\s*$", re.IGNORECASE) -# `` DS415PLUS <00> - B `` -_STATUS_NAME_RE = re.compile(r"^\s+(\S+)\s+<([0-9a-fA-F]{2})>\s*-") - - -def _parse_ip_name_suffix(rest: str) -> tuple[str, str] | None: - """Parse ``HOSTNAME<00>`` tail after first column.""" - m = re.match(r"^(.+)<([0-9a-fA-F]{2})>\s*$", rest.strip()) - if not m: - return None - return m.group(1).strip(), m.group(2).lower() - - -def _parse_flat_ip_line(line: str) -> tuple[str, str, str] | None: - """Parse ``192.168.1.10 HOST<00>`` or IPv6 equivalent.""" - line = line.strip() - if not line or line.lower().startswith("querying"): - return None - parts = line.split(None, 1) - if len(parts) != 2: - return None - ip_s, rest = parts[0], parts[1].strip() - try: - addr = ipaddress.ip_address(ip_s) - except ValueError: - return None - parsed = _parse_ip_name_suffix(rest) - if not parsed: - return None - name, suf = parsed - return str(addr), name, suf - - -def _ip_rank(ip_s: str) -> tuple[int, int]: - """Sort key: lower = better. Prefer LAN IPv4 over IPv6 (esp. link-local).""" - try: - a = ipaddress.ip_address(ip_s) - except ValueError: - return (99, 99) - if isinstance(a, ipaddress.IPv4Address): - if a.is_loopback: - return (5, 0) - if a.is_private or a.is_link_local: - return (0, 0) - return (1, 0) - if isinstance(a, ipaddress.IPv6Address): - if a.is_loopback: - return (6, 0) - if a.is_link_local: - return (4, 0) - if a.is_private: - return (3, 0) - return (2, 0) - return (99, 99) - - -def _is_placeholder_netbios_name(name: str) -> bool: - n = (name or "").strip() - return n in {"*", "?"} - - -def _parse_nmblookup_output(text: str) -> list[tuple[str, str, str]]: - """Return rows ``(ip, netbios_name, suffix_hex)`` from ``nmblookup`` stdout/stderr.""" - rows: list[tuple[str, str, str]] = [] - current_status_ip: str | None = None - for raw in (text or "").splitlines(): - line = raw.rstrip() - if not line.strip(): - continue - if line.lower().lstrip().startswith("querying"): - continue - - m_hdr = _STATUS_OF_RE.match(line.strip()) - if m_hdr: - ip_raw = m_hdr.group(1).strip() - if ip_raw.startswith("[") and "]" in ip_raw: - ip_raw = ip_raw.split("[", 1)[1].split("]", 1)[0].strip() - try: - current_status_ip = str(ipaddress.ip_address(ip_raw)) - except ValueError: - current_status_ip = None - continue - - m_stat = _STATUS_NAME_RE.match(line) - if m_stat and current_status_ip: - name, suf = m_stat.group(1), m_stat.group(2).lower() - rows.append((current_status_ip, name, suf)) - continue - - flat = _parse_flat_ip_line(line) - if flat: - rows.append(flat) - continue - - return rows - - -def _noise_netbios_name(name: str, suffix: str) -> bool: - bu = name.strip().upper() - su = (suffix or "").strip().lower() - # Group/workgroup registrations — not a machine unique name (do not hide whole IP if only `<20>` etc. remains). - if bu == "WORKGROUP" and su in ("00", "1e", "1d"): - return True - if "__MSBROWSE__" in bu: - return True - if bu.startswith("__MSBROWSE__"): - return True - if bu == "MSBROWSE": - return True - return False - - -def _pick_netbios_display_name(candidates: Sequence[tuple[str, str]]) -> str | None: - """Pick host-style NetBIOS label for one IP; skip workgroup / wildcard.""" - filtered: list[tuple[str, str]] = [] - for base, suf in candidates: - if _noise_netbios_name(base, suf): - continue - if _is_placeholder_netbios_name(base): - continue - filtered.append((base.strip(), suf)) - if not filtered: - return None - for base, suf in filtered: - if suf == "00": - return base - for base, suf in filtered: - if suf == "20": - return base - return filtered[0][0] - - -def _merge_row_sort_key(r: tuple[str, str, str]) -> tuple[tuple[int, int], int]: - ip_s = r[0] - try: - a = ipaddress.ip_address(ip_s) - v6 = 1 if isinstance(a, ipaddress.IPv6Address) else 0 - except ValueError: - v6 = 9 - return (_ip_rank(ip_s), v6) - - -def _merge_rows_prefer_ipv4(rows: list[tuple[str, str, str]]) -> list[tuple[str, str, str]]: - """One row per distinct NetBIOS name; prefer IPv4 / routable over link-local IPv6.""" - by_ip: dict[str, list[tuple[str, str]]] = defaultdict(list) - for ip_s, name, suf in rows: - by_ip[ip_s].append((name, suf)) - - per_name: dict[str, list[tuple[str, str, str]]] = defaultdict(list) - for ip_s, cands in by_ip.items(): - display = _pick_netbios_display_name(cands) - if not display or _is_placeholder_netbios_name(display): - continue - suf_pick = "" - for nb, suf in cands: - if nb.strip() == display.strip(): - suf_pick = suf - break - per_name[display.strip().lower()].append((ip_s, display, suf_pick)) - - merged: list[tuple[str, str, str]] = [] - for _k, group in per_name.items(): - merged.append(min(group, key=_merge_row_sort_key)) - return merged - - -class NetbiosDiscovery(BaseDiscovery): - """Periodic ``nmblookup`` sweep; emits ``computer`` rows when hosts respond on NMB.""" - - def __init__( - self, - *, - interval_seconds: float | None = None, - timeout_seconds: float | None = None, - argv: list[str] | None = None, - directed_ips: list[str] | None = None, - ) -> None: - super().__init__(source="nmb") - self._logger = logging.getLogger(__name__) - self._interval_s = ( - float(interval_seconds) if interval_seconds is not None else _DEFAULT_INTERVAL_S - ) - self._timeout_s = ( - float(timeout_seconds) if timeout_seconds is not None else _DEFAULT_TIMEOUT_S - ) - self._interval_s = max(60.0, min(3600.0, self._interval_s)) - self._timeout_s = max(5.0, min(120.0, self._timeout_s)) - # ``-S`` adds node status so we get real names (plain ``*`` only yields ``*<00>`` per IP). - self._argv_rest: list[str] = list(argv) if argv else ["-S", "*"] - self._directed_ips: list[str] = [] - for raw in directed_ips or []: - if not isinstance(raw, str) or not raw.strip(): - continue - try: - self._directed_ips.append(str(ipaddress.ip_address(raw.strip()))) - except ValueError: - self._logger.debug("NetBIOS directed_ips skip invalid IP: %r", raw) - self._nmblookup = shutil.which("nmblookup") - self._running = False - self._stop_event = threading.Event() - self._wake_event = threading.Event() - self._probe_thread: threading.Thread | None = None - self._missing_logged = False - self._extra_directed_lock = threading.Lock() - # IPs to probe with ``nmblookup -A`` (e.g. suggested when WSD only has a synthetic label). - self._extra_directed: OrderedDict[str, None] = OrderedDict() - self._max_extra_directed = 64 - - def suggest_directed_ip(self, ip_s: str) -> None: - """Queue ``nmblookup -A`` for this IP on the next probe (LAN PCs missed by broadcast sweep).""" - if not self._running or not self._nmblookup: - return - try: - normalized = str(ipaddress.ip_address((ip_s or "").strip())) - except ValueError: - return - with self._extra_directed_lock: - self._extra_directed.pop(normalized, None) - self._extra_directed[normalized] = None - while len(self._extra_directed) > self._max_extra_directed: - self._extra_directed.popitem(last=False) - self._logger.debug("NetBIOS: extra directed probe queued for %s", normalized) - self.refresh() - - def start(self) -> None: - if self._running: - return - if not self._nmblookup: - if not self._missing_logged: - self._logger.warning( - "NetBIOS discovery unavailable: nmblookup not in PATH " - "(install samba-common-bin or samba-common; ensure nmbd can answer on the LAN)" - ) - self._missing_logged = True - return - self._running = True - self._stop_event.clear() - self._wake_event.clear() - self._probe_thread = threading.Thread(target=self._probe_loop, name="nmb-probe", daemon=True) - self._probe_thread.start() - self._logger.info( - "NetBIOS discovery started (interval=%.1fs timeout=%.1fs argv=%s)", - self._interval_s, - self._timeout_s, - self._argv_rest, - ) - - def stop(self) -> None: - if not self._running: - return - self._running = False - self._stop_event.set() - self._wake_event.set() - if self._probe_thread is not None: - self._probe_thread.join(timeout=2.0) - self._probe_thread = None - self._logger.info("NetBIOS discovery stopped") - - def refresh(self) -> None: - if not self._running: - return - self._wake_event.set() - - def _probe_loop(self) -> None: - while self._running: - self._run_once() - if self._stop_event.is_set(): - break - if self._wake_event.wait(timeout=self._interval_s): - self._wake_event.clear() - - def _run_once(self) -> None: - if self._nmblookup is None: - return - cmd = [self._nmblookup, *self._argv_rest] - try: - proc = subprocess.run( - cmd, - capture_output=True, - text=True, - timeout=float(self._timeout_s), - check=False, - ) - except subprocess.TimeoutExpired: - self._logger.debug("nmblookup timed out after %.1fs", self._timeout_s) - return - except OSError: - self._logger.debug("nmblookup failed to run", exc_info=True) - return - out = (proc.stdout or "") + "\n" + (proc.stderr or "") - rows = _parse_nmblookup_output(out) - with self._extra_directed_lock: - extra_directed = list(self._extra_directed.keys()) - directed_chain = list(dict.fromkeys([*self._directed_ips, *sorted(extra_directed)])) - - def _probe_one(dip: str) -> list: - try: - proc_d = subprocess.run( - [self._nmblookup, "-A", dip], - capture_output=True, - text=True, - timeout=float(self._timeout_s), - check=False, - ) - return _parse_nmblookup_output((proc_d.stdout or "") + "\n" + (proc_d.stderr or "")) - except subprocess.TimeoutExpired: - self._logger.debug("nmblookup -A %s timed out after %.1fs", dip, self._timeout_s) - except OSError: - self._logger.debug("nmblookup -A %s failed", dip, exc_info=True) - return [] - - if directed_chain: - workers = min(8, len(directed_chain)) - with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: - for partial_rows in pool.map(_probe_one, directed_chain): - rows.extend(partial_rows) - merged = _merge_rows_prefer_ipv4(rows) - if not merged: - self._logger.debug( - "NetBIOS: no hosts parsed (nmblookup exit=%s; try ``nmblookup -S '*'`` / LAN NMB)", - proc.returncode, - ) - if self._directed_ips: - self._logger.warning( - "NetBIOS: directed_ips=%s returned no usable names — check ``nmblookup -A `` from this host", - self._directed_ips, - ) - return - self._logger.info("NetBIOS: publishing %d host row(s)", len(merged)) - self._logger.debug( - "NetBIOS host rows (ip=name): %s", - ", ".join(f"{ip}={name}" for ip, name, _suf in merged), - ) - for ip_s, name, suffix_primary in merged: - payload = { - "name": name, - "ip": ip_s, - "port": 445, - "type": "computer", - "category": _("Computers"), - "source": self.source, - "url": None, - "metadata": { - "nmb_name": name, - "nmb_suffix": suffix_primary, - "nmb_argv": list(self._argv_rest), - }, - "online": True, - "icon": None, - } - self._emit("device", payload) diff --git a/discovery/ssdp.py b/discovery/ssdp.py deleted file mode 100644 index 432c6b3e..00000000 --- a/discovery/ssdp.py +++ /dev/null @@ -1,1075 +0,0 @@ -# File ssdp.py for NetNeighbor version 1.0.0 -# Internal version : 1.0.0 date: 2026-05-07 11:44 -# Owner: Luc LEBOSSE all copyrights -# License: LGPL3 -"""Minimal live SSDP discovery (M-SEARCH + response parsing).""" - -from __future__ import annotations - -from datetime import datetime, timedelta, timezone -import ipaddress -import json -import logging -from pathlib import Path -import socket -import threading -import time -from urllib.error import URLError -from urllib.parse import urljoin, urlparse -from urllib.request import urlopen -import xml.etree.ElementTree as ET - -from discovery.base import BaseDiscovery -from utils.discovery_cache import load_discovery_cache, save_discovery_cache -from utils.user_config_overlay import merge_ssdp_rules_overlays - -_SSDP_ADDR = ("239.255.255.250", 1900) -_DEFAULT_TIMEOUT_SECONDS = 180 -_REFRESH_INTERVAL_SECONDS = 60 -_MAX_TIMEOUT_SECONDS = 3600 -_RULES_PATH = Path(__file__).resolve().parent.parent / "config" / "ssdp_rules.json" -_RX_FRAME_DELIMITER = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" -_TX_FRAME_DELIMITER = "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" -_XML_CACHE_MEMORY_TTL_SECONDS = 60 -_XML_CACHE_DISK_TTL_SECONDS = 1800 -_PROFILE_CACHE_DISK_TTL_SECONDS = 86400 -_CACHE_FLUSH_INTERVAL_SECONDS = 3.0 - - -def _descriptor_xml_host_key(location: str) -> str: - """Group descriptor HTTP traffic by remote host: canonical IP literal or lowercase hostname. - - All XML GETs whose LOCATION URL resolves to the same IP share one min-interval bucket. - """ - p = urlparse((location or "").strip()) - raw = (p.hostname or "").strip() - if not raw: - return "" - inner = raw[1:-1] if raw.startswith("[") and raw.endswith("]") else raw - try: - addr = ipaddress.ip_address(inner) - return addr.compressed - except ValueError: - return raw.lower() - - -class SSDPDiscovery(BaseDiscovery): - def __init__( - self, - rules_enabled: bool = True, - query_interval_seconds: int | None = None, - mx_seconds: int | None = None, - descriptor_http_min_interval_seconds: float | None = None, - ) -> None: - super().__init__(source="ssdp") - self._logger = logging.getLogger(__name__) - self._rules_enabled = bool(rules_enabled) - self._refresh_interval_seconds = ( - int(query_interval_seconds) if query_interval_seconds is not None else _REFRESH_INTERVAL_SECONDS - ) - mx = int(mx_seconds) if mx_seconds is not None else 5 - self._mx_seconds = max(5, min(6, mx)) - if descriptor_http_min_interval_seconds is None: - self._descriptor_http_min_interval = 5.0 - else: - self._descriptor_http_min_interval = max(0.0, float(descriptor_http_min_interval_seconds)) - self._last_descriptor_http_mono: dict[str, float] = {} - self._xml_fetch_gates: dict[str, threading.Lock] = {} - self._xml_fetch_gates_lock = threading.Lock() - self._rules = self._load_rules() - self._running = False - self._socket: socket.socket | None = None - self._listen_thread: threading.Thread | None = None - self._gc_thread: threading.Thread | None = None - self._refresh_thread: threading.Thread | None = None - self._lock = threading.Lock() - self._seen_devices: dict[str, tuple[datetime, int, dict]] = {} - self._xml_cache: dict[str, tuple[datetime, dict, str | None]] = {} - self._xml_disk_cache: dict[str, tuple[datetime, dict, str | None]] = self._load_persistent_xml_cache() - self._profile_disk_cache: dict[str, tuple[datetime, dict]] = self._load_persistent_profile_cache() - self._cache_dirty = False - self._last_cache_flush_monotonic = 0.0 - self._stop_event = threading.Event() - - def start(self) -> None: - if self._running: - return - self._running = True - self._stop_event.clear() - self._socket = self._create_socket() - self._logger.info("SSDP discovery started") - self._listen_thread = threading.Thread(target=self._listen_loop, name="ssdp-listener", daemon=True) - self._listen_thread.start() - self._gc_thread = threading.Thread(target=self._gc_loop, name="ssdp-gc", daemon=True) - self._gc_thread.start() - self._refresh_thread = threading.Thread(target=self._refresh_loop, name="ssdp-refresh", daemon=True) - self._refresh_thread.start() - self.refresh() - - def stop(self) -> None: - if not self._running: - return - self._running = False - self._stop_event.set() - sock = self._socket - self._socket = None - if sock is not None: - try: - sock.close() - except OSError: - pass - if self._listen_thread is not None: - self._listen_thread.join(timeout=0.25) - if self._gc_thread is not None: - self._gc_thread.join(timeout=0.25) - if self._refresh_thread is not None: - self._refresh_thread.join(timeout=0.25) - self._flush_persistent_caches_if_due(force=True) - self._logger.info("SSDP discovery stopped") - - def refresh(self) -> None: - if not self._running: - return - sock = self._socket - if sock is None: - return - search_targets = ["ssdp:all", "upnp:rootdevice", "urn:dial-multiscreen-org:service:dial:1"] - for st in search_targets: - payload = ( - "M-SEARCH * HTTP/1.1\r\n" - "HOST: 239.255.255.250:1900\r\n" - "MAN: \"ssdp:discover\"\r\n" - f"MX: {self._mx_seconds}\r\n" - f"ST: {st}\r\n" - "\r\n" - ).encode("utf-8") - try: - sock.sendto(payload, _SSDP_ADDR) - payload_text = payload.decode("utf-8", errors="ignore") - self._logger.debug( - "SSDP TX %s:%s\n%s\n%s\n%s", - _SSDP_ADDR[0], - _SSDP_ADDR[1], - _TX_FRAME_DELIMITER, - payload_text, - _TX_FRAME_DELIMITER, - ) - except OSError: - self._logger.exception("Failed to send SSDP M-SEARCH for ST=%s", st) - - def _create_socket(self) -> socket.socket: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - except OSError: - pass - sock.settimeout(0.2) - try: - sock.bind(("", 1900)) - except OSError: - # Fallback when 1900 cannot be acquired. - sock.bind(("", 0)) - try: - membership = socket.inet_aton(_SSDP_ADDR[0]) + socket.inet_aton("0.0.0.0") - sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership) - except OSError: - self._logger.debug("Unable to join SSDP multicast group", exc_info=True) - return sock - - def _listen_loop(self) -> None: - while self._running: - sock = self._socket - if sock is None: - break - try: - data, addr = sock.recvfrom(65535) - except socket.timeout: - continue - except OSError: - break - payload = data.decode("utf-8", errors="ignore") - is_reply = payload.startswith("HTTP/1.1 200") - is_notify = payload.startswith("NOTIFY * HTTP/1.1") - if not (is_reply or is_notify): - continue - self._logger.debug( - "SSDP RX from %s\n%s\n%s\n%s", - addr[0], - _RX_FRAME_DELIMITER, - payload, - _RX_FRAME_DELIMITER, - ) - headers = self._parse_headers(payload) - if not headers: - continue - if is_notify: - nts = headers.get("NTS", "").lower() - if nts == "ssdp:byebye": - offline_payload = self._build_notify_offline_payload(headers, addr[0]) - self._logger.info( - "SSDP NOTIFY byebye: %s %s:%s", - offline_payload.get("name"), - offline_payload.get("ip"), - offline_payload.get("port"), - ) - self._emit("device", offline_payload) - continue - if nts and nts != "ssdp:alive": - continue - device_payload = self._build_device_payload(headers, addr[0]) - self._logger.debug( - "SSDP response from %s -> %s %s:%s", - addr[0], - device_payload.get("name"), - device_payload.get("ip"), - device_payload.get("port"), - ) - device_key = self._device_key(device_payload) - now = datetime.now(timezone.utc) - timeout_seconds = self._timeout_seconds_for_payload(device_payload) - with self._lock: - self._seen_devices[device_key] = (now, timeout_seconds, device_payload) - self._emit("device", device_payload) - - def _refresh_loop(self) -> None: - while self._running: - if self._stop_event.wait(timeout=self._refresh_interval_seconds): - break - if not self._running: - break - self._logger.debug("Periodic SSDP refresh tick") - self._flush_persistent_caches_if_due() - self.refresh() - - def _gc_loop(self) -> None: - while self._running: - now = datetime.now(timezone.utc) - expired: list[dict] = [] - with self._lock: - for key, (seen, timeout_seconds, payload) in self._seen_devices.items(): - if (now - seen) > timedelta(seconds=timeout_seconds): - expired.append(payload) - for payload in expired: - key = self._device_key(payload) - self._seen_devices.pop(key, None) - for payload in expired: - offline_payload = dict(payload) - offline_payload["online"] = False - self._logger.debug( - "SSDP timeout -> offline %s %s:%s", - offline_payload.get("name"), - offline_payload.get("ip"), - offline_payload.get("port"), - ) - self._emit("device", offline_payload) - # Lightweight periodic scan. - if self._stop_event.wait(timeout=2.0): - break - - def _parse_headers(self, response: str) -> dict[str, str]: - lines = response.split("\r\n") - headers: dict[str, str] = {} - for line in lines[1:]: - if not line or ":" not in line: - continue - key, value = line.split(":", 1) - headers[key.strip().upper()] = value.strip() - return headers - - def _build_device_payload(self, headers: dict[str, str], fallback_ip: str) -> dict: - location = headers.get("LOCATION") - parsed = urlparse(location) if location else None - ip = parsed.hostname if parsed and parsed.hostname else fallback_ip - port = parsed.port if parsed and parsed.port is not None else 80 - st = headers.get("ST") or headers.get("NT") or "ssdp:all" - nt = headers.get("NT") - server = headers.get("SERVER", "") - usn = headers.get("USN", "") - profile_key = self._profile_key_from_headers(headers, ip) - profile = self._best_profile_for_headers(headers, ip) - name = self._infer_name(server=server, st=st, ip=ip) - device_type = self._infer_type(st, usn=usn, server=server, model_name=None, manufacturer=None) - if profile is not None: - _seen_at, prof = profile - prof_name = prof.get("name") - prof_type = prof.get("type") - if isinstance(prof_name, str) and prof_name.strip(): - name = prof_name.strip() - if isinstance(prof_type, str) and prof_type.strip(): - device_type = prof_type.strip() - xml_fields, raw_xml = self._fetch_and_parse_xml(location) - if not xml_fields and profile is not None: - _seen_at, prof = profile - prof_xml = prof.get("xml_fields") - prof_raw = prof.get("raw_xml") - if isinstance(prof_xml, dict): - xml_fields = dict(prof_xml) - if not raw_xml and isinstance(prof_raw, str) and prof_raw.strip(): - raw_xml = prof_raw - if xml_fields.get("friendlyName"): - name = xml_fields["friendlyName"] - elif xml_fields.get("displayName"): - name = xml_fields["displayName"] - type_seed = xml_fields.get("deviceType") or st - device_type = self._infer_type( - type_seed, - usn=usn, - server=server, - model_name=xml_fields.get("modelName"), - manufacturer=xml_fields.get("manufacturer"), - model_type=xml_fields.get("modelType"), - ) - info_text = self._build_information_text(xml_fields) - if info_text: - self._logger.debug("SSDP info extracted for %s:%s -> %s", ip, port, info_text) - if self._rules_enabled: - rule_name = self._apply_name_rules(xml_fields) - if rule_name: - name = rule_name - rule_type = self._apply_type_rules(headers=headers, xml_fields=xml_fields) - if rule_type: - device_type = rule_type - presentation_url = xml_fields.get("presentationURL") - services_description = self._build_services_description(xml_fields) - payload = { - "name": name, - "ip": ip, - "port": port, - "type": device_type, - "category": self._infer_category(device_type), - "source": "ssdp", - # Only use a real presentation URL from SSDP XML. - "url": presentation_url if isinstance(presentation_url, str) and presentation_url.strip() else None, - "metadata": { - "location": location, - "st": st, - "nt": nt, - "usn": usn, - "server": server, - "mac_address": xml_fields.get("mac"), - "information": info_text, - "cache_control": headers.get("CACHE-CONTROL"), - "headers": headers, - "xml_fields": { - "friendlyName": xml_fields.get("friendlyName"), - "deviceType": xml_fields.get("deviceType"), - "manufacturer": xml_fields.get("manufacturer"), - "manufacturerURL": xml_fields.get("manufacturerURL"), - "modelName": xml_fields.get("modelName"), - "modelType": xml_fields.get("modelType"), - "displayName": xml_fields.get("displayName"), - "roomName": xml_fields.get("roomName"), - "modelURL": xml_fields.get("modelURL"), - "serialNumber": xml_fields.get("serialNumber"), - "mac": xml_fields.get("mac"), - "UDN": xml_fields.get("UDN"), - "presentationURL": xml_fields.get("presentationURL"), - "iconURL": xml_fields.get("iconURL"), - "icons_description": xml_fields.get("icons_description", "unavailable"), - "services_description": services_description or "unavailable", - "services_records": xml_fields.get("services_records"), - }, - "xml": raw_xml, - }, - "online": True, - } - self._persist_profile_cache_entries(headers, ip, payload) - self._logger.info( - "SSDP device detected: %s %s:%s type=%s category=%s st=%s nt=%s", - payload["name"], - payload["ip"], - payload["port"], - payload["type"], - payload["category"], - st, - nt, - ) - return payload - - def _build_notify_offline_payload(self, headers: dict[str, str], fallback_ip: str) -> dict: - st = headers.get("NT") or headers.get("ST") or "ssdp:all" - usn = headers.get("USN", "") - server = headers.get("SERVER", "") - location = headers.get("LOCATION") - parsed = urlparse(location) if location else None - ip = parsed.hostname if parsed and parsed.hostname else fallback_ip - port = parsed.port if parsed and parsed.port is not None else 80 - seen_payload = self._find_seen_payload_for_byebye(ip, usn) - if seen_payload is not None: - offline_payload = dict(seen_payload) - offline_payload["online"] = False - return offline_payload - device_type = self._infer_type(st, usn=usn, server=server) - return { - "name": self._infer_name(server=server, st=st, ip=fallback_ip), - "ip": ip, - "port": port, - "type": device_type, - "category": self._infer_category(device_type), - "source": "ssdp", - "url": None, - "metadata": { - "location": location, - "st": st, - "nt": headers.get("NT"), - "usn": usn, - "server": server, - "headers": headers, - }, - "online": False, - } - - def _find_seen_payload_for_byebye(self, ip: str, usn: str) -> dict | None: - base_usn = usn.split("::", 1)[0].strip().lower() - with self._lock: - for _key, (_seen, _timeout_seconds, payload) in self._seen_devices.items(): - payload_ip = str(payload.get("ip", "")) - if payload_ip != ip: - continue - payload_usn = str(payload.get("metadata", {}).get("usn", "")).strip().lower() - payload_base_usn = payload_usn.split("::", 1)[0] - if base_usn and (payload_usn == usn.lower() or payload_base_usn == base_usn): - return dict(payload) - return None - - def _timeout_seconds_for_payload(self, payload: dict) -> int: - metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} - cache_control = metadata.get("cache_control") - max_age = None - if isinstance(cache_control, str): - value = cache_control.strip().lower() - if "max-age=" in value: - try: - max_age_text = value.split("max-age=", 1)[1].split(",", 1)[0].strip() - max_age = int(max_age_text) - except ValueError: - max_age = None - if max_age is None or max_age <= 0: - return _DEFAULT_TIMEOUT_SECONDS - timeout = max_age * 2 - return max(_DEFAULT_TIMEOUT_SECONDS, min(timeout, _MAX_TIMEOUT_SECONDS)) - - def _infer_name(self, server: str, st: str, ip: str) -> str: - if "router" in server.lower() or "wan" in st.lower(): - return f"Router {ip}" - if "mediaserver" in st.lower() or "dlna" in server.lower(): - return f"Media Server {ip}" - if "printer" in st.lower(): - return f"Printer {ip}" - return f"SSDP Device {ip}" - - def _infer_type( - self, - st: str, - usn: str = "", - server: str = "", - model_name: str | None = None, - manufacturer: str | None = None, - model_type: str | None = None, - ) -> str: - if (model_type or "").strip().lower() == "nas": - return "nas" - st_l = st.lower() - usn_l = usn.lower() - server_l = server.lower() - model_l = (model_name or "").lower() - manufacturer_l = (manufacturer or "").lower() - combined = " ".join([st_l, usn_l, server_l, model_l, manufacturer_l]) - - if "sonos" in combined: - return "mediaserver" - if ( - "mediaserver" in combined - or "contentdirectory" in combined - or "mediarenderer" in combined - or "dial-multiscreen" in combined - or "urn:dial-multiscreen-org:service:dial" in combined - or "googletv" in combined - or "android tv" in combined - or "chromecast" in combined - ): - return "mediaserver" - if ( - "wan" in combined - or "internetgatewaydevice" in combined - or "router" in combined - or "gateway" in combined - or "wifialliance" in combined - or "wfadevice" in combined - or "wfawlanconfig" in combined - ): - return "router" - if "nas" in combined or "synology" in combined or "qnap" in combined: - return "nas" - if "printer" in combined: - return "printer" - if "basic" in combined or "computer" in combined: - return "computer" - return "unknown" - - def _infer_category(self, device_type: str) -> str: - return { - "router": _("Routers & Gateways"), - "mediaserver": _("Media Servers"), - "printer": _("Printers"), - "networkprinter": _("Printers"), - "multifunction_printer": _("Printers"), - "smartspeaker": _("Smart Speakers"), - "smarttv": _("Smart TVs"), - "smartdevice": _("Smart Devices"), - "camera": _("Cameras"), - "homeappliance": _("Home Appliances"), - "cnc": _("CNC Machines"), - "3dprinter": _("3D Printers"), - "nas": _("NAS / File Servers"), - "computer": _("Computers"), - "unknown": _("Unknown Devices"), - }.get(device_type, _("Unknown Devices")) - - def _device_key(self, payload: dict) -> str: - metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} - xml_fields = metadata.get("xml_fields") if isinstance(metadata.get("xml_fields"), dict) else {} - - udn = xml_fields.get("UDN") or metadata.get("udn") - if isinstance(udn, str) and udn.strip(): - return f"ssdp:udn:{udn.strip().lower()}" - - usn = metadata.get("usn") - if isinstance(usn, str) and usn.strip(): - usn_base = usn.strip().lower().split("::", 1)[0] - if usn_base: - return f"ssdp:usn:{usn_base}" - - mac = ( - xml_fields.get("mac") - or metadata.get("mac") - or metadata.get("mac_address") - or metadata.get("MAC") - or metadata.get("macAddress") - ) - if isinstance(mac, str) and mac.strip(): - return f"ssdp:mac:{mac.strip().lower()}" - - ip = str(payload.get("ip", "0.0.0.0")) - port = int(payload.get("port", 0)) - return f"ssdp:endpoint:{ip}:{port}" - - def _profile_key_from_headers(self, headers: dict[str, str], fallback_ip: str) -> str: - usn = headers.get("USN", "") - if isinstance(usn, str) and usn.strip(): - usn_base = usn.strip().lower().split("::", 1)[0] - if usn_base: - return f"ssdp:usn:{usn_base}" - location = headers.get("LOCATION") - parsed = urlparse(location) if location else None - ip = parsed.hostname if parsed and parsed.hostname else fallback_ip - return f"ssdp:host:{str(ip).strip().lower()}" - - def _profile_candidate_keys(self, headers: dict[str, str], fallback_ip: str) -> list[str]: - keys: list[str] = [] - seen: set[str] = set() - - def add(key: str) -> None: - k = str(key).strip().lower() - if not k or k in seen: - return - seen.add(k) - keys.append(k) - - usn = headers.get("USN", "") - if isinstance(usn, str) and usn.strip(): - usn_full = usn.strip().lower() - add(f"ssdp:usn:{usn_full}") - add(f"ssdp:usn:{usn_full.split('::', 1)[0]}") - - location = headers.get("LOCATION") - parsed = urlparse(location) if location else None - ip = parsed.hostname if parsed and parsed.hostname else fallback_ip - ip_s = str(ip).strip().lower() - if ip_s: - add(f"ssdp:host:{ip_s}") - return keys - - def _best_profile_for_headers(self, headers: dict[str, str], fallback_ip: str) -> tuple[datetime, dict] | None: - best: tuple[datetime, dict] | None = None - for key in self._profile_candidate_keys(headers, fallback_ip): - cached = self._profile_disk_cache.get(key) - if cached is None: - continue - if best is None or cached[0] > best[0]: - best = cached - return best - - def fetch_descriptor_xml(self, location_url: str | None) -> tuple[dict, str | None]: - """Fetch and parse UPnP device descriptor XML (same caches as live SSDP LOCATION handling).""" - return self._fetch_and_parse_xml(location_url) - - def _cached_xml_for_same_host(self, host_key: str, now: datetime) -> tuple[dict, str | None] | None: - """Return freshest valid cache entry for any LOCATION whose host matches ``host_key``.""" - if not host_key: - return None - best: tuple[datetime, dict, str | None] | None = None - for loc_key, tup in self._xml_cache.items(): - if _descriptor_xml_host_key(loc_key) != host_key: - continue - seen_at, fields, raw = tup - if (now - seen_at) >= timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): - continue - if best is None or seen_at > best[0]: - best = (seen_at, dict(fields), raw) - if best is not None: - return best[1], best[2] - for loc_key, tup in self._xml_disk_cache.items(): - if _descriptor_xml_host_key(loc_key) != host_key: - continue - seen_at, fields, raw = tup - if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): - return dict(fields), raw - return None - - def _fetch_and_parse_xml(self, location: str | None) -> tuple[dict, str | None]: - if not location: - return {}, None - now = datetime.now(timezone.utc) - memory_cached = self._xml_cache.get(location) - if memory_cached is not None: - seen_at, cached_fields, cached_raw = memory_cached - if (now - seen_at) < timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): - return dict(cached_fields), cached_raw - - disk_cached = self._xml_disk_cache.get(location) - if disk_cached is not None: - seen_at, cached_fields, cached_raw = disk_cached - if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): - self._xml_cache[location] = (now, dict(cached_fields), cached_raw) - self._logger.debug("SSDP XML cache hit (disk) for %s", location) - return dict(cached_fields), cached_raw - - host_key = _descriptor_xml_host_key(location) - with self._xml_fetch_gates_lock: - if host_key not in self._xml_fetch_gates: - self._xml_fetch_gates[host_key] = threading.Lock() - host_gate = self._xml_fetch_gates[host_key] - with host_gate: - now = datetime.now(timezone.utc) - mem2 = self._xml_cache.get(location) - if mem2 is not None: - seen_at, cached_fields, cached_raw = mem2 - if (now - seen_at) < timedelta(seconds=_XML_CACHE_MEMORY_TTL_SECONDS): - return dict(cached_fields), cached_raw - disk2 = self._xml_disk_cache.get(location) - if disk2 is not None: - seen_at, cached_fields, cached_raw = disk2 - if (now - seen_at) < timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): - self._xml_cache[location] = (now, dict(cached_fields), cached_raw) - return dict(cached_fields), cached_raw - - mono = time.monotonic() - if self._descriptor_http_min_interval > 0 and host_key: - last_http = self._last_descriptor_http_mono.get(host_key) - if last_http is not None and (mono - last_http) < self._descriptor_http_min_interval: - alt = self._cached_xml_for_same_host(host_key, now) - if alt is not None: - fields_a, raw_a = alt - self._xml_cache[location] = (now, dict(fields_a), raw_a) - self._logger.debug( - "SSDP descriptor coalesced (min-interval) for %s host=%s", - location, - host_key, - ) - return dict(fields_a), raw_a - self._logger.debug( - "SSDP descriptor HTTP skipped (min-interval %.1fs, no cache for host %s) %s", - self._descriptor_http_min_interval, - host_key, - location, - ) - return {}, None - - try: - with urlopen(location, timeout=1.5) as response: - raw_xml = response.read().decode("utf-8", errors="ignore") - self._logger.debug("SSDP XML fetched from %s\n%s", location, raw_xml) - except (URLError, OSError, TimeoutError): - self._logger.debug("Failed to fetch SSDP XML at %s", location, exc_info=True) - mem_f = self._xml_cache.get(location) - if mem_f is not None: - _seen_at, cached_fields, cached_raw = mem_f - return dict(cached_fields), cached_raw - disk_f = self._xml_disk_cache.get(location) - if disk_f is not None: - _seen_at, cached_fields, cached_raw = disk_f - return dict(cached_fields), cached_raw - return {}, None - - fields: dict = {} - try: - root = ET.fromstring(raw_xml) - device_elem = self._find_first(root, "device") - if device_elem is not None: - fields["friendlyName"] = self._find_text(device_elem, "friendlyName") - fields["deviceType"] = self._find_text(device_elem, "deviceType") - fields["manufacturer"] = self._find_text(device_elem, "manufacturer") - fields["manufacturerURL"] = self._find_text(device_elem, "manufacturerURL") - fields["modelName"] = self._find_text(device_elem, "modelName") - fields["modelType"] = self._find_text(device_elem, "modelType") - fields["displayName"] = self._find_text(device_elem, "displayName") - fields["roomName"] = self._find_text(device_elem, "roomName") - fields["modelURL"] = self._find_text(device_elem, "modelURL") - fields["serialNumber"] = self._find_text(device_elem, "serialNumber") - fields["mac"] = self._find_text(device_elem, "MACAddress") or self._find_text(device_elem, "mac") - fields["UDN"] = self._find_text(device_elem, "UDN") - fields["presentationURL"] = self._find_text(device_elem, "presentationURL") - fields["icons_description"] = self._build_icons_description(device_elem) - fields["services_description"] = self._build_services_description_from_device(device_elem) - fields["services_records"] = self._build_services_records(device_elem, location) - fields["iconURL"] = self._build_preferred_icon_url(device_elem, location) - except ET.ParseError: - self._logger.debug("Invalid SSDP XML received from %s", location, exc_info=True) - if host_key: - self._last_descriptor_http_mono[host_key] = time.monotonic() - return {}, raw_xml - normalized = {k: v for k, v in fields.items() if v} - self._xml_cache[location] = (now, normalized, raw_xml) - self._xml_disk_cache[location] = (now, dict(normalized), raw_xml) - if host_key: - self._last_descriptor_http_mono[host_key] = time.monotonic() - self._mark_cache_dirty() - return dict(normalized), raw_xml - - def _load_persistent_xml_cache(self) -> dict[str, tuple[datetime, dict, str | None]]: - out: dict[str, tuple[datetime, dict, str | None]] = {} - cache_data = load_discovery_cache() - raw = cache_data.get("ssdp_xml_cache") - if not isinstance(raw, dict): - return out - entries = raw.get("entries") - if not isinstance(entries, dict): - return out - now = datetime.now(timezone.utc) - for location, row in entries.items(): - if not isinstance(location, str) or not location.strip() or not isinstance(row, dict): - continue - ts_text = row.get("updated_at") - if not isinstance(ts_text, str) or not ts_text.strip(): - continue - try: - seen_at = datetime.fromisoformat(ts_text) - except ValueError: - continue - if seen_at.tzinfo is None: - seen_at = seen_at.replace(tzinfo=timezone.utc) - if (now - seen_at) >= timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): - continue - xml_fields = row.get("xml_fields") - if not isinstance(xml_fields, dict): - xml_fields = {} - raw_xml = row.get("raw_xml") - if not isinstance(raw_xml, str) or not raw_xml.strip(): - raw_xml = None - out[location.strip()] = (seen_at, dict(xml_fields), raw_xml) - return out - - def _build_persistent_xml_cache_entries(self) -> dict[str, dict]: - entries: dict[str, dict] = {} - now = datetime.now(timezone.utc) - for location, cached in self._xml_disk_cache.items(): - if not isinstance(location, str) or not location.strip(): - continue - seen_at, xml_fields, raw_xml = cached - if (now - seen_at) >= timedelta(seconds=_XML_CACHE_DISK_TTL_SECONDS): - continue - entries[location] = { - "updated_at": seen_at.isoformat(), - "xml_fields": dict(xml_fields) if isinstance(xml_fields, dict) else {}, - "raw_xml": raw_xml if isinstance(raw_xml, str) else None, - } - return entries - - def _load_persistent_profile_cache(self) -> dict[str, tuple[datetime, dict]]: - out: dict[str, tuple[datetime, dict]] = {} - cache_data = load_discovery_cache() - raw = cache_data.get("ssdp_profile_cache") - if not isinstance(raw, dict): - return out - entries = raw.get("entries") - if not isinstance(entries, dict): - return out - now = datetime.now(timezone.utc) - for key, row in entries.items(): - if not isinstance(key, str) or not key.strip() or not isinstance(row, dict): - continue - ts_text = row.get("updated_at") - if not isinstance(ts_text, str) or not ts_text.strip(): - continue - try: - seen_at = datetime.fromisoformat(ts_text) - except ValueError: - continue - if seen_at.tzinfo is None: - seen_at = seen_at.replace(tzinfo=timezone.utc) - if (now - seen_at) >= timedelta(seconds=_PROFILE_CACHE_DISK_TTL_SECONDS): - continue - out[key.strip()] = (seen_at, dict(row)) - return out - - def _build_persistent_profile_cache_entries(self) -> dict[str, dict]: - entries: dict[str, dict] = {} - now = datetime.now(timezone.utc) - for key, cached in self._profile_disk_cache.items(): - if not isinstance(key, str) or not key.strip(): - continue - seen_at, row = cached - if (now - seen_at) >= timedelta(seconds=_PROFILE_CACHE_DISK_TTL_SECONDS): - continue - payload = dict(row) - payload["updated_at"] = seen_at.isoformat() - entries[key] = payload - return entries - - def _persist_profile_cache_entry(self, profile_key: str, payload: dict) -> None: - if not isinstance(profile_key, str) or not profile_key.strip() or not isinstance(payload, dict): - return - metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {} - xml_fields = metadata.get("xml_fields") if isinstance(metadata, dict) else {} - if not isinstance(xml_fields, dict): - xml_fields = {} - now = datetime.now(timezone.utc) - ssdp_loc = metadata.get("location") if isinstance(metadata.get("location"), str) else "" - row = { - "name": payload.get("name"), - "type": payload.get("type"), - "category": payload.get("category"), - "url": payload.get("url"), - "xml_fields": dict(xml_fields), - "raw_xml": metadata.get("xml") if isinstance(metadata, dict) else None, - "ssdp_location": ssdp_loc.strip() if ssdp_loc.strip() else None, - } - self._profile_disk_cache[profile_key.strip()] = (now, row) - self._mark_cache_dirty() - - def _persist_profile_cache_entries(self, headers: dict[str, str], fallback_ip: str, payload: dict) -> None: - for key in self._profile_candidate_keys(headers, fallback_ip): - self._persist_profile_cache_entry(key, payload) - - def _mark_cache_dirty(self) -> None: - self._cache_dirty = True - self._flush_persistent_caches_if_due() - - def _flush_persistent_caches_if_due(self, force: bool = False) -> None: - if not self._cache_dirty and not force: - return - now_mono = time.monotonic() - if not force and self._last_cache_flush_monotonic > 0: - if (now_mono - self._last_cache_flush_monotonic) < _CACHE_FLUSH_INTERVAL_SECONDS: - return - - xml_entries = self._build_persistent_xml_cache_entries() - profile_entries = self._build_persistent_profile_cache_entries() - save_discovery_cache( - { - "ssdp_xml_cache": {"version": 1, "entries": xml_entries}, - "ssdp_profile_cache": {"version": 1, "entries": profile_entries}, - } - ) - - self._xml_disk_cache = { - loc: (datetime.fromisoformat(row["updated_at"]), row["xml_fields"], row.get("raw_xml")) - for loc, row in xml_entries.items() - } - self._profile_disk_cache = { - key: (datetime.fromisoformat(row["updated_at"]), dict(row)) - for key, row in profile_entries.items() - } - self._cache_dirty = False - self._last_cache_flush_monotonic = now_mono - - def _build_services_description(self, xml_fields: dict[str, str]) -> str: - return xml_fields.get("services_description", "") - - def _build_services_description_from_device(self, device_elem: ET.Element) -> str: - services: list[str] = [] - for elem in device_elem.iter(): - if elem.tag.rsplit("}", 1)[-1] == "serviceType": - value = (elem.text or "").strip() - if value: - services.append(value) - return ", ".join(services) - - def _build_services_records(self, device_elem: ET.Element, location: str | None) -> list[dict[str, str]]: - parsed_location = urlparse(location or "") - target_default = parsed_location.hostname or "" - port_default = str(parsed_location.port) if parsed_location.port is not None else "" - records: list[dict[str, str]] = [] - for service_elem in self._find_elements(device_elem, "service"): - service_type = self._find_text(service_elem, "serviceType") - if not service_type: - continue - control_url = self._find_text(service_elem, "controlURL") - parsed_control = urlparse(urljoin(location or "", control_url)) if control_url else None - target = target_default - port = port_default - if parsed_control is not None: - if parsed_control.hostname: - target = parsed_control.hostname - if parsed_control.port is not None: - port = str(parsed_control.port) - records.append( - { - "service": service_type, - "target": target or "unavailable", - "port": port or "unavailable", - } - ) - return records - - def _build_icons_description(self, device_elem: ET.Element) -> str: - items: list[str] = [] - current: dict[str, str] = {} - for elem in device_elem.iter(): - local = elem.tag.rsplit("}", 1)[-1] - if local in {"mimetype", "width", "height", "url"}: - current[local] = (elem.text or "").strip() - if local == "icon": - if current: - items.append( - f"mimetype={current.get('mimetype', '')};" - f"width={current.get('width', '')};" - f"height={current.get('height', '')};" - f"url={current.get('url', '')}" - ) - current = {} - return ", ".join([item for item in items if item.strip(";,")]) - - def _build_preferred_icon_url(self, device_elem: ET.Element, location: str | None) -> str: - base_url = location or "" - best_url = "" - best_area = -1 - for icon_elem in self._find_elements(device_elem, "icon"): - icon_url = self._find_text(icon_elem, "url") - if not icon_url: - continue - width_txt = self._find_text(icon_elem, "width") - height_txt = self._find_text(icon_elem, "height") - try: - area = int(width_txt or "0") * int(height_txt or "0") - except ValueError: - area = 0 - if area >= best_area: - best_area = area - best_url = urljoin(base_url, icon_url) - return best_url - - def _find_first(self, root: ET.Element, local_name: str) -> ET.Element | None: - for elem in root.iter(): - if elem.tag.rsplit("}", 1)[-1] == local_name: - return elem - return None - - def _find_elements(self, root: ET.Element, local_name: str) -> list[ET.Element]: - return [elem for elem in root.iter() if elem.tag.rsplit("}", 1)[-1] == local_name] - - def _find_text(self, root: ET.Element, local_name: str) -> str: - for elem in root.iter(): - if elem.tag.rsplit("}", 1)[-1] == local_name: - return (elem.text or "").strip() - return "" - - def _load_rules(self) -> dict: - default_rules = { - "name_rules": { - "fallback_fields": ["friendlyName", "displayName"], - "prefer_display_name_when_no_friendly_name": True, - }, - "information_rules": { - "concat_fields": ["roomName", "displayName"], - "separator": " / ", - }, - "type_rules": [ - {"contains_any": ["smartspeaker-audio", "sonos"], "type": "mediaserver"}, - {"contains_any": ["dial-multiscreen", "chromecast", "googletv", "android tv"], "type": "mediaserver"}, - {"contains_any": ["wifialliance", "wfadevice", "wfawlanconfig"], "type": "router"}, - {"contains_any": ["synology", "qnap", "nas"], "type": "nas"}, - ], - } - try: - if not _RULES_PATH.exists(): - return merge_ssdp_rules_overlays(default_rules) - parsed = json.loads(_RULES_PATH.read_text(encoding="utf-8")) - if not isinstance(parsed, dict): - return merge_ssdp_rules_overlays(default_rules) - merged = dict(default_rules) - merged.update(parsed) - self._logger.info("Loaded SSDP rules from %s", _RULES_PATH) - return merge_ssdp_rules_overlays(merged) - except (OSError, json.JSONDecodeError): - self._logger.exception("Failed to load SSDP rules, using defaults") - return merge_ssdp_rules_overlays(default_rules) - - def _apply_name_rules(self, xml_fields: dict[str, str]) -> str: - rules = self._rules.get("name_rules", {}) - if not isinstance(rules, dict): - return "" - fallback_fields = rules.get("fallback_fields", []) - if not isinstance(fallback_fields, list): - fallback_fields = [] - friendly = str(xml_fields.get("friendlyName", "")).strip() - display = str(xml_fields.get("displayName", "")).strip() - if rules.get("prefer_display_name_when_no_friendly_name") and (not friendly) and display: - return display - for field in fallback_fields: - value = xml_fields.get(str(field)) - if isinstance(value, str) and value.strip(): - return value.strip() - return "" - - def _build_information_text(self, xml_fields: dict[str, str]) -> str: - if not self._rules_enabled: - return "" - rules = self._rules.get("information_rules", {}) - if not isinstance(rules, dict): - return "" - fields = rules.get("concat_fields", []) - if not isinstance(fields, list): - fields = [] - separator = str(rules.get("separator", " / ")) - values: list[str] = [] - for field in fields: - value = xml_fields.get(str(field)) - if isinstance(value, str) and value.strip(): - value_norm = value.strip() - if value_norm not in values: - values.append(value_norm) - return separator.join(values) - - def _apply_type_rules(self, headers: dict[str, str], xml_fields: dict[str, str]) -> str: - rule_list = self._rules.get("type_rules", []) - if not isinstance(rule_list, list): - return "" - searchable_parts = [ - str(headers.get("ST", "")), - str(headers.get("NT", "")), - str(headers.get("USN", "")), - str(headers.get("SERVER", "")), - str(xml_fields.get("deviceType", "")), - str(xml_fields.get("manufacturer", "")), - str(xml_fields.get("modelName", "")), - str(xml_fields.get("modelType", "")), - str(xml_fields.get("friendlyName", "")), - str(xml_fields.get("displayName", "")), - str(xml_fields.get("roomName", "")), - ] - haystack = " ".join(searchable_parts).lower() - for rule in rule_list: - if not isinstance(rule, dict): - continue - target_type = rule.get("type") - contains_any = rule.get("contains_any", []) - if not isinstance(target_type, str) or not isinstance(contains_any, list): - continue - for token in contains_any: - token_norm = str(token).strip().lower() - if token_norm and token_norm in haystack: - return target_type.strip().lower() - return "" diff --git a/docs/CONTRIBUTING_ICONS.md b/docs/CONTRIBUTING_ICONS.md deleted file mode 100644 index 63c7a04d..00000000 --- a/docs/CONTRIBUTING_ICONS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Contributing Icons - -## Required format -- PNG required, SVG optional -- Minimum size: 64x64 -- Recommended size: 256x256 -- Transparent background - -## Naming -- Use `{type_id}.png` naming, for example `esp32.png` - -## Registering an icon -1. Add the icon file under `assets/icons/`. -2. Add or update corresponding mapping in `data/device_types.json` (or document the same snippet for **`~/.config/netneighbor/device_types.json`** overlays — [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md)). -3. Ensure `fallback.icon` remains set to `unknown.png`. diff --git a/docs/MAINTENANCE.md b/docs/MAINTENANCE.md deleted file mode 100644 index dd4a9ba6..00000000 --- a/docs/MAINTENANCE.md +++ /dev/null @@ -1,79 +0,0 @@ -# Maintenance and follow-up - -This complements [`README.md`](../README.md) and the [developer index](README.md) for anyone -keeping the project healthy between releases. - -## Configuration paths - -| Path | Content | -|------|---------| -| `~/.config/netneighbor/ui_prefs.json` | UI state + per-device overrides + rules (not a full device DB). Tray-related booleans include **`close_to_tray`** (default true), **`start_minimized_to_tray`**, **`start_at_login`** (writes XDG autostart when enabled). **`custom_command_template`** (**Tools → External applications**) for **Run custom command**; **`connect_command_templates`** overrides **Open** per URL scheme; **`device_commands`** stores per-device connection command lists from the **Options** tab (see [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md)). | -| `~/.config/autostart/io.esp3d.netneighbor.desktop` | Present when **Start NetNeighbor when logging in** is checked in View → Preferences; standard XDG autostart entry. **`Exec=`** appends **`--start-minimized-to-tray`** (tray-only login start) while the **menu** `.desktop` from packaging stays without that flag. Implemented in `utils/session_autostart.py`. | -| `~/.cache/netneighbor/discovery-cache.json` | Volatile discovery cache (`last_seen_overrides`, monitored snapshots metadata, SSDP XML/profile cache). Safe to delete; app rebuilds it. | -| `~/.config/netneighbor/logging.json` | Per-area log levels (`default`, `app`, `ssdp`, `mdns`). Created with defaults on first run if missing. | -| `~/.cache/netneighbor/netneighbor.log` | Log file when file logging is enabled (see `app.py`). | -| `~/.cache/netneighbor/remote_icons/` | On-disk cache for **device-provided** icons fetched from SSDP/mDNS URLs (normalized). Primary file per URL: **`{SHA256(url)}.payload`** raw HTTP body (decoded with GdkPixbuf on load — avoids flaky `savev`). The digest uses a **canonical URL** after rewriting typical LAN hosts (`*.local`, `*.lan`, single-label names) to the **device IP** (stable fetch + hash), then normalizing (lowercased scheme/host, trailing FQDN dot stripped, **default HTTP/HTTPS ports omitted**). Disk lookup also tries **legacy explicit `:80` / `:443`** variants so filenames from older canonicalization rules still resolve. A second lookup tries the **canonical raw URL** (pre-IP rewrite) for older payloads. **HTTPS** to `*.local` / `*.lan` or **RFC1918** hosts uses a relaxed TLS verify context (typical self-signed printer certs). Legacy **`.png`** files from older releases are still read if present. Clearing the folder forces a fresh download; if icons look wrong after a firmware change, clear **`remote_icon_index.json`** (see next row) as well. | -| `~/.cache/netneighbor/remote_icon_index.json` | **Host → icon cache index** (version 2 JSON): per **IPv4/IPv6 key** stores **`canonical_url`**, **`payload_sha256`** (same stem as **`remote_icons/{sha256}.payload`**), and **`updated_at`**. Lets the UI load the correct cached icon **on cold start** without waiting for every mDNS TXT variant. Delete this file to drop remembered host→URL mappings (payload files remain until removed manually). | -| `~/.config/netneighbor/discovery.json` | Discovery toggles + startup refresh schedule. Top-level **`mdns`** / **`ssdp`** with **`enabled`**, **`rules`**, optional **`query`**: SSDP **`interval_seconds`** (periodic M-SEARCH cadence, default 60), **`mx_seconds`** (M-SEARCH **MX** max wait, clamped **5–6**, default 5), **`descriptor_http_min_interval_seconds`** (minimum gap between HTTP GETs for descriptor URLs whose **host is the same IP** (or same hostname if not numeric); avoids duplicate fetches when anticipatory XML and SSDP LOCATION arrive close together; **0** disables; default **5**, max **120**); mDNS **`enumeration_timeout_seconds`** (DNS-SD type scan, **2–3** s, default 2.5), **`enumeration_interval_seconds`** (repeat scan, default 240), **`service_info_timeout_ms`** (`get_service_info`, **2000–3000** ms, default 2500). **`merge.protocol_order`**: ordered protocol **`source`** ids (default **`ssdp`**, **`mdns`**) — earlier = stronger for live-row tie-breaks. **`merge.information_precedence`**: ordered roles (**`user_override`**, **`ssdp_live`**, **`ssdp_profile_cache`**, **`mdns`**) — must list all four exactly once to customize; defaults favour user prefs, then live SSDP, then disk-cache hints on mDNS, then raw mDNS (see `utils/discovery_config.py`). **`startup_refresh_seconds`** at root (comma-separated string or JSON array). | - -## Logging - -- Root logging is configured in `app.py` (console + optional rotating file under cache dir). -- **`logging.json`**: keys `ssdp` and `mdns` apply both to the protocol module (`discovery.ssdp`, `discovery.mdns`) and to manager-side lines for that source (`discovery.manager.ssdp`, `discovery.manager.mdns`), including “Device added/updated”, **location** resolution (`Location: …`), and **device appearance** (type, bundled icon filename, `user_location`). Set **`app`** to **DEBUG** for **`ui.device_list`** messages (remote vs bundled icon path, GTK theme fallback). -- Special levels **`NONE`**, **`OFF`**, **`DISABLED`**, **`SILENT`** turn off that area (no INFO/DEBUG/WARNING from those loggers). -- **`NETNEIGHBOR_LOG_LEVEL`** still overrides the root/default level when set. -- Other useful loggers: `discovery.manager` (start/stop, publishing at DEBUG), `ui`. - -## Systray, window chrome, fullscreen - -- **Tray**: `ui/tray_indicator.py` — prefers Ayatana **AppIndicator** (`gir1.2-ayatanaappindicator3-0.1`) or legacy **AppIndicator3** (`gir1.2-appindicator3-0.1`), else **Gtk.StatusIcon**. Tray menu: **Open** / **Minimize to tray** (sensitive while the window is visible) / **Quit**. Without any of these backends, **close-to-tray** cannot hide to the panel; the window still closes normally. -- **Icons**: canonical vector logo — **`assets/svg/netneighbor.svg`**. Theme resolution uses **`assets/icons/`** as an extra icon search path; **`hicolor/scalable/apps/`** contains symlinks **`io.esp3d.netneighbor.svg`** and **`io.esp3d.netneighbor-tray.svg`** pointing at that file (so GTK finds app + tray names). Installed `.deb` copies the SVG into `/usr/share/icons/hicolor/scalable/apps/` under both names. -- **Close-to-tray + tray available**: main window uses a **Gtk.HeaderBar** with **Maximize** and **Close** only (explicit minimize lives on the tray menu). **CLI** **`--start-minimized-to-tray`** and first-run flow can skip stealing focus until the user opens from the tray (`app.py` → `MainWindow`). **F11** toggles fullscreen (useful for the icon grid); implemented via a window **Gtk.AccelGroup** in `ui/main_window.py`. -- **`utils/gtk_dialog.py`**: **`prepare_gtk_dialog`** disables CSD/header-bar dialogs that lose WM title bars on some compositors/window managers (used by main window, details, list, and related dialogs). -- **Open on PCs**: **Open** / double-click uses **`resolve_connect_target`** — **HTTP(S)** first, then **SMB** / **FTP** / **SSH** / **Telnet** from merged mDNS or explicit device URLs; type **`computer`** with no other target opens **`smb://`** toward the host IP (file manager). The resulting URI is opened via **`launch_connect_for_uri`** (`utils/connect_launcher.py`) — empty per-scheme template in **Tools → External applications…** keeps the system default. If no target exists, **Open** is inactive. - -## Common tasks - -- **Rules tuning**: shipped `config/ssdp_rules.json` / `config/mdns_rules.json`; user overlays in **`~/.config/netneighbor/`** — [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md). -- **Icons / types**: `data/device_types.json` and [`CONTRIBUTING_ICONS.md`](CONTRIBUTING_ICONS.md); optional user merge from `~/.config/netneighbor/device_types.json` ([`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md)). Icons loaded from SSDP/mDNS URLs are persisted under **`~/.cache/netneighbor/remote_icons/`** with a **`remote_icon_index.json`** host map (see table above). -- **Translations**: `locale/*/LC_MESSAGES/netneighbor.po`, compile with `msgfmt`; see [`I18N.md`](I18N.md) for full workflow. - -## Discovery extension hooks - -- **`DiscoveryManager.register_presence_transition_hook` / `unregister_presence_transition_hook`** (`discovery/manager.py`): optional observers for **`"online"`** / **`"offline"`** transitions per device identity row (not wired in core UI). Callbacks run on the same thread as the discovery update — use `GLib.idle_add` before touching GTK. Failures are logged and do not stop discovery. Planned use: future plugins / alerting. Extension code may import `DiscoveryManager`, `PresenceTransitionHook`, and `PresenceTransitionKind` from the **`discovery`** package (`from discovery import …`). - -## Debugging discovery issues - -1. Confirm only **one** app instance (SSDP bind + multicast). -2. Check firewall allows UDP 1900 inbound / multicast. -3. Inspect SSDP details in the UI for `LOCATION`, `USN`, XML presence. -4. Compare logs for “XML fetched” vs failures (timeouts, parse errors). -5. **Location looks like a URL / `description.xml`**: should no longer happen; if prefs were polluted earlier, open **Location presets** or edit **`ui_prefs.json`** — invalid URL-like presets are stripped on load. **`utils/location_label.py`** documents the rejection rules. -6. **Wrong or delayed device icon**: confirm **`remote_icons/*.payload`** and **`remote_icon_index.json`** together; bump **`mdns`** / **`app`** to **DEBUG** to trace aggregate + icon load path. -7. **Device details (first tab)**: duplicate **Last seen** rows are collapsed to the latest timestamp; bundled WSD/wsdd/NMB-only rows omit legacy **Discovery** / **WSD XAddrs** / **NetBIOS registration** lines (overview + protocol fields stay minimal). **IPv6 (link-local)** in the overview only appears when a `fe80::` address is inferred from device IP or WSD/wsdd payloads — many Windows PCs only advertise IPv4 in WSD URLs, so an empty IPv6 line there is expected. - -## Changelog / release notes - -Archived in [`archive/CHANGELOG.md`](archive/CHANGELOG.md) (up to **0.8.0**). New release notes go in the repository changelog or release tags. - -## Suggested additional docs (optional) - -| Document | When to add | -|----------|-------------| -| `TESTING.md` | Once you have automated tests or a repeatable manual checklist per release. | -| `PACKAGING.md` | When AppImage / `.deb` pipeline is scripted (commands, deps, smoke test). | -| `TROUBLESHOOTING.md` | User-facing FAQ distilled from GitHub issues (short). | - -Architecture Decision Records (ADR): optional short files under `docs/adr/` for major choices -(why GTK3, why in-memory store first, etc.) if the team grows. - -## Release checklist (minimal) - -- [ ] **`VERSION`** bumped. -- [ ] `README.md` and `USER_DOCUMENTATION.md` aligned with new behavior. -- [ ] `docs/MAINTENANCE.md`, `docs/PACKAGING.md`, and `docs/COMMUNITY_OVERRIDES.md` updated if behavior or deps changed. -- [ ] `docs/TODO.md` updated (move done items, add new known issues). -- [ ] Translation catalogs merged (`msgmerge`) and `.mo` files compiled. -- [ ] Smoke run: start app, discovery, details, tray hide/show, **CLI** `--start-minimized-to-tray`, optional autostart toggle, monitored device restart. -- [ ] Test Open / double-click with Override and Additional device commands. -- [ ] Packaging smoke: `./packaging/build_deb.sh`, install in VM, verify icons + `Recommends` (tray + `nmblookup`). diff --git a/docs/MDNS.md b/docs/MDNS.md deleted file mode 100644 index 0e6803d1..00000000 --- a/docs/MDNS.md +++ /dev/null @@ -1,108 +0,0 @@ -# mDNS in NetNeighbor - -## Protocol overview - -**mDNS** (multicast DNS / DNS-SD) advertises services on the local network under `*.local.` names. -NetNeighbor uses `zeroconf` browsing callbacks; it does not perform an active LAN scan. - -Typical service types discovered: - -| Type | Meaning | -|------|---------| -| `_http._tcp` | Web UI | -| `_smb._tcp`, `_microsoft-ds._tcp` | File sharing | -| `_ssh._tcp` | SSH | -| `_ftp._tcp` | FTP | -| `_telnet._tcp` | Telnet | -| `_esp3d._tcp` | ESP3D firmware | - -## Code map - -| Area | File / symbol | Role | -|------|---------------|------| -| Provider | `discovery/mdns.py` | `MDNSDiscovery` — zeroconf browser/listener, TXT decode, host aggregation | -| Contract | `discovery/base.py` | `BaseDiscovery._emit("device", payload)` → normalized dict to manager | -| Orchestration | `discovery/manager.py` | Receives `mdns` payloads, applies overrides, stores and notifies | -| Mapping hints | `data/device_types.json` | Per-service defaults (`type`, `icon`, `default_port`) | -| UI payload | `utils/details_payload.py` | `build_mdns_payload` — per-service sections for the Services tab | -| Rules | `config/mdns_rules.json` | TXT → summary line mappings and optional `type_rules` | - -## Browse strategy - -- Service types from `data/device_types.json` (`mdns` section) are browsed immediately. -- **DNS-SD enumeration** (`_services._dns-sd._udp`) runs in background to catch unlisted types. -- Enumeration repeats on a timer and on `refresh()` — no types need to be listed statically. - -## Host-level aggregation - -mDNS announces per-service. NetNeighbor aggregates services to one logical host entry: - -1. Track per-service payloads `(service_type, instance_name)` -2. Map each service to a host key (prefer IP, fallback hostname) -3. Emit an aggregated payload with all services under `metadata["services"]` - -A device like ESP3D exposing both `_esp3d._tcp` and `_telnet._tcp` appears as one entry -with both services visible in the Details dialog. - -## URL policy - -A presentation URL is built **only if `_http._tcp` is actually present**. Port numbers alone do not imply HTTP — this avoids wrong browser links for non-HTTP services on common ports. - -## TXT records - -- Raw `ServiceInfo.text` is decoded preserving duplicate keys and ordering → `metadata["services"][].txt_records` -- A flat `metadata["txt"]` (last-key-wins) is kept for type heuristics -- Details dialog shows one expandable row per service with TXT pairs nested under it - -## Type heuristics - -Type starts from `device_types.json`, refined by heuristics (`fluidnc→cnc`, `synology/qnap→nas`, etc.), then `type_rules` in `mdns_rules.json`. - -## Online / offline lifecycle - -A host stays online while at least one tracked service remains. Removing one service updates the aggregated payload; offline is emitted only when all services are gone — avoids flapping for multi-service hosts. - ---- - -## Rules file (`config/mdns_rules.json`) - -Lets you **map TXT keys onto summary lines** and **extend type classification** without Python changes. -User overlay: `~/.config/netneighbor/mdns_rules.json` — merged with bundled defaults. -See [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md). - -### `summary_from_txt` - -Ordered list; each entry emits at most one first-tab detail row. - -| Field | Type | Meaning | -|-------|------|---------| -| `label` | string | Detail column heading (match SSDP wording to enable cross-protocol merge) | -| `keys` | list | TXT key aliases, priority order, case-insensitive | - -### `type_rules` - -Evaluated after fixed heuristics. First match wins. - -| Field | Type | Meaning | -|-------|------|---------| -| `contains_any` | list | Lowercase substrings searched in service key, name, and TXT pairs | -| `type` | string | Internal type id (e.g. `nas`, `router`) | - -### How to extend - -1. Add `summary_from_txt` entries matching your devices' actual TXT keys (check Services tab in Details). -2. Use the same `label` as SSDP counterparts so SSDP+mDNS detail rows merge correctly. -3. Add `type_rules` with specific `contains_any` before generic ones. -4. Validate: `python -m json.tool config/mdns_rules.json` -5. Restart the app (rules are cached at startup). - -## Debugging - -- Enable `mdns` in `~/.config/netneighbor/logging.json` -- Details dialog → Services tab: verify TXT records, services list, URL present only when `_http._tcp` exists - -## See also - -- [`SSDP.md`](SSDP.md) — parallel SSDP pipeline -- [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md) — user overlay rules -- [`BACKEND_ARCHITECTURE.md`](BACKEND_ARCHITECTURE.md) — discovery manager overview diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md deleted file mode 100644 index 9880f609..00000000 --- a/docs/PACKAGING.md +++ /dev/null @@ -1,123 +0,0 @@ -# Packaging (`.deb` + `tar.gz`) - -This project ships helper scripts under `packaging/` to build: - -- a Debian package (`.deb`) for Ubuntu/Debian/Linux Mint -- a portable source/runtime archive (`tar.gz`) - -## Prerequisites (build machine) - -- Debian/Ubuntu-like environment -- `git` -- `dpkg-deb` -- `tar` - -Optional (post-install hooks in `.deb` call these if available): - -- `desktop-file-utils` (`update-desktop-database`) -- `gtk-update-icon-cache` - -## Build commands - -From repository root: - -```bash -chmod +x packaging/build_deb.sh packaging/build_tarball.sh packaging/netneighbor -./packaging/build_deb.sh -./packaging/build_tarball.sh -``` - -Both scripts default to the repository root `VERSION` file (first non-empty line). -You can still override explicitly, e.g. `./packaging/build_deb.sh 0.7.0`. - -## One-command release helper - -Use `packaging/release.sh` to run build + checks in one go: - -```bash -./packaging/release.sh -``` - -What it does: - -- Python syntax sanity checks (`app.py`, `ui/main_window.py`, `discovery/manager.py`, `utils/app_version.py`) -- Bash syntax checks for packaging scripts -- Build `.deb` and `tar.gz` -- Verify `.deb` metadata (`Version`, `Installed-Size`) -- Verify embedded runtime `VERSION` and desktop entry `Version=...` -- Generate checksums file: `dist/SHA256SUMS-.txt` - -Optional arguments: - -```bash -./packaging/release.sh [architecture] -``` - -Outputs: - -- `dist/netneighbor__.deb` -- `dist/netneighbor-.tar.gz` - -## `.deb` package layout - -- App files: `/usr/share/netneighbor/` -- Launcher: `/usr/bin/netneighbor` -- Desktop entry: `/usr/share/applications/netneighbor.desktop` -- Icons (**SVG scalable**): - - `/usr/share/icons/hicolor/scalable/apps/io.esp3d.netneighbor.svg` — app/launcher icon (source: `assets/svg/netneighbor_icon.svg`) - - `/usr/share/icons/hicolor/scalable/apps/io.esp3d.netneighbor-tray.svg` — coloured tray icon for light GTK themes (source: `assets/svg/netneighbor-tray.svg`) - - `/usr/share/icons/hicolor/scalable/status/io.esp3d.netneighbor-tray-symbolic.svg` — white symbolic tray icon for dark GTK themes (source: `assets/svg/netneighbor-tray-symbolic.svg`) - - The tray code (`ui/tray_indicator.py`) selects the icon at startup based on `gtk-theme-name`: themes containing `"dark"` or with `gtk-application-prefer-dark-theme=true` use the symbolic (white) variant; others use the coloured variant. - - In dev mode (running from source) the same icons are resolved via `assets/icons/hicolor/` symlinks registered with `Gtk.IconTheme.append_search_path()`. - -The `.deb` embeds runtime-relevant tracked paths only (`discovery/`, `ui/`, `utils/`, `model/`, `data/`, `config/`, `assets/`, `locale/`, plus entrypoint/docs files listed in `packaging/build_deb.sh`). - -Desktop category is network-oriented: - -```ini -Categories=Network;Utility;GTK; -``` - -## Runtime dependencies in `.deb` - -**Depends** (hard): - -- `python3`, `python3-gi`, `python3-gi-cairo`, `gir1.2-gtk-3.0`, `python3-zeroconf` - -**Recommends** (installed by default with `apt install ./…deb` unless `--no-install-recommends`): - -- `samba-common-bin` — provides **`nmblookup`** for NetBIOS discovery (**not** the Samba server). -- `gir1.2-ayatanaappindicator3-0.1` **|** `gir1.2-appindicator3-0.1` — GObject bindings so the panel tray icon works on typical desktops. - -## Install / uninstall (`.deb`) - -```bash -sudo apt install ./dist/netneighbor__amd64.deb -netneighbor -sudo apt remove netneighbor -``` - -Notes: - -- `apt remove` / `apt purge` do not delete per-user data under `~/.config/netneighbor` and `~/.cache/netneighbor`. -- For explicit user-data cleanup, run: - -```bash -./packaging/cleanup-user-data.sh -``` - -## `tar.gz` usage - -```bash -tar -xzf dist/netneighbor-.tar.gz -cd netneighbor- -./run.sh -``` - -Notes: - -- `tar.gz` does not register desktop launchers/icons automatically. -- `install-desktop.sh` included in the tarball installs launcher + icon under `~/.local`. -- System GTK/PyGObject dependencies must already be present. diff --git a/docs/README.md b/docs/README.md index 0dcea640..fa8bd005 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,34 +1,70 @@ # NetNeighbor — developer documentation This folder contains technical documentation for contributors and maintainers. End-user -documentation remains in the repository root [`README.md`](../README.md) and -[`USER_DOCUMENTATION.md`](../USER_DOCUMENTATION.md). +documentation is in [`USER_DOCUMENTATION.md`](USER_DOCUMENTATION.md). -## Documents +## Structure + +``` +docs/ + reference/ Protocol and architecture deep-dives + contributing/ How to contribute icons, translations, and rule overlays + operations/ Build, packaging, and maintenance guides + archive/ Historical documents (GTK 1.x era) + images/ Screenshots and logos + esp3d-overview/ ESP3D project overview pages +``` + +## User and project + +| Document | Purpose | +|----------|---------| +| [`USER_DOCUMENTATION.md`](USER_DOCUMENTATION.md) | End-user guide: UI, menus, preferences, tray. | +| [`ROADMAP.md`](ROADMAP.md) | Planned and completed work, backlog, ideas. | + +## Reference + +| Document | Purpose | +|----------|---------| +| [`reference/BACKEND_ARCHITECTURE.md`](reference/BACKEND_ARCHITECTURE.md) | DiscoveryManager, override system, device commands model, protocol modules, data model, cross-protocol merge, config files, thread safety. | +| [`reference/SSDP.md`](reference/SSDP.md) | SSDP protocol basics, M-SEARCH, XML parsing, TTL/offline handling, `ssdp_rules.json` schema. | +| [`reference/MDNS.md`](reference/MDNS.md) | mDNS browse/aggregation model, service mapping, URL rules, lifecycle, `mdns_rules.json` schema. | +| [`reference/WSD.md`](reference/WSD.md) | WS-Discovery (Windows PCs, printers), EPR/scope parsing, type classification, offline detection. | +| [`reference/NETBIOS.md`](reference/NETBIOS.md) | NetBIOS name browse via `nmblookup`, suffix table, integration as supplementary source. | + +## Contributing + +| Document | Purpose | +|----------|---------| +| [`contributing/COMMUNITY_OVERRIDES.md`](contributing/COMMUNITY_OVERRIDES.md) | User overlays in `~/.config/netneighbor/` (rules + device types) plus notes on **`ui_prefs.json`** keys. | +| [`contributing/CONTRIBUTING_ICONS.md`](contributing/CONTRIBUTING_ICONS.md) | Icon assets and `device_types.json` contributions. | +| [`contributing/I18N.md`](contributing/I18N.md) | How to add/update translations (`.po`/`.mo`), merge catalogs, and test locales. | + +## Operations + +| Document | Purpose | +|----------|---------| +| [`operations/MAINTENANCE.md`](operations/MAINTENANCE.md) | Ongoing care: logging, config paths, debugging discovery, release checklist. | +| [`operations/PACKAGING.md`](operations/PACKAGING.md) | Build and validate release artifacts (`.deb` / `tar.gz` / AppImage / PyInstaller / Inno Setup). | + +## Archive | Document | Purpose | |----------|---------| -| [`BACKEND_ARCHITECTURE.md`](BACKEND_ARCHITECTURE.md) | DiscoveryManager, override system, device commands model, protocol modules, data model, cross-protocol merge, config files, thread safety. | -| [`UI_ARCHITECTURE.md`](UI_ARCHITECTURE.md) | GTK layer: main window, device list, threading, preferences, notifications history. | -| [`SSDP.md`](SSDP.md) | SSDP protocol basics, M-SEARCH, XML parsing, TTL/offline handling, `ssdp_rules.json` schema. | -| [`MDNS.md`](MDNS.md) | mDNS browse/aggregation model, service mapping, URL rules, lifecycle, `mdns_rules.json` schema. | -| [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md) | User overlays in `~/.config/netneighbor/` (rules + device types) plus notes on **`ui_prefs.json`** keys. | -| [`MAINTENANCE.md`](MAINTENANCE.md) | Ongoing care: logging, config paths, debugging discovery, release checklist. | -| [`PACKAGING.md`](PACKAGING.md) | Build and validate release artifacts (`.deb` + `tar.gz`) with helper scripts. | -| [`I18N.md`](I18N.md) | How to add/update translations (`.po`/`.mo`), merge catalogs, and test locales. | -| [`CONTRIBUTING_ICONS.md`](CONTRIBUTING_ICONS.md) | Icon assets and `device_types.json` contributions. | -| [`TODO.md`](TODO.md) | Known items and ideas for future work. | -| [`archive/`](archive/) | Archived documents (Brief v1.3, v1.4, ROADMAP, CHANGELOG). | +| [`archive/ROADMAP_QT_2_0.md`](archive/ROADMAP_QT_2_0.md) | Completed Qt 2.0 migration checklist (GTK → PySide6). | +| [`archive/UI_ARCHITECTURE.md`](archive/UI_ARCHITECTURE.md) | GTK 3 UI layer — archived, no longer current. | +| [`archive/CHANGELOG.md`](archive/CHANGELOG.md) | Release notes up to 0.8.0. | +| [`archive/`](archive/) | Brief v1.3, v1.4, GTK roadmap. | ## Quick orientation -- **Discovery**: `discovery/base.py` (contract), `discovery/manager.py` (cache + merges + override system), `discovery/ssdp.py`, `discovery/mdns.py`, `discovery/wsd.py` (WS-Discovery; PyPI `WSDiscovery`), `discovery/netbios.py`. -- **UI**: `app.py` (single instance, activation), `ui/main_window.py`, `ui/device_list.py`, `ui/device_details.py`, `ui/tray_indicator.py` (panel icon), `utils/session_autostart.py` (XDG login entry). -- **Connect**: `utils/double_click_open.py` (target resolution), `utils/connect_launcher.py` (command templates + launch). +- **Discovery**: `app/discovery/base.py` (contract), `app/discovery/manager.py` (cache + merges + override system), `app/discovery/ssdp.py`, `app/discovery/mdns.py`, `app/discovery/wsd.py` (WS-Discovery), `app/discovery/netbios.py`. +- **UI**: `app/app_qt.py` (single instance, activation), `app/ui/` (`NetNeighborMainWindow`, `MainThreadScheduler`, `PreferencesDialog`, `NetNeighborTray`, …), `app/utils/session_autostart.py` (XDG/registry login entry). +- **Connect**: `app/utils/double_click_open.py` (target resolution), `app/utils/connect_launcher.py` (command templates + launch). - **Config**: - `~/.config/netneighbor/ui_prefs.json` (UI state + user choices/rules/overrides including `device_commands`) - - `~/.config/netneighbor/discovery.json` (per-protocol `mdns`/`ssdp` blocks with `enabled`/`rules`, `merge.protocol_order`, `merge.information_precedence`, plus `startup_refresh_seconds`; see [`MAINTENANCE.md`](MAINTENANCE.md)) + - `~/.config/netneighbor/discovery.json` (per-protocol `mdns`/`ssdp` blocks with `enabled`/`rules`, `merge.protocol_order`, `merge.information_precedence`, plus `startup_refresh_seconds`; see [`operations/MAINTENANCE.md`](operations/MAINTENANCE.md)) - `~/.cache/netneighbor/discovery-cache.json` (volatile discovery cache: `last_seen`, monitored snapshots, SSDP XML/profile cache) - - `config/default_commands.json` (built-in per-scheme command templates; loaded by `utils/connect_launcher.py`) + - `app/config/default_commands.json` (per-OS built-in scheme templates; loaded by `app/utils/connect_launcher.py`) If you add a new protocol, start from `BaseDiscovery` and register the provider in `DiscoveryManager`. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 00000000..9a15ebf0 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,539 @@ +# NetNeighbor — Implementation Roadmap + +Last updated: 2026-11-30 + +This document tracks planned and completed improvements, grouped by theme. +Each section lists the motivation, the files involved, the acceptance criteria, +and the implementation status. + +--- + +## Status legend + +| Symbol | Meaning | +|--------|---------| +| ✅ | Done — merged and tested | +| 🔄 | In progress | +| 📋 | Planned — design agreed | +| 💡 | Idea — not yet scoped | + +--- + +## Theme A — Startup performance + +**Context:** The application was taking 3+ seconds before showing the window, then +another 3–4 seconds before devices appeared. The UI thread was blocked by heavy imports +and by `manager.start()` running synchronously. + +### A-1 Lazy imports for wsdiscovery and zeroconf ✅ + +- **Files:** `discovery/wsd.py`, `discovery/mdns.py` +- **Change:** Moved `import wsdiscovery` / `import zeroconf` inside `start()` via + `_ensure_wsd_libs()` / `_ensure_zeroconf_libs()`. Both are now imported on first use + rather than at module load time. +- **Gain:** ~500 ms moved after window display. + +### A-2 Single-instance timeout reduction ✅ + +- **File:** `utils/qt_single_instance.py` +- **Change:** `waitForConnected` reduced from 800 ms to 200 ms. + +### A-3 Discovery start in background thread ✅ + +- **File:** `app_qt.py` +- **Change:** `manager.start()` + `manager.refresh()` now run in a `threading.Thread` + launched via `QTimer.singleShot(0, ...)` so the Qt event loop starts clean and the + window (and overlay) paint before any blocking work begins. + +### A-4 Scanning overlay ✅ + +- **File:** `ui/main_window.py` — class `_ScanningOverlay` +- **Change:** Centered translucent overlay with animated spinner and "Start Scanning…" + text, shown while waiting for the first devices. Animation runs in a background thread + emitting a `Signal(QueuedConnection)` at 11 Hz to stay independent of main-thread load. + Auto-dismissed when the first device appears, or after 12 s. + +--- + +## Theme B — System tray and session autostart + +**Context:** Users want the application to live in the system tray, minimize to the +tray instead of the taskbar, and optionally start automatically at session login. + +### B-1 System tray icon ✅ + +- **File:** `ui/systray.py` (new), `ui/__init__.py`, `app_qt.py` +- **Change:** `NetNeighborTray(QSystemTrayIcon)` with Show/Hide + Quit context menu. + Left-click toggles window visibility. Label stays in sync with window state. + Created in `app_qt.py` when `QSystemTrayIcon.isSystemTrayAvailable()`. + +### B-2 Minimize to tray instead of taskbar ✅ + +- **File:** `ui/main_window.py` — `changeEvent` +- **Change:** Intercepts `WindowStateChange` when `isMinimized()`. Schedules + `self.hide()` via `QTimer.singleShot(0, ...)` to avoid in-transition side effects. + `bring_to_front()` uses `showNormal()` to clear the minimized state on restore. + +### B-3 Close to tray ✅ + +- **File:** `ui/main_window.py` — `closeEvent` +- **Change:** If `close_to_tray` preference is `True` (default) and a tray is available, + `closeEvent` calls `event.ignore()` + `self.hide()` instead of accepting the close. + +### B-4 Session autostart ✅ + +- **File:** `utils/session_autostart.py` +- **Change:** Extended with Windows registry support (`HKCU\...\Run`). Unified public + API — `autostart_enabled_on_disk()` and `apply_autostart_pref()` — dispatches by + platform (XDG `.desktop` on Linux/macOS, `winreg` on Windows). Launch command always + includes `--start-minimized-to-tray`. + +### B-5 Start minimized to tray ✅ + +- **File:** `app_qt.py` +- **Change:** `--start-minimized-to-tray` CLI argument. When set and tray is available, + `window.show()` is skipped so the application starts invisible. + +--- + +## Theme C — UI correctness fixes + +### C-1 Icon view empty after restore from tray ✅ + +- **File:** `ui/main_window.py` — `_rebuild_grouped_icon_page` +- **Root cause:** `was_page_visible = page.isVisible()` returned `False` while the + window was hidden. The page was then explicitly hidden via `setVisible(False)`, + preventing Qt from showing it when the window was restored. +- **Fix:** Changed to `was_page_visible = not page.isHidden()` which tests the + explicit-hide flag rather than effective screen visibility. + +### C-2 Sidebar loses all types when a filter is active ✅ + +- **File:** `ui/main_window.py` — `_rebuild_sidebar` +- **Root cause:** Sidebar was built from `_filtered_bundles()` which already applied + `_selected_category`. Clicking "by Type" (already selected) triggered a rebuild + where only the filtered type remained visible; other types were dropped. +- **Fix:** Sidebar is now built from all non-hidden bundles (`self._bundles` minus + hidden), independent of the active filter. + +### C-3 Empty line at top of sidebar in list mode ✅ + +- **File:** `ui/main_window.py` — `_sync_sidebar_top_spacer` +- **Root cause:** A spacer equal to the table header height was added to align the + sidebar list with the table body. It appeared as a blank row. +- **Fix:** Removed the list-mode special case; spacer is always 0. + +### C-4 Location auto-add not implemented ✅ + +- **File:** `ui/main_window.py` +- **Root cause:** The `auto_add_discovered_locations` preference was saved but never + read to actually populate `_location_options`. +- **Fix:** `_maybe_auto_add_discovered_locations()` is called after each device + snapshot. If the pref is enabled, it collects `user_location` from all bundles, + merges into `_location_options` via `normalize_location_options`, and persists. + +### C-5 Current device location missing from context menu ✅ + +- **File:** `ui/main_window.py` — `_show_device_context_menu` +- **Root cause:** If `_location_options` is empty (fresh config), the location menu + was empty even for devices that already had a location assigned. +- **Fix:** The device's current `bundle_location_label` is injected into `loc_opts` + before passing to the menu, without modifying the global `_location_options`. + +--- + +## Theme D — UI responsiveness (refresh / idle management) + +**Context:** Periodic discovery events were triggering full UI rebuilds even with no +visible changes. Context menus disappeared, hover states jumped, scroll position reset. + +### D-1 Active popup guard ✅ + +- **File:** `ui/main_window.py` — `_flush_pending_devices` +- **Change:** If `QApplication.activePopupWidget()` is not None (a context menu is + open), the flush is rescheduled 400 ms later. Prevents widget rebuilds from closing + an active menu. + +### D-2 User activity guard ✅ + +- **File:** `ui/main_window.py` — `_UserActivityGuard`, `_flush_pending_devices` +- **Change:** Application-level event filter tracks last mouse/keyboard timestamp. + Flush is deferred by 250 ms if `idle_ms() < 200`. Prevents hover-state jumps while + the user is navigating. + +### D-3 Fingerprint early bail ✅ + +- **File:** `ui/main_window.py` — `_apply_devices_snapshot`, + `_device_snapshot_ui_fingerprint` +- **Change:** `user_location` added to the device fingerprint. If the device fingerprint + and the precedence list are unchanged and the view has already been rendered + (`_last_device_view_sig is not None`), the snapshot is skipped entirely — no bundle + build, no sidebar check, no view refresh timer. + +### D-4 Scroll position preserved ✅ + +- **Files:** `ui/main_window.py` — `_fill_table`, `_fill_flat_icon_list` +- **Change:** Vertical scroll position is saved before and restored after each rebuild. + For the flat icon list, restoration is deferred via `QTimer.singleShot(0, ...)` to + allow the relayout pass to complete first. + +--- + +## Theme E — Device lifetime and cache validity + +**Context:** Devices that silently disappear can remain "online" for minutes. The +disk cache accumulates stale entries indefinitely. There is no active validation of +cached devices at startup, and no visual distinction between "confirmed live" and +"last seen N hours ago". + +### E-1 Cache purge and `last_seen` timestamp ✅ + +- **Files:** `utils/discovery_cache.py` +- **Change:** + - Add `last_seen` (ISO-8601 UTC) field to each cache entry, updated on every write. + - At load time: skip entries older than a configurable threshold (default 48 h). + Currently entries > 24 h are skipped, but stale entries are not removed from disk. + - At save time: remove entries that have exceeded the threshold instead of only + merging new data. +- **Acceptance:** After 48 h without seeing a device, it does not appear at next + startup. Cache file does not grow unboundedly. + +### E-2 "Last seen" indicator in UI ✅ + +- **Files:** `ui/main_window.py` (tooltip), `ui/icon_tile_delegate.py` (optional + visual dimming) +- **Change:** + - Device tooltip includes "Last seen: 3 h ago" when `last_seen` is available and the + device has not been confirmed live in this session. + - Optionally: icon slightly desaturated / opacity reduced for cache-only devices not + yet confirmed live. +- **Acceptance:** User can distinguish a device seen 30 s ago from one seen 23 h ago. + +### E-3 NetBIOS TTL at refresh ✅ + +- **File:** `discovery/netbios.py` +- **Change:** `NetbiosDiscovery` now tracks `_nmb_known` (last payload per IP) and + `_nmb_miss_counts` (consecutive sweeps without a response). After each `_run_once`, + hosts absent for ≥ 2 consecutive sweeps receive an offline event. Transient failures + (timeout / OSError) return early without incrementing miss counts. `stop()` clears + both dicts. +- **Acceptance:** A NetBIOS device that leaves the network is marked offline within + 2 refresh cycles (default: ~6 min with 3-minute interval). + +### E-4 WSD / wsdd offline detection ✅ + +- **Files:** `discovery/wsd.py`, `discovery/wsdd_client.py` +- **Change:** + - **WSD:** `WSDiscovery._run_once` now calls `eng.clearRemoteServices()` before each + probe sweep, so `_remoteServices` only contains devices that responded in the current + cycle. TTL tracking via `_wsd_known_eprs` / `_wsd_miss_counts` emits offline after + 2 missed sweeps. Transient probe failures return early without penalising known hosts. + - **wsdd:** `WsddSocketDiscovery._poll_once` collects all list-response payloads first, + then applies TTL via `_wsdd_known` / `_wsdd_miss_counts` (grace: 2 polls). + Socket failures return early without penalising known hosts. +- **Acceptance:** A WSD/wsdd device that disappears from the network is marked offline + within 2 sweep/poll cycles. + +### E-5 TCP probe validation for cached devices ✅ + +- **Files:** `discovery/manager.py`, `utils/tcp_probe.py` (new) +- **Change:** + - `utils/tcp_probe.py`: `probe_tcp(ip, port, timeout_s)` performs a single TCP + connect. `probe_devices_background(targets, on_result, ...)` runs all targets + concurrently in a `ThreadPoolExecutor` inside a daemon thread, calling + `on_result(ip, port, reachable)` for each. + - `manager.start()` calls `_start_tcp_probes_for_cached_devices()` right after + `_emit_cached_devices()`. It collects all online cached endpoints with a valid port + (skips loopback and link-local IPv6), then launches a background probe (max 8 + concurrent, 1.5 s timeout). + - On success: `last_seen` updated to now on all matching devices. + - On failure: `device.online = False` set directly, then `_notify()` called. + Guard: if a live protocol has already confirmed the device online since probe start + (`last_seen > probe_start`), the offline flip is skipped. +- **Acceptance:** Cached devices that are unreachable are marked offline within ~5 s + of startup, before the full protocol discovery completes (~15–30 s). + +--- + +## Theme F — Discovery enhancements 💡 + +*Outstanding ideas — not yet scheduled.* + +- SFTP service detection via mDNS (`_sftp-ssh._tcp`) +- NetBIOS: hint in UI when `nmblookup` is not installed +- SSDP XML fetches: per-host lock for concurrent descriptor fetches +- wsdd_client: remove hardcoded 0.35 s sleep between probe and list +- NetBIOS directed probes: parallel `ThreadPoolExecutor` instead of sequential `nmblookup -A` calls +- Performance — cache pre-population at startup (emit cached SSDP devices before live discovery completes, so the window is populated in < 100 ms) + +--- + +## Theme G — UX polish + +### G-1 Reset all application data ✅ + +- **Files:** `utils/device_remote_icon.py`, `ui/preferences_dialog.py`, `ui/main_window.py` +- **Change:** Added "Maintenance" section in Preferences → General with a + "Reset all application data…" button. Confirmation dialog warns that + `~/.config/netneighbor` and `~/.cache/netneighbor` will be permanently deleted. + On confirm, calls `clear_all_app_data()` which clears both directories, then + disables the button with "Reset done — please restart". + Translated in all 8 languages (fr, es, de, it, nl, ja, zh_CN, zh_TW). + +### G-2 Global enable/disable of "Open" protocols 💡 + +- **Context:** "Open" targets are resolved per protocol (`http`, `https`, `smb`, `ftp`, + `ssh`, `sftp`, `telnet`, and since 2.1.1 `spotify` for `_spotify-connect._tcp`). + More application-style protocols of this kind are expected; not every user wants all of + them in the context menu or competing for the double-click. +- **Today:** a protocol can only be hidden **per device** (Options tab, mode `disabled`). + There is no global switch. +- **UI (agreed):** Preferences → **Applications** tab (`_build_applications_tab`, + `ui/preferences_dialog.py`; rows from `_SCHEME_ROWS`, `ui/preset_editors.py`): + - one checkbox in front of each protocol row, checked by default; + - unchecking it greys out (disables) the rest of that row — its command stays visible and + saved, just not editable; + - the protocol list becomes a scrollable table, so the tab keeps working as more + protocols/applications are added. + No other UI change is needed. +- **Behaviour:** checked = protocol used, + unchecked = the protocol is hidden **everywhere**, i.e. nothing tied to it is shown: + auto-detected targets **and** per-device `override` / `additional` entries, in the + context menu "Open" entries and in double-click resolution. +- **Hide, don't delete:** a globally disabled protocol only stops being displayed/used. + Per-device entries for it are kept in the preferences untouched, and come back as they + were when the protocol is re-enabled. +- **Files (expected):** `ui/preset_editors.py` / `ui/preferences_dialog.py` (column + save), + `utils/ui_prefs.py` (persist e.g. `disabled_connect_schemes: list[str]`), + `utils/double_click_open.py` (skip globally disabled schemes in `resolve_connect_target` + and `resolve_all_connect_targets`, alongside the existing per-device `_disabled_schemes`), + `ui/main_window.py` (pass the setting through). +- **Acceptance:** unchecking a protocol removes every entry of that protocol (auto-detected + and per-device override/additional) from every device's "Open" menu and from double-click + resolution, without modifying or deleting any per-device setting; re-checking restores + everything as before. Default: all protocols checked (no behaviour change). + +*Ideas (not yet scheduled):* + +- Context menu "Open" submenu: keyboard navigation improvement +- Per-device command label in tile tooltip +- Notifications history: persist across sessions +- Preferences: expose cache TTL threshold (currently hardcoded 48 h) + +## Testing / QA 💡 + +- Add a repeatable manual smoke-test checklist per release (see `operations/MAINTENANCE.md`) +- Unit tests for `_normalize_command_list`, `resolve_connect_target` priority logic, and `resolve_all_connect_targets` label generation + +--- + +## Theme H — Translation review and updates ✅ + +**Context:** The application was ported from GTK to PySide6 (version 2.0). Several new +UI strings were added (system tray, scanning overlay, preferences, context menus, +autostart). All existing `.po` files needed to be audited for completeness and accuracy +against the current source strings. + +8 languages are currently shipped: `fr`, `es`, `de`, `it`, `nl`, `ja`, `zh_CN`, `zh_TW`. + +### H-1 Extract updated source strings ✅ + +- **Tool:** `tools/extract_new_strings.py` — AST-based extraction via `ast.parse()`, + walks all `Call(func=Name(id='_'))` nodes with `Constant` string arguments. +- **Files:** `ui/**/*.py`, `discovery/*.py`, `utils/*.py` → `locale/netneighbor.pot` +- **Result:** 74 new strings found not present in the old `.pot` (which referenced GTK paths). + +### H-2 Audit and update each `.po` file ✅ + +- **Tool:** `tools/update_translations.py` — appends new `msgid`/`msgstr` pairs to each `.po`. +- **Files:** `locale/*/LC_MESSAGES/netneighbor.po` — all 8 languages updated. +- **New strings include:** tray menu (`Show window`, `Hide window`, `Show/Hide sidebar`), + overlay (`Start Scanning…`), last-seen tooltips (`Last seen: {n} min/h/d ago`), + preferences sections (`Theme`, `Light`, `Dark`, `General`, `Session`, `Notifications`, + `Sidebar`, `Types`, `Locations`, `Icons size`, `Small`/`Medium`/`Large`/`Extra large`), + context menu (`Hide device`), commands prefs, field mapping, about dialog, etc. +- **All 74 strings fully translated** in all 8 languages. + +### H-3 Recompile `.mo` files and smoke-test ✅ + +- **Tool:** `babel` (`read_po` + `write_mo`) — compiled directly from Python. +- **Result:** All 8 `.mo` files recompiled and verified via `gettext.translation()`. +- **Spot-check passed:** `{} devices`, `Online`, `Offline`, `Start Scanning…` return + correct translated strings in every locale. + +--- + +## Theme I — Packaging 🔄 + +**Context:** The packaging scripts under `packaging/` were written for the GTK 1.x +version and reference `app.py` (which no longer exists) and GTK runtime dependencies. +All three platform targets need to be updated for PySide6 / `main.py`. + +Test targets: **Windows** and **Linux**. macOS packaging will be scripted but cannot +be validated without a macOS test machine. + +### I-0 Pre-release audit and header update ✅ + +- **Files:** all `*.py` source files (66 updated + 3 tools), `README.md`, + `USER_DOCUMENTATION.md`, `docs/PACKAGING.md`, `docs/UI_ARCHITECTURE.md` (archived), + `docs/ROADMAP_QT_2_0.md`, `packaging/README.md`, `docs/MAINTENANCE.md` +- **Change:** All Python file headers updated to version 2.0.0 / date 2026-05-19. + Remaining GTK references removed. `USER_DOCUMENTATION.md` completely rewritten + for the Qt 2.0 UI (menus, context menu, dialog tabs, preferences, tray). + `.gitkeep` files removed from non-empty directories. + +### I-1 Audit and update existing packaging scripts ✅ + +- **Files:** `packaging/linux/build_deb.sh`, `packaging/linux/build_tarball.sh`, + `packaging/linux/build_appimage.sh`, `packaging/windows/build.ps1`, + `packaging/windows/netneighbor.spec`, `packaging/POST_PORT.md` +- **Change:** + - Entry point updated to `main.py` in all scripts and the PyInstaller spec. + - GTK runtime dependencies removed from `.deb` control file; replaced with + `python3 (>= 3.10), python3-pip, samba-common-bin`. + - `postinst` now pip-installs `requirements-qt.txt` (PySide6, zeroconf, WSDiscovery). + - File copy lists updated: `ui/`, `app_qt.py`, `requirements-qt.txt` added; `ui/` (GTK) removed. + - PyInstaller `hiddenimports` updated: added `PySide6.QtNetwork`, `PySide6.QtSvg`. + - `.deb` description updated (GTK → Qt/PySide6). + +### I-1b netneighbor icon trimming in packages ✅ + +- **Files:** `packaging/linux/build_deb.sh`, `packaging/linux/build_tarball.sh`, + `packaging/linux/build_appimage.sh`, `packaging/windows/build.ps1` +- **Change:** The `assets/icons/netneighbor/` directory contains ~151 MB across + 10 resolution subdirectories. Source tree retains all resolutions for archival. + All four packaging scripts now trim the directory to the 5 sizes actually used by + the Qt UI (16, 32, 48, 96, 256), saving ~143 MB per package artifact. + The `bundled_freedesktop_png_side_sizes()` helper discovers available sizes dynamically + at runtime, so no code change is needed. + +### I-2 Linux packaging (`.deb` + `AppImage` + tarball) 📋 + +- **Files:** `packaging/linux/` +- **Change:** + - `.deb`: update `Depends` control field — remove GTK, keep `python3`, `python3-pip`, + `samba-common-bin` (NetBIOS); add post-install `pip install -r requirements-qt.txt` + or vendor PySide6 wheels inside the package. + - AppImage: bundle PySide6 + all Python dependencies inside the image so it runs + without any system Python packages. + - Tarball: add a `run.sh` that creates a venv and installs `requirements-qt.txt` on + first run. + - System tray: verify `libxcb-cursor0` and Qt platform plugins are present on + Ubuntu 22.04 / Debian 12 / Linux Mint 21. +- **Test platform:** Ubuntu 22.04 LTS, Linux Mint 21, Debian 12. +- **Acceptance:** `sudo dpkg -i netneighbor_2.0.0_amd64.deb && netneighbor` launches + the application with tray and discovery working. + +### I-3 Windows packaging (PyInstaller + Inno Setup installer) ✅ + +- **Files:** `packaging/windows/build.ps1`, `packaging/windows/build_installer.ps1`, + `packaging/windows/netneighbor.spec`, `packaging/windows/netneighbor.iss` +- **Change:** + - PyInstaller spec: entry point updated to `main.py`; `hiddenimports` corrected + (`wsdiscovery`/`wsdiscovery.discovery` replacing wrong `WSDiscovery`; added + `PySide6.QtNetwork`, `PySide6.QtSvg`). + - Inno Setup 6 installed via `winget install JRSoftware.InnoSetup --source winget`. + - Two critical Windows-only bugs discovered and fixed during testing (see below). +- **Test platform:** Windows 11 23H2. +- **Artifacts:** `dist/NetNeighbor-2.0.0-win64.zip` (203 MB), `dist/NetNeighbor-2.0.0-win64-setup.exe` (187 MB). + +#### ⚠️ CRITICAL bugs fixed — document for all future maintainers + +**Bug 1 — `multiprocessing.freeze_support()` missing** (`main.py`) + +Without this call, launching the frozen `.exe` spawns hundreds of windows: +PyInstaller uses the `spawn` multiprocessing method on Windows; any child process +re-executes the full `.exe`, which spawns another child, infinitely. +The app looked like malware — dozens of semi-transparent windows that could not be +closed, requiring Task Manager to kill the process tree. + +Fix: `multiprocessing.freeze_support()` must be the **first statement** inside +`if __name__ == "__main__":`, before any import. See `app/main.py` and `docs/operations/PACKAGING.md`. + +**Bug 2 — `subprocess` without `CREATE_NO_WINDOW`** (`utils/neighbor_mac.py`) + +`arp -a` was called without `creationflags=subprocess.CREATE_NO_WINDOW` for every +device on every UI refresh (~10–30 calls/cycle). Each call created a visible console +window, flooding the desktop with flashing terminal windows. + +Fix: added `CREATE_NO_WINDOW` flag + an 850 ms cache so `arp -a` runs at most once +per refresh cycle regardless of device count. See `docs/operations/PACKAGING.md` for the rule +that applies to all future `subprocess` calls on Windows code paths. + +### I-4 macOS packaging (PyInstaller `.app` + `.dmg`) 📋 + +- **Files:** `packaging/macos/build_app.sh`, `packaging/macos/*.spec` +- **Change:** + - PyInstaller spec: entry point `main.py`, include locale/assets/config trees, + PySide6 Qt plugins. + - `.plist` — `LSUIElement = NO` (show in Dock), `NSHighResolutionCapable = YES`. + - `dmg` creation via `create-dmg` or `hdiutil`. + - Note: system tray on macOS requires `NSStatusBar` via Qt which should work + out of the box with PySide6. Autostart uses the XDG `.desktop` path + (`session_autostart.py` already handles macOS via `_xdg_apply_autostart`). +- **Test platform:** ⚠️ Cannot be validated without a macOS machine. Script will be + written and reviewed but marked untested until a macOS build environment is available. +- **Acceptance (provisional):** Build script completes without errors on macOS 13+; + application launches from `.app` bundle. + +### I-5 CI / release pipeline 💡 + +- GitHub Actions workflow: build + package on push to `release/*` branch. +- Linux: Ubuntu runner → `.deb` + AppImage. +- Windows: `windows-latest` runner → PyInstaller `.exe` + Inno Setup `.exe`. +- macOS: `macos-latest` runner → `.app` + `.dmg` (untested by owner). +- Upload artifacts to GitHub Releases automatically. + +--- + +## Implementation order (Theme E) + +``` +E-1 (cache + last_seen) → E-2 (UI indicator) → E-3 (NetBIOS TTL) + → E-4 (WSD IP change) + → E-5 (TCP probe) +``` + +E-1 and E-2 are independent of the discovery layer and carry no risk of regressions. +E-3 and E-4 touch discovery internals and should be validated on a live LAN before +merging. E-5 is the most complex; it requires careful thread-pool sizing and +timeout tuning to avoid slowing startup on large networks. + +## Implementation order (Theme H) + +``` +H-1 (extract .pot) → H-2 (audit + translate, fr first) → H-3 (compile + test) +``` + +H-2 can run in parallel per language once the `.pot` is generated. +Recommend using `poedit` or `Lokalize` for the translation review step. + +## Implementation order (Theme I) + +``` +I-1 (audit scripts) → I-2 (Linux, tested) + → I-3 (Windows, tested) + → I-4 (macOS, untested — scripted only) + → I-5 (CI pipeline, after I-2 + I-3 validated) +``` + +I-1 is a prerequisite for all platform builds. I-2 and I-3 can proceed in parallel +once I-1 is done. I-4 is low priority until a macOS test machine is available. +I-5 should only be wired once I-2 and I-3 produce verified artifacts. + +--- + +## Global roadmap summary + +``` +Themes A–D ✅ Done +Theme E ✅ Device lifetime (E-1 → E-5) +Theme F 💡 Future — discovery enhancements +Theme G ✅ G-1 (reset app data) 💡 G-2 (global protocol filter) + ideas not yet scheduled +Theme H ✅ Translation review (H-1 → H-3) — 74 strings, 8 languages +Theme I 🔄 Packaging — I-0 ✅ I-1 ✅ I-1b ✅ I-3 ✅ I-2 📋 (Linux .deb) I-4/I-5 💡 +``` + +> **Windows maintainers:** read the ⚠️ CRITICAL section in I-3 and `docs/operations/PACKAGING.md` +> before any PyInstaller build. The `freeze_support()` and `CREATE_NO_WINDOW` bugs +> cause the app to appear as malware on first launch. diff --git a/docs/SSDP.md b/docs/SSDP.md deleted file mode 100644 index e8c91452..00000000 --- a/docs/SSDP.md +++ /dev/null @@ -1,97 +0,0 @@ -# SSDP in NetNeighbor - -## Protocol overview - -**SSDP** (Simple Service Discovery Protocol, part of UPnP) uses UDP multicast on `239.255.255.250:1900`. - -| Message | Direction | Meaning | -|---------|-----------|---------| -| M-SEARCH | Client → multicast | "Who is there?" — devices respond with HTTP 200 | -| NOTIFY alive | Device → multicast | Unsolicited announcement | -| NOTIFY byebye | Device → multicast | Device going offline | - -The announced **LOCATION** is an HTTP URL pointing to a device description XML file. -NetNeighbor fetches that document to get friendly name, device type, icons, presentation URL, etc. - -NetNeighbor **listens** and **periodically sends M-SEARCH** — it does not scan the LAN. - -## Code map - -| Area | File / symbol | Role | -|------|---------------|------| -| Provider | `discovery/ssdp.py` | `SSDPDiscovery` — socket, listen thread, refresh thread, GC, XML fetch | -| Contract | `discovery/base.py` | `BaseDiscovery._emit("device", payload)` → normalized dict to manager | -| Orchestration | `discovery/manager.py` | `add_or_update_device` — overrides, SSDP merge, notify listeners | -| Model | `model/device.py` | `Device` — key prefers `UDN`, then `USN` base, then MAC, then `source:ip:port` | -| Rules | `config/ssdp_rules.json` | Naming / information / type rules | -| UI payload | `utils/details_payload.py` | `build_ssdp_payload` — rows for the details dialog | - -## From packet to Device - -1. Parse headers (`LOCATION`, `ST`/`NT`, `USN`, `SERVER`, `CACHE-CONTROL`, …) -2. Derive `ip`/`port` from `LOCATION` URL (default 80) -3. Fetch and parse XML from `LOCATION` (cached briefly) -4. Infer `name` and `type` from headers + XML; apply `ssdp_rules.json` -5. Emit payload with `metadata` holding headers, `xml_fields`, raw XML - -## Online / offline - -- **Online**: every valid response or NOTIFY alive refreshes the seen timestamp -- **NOTIFY byebye**: immediate `online: false` payload -- **Timeout**: GC emits `online: false` when expiry passes. - Expiry ≈ `2 × CACHE-CONTROL max-age`, clamped to a maximum; default minimum when not specified. - -## Merge (same physical device) - -`DiscoveryManager` may merge SSDP updates sharing the same `ip:port` (MAC-assisted) and merges XML metadata so the UI shows one logical row per stable `Device.key`. - ---- - -## Rules file (`config/ssdp_rules.json`) - -Lets you **tune naming, information text, and type classification** without Python changes. -User overlay: `~/.config/netneighbor/ssdp_rules.json` — merged with bundled defaults. -See [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md). - -### `name_rules` - -| Field | Type | Meaning | -|-------|------|---------| -| `fallback_fields` | list | Ordered `xml_fields` keys to use as name when earlier keys are empty | -| `prefer_display_name_when_no_friendly_name` | bool | Use `displayName` if `friendlyName` is missing | - -### `information_rules` - -| Field | Type | Meaning | -|-------|------|---------| -| `concat_fields` | list | XML field names to join for the "Information" detail row | -| `separator` | string | Placed between non-empty values | - -### `type_rules` - -Evaluated in order; first match wins. - -| Field | Type | Meaning | -|-------|------|---------| -| `contains_any` | list | Lowercase substrings searched in SSDP headers + selected XML fields | -| `type` | string | Internal type id (e.g. `router`, `nas`, `smarttv`) | - -### How to extend - -1. Put specific `contains_any` groups **before** generic ones. -2. Use tokens that appear in your network's actual SSDP/XML (check SSDP details dialog). -3. Keep `type` values consistent with `data/device_types.json`. -4. Validate: `python -m json.tool config/ssdp_rules.json` -5. Restart the app. - -## Debugging - -- Enable `ssdp` in `~/.config/netneighbor/logging.json` -- SSDP details dialog: inspect LOCATION, USN, XML presence -- Watch for "XML fetched" vs fetch failures (timeout, parse error) - -## See also - -- [`MDNS.md`](MDNS.md) — parallel mDNS pipeline -- [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md) — user overlay rules -- [`BACKEND_ARCHITECTURE.md`](BACKEND_ARCHITECTURE.md) — discovery manager overview diff --git a/docs/TODO.md b/docs/TODO.md deleted file mode 100644 index 1933b8e6..00000000 --- a/docs/TODO.md +++ /dev/null @@ -1,28 +0,0 @@ -# TODO - -Known items and ideas for future work. No priority order. - -## Discovery - -- SFTP service detection via mDNS (`_sftp-ssh._tcp`) -- Optional WSD multicast interface selection (multi-homed hosts) -- NetBIOS: show a hint in the UI when `nmblookup` is not installed -- **Performance** — cache pre-population at startup (emit cached SSDP devices before - live discovery completes, so the window is populated in < 100 ms) -- **Performance** — NetBIOS directed probes: run in parallel with `ThreadPoolExecutor` - instead of sequential `nmblookup -A` calls (see `docs/MAINTENANCE.md`) -- **Performance** — SSDP XML fetches: per-host lock instead of single global lock - (allows concurrent descriptor fetches at startup) -- **Performance** — wsdd_client: remove hardcoded 0.35 s sleep between probe and list - -## UI - -- Context menu "Open" submenu: keyboard navigation improvement -- Per-device command label shown in tooltip when hovering a device tile -- Notifications history: persist across sessions (currently session-only) - -## Testing - -- Add a repeatable manual smoke-test checklist per release (see `MAINTENANCE.md`) -- Unit tests for `_normalize_command_list`, `resolve_connect_target` priority logic, - and `resolve_all_connect_targets` label generation diff --git a/docs/UI_ARCHITECTURE.md b/docs/UI_ARCHITECTURE.md deleted file mode 100644 index 16c1bcd3..00000000 --- a/docs/UI_ARCHITECTURE.md +++ /dev/null @@ -1,96 +0,0 @@ -# UI architecture (GTK 3) - -## Goals and choices - -- **Native Linux desktop**: GTK 3 + PyGObject, no embedded browser for the main list. -- **Responsive discovery**: protocol threads must not block the GTK main loop; updates are - marshaled with `GLib.idle_add` from `MainWindow._on_devices_updated`. -- **Two views**: list (`Gtk.TreeView`) and icon grid (`Gtk.FlowBox` sections) — user preference persisted. -- **Fullscreen**: **F11** toggles `Gtk.Window` fullscreen (accel group on the main window; works while child widgets have focus). -- **Tray-capable session**: optional **close-to-tray**, **start minimized to tray**, and **XDG autostart** — see `MainWindow` + `TrayIndicator` + `utils/session_autostart.py`. -- **Discoverability**: sidebar grouped by type or location (depending on arrange mode), context menus for monitor / type / rename / location / icon details. - -Dialog chrome: **`prepare_gtk_dialog`** in `utils/gtk_dialog.py` (disable header-bar dialogs where needed). - -## Module layout - -| Module | Responsibility | -|--------|----------------| -| `app.py` | `Gtk.Application`, single-instance lock, activation socket, `DiscoveryManager`, `MainWindow` lifecycle, optional demo mode. Parses **`--start-minimized-to-tray`** (and demo flags) via `parse_known_args` before `run()`; forwards remaining argv for GTK plumbing. | -| `ui/main_window.py` | Menu bar, paned layout (sidebar + content), discovery listener wiring, notifications mode, UI prefs load/save, notification history (session), sidebar counts. When **close-to-tray** works, installs a **Gtk.HeaderBar** (**Maximize + Close**; minimize via tray menu). **F11** fullscreen accel. Tray creation on idle; skip initial present when starting minimized-to-tray; **View → Quit** calls `application.quit()`. | -| `ui/tray_indicator.py` | Ayatana **AppIndicator** / **AppIndicator3**, else **Gtk.StatusIcon**; tray menu **Open** / **Minimize to tray** / **Quit**; resolves icon names (bundled hicolor **SVG** under `assets/icons/`). | -| `utils/session_autostart.py` | Writes or removes `~/.config/autostart/io.esp3d.netneighbor.desktop` from the **Start when logging in** preference. | -| `ui/device_list.py` | `DeviceList`: bundles devices by `(ip, port)` for display (mDNS + SSDP on same host), list store, icon tiles, context menus, details entry points. **Open** / double-click resolves **`resolve_connect_target`** (`utils/double_click_open.py`), then **`launch_connect_for_uri`** (`utils/connect_launcher.py`) using **`connect_command_templates`** from **Tools → External applications…**. When ≥ 2 targets exist, right-click shows **Open ▶** submenu (via **`resolve_all_connect_targets`**) with labelled entries. **Run custom command** uses **`custom_command_template`** (`utils/custom_command.py`). | -| `ui/device_details.py` | Dialog: **Overview** summary + protocol fields; **Options** tab for per-device commands (dynamic list — scheme, mode, label, IP, port); optional raw XML, SSDP services table, mDNS service expanders **Services** tab, icon tab. Multiline values are not rendered as `Gtk.LinkButton`. | -| `utils/details_payload.py` | Pure builders for SSDP / mDNS / WSD-family detail rows; merges duplicate **Last seen** to the latest; WSD-only supplementary rows are minimal (no Discovery / XAddrs / NetBIOS registration lines). | -| `utils/ui_prefs.py` | JSON read/write under `~/.config/netneighbor/ui_prefs.json`. | - -## Data flow (UI) - -``` -DiscoveryManager._notify() - → listener(devices) registered in MainWindow - → GLib.idle_add(_update_ui_devices) - → _notify_device_transitions (desktop notifications, optional) - → _rebuild_sidebar - → DeviceList.set_devices(devices) -``` - -`DeviceList.set_devices` rebuilds filtered bundles and both views. - -## Bundling and display identity - -`_DeviceBundle` groups multiple `Device` rows that share the same `(ip, port)` so one tile -represents one host/device entry. The **primary** row follows **`merge.information_precedence`** in `discovery.json` across live protocol rows for that endpoint (not “mDNS always wins”). - -## Threading and notifications - -- Desktop notifications are triggered from transition logic on the GTK idle callback path; - sending is done in a **background thread** so a stalled notification daemon cannot freeze the UI. -- **Notification history** (menu → Tools → Notifications history) stores session-only rows (timestamp, device name, status). - -## Preferences (persisted) - -Stored in `ui_prefs.json`, including view mode, sidebar position, notification mode, category/location selection, -type overrides, monitored flags, last-seen overrides, icon appearance overrides (system/provided/custom + custom icon choice), **monitored device -snapshots** used to show greyed monitored entries after restart before rediscovery, and tray/session flags: -**`close_to_tray`**, **`start_minimized_to_tray`**, **`start_at_login`**. -See [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md) for a short key reference; [`MAINTENANCE.md`](MAINTENANCE.md) for paths and tray dependencies. - -## Styling - -`DeviceList` installs a small CSS provider for offline monitored tint (`.offline-device-monitored`). - -## Internationalization - -GNU gettext; catalogs under `locale/`. UI strings use `_()` where wired. -See [`I18N.md`](I18N.md) for add/update workflow. - -## Per-device command model - -The **Options** tab in `device_details.py` manages a list of `dict` entries: - -```python -[ - {"scheme": "http", "ip": "", "port": 0, "mode": "override", "label": ""}, - {"scheme": "ssh", "ip": "192.168.1.10", "port": 22, "mode": "additional", "label": "Admin"}, -] -``` - -- Stored in `ui_prefs.json` under `device_commands` (keyed by device identity). -- Validated and normalized by `_normalize_command_list()` in `discovery/manager.py`. -- Applied to each `Device` on every pipeline run via `_apply_device_commands`. -- Read by `resolve_connect_target` / `resolve_all_connect_targets` in `utils/double_click_open.py`. - -## Title bar and tray - -When **close-to-tray** is active the window uses a `Gtk.HeaderBar` set via `set_titlebar()`. -This call must happen **before** `show_all()` — calling it afterwards loses WM decorations on -Muffin/Cinnamon. `_ensure_tray()` and `_apply_tray_window_decorations()` are therefore invoked -in `__init__` before `show_all()`. - -## See also - -- [`BACKEND_ARCHITECTURE.md`](BACKEND_ARCHITECTURE.md) — DiscoveryManager, override system, device commands. -- [`MAINTENANCE.md`](MAINTENANCE.md) — paths, tray, packaging-related runtime deps, troubleshooting. -- [`PACKAGING.md`](PACKAGING.md) — `.deb` layout and **Recommends** (AppIndicator, `nmblookup`). diff --git a/docs/USER_DOCUMENTATION.md b/docs/USER_DOCUMENTATION.md new file mode 100644 index 00000000..c8680827 --- /dev/null +++ b/docs/USER_DOCUMENTATION.md @@ -0,0 +1,329 @@ +# NetNeighbor — User Documentation + +## What is NetNeighbor? + +NetNeighbor discovers and monitors devices on your local network. +It listens for device announcements (SSDP, mDNS/Bonjour, WS-Discovery, NetBIOS) and +displays them with icons or in a list — no active port scan required. + +Previously-seen devices appear instantly at startup from the local cache; live discovery +updates them within a few seconds. + +One NetNeighbor instance is allowed at a time; a second launch raises the existing window. + +--- + +## Main window + +![Main window — icon grid view](images/main-grid.png) + +- **List view** and **icon grid** — toggle from **View → Display** +- **Sidebar**: categories grouped by device type or location (**View → Arrange**) +- **View → Reload discovery**: force an immediate refresh of all discovery protocols + +### Menu bar + +#### View menu + +![View menu](images/menu-view.png) + +| Item | Description | +|------|-------------| +| **Reload discovery** | Force refresh of all discovery protocols | +| **Sidebar** | Show/hide the left sidebar | +| **Display → Icons / List** | Switch between icon grid and list view | +| **Arrange → Unsorted / by Type / by Location** | Group devices in the sidebar and grid | +| **Icons size → Small / Medium / Large / Extra large** | Icon grid tile size (icon view only) | +| **Preferences…** (`Ctrl+,`) | Open the preferences dialog | +| **Quit** (`Ctrl+Q`) | Quit the application | + +#### Tools menu + +![Tools menu](images/menu-tools.png) + +| Item | Description | +|------|-------------| +| **Notifications history** | View past device online/offline notifications | +| **Hidden devices** | Manage devices that have been hidden from the main view | + +#### Help menu + +| Item | Description | +|------|-------------| +| **About NetNeighbor** | Version information and credits | + +### Icon view + +Two arrangement modes controlled by **View → Arrange**: + +- **Unsorted**: flat grid of all device tiles +- **by Type / by Location**: devices are grouped into collapsible sections (click the section header to collapse/expand) + +### List view + +![Main window — list view](images/main-list.png) + +Table with columns: **Name · IP · Type · Location · Online**. Click a column header to sort. + +--- + +## Opening devices + +**Double-click** or right-click → **Open** launches the best connection for that device. + +Priority order: `HTTP → HTTPS → SMB → SSH → FTP → SFTP → Telnet` + +For each scheme the resolution follows: +1. **Override** command (from the device's Options tab) — replaces the auto-detected default +2. **Detected** default (URL advertised by discovery) +3. **Additional** command (from the device's Options tab) — adds to the submenu without replacing +4. **Custom command** (from **View → Preferences… → Applications**) +5. Nothing — Open is disabled + +When a device has **two or more** connection targets, right-click shows **Open ▶** with a submenu +listing all of them with labels (`HTTP`, `SSH (Admin)`, `HTTP (override)`, etc.). + +--- + +## Right-click menu + +![Right-click context menu](images/context-menu.png) + +| Action | Description | +|--------|-------------| +| **Open** / **Open ▶** | Launch connection (single target or submenu) | +| **Run custom command** | Execute the custom command set in **Preferences → Applications** (shown only if a template is configured) | +| **Details** | Open the details dialog (Overview, Services, Device data tabs) | +| **Options** | Open the details dialog directly on the Options tab (icon, connection commands) | +| **Monitor** / **Unfollow** | Keep the device visible when offline (greyed tile) / stop monitoring | +| **Hide device** | Remove this device from the main view (recoverable via **Tools → Hidden devices**) | +| **Rename** | Set a custom display name for this device | +| **Clear device** | Completely purge this device from the cache, icons, and all preferences. The device will disappear immediately; if it is still active on the network it will reappear on the next discovery scan with fresh, complete data. Useful to clean up incomplete or duplicate entries caused by interrupted scans. | +| **Location ▶** | Assign a location label (Auto or preset list) | +| **Device type ▶** | Override the auto-detected device type (Auto or preset list) | + +--- + +## Device details dialog + +### Overview tab + +![Device details — Overview tab](images/device-details.png) + +Summary of discovered fields: IP, name, type, location, last seen, services. + +### Services tab + +mDNS service records with TXT fields. Right-click a TXT row to use a value as: +- **Use as Friendly name** +- **Use as Location** +- **Use as Information** + +Also contains the **Field mapping rules** table (rules that map TXT records to device fields). + +### Device data tab + +Raw SSDP/UPnP XML received from the device. A **Copy to clipboard** button copies the full content. + +### Options tab + +![Device details — Options tab](images/device-options.png) + +**Icon source** — choose between: +- **System**: use the bundled type icon from the active icon pack +- **From device**: use the icon fetched from the device's SSDP/mDNS URL (shown only when available) +- **Custom**: open the icon picker to choose from the active pack or your own PNGs + +![Icon picker](images/icon-picker.png) + +The icon picker displays all icons from the active pack (with built-in icons as fallback for any missing ones). The selected id is stored pack-independently — switching packs later applies the new pack's version of that icon automatically. + +**Connection commands** — per-device overrides and additional commands: + +| Column | Description | +|--------|-------------| +| **Scheme** | `http`, `https`, `smb`, `ftp`, `ssh`, `sftp`, `telnet` | +| **Command** | Command template (leave empty for auto-detected URL) | +| **Port** | Leave empty or `0` to use the scheme default port | +| **Mode** | **Override** — replaces the auto-detected default. **Additional** — adds an extra entry in the Open submenu | +| **Label** | Display name shown in the submenu (e.g. `Admin`). When empty, auto-generated | + +Click **Add** to add a row, **Delete** to remove the selected row, **Apply** to save. + +Placeholders for command templates: `{url} {ip} {port} {name} {type} {category}` + +--- + +## Preferences + +Open with **View → Preferences…** (`Ctrl+,`). + +### General tab + +![Preferences — General tab](images/preferences-general.png) + +**Theme** + +| Option | Description | +|--------|-------------| +| **Light** | Force light colour scheme | +| **Auto** | Follow the OS/desktop setting | +| **Dark** | Force dark colour scheme | + +**Icon pack** + +| Setting | Description | +|---------|-------------| +| Pack dropdown | Select the active icon pack for device-type icons. The scrollable strip below previews all icons in the selected pack. | +| **Open folder…** | Opens `~/.config/netneighbor_icon_packs/` in the file manager. The list refreshes automatically when you return to the dialog. | + +User-installed packs go in `~/.config/netneighbor_icon_packs/{pack_id}/` (one subfolder per pack). +Each folder may contain an optional `iconpack.json` with `name`, `owner`, `version`, `license`, `repository` fields. +Icon files are placed in `{N}x{N}/` or flat `{N}/` subdirectories (both naming conventions are supported). +The built-in *NetNeighbor* pack lives under `assets/icons/netneighbor/` and is always available as a fallback. + +**Session** + +| Setting | Description | +|---------|-------------| +| **Close to system tray / panel instead of exiting** | Hide the window instead of quitting when closed (requires tray icon) | +| **Start minimized to tray** | Start hidden to the panel; open from the tray icon | +| **Start NetNeighbor when logging in** | Add/remove a session autostart entry (registry Run key on Windows, LaunchAgent on macOS, `~/.config/autostart/` on Linux) | + +**Maintenance** + +| Button | Description | +|--------|-------------| +| **Reset all application data…** | Permanently delete all settings, cached icons, discovery data and logs (confirmation required; restart recommended afterwards) | + +### Notifications tab + +| Option | Description | +|--------|-------------| +| **Notifications off** | No desktop notifications | +| **Monitored devices only** | Notify only for devices set to Monitor | +| **All devices** | Notify for every device coming online or going offline | + +### Locations tab + +![Location presets](images/location-presets.png) + +Manage the list of location labels available in the right-click **Location** menu. + +| Button | Action | +|--------|--------| +| **Add** | Create a new location label | +| **Rename** | Edit the selected label | +| **Remove** | Delete the selected label | +| **Clear all** | Remove all location presets | + +Checkbox: **Automatically add locations discovered on the network to this list** + +Labels are stored in `~/.config/netneighbor/ui_prefs.json`. + +### Types tab + +![Type presets](images/type-presets.png) + +Manage the list of device types available in the right-click **Device type** menu. +Each entry has a **Label** (display name) and a **Type ID** (internal slug used for icon lookup). + +| Button | Action | +|--------|--------| +| **Add** | Create a new type entry | +| **Edit** | Edit the selected entry | +| **Remove** | Delete the selected entry | +| **Restore defaults** | Reset to the built-in device types | + +### Applications tab + +![External applications](images/external-applications.png) + +Override the command used to open devices **per scheme** (HTTP, HTTPS, SMB, FTP, SSH, Telnet, SFTP). +Leave a field empty to use the system default (`xdg-open` for HTTP/HTTPS, file manager for SMB/FTP/SFTP, terminal for SSH/Telnet). + +On **Windows**, the defaults use `local*://` pseudo-schemes — `localhttp://{ip}`, `localhttps://{ip}`, `localftp://{ip}`, `localsftp://{ip}` and `localsmb://{ip}`. These are opened directly through Windows instead of a `cmd.exe` command, so **no ephemeral console window flashes** when you open a device. They still honour the `{ip}`/`{port}` placeholders, so you can override the port, e.g. `localhttp://{ip}:{port}` or `localhttps://{ip}:8443`. + +- `localhttp://` / `localhttps://` open the default browser (`ShellExecute`). +- `localsmb://` uses the native Windows credential dialog (WNetAddConnection2) before opening the share in Explorer. +- `localftp://` / `localsftp://` open in Windows **Explorer** (browsers no longer support FTP). Explorer's FTP client connects before showing the window, so it can take a few seconds — for faster transfers, replace the template with a dedicated client, e.g. `"C:\Program Files (x86)\WinSCP\WinSCP.exe" ftp://{ip}` or FileZilla. + +Replace any of them with a custom command if you prefer a different client. + +**Reset** restores the built-in default for that scheme. + +**Custom** at the bottom sets the command run by **right-click → Run custom command** — +useful for port scans, terminal launchers, etc. + +Placeholders: `{url}`, `{ip}`, `{port}`, `{name}`, `{type}`, `{category}` + +--- + +## System tray + +![System tray menu](images/tray-menu.png) + +When the tray icon is active, the window can be shown/hidden from the tray. + +| Tray action | Description | +|-------------|-------------| +| **Left-click** on icon | Toggle window visibility | +| **Show window** | Bring the main window to the foreground | +| **Hide window** | Send the main window to the tray | +| **Quit** | Quit the application | + +--- + +## Autodetection is heuristic + +Device names and types are inferred from SSDP, mDNS, and cached data. They are best-effort and +may not match every device or firmware revision. + +Corrections: + +1. **Per-device overrides**: right-click a device tile → **Rename**, **Device type**, **Location**, or **Options** (icon + connection commands). +2. **User rule overlays**: JSON files in `~/.config/netneighbor/` extend mDNS and SSDP matching + (see [`docs/contributing/COMMUNITY_OVERRIDES.md`](contributing/COMMUNITY_OVERRIDES.md)). + +--- + +## Troubleshooting + +**Device does not appear:** +- Confirm the device is on the same local network segment +- Allow UDP 1900 (SSDP multicast) through local firewall +- Wait a few seconds after startup; use **View → Reload discovery** + +**Device appears/disappears:** +- SSDP `byebye` causes immediate offline; timeout-based offline if announcements stop +- A device that is unplugged or powered off is detected within ~3 minutes by a background reachability check (ICMP ping), even if it sent no goodbye message +- Once offline, a **monitored** device stays visible greyed out; a non-monitored device is removed from the list. A device that returns (e.g. wakes from sleep) reappears automatically on the next discovery scan or after **View → Reload discovery** +- After **Reload discovery**, devices that no longer respond are dropped within ~15 seconds instead of waiting for the full timeout + +**Device is listed but its icon does not load, Open fails, or it keeps going offline and coming back:** +- NetNeighbor sees the device through multicast announcements (mDNS/SSDP), but icon download, + Open and reachability checks need a direct connection to the device +- A VPN or firewall running **on the device itself** (e.g. a VPN app on a smart TV) can block + these local connections while announcements keep arriving. The device then appears, fails + its reachability check, disappears, and reappears on its next announcement +- Such a device may even keep announcing itself while in standby, whereas the same model + without a VPN goes silent when switched off +- Disconnect the VPN, or allow local network access in its settings, then use + **View → Reload discovery** +- To check, open the icon URL shown in Details in a browser on your computer: if it does not + load there either, the block is on the device or network side + +**Open is disabled:** +- No connection target was found; check the device's IP/services in Details +- Add a command manually in the device's Options tab + +**NetBIOS names not showing:** +- Install `samba-common-bin` (`sudo apt install samba-common-bin`) + +**No tray icon:** +- On Linux, tray support requires a system tray (most desktop environments include one) + +**Icons wrong after a device firmware update:** +- Open **View → Preferences… → General → Reset all application data…** to clear the icon cache, + or delete `~/.cache/netneighbor/remote_icon_index.json` and restart + diff --git a/docs/archive/CHANGELOG.md b/docs/archive/CHANGELOG.md deleted file mode 100644 index e441e566..00000000 --- a/docs/archive/CHANGELOG.md +++ /dev/null @@ -1,27 +0,0 @@ -# Changelog - -## 0.8.0 — 2026-05 - -### Discovery & identity - -- **Kernel neighbor cache**: resolve **MAC** from `/proc/net/arp` and `ip neigh` when metadata omits it (`utils/neighbor_mac.py`). -- **IPv4 surfacing**: when discovery only exposes **IPv6** (common for WSD + link-local) but ARP/neigh already has a **LAN IPv4** for the same MAC, show **IPv4 + IPv6** in list, overview, and protocol details (`format_device_ip_for_details` + `lookup_ipv4_for_mac`). -- **NetBIOS after WSD (IPv6-only rows)**: if the hostname is synthetic (`WSD-…`, `ws-…`) on **IPv6**, derive LAN IPv4 from neighbor/MAC and queue **`nmblookup -A `** so the NetBIOS name appears sooner (`discovery/manager.py`). -- **Fewer duplicate tiles**: bundle merge adds a **`mac:`** merge key using **neighbor-resolved MAC** so IPv4 vs IPv6 rows for the same host collapse earlier (`ui/device_list.py`). - -### UI / tray / session - -- **Provisional device affordance**: weak WSD-style names on **IPv6** and/or **remote icon fetch pending** — soft pulse (list + icons), italic/dim copy, richer tooltips (`ui/device_list.py`). -- **`Gtk.Dialog` decorations**: **`prepare_gtk_dialog`** disables header-bar dialogs that lost WM titlebars on some setups (`utils/gtk_dialog.py`, wired across main/details/list dialogs). -- **First launch**: after the session-startup onboarding dialog, hide the **main window to the tray** when available (recommended post-install UX). -- **CLI**: **`--start-minimized-to-tray`** hides to tray on startup (wired from `MainWindow` + skips initial `Gtk.Application` present/focus steal). **Login autostart** (`utils/session_autostart.py`) appends this flag only in **`~/.config/autostart/`** — the **applications menu `.desktop`** in packaging stays plain `Exec=netneighbor`. -- **Tray menu**: **`Minimize to tray`** row ( **`hide()`** ), sensitive only while the main window is **visible**. -- **`app.py`**: forwards unknown argv remnants to **`Gtk.Application.run`** after parsing CLI flags. - -### Documentation - -- This file; **`README.md`**, **`docs/MAINTENANCE.md`**, **`docs/UI_ARCHITECTURE.md`**, **`USER_DOCUMENTATION.md`**, and **`docs/ROADMAP.md`** updated for 0.8.0. - ---- - -Older releases did not maintain a changelog in-tree; **`git log`** remains the historic source prior to **0.8.0**. diff --git a/docs/archive/NetNeighbor_Brief_v1.3.md b/docs/archive/NetNeighbor_Brief_v1.3.md deleted file mode 100644 index ae9c9f8d..00000000 --- a/docs/archive/NetNeighbor_Brief_v1.3.md +++ /dev/null @@ -1,470 +0,0 @@ -# NetNeighbor — Project Brief v1.3 - -> **Note:** For an architecture and roadmap aligned with the current repository, use **`NetNeighbor_Brief_v1.4.md`**. This file is retained as a historical reference. - -## Description -NetNeighbor is a Linux desktop application that replicates and extends the Windows Network -Neighborhood experience, using SSDP and mDNS protocols to discover and display local network -devices in a user-friendly GUI. - -## Goals -- Provide a simple, native-feeling GUI for local network device discovery on Linux -- Support SSDP (UPnP) and mDNS discovery protocols -- Target ESP32/ESP8266 devices (ESP3D ecosystem) as primary use case, while remaining generic -- Extensible architecture — new protocols can be added without rewriting existing code - -## Target Platform -- Linux (primary: Linux Mint / Ubuntu / Debian) -- Python 3 + GTK3 + PyGObject -- Distributable as AppImage / .deb - ---- - -## Scope - -### In scope (MVP) -- SSDP (UPnP multicast) discovery -- mDNS (zeroconf/Avahi) discovery -- PC detection via WSD/SSDP (`urn:schemas-microsoft-com:device:Computer:1`) -- PC detection via `_smb._tcp` mDNS if Avahi active - -### Out of scope (future protocols) -- NetBIOS/LLMNR discovery -- Active network scan (no ping sweep, no ARP scan) -- Linux PC detection without Avahi/Samba -- Proprietary protocols (Sonos, Philips Hue, etc.) -- SMB share authentication / access -- IPv6 support - -> **Rule:** NetNeighbor listens and displays what announces itself. -> It does not actively search for what is hidden. -> New protocols will be added in future versions via the discovery API. - ---- - -## Architecture - -``` -netneighbor/ -├── main.py # Entry point -├── app.py # GTK Application class -│ -├── discovery/ -│ ├── __init__.py -│ ├── base.py # BaseDiscovery abstract class (protocol API) -│ ├── manager.py # Discovery orchestrator -│ ├── ssdp.py # SSDP multicast discovery -│ └── mdns.py # mDNS discovery via zeroconf -│ -├── model/ -│ ├── __init__.py -│ └── device.py # Device data class -│ -├── ui/ -│ ├── __init__.py -│ ├── main_window.py # Main GTK window -│ ├── device_list.py # GTK TreeView with category sections -│ ├── device_details.py # Details dialog (XML / TXT records) -│ └── icons.py # Icon resolver -│ -├── assets/ -│ └── icons/ # Self-contained icon set (PNG + SVG) -│ ├── esp32.png -│ ├── printer.png -│ ├── nas.png -│ ├── router.png -│ ├── mediaserver.png -│ ├── computer.png -│ ├── http.png -│ └── unknown.png -│ -├── utils/ -│ ├── __init__.py -│ └── browser.py # Open URL in default browser -│ -├── data/ -│ └── device_types.json # Static mapping: UPnP deviceType / mDNS service → icon + label + category -│ -├── config/ -│ └── (~/.config/netneighbor/) -│ └── devices.json # Lightweight local device history -│ -├── docs/ -│ └── CONTRIBUTING_ICONS.md # Icon specs + how to register in device_types.json -│ -├── requirements.txt -├── README.md -└── LICENSE -``` - ---- - -## Discovery API - -```python -# discovery/base.py -class BaseDiscovery: - """Base class for all discovery protocols. - New protocols must inherit this class and implement all methods. - Register in DiscoveryManager to activate.""" - - def start(self) -> None: - """Start discovery listener""" - raise NotImplementedError - - def stop(self) -> None: - """Stop discovery listener""" - raise NotImplementedError - - def refresh(self) -> None: - """Trigger active discovery query""" - raise NotImplementedError - - def set_callback(self, callback: callable) -> None: - """Register callback for device found/updated/lost events""" - raise NotImplementedError -``` - -```python -# discovery/manager.py -class DiscoveryManager: - def __init__(self): - self._protocols: list[BaseDiscovery] = [ - SSDPDiscovery(), - mDNSDiscovery(), - # Future: WSDDiscovery(), NetBIOSDiscovery()... - ] -``` - ---- - -## Data Flow - -``` -DiscoveryManager - ├── SSDPDiscovery ──→ Device objects - └── mDNSDiscovery ──→ Device objects - │ - ▼ - DeviceStore (in-memory list) - │ - ├──→ devices.json (~/.config/netneighbor/) - │ - ▼ - GTK TreeView (categories) ──→ MainWindow -``` - ---- - -## Device Model - -```python -Device: - name: str # Human-readable name - ip: str # IP address - port: int # Primary service port - type: str # Device type id (ex: "esp32", "printer") - category: str # UI category (ex: "ESP3D Devices") - source: str # Discovery protocol: "ssdp" | "mdns" - url: str # URL to open in browser - metadata: dict # raw XML (SSDP) or TXT records (mDNS) - last_seen: datetime - online: bool # False = greyed out in UI - icon: str | None # Icon filename, resolved by icons.py -``` - ---- - -## Device Categories (UI) - -``` -▼ Computers (WSD/SSDP, _smb._tcp, _afpovertcp._tcp) -▼ ESP3D Devices (_esp3d._tcp, _arduino._tcp) -▼ Routers & Gateways (UPnP WANDevice) -▼ Media Servers (UPnP MediaServer, _daap._tcp) -▼ Printers (UPnP Printer, _printer._tcp, _ipp._tcp) -▼ NAS / File Servers (Synology, QNAP, _nfs._tcp) -▼ Unknown Devices (everything else) -``` - ---- - -## Device Types Database (`data/device_types.json`) - -```json -{ - "ssdp": { - "urn:schemas-upnp-org:device:MediaServer:1": { - "label": "Media Server", - "category": "Media Servers", - "icon": "mediaserver.png", - "default_port": 80, - "info_url": "http://{ip}:{port}/" - }, - "urn:schemas-upnp-org:device:WANDevice:1": { - "label": "Router / Gateway", - "category": "Routers & Gateways", - "icon": "router.png", - "default_port": 80, - "info_url": "http://{ip}:{port}/" - }, - "urn:schemas-upnp-org:device:Printer:1": { - "label": "Printer", - "category": "Printers", - "icon": "printer.png", - "default_port": 80, - "info_url": null - }, - "urn:schemas-microsoft-com:device:Computer:1": { - "label": "Computer", - "category": "Computers", - "icon": "computer.png", - "default_port": 80, - "info_url": null - } - }, - "mdns": { - "_esp3d._tcp": { - "label": "ESP3D Device", - "category": "ESP3D Devices", - "icon": "esp32.png", - "default_port": 80, - "info_url": "http://{ip}:{port}/" - }, - "_smb._tcp": { - "label": "Computer", - "category": "Computers", - "icon": "computer.png", - "default_port": 445, - "info_url": null - }, - "_printer._tcp": { - "label": "Printer", - "category": "Printers", - "icon": "printer.png", - "default_port": 631, - "info_url": null - }, - "_ipp._tcp": { - "label": "Printer (IPP)", - "category": "Printers", - "icon": "printer.png", - "default_port": 631, - "info_url": null - }, - "_afpovertcp._tcp": { - "label": "Mac (File Sharing)", - "category": "Computers", - "icon": "computer.png", - "default_port": 548, - "info_url": null - }, - "_daap._tcp": { - "label": "Media Server (DAAP)", - "category": "Media Servers", - "icon": "mediaserver.png", - "default_port": 3689, - "info_url": null - }, - "_nfs._tcp": { - "label": "NAS / File Server", - "category": "NAS / File Servers", - "icon": "nas.png", - "default_port": 2049, - "info_url": null - }, - "_http._tcp": { - "label": "HTTP Device", - "category": "Unknown Devices", - "icon": "http.png", - "default_port": 80, - "info_url": "http://{ip}:{port}/" - } - }, - "fallback": { - "label": "Unknown Device", - "category": "Unknown Devices", - "icon": "unknown.png", - "default_port": 80, - "info_url": null - } -} -``` - ---- - -## Icon Resolution Priority - -``` -1. Icon provided in SSDP XML -2. Icon from assets/icons/ via device_types.json -3. assets/icons/unknown.png (final fallback) -``` - -## Icon Specs - -- **Format**: PNG (required) + SVG (recommended) -- **Size**: 64x64px minimum, 256x256px recommended -- **Background**: transparent -- **Naming**: `{type_id}.png` (ex: `esp32.png`) -- **Self-contained**: no system icon theme dependency -- See `docs/CONTRIBUTING_ICONS.md` for contribution guidelines - ---- - -## Features - -### MVP -- SSDP multicast discovery -- mDNS discovery via zeroconf -- Device list with category sections (GTK TreeView) -- Icon per device type -- Manual Refresh button -- Double-click → opens device URL in browser -- Right-click menu → Details (SSDP XML / mDNS TXT records) -- Offline devices shown greyed out (from devices.json history) - -### Future -- Additional protocol support (NetBIOS, WSD, etc.) -- Filter / search bar -- Copy IP to clipboard -- Desktop notifications for new devices -- Icon grid view -- IPv6 support - ---- - -## Implementation Constraints (MVP) - -To keep the first release reliable across Linux desktop environments, the following technical -constraints are part of the MVP scope. - -### 1) Cross-protocol deduplication -- The same physical device may be discovered by both SSDP and mDNS. -- `DeviceStore` must merge entries that represent the same host instead of showing duplicates. -- A deterministic merge strategy is required: - - Prefer stable identifiers when available (USN/UUID, hostname/FQDN, serial-like TXT fields) - - Fallback to heuristic matching (`ip + normalized_name + type`) -- Store all contributing sources in metadata (`sources: ["ssdp", "mdns"]`) for traceability. - -### 2) Thread-safe GTK updates -- Discovery listeners may run outside the GTK main loop. -- UI updates must only happen on the GTK thread. -- All device add/update/remove signals routed to UI must be marshaled through `GLib.idle_add(...)`. - -### 3) Presence and offline lifecycle -- "Offline" state must not depend on instantaneous packet loss. -- Each device keeps `last_seen` and protocol-specific timeout/TTL information. -- A periodic lifecycle check marks devices offline only after timeout expiration. -- A device returning on the network must be transitioned back to online cleanly (same logical entry). - -### 4) URL and endpoint normalization -- Announced service endpoints may be incomplete or inconsistent. -- URL construction must be centralized in one resolver utility: - - Respect protocol metadata when valid - - Fallback to mapping defaults from `device_types.json` - - Never generate malformed URLs -- Resolver output is the single source used by double-click "Open in browser". - -### 5) Linux packaging and runtime dependencies -- Packaging targets remain AppImage and `.deb`, but system prerequisites must be explicit. -- Runtime validation must cover at least: - - `python3-gi` / GTK3 availability - - `zeroconf` Python dependency - - mDNS backend expectations on target distros (Avahi/DBus ecosystem) -- README and release notes must include a dependency troubleshooting section for Mint/Ubuntu/Debian. - ---- - -## Acceptance Criteria (MVP) - -The MVP is considered valid only if all criteria below are met on at least Linux Mint, Ubuntu, -or Debian test environments. - -### A) Discovery and deduplication -- Given one device announcing both via SSDP and mDNS, only one logical entry appears in the UI. -- The merged entry retains traceability of protocol origins in metadata. -- Repeated announcements do not create duplicate rows. - -### B) UI thread safety and responsiveness -- No GTK thread warnings/crashes occur during continuous discovery traffic. -- Device list updates remain fluid while listeners are active. -- All add/update/remove UI operations are executed through GTK main-loop-safe dispatch. - -### C) Online/offline lifecycle behavior -- A discovered device is marked offline only after timeout expiration, not after a single missed packet. -- If the same device reappears, its existing entry is reactivated (not duplicated). -- `last_seen` is updated on every valid re-announcement. - -### D) URL resolution reliability -- Double-click action opens a valid browser URL when an endpoint is available. -- If announced endpoint fields are incomplete, fallback mapping from `device_types.json` is applied. -- No malformed URL is emitted by the resolver for known mappings. - -### E) Packaging and runtime readiness -- Application starts successfully on target distro with documented dependencies installed. -- Missing dependency scenarios produce understandable user-facing diagnostics (or actionable logs). -- Build and run steps for AppImage and `.deb` are documented and reproducible from repository docs. - -### F) Regression and data persistence checks -- `devices.json` persists history across app restarts. -- Previously seen devices can be displayed as offline (greyed out) until rediscovered. -- Corrupted or missing `devices.json` does not crash the application (safe fallback to empty state). - ---- - -## Implementation Roadmap - -### Phase 0 — Foundation (project bootstrap) -- Create package structure (`discovery`, `model`, `ui`, `utils`, `data`). -- Add app entrypoint and GTK application/window wiring. -- Add typed `Device` model and in-memory store contract. -- Deliverable: app launches with empty UI and manual refresh action. - -### Phase 1 — mDNS integration -- Implement `mDNSDiscovery` using `zeroconf` service browser. -- Normalize mDNS records into `Device` objects. -- Wire callbacks to manager and thread-safe UI updates via `GLib.idle_add(...)`. -- Deliverable: `_esp3d._tcp`, `_smb._tcp`, `_http._tcp` devices appear in UI. - -### Phase 2 — SSDP integration -- Implement `SSDPDiscovery` multicast listener/query over UDP. -- Parse SSDP headers and resolve device descriptor metadata. -- Normalize SSDP records into `Device` objects and feed manager callbacks. -- Deliverable: UPnP devices appear in UI and can be opened in browser if URL exists. - -### Phase 3 — Merge, lifecycle, and persistence -- Add cross-protocol deduplication logic in store/manager. -- Implement offline lifecycle checks (`last_seen`, timeout scheduler). -- Persist lightweight history to `~/.config/netneighbor/devices.json`. -- Deliverable: no duplicate rows for same host, offline state visible after timeout. - -### Phase 4 — UX hardening and diagnostics -- Add details dialog for raw metadata (XML/TXT). -- Add robust URL resolver with mapping fallback. -- Improve error handling for missing dependencies and parsing failures. -- Deliverable: stable daily-use MVP with actionable diagnostics. - -### Phase 5 — Packaging and release -- Add Linux install/run docs for Mint/Ubuntu/Debian. -- Prepare reproducible AppImage and `.deb` build process. -- Validate acceptance criteria on target distros. -- Deliverable: tagged MVP release candidate ready for user validation. - ---- - -## Dependencies - -| Package | Purpose | -|---------|---------| -| `pygobject` | GTK3 UI | -| `zeroconf` | mDNS discovery | -| stdlib `socket` | SSDP multicast (no extra dep) | - ---- - -## License -GNU Lesser General Public License v3 (LGPL v3) - -## Author -Luc — ESP3D ecosystem diff --git a/docs/archive/NetNeighbor_Brief_v1.4.md b/docs/archive/NetNeighbor_Brief_v1.4.md deleted file mode 100644 index d7b508b5..00000000 --- a/docs/archive/NetNeighbor_Brief_v1.4.md +++ /dev/null @@ -1,238 +0,0 @@ -# NetNeighbor — Project Brief v1.4 - -**Supersedes:** architecture and roadmap sections of v1.3 (kept in repo for history). -**Developer index:** [`docs/README.md`](README.md) - -## Changes from v1.3 - -- Documents **current codebase**: SSDP and mDNS implemented (zeroconf-based mDNS with multi-service host aggregation). -- Persistence described as **`~/.config/netneighbor/ui_prefs.json`** (UI state, overrides, monitored device snapshots), not a separate `devices.json` device database. -- Features and roadmap aligned with [`ROADMAP.md`](ROADMAP.md). - -## Description - -NetNeighbor is a Linux desktop application that replicates and extends the Windows Network -Neighborhood experience, using SSDP and mDNS protocols to discover and display local network -devices in a user-friendly GUI. - -## Goals - -- Provide a simple, native-feeling GUI for local network device discovery on Linux -- Support SSDP (UPnP) and mDNS discovery protocols -- Target ESP32/ESP8266 devices (ESP3D ecosystem) as primary use case, while remaining generic -- Extensible architecture — new protocols can be added without rewriting existing code - -## Target Platform - -- Linux (primary: Linux Mint / Ubuntu / Debian) -- Python 3 + GTK3 + PyGObject -- Distributable as AppImage / `.deb` - ---- - -## Scope - -### In scope (MVP) - -- SSDP (UPnP multicast) discovery — **implemented** -- mDNS (zeroconf) discovery — **implemented** -- PC detection via WSD/SSDP (`urn:schemas-microsoft-com:device:Computer:1`) — subject to devices on network -- PC detection via `_smb._tcp` mDNS - -### Out of scope (future protocols) - -- NetBIOS/LLMNR discovery -- Active network scan (no ping sweep, no ARP scan) -- Linux PC detection without Avahi/Samba -- Proprietary protocols (Sonos, Philips Hue, etc.) -- SMB share authentication / access -- IPv6 support - -> **Rule:** NetNeighbor listens and displays what announces itself. -> It does not actively search for what is hidden. -> New protocols will be added in future versions via the discovery API. - ---- - -## Architecture (current tree) - -``` -netneighbor/ -├── main.py # Entry point -├── app.py # Gtk.Application, single-instance, DiscoveryManager, MainWindow -│ -├── discovery/ -│ ├── base.py # BaseDiscovery — protocol callback contract -│ ├── manager.py # DiscoveryManager — cache, merges, overrides, listeners -│ ├── ssdp.py # SSDP UDP multicast + XML descriptors + rules -│ └── mdns.py # mDNS discovery (zeroconf) -│ -├── model/ -│ └── device.py # Device dataclass + stable SSDP key -│ -├── ui/ -│ ├── main_window.py # Shell, menus, prefs, notifications, GLib.idle_add bridge -│ ├── device_list.py # List + icon grid, bundles by (ip, port), context menus -│ ├── device_details.py # Details dialog -│ └── icons.py # Icon resolver -│ -├── assets/icons/ # Bundled PNG/SVG -├── data/device_types.json # Optional mapping (icons / labels) -├── config/ -│ ├── ssdp_rules.json # Heuristic SSDP name / type / information rules (shipped) -│ └── mdns_rules.json # Heuristic mDNS TXT summary + optional type_rules (shipped) -├── utils/ -│ ├── browser.py -│ ├── details_payload.py # SSDP/mDNS detail panels -│ ├── ui_prefs.py # ~/.config/netneighbor/ui_prefs.json -│ └── notifications.py # Desktop notifications (best-effort) -├── docs/ # Developer docs (README index, SSDP, UI, roadmap, …) -├── requirements.txt -├── README.md -└── LICENSE -``` - -**Runtime config (user):** `~/.config/netneighbor/` — `ui_prefs.json` (UI + overrides); optional **`device_types.json`**, **`ssdp_rules.json`**, **`mdns_rules.json`** merged with bundled defaults (`COMMUNITY_OVERRIDES.md`). -**Optional log:** `~/.cache/netneighbor/netneighbor.log` when file logging is enabled. - ---- - -## Discovery API - -See `discovery/base.py` — `start`, `stop`, `refresh`, `set_callback`. -Protocols emit `("device", payload_dict)`; `DiscoveryManager` builds `Device` instances and notifies UI listeners. - ---- - -## Data flow - -``` -SSDPDiscovery / MDNSDiscovery - │ - ▼ -DiscoveryManager (in-memory dict by Device.key) - │ - ├── user overrides: type, monitored, last_seen (from ui_prefs) - │ - ▼ -MainWindow listener → GLib.idle_add → DeviceList (list + icon grid, categories) -``` - ---- - -## Device model - -```text -Device: - name, ip, port, type, category, source - url: optional presentation URL - metadata: dict — SSDP XML fields / raw XML; mDNS TXT + discovered services - last_seen: datetime - online: bool - monitored: bool # user follow; grey when offline and monitored - icon: str | None -``` - -Stable **`Device.key`**: for SSDP, prefer `UDN`, then `USN` root, then MAC, else `ssdp:ip:port` style endpoint key; other sources use `source:ip:port`. - ---- - -## Device categories (UI) - -Same intent as v1.3 — actual classification comes from inferred `type` and overrides. - ---- - -## Device types database (`data/device_types.json`) - -Still used for icon/type hints where applicable. See embedded example in v1.3 or the live JSON file. - ---- - -## Features - -### Implemented (baseline) - -- SSDP multicast discovery, M-SEARCH refresh, NOTIFY handling, XML descriptors -- Offline policy: NOTIFY byebye immediate; TTL timeout uses **`2 × max-age`** when present (bounded) -- Configurable SSDP heuristics via `config/ssdp_rules.json`; mDNS TXT→summary and optional type rules via `config/mdns_rules.json` -- Device list + **icon grid**, category sidebar, manual reload -- Details dialogs (SSDP/mDNS payload builders with protocol metadata and services) -- Monitor / unfollow, user type/name/location overrides, icon appearance override (system/provided/custom with picker) -- Desktop notifications (connected / left) with optional **session notification history** -- Monitored devices restored as offline from prefs snapshots until rediscovered -- Single-instance behavior (one discovery stack per machine) - -### MVP still open - -- Continue field validation of **cross-protocol deduplication hardening** on diverse networks (edge cases around sleep/wake and endpoint changes) - -### Future - -- Additional protocols (NetBIOS, WSD, …), filter/search, copy IP, IPv6, packaging hardening - ---- - -## Implementation constraints (MVP) - -### 1) Cross-protocol deduplication - -Same host may appear via SSDP and mDNS. The UI bundles rows with the same `(ip, port)`, and override persistence now prefers host identity (`UID`, then `MAC`, then IP fallback) to keep behavior stable across sources. - -### 2) Thread-safe GTK updates - -Discovery runs on background threads; UI updates use **`GLib.idle_add`** from `MainWindow`. - -### 3) Presence and offline lifecycle - -Offline must not flip on a single missed packet. SSDP uses announced **`max-age`** (doubled) plus NOTIFY byebye. mDNS uses host-level aggregation so one missing service does not instantly hide a still-present host. - -### 4) URL and endpoint normalization - -Centralize safe browser open; respect SSDP `presentationURL` when present. - -### 5) Linux packaging and runtime dependencies - -GTK + PyGObject from distro packages; `zeroconf` required for mDNS. Document prerequisites in README. - ---- - -## Acceptance criteria (MVP) — status - -| Area | Note | -|------|------| -| A Deduplication | Partial: SSDP stable keys + UI bundling; stronger cross-protocol merge still open | -| B GTK safety | Required pattern in place | -| C Lifecycle | SSDP + mDNS lifecycle implemented; tuning remains possible | -| D URLs | Best-effort from SSDP XML | -| E Packaging | Still to finalize | -| F Persistence | **`ui_prefs.json`** + monitored snapshots; safe if missing/corrupt prefs | - ---- - -## Implementation roadmap (high level) - -See **[`ROADMAP.md`](ROADMAP.md)** for ordered phases. Summary: - -1. **Done:** foundation, SSDP, UI shell, prefs, monitored restore, notifications. -2. **Next:** runtime mode decision (app/service/tray/file manager/TBD), then packaging/release polish. - ---- - -## Dependencies - -| Package | Purpose | -|---------|---------| -| `pygobject` | GTK3 UI | -| `zeroconf` | mDNS discovery | -| stdlib `socket` | SSDP multicast | - ---- - -## License - -GNU Lesser General Public License v3 (LGPL v3) - -## Author - -Luc — ESP3D ecosystem diff --git a/docs/archive/ROADMAP.md b/docs/archive/ROADMAP.md deleted file mode 100644 index 7a24e79f..00000000 --- a/docs/archive/ROADMAP.md +++ /dev/null @@ -1,71 +0,0 @@ -# Roadmap (development) - -This file tracks **implementation** progress. Product vision and constraints live in -[`NetNeighbor_Brief_v1.4.md`](NetNeighbor_Brief_v1.4.md). - -## Done (current baseline) - -- **0.8.0 (2026-05)** — **[`CHANGELOG`](CHANGELOG.md)**: kernel **neighbor MAC** assist for merge + **IPv4** when discovery showed **IPv6** only; **IPv6 synthetic WSD/wsdd** **`nmblookup -A`** queue; provisional row **pulse** + icon-load affordance; **`prepare_gtk_dialog`**; **first-run hide to tray**; **`--start-minimized-to-tray`** + autostart **`Exec`** vs menu launcher; tray **Minimize to tray**; **`app.py`** known-args parsing + forwarding remainder to **`Gtk.Application.run`**. -- GTK application shell, single-instance lock, locale activation socket (second launch raises existing window). -- **`DiscoveryManager`**: in-memory device cache, listener callbacks, SSDP merge rules, user overrides (type/name/location/monitored/last seen), cross-protocol host identity keys (`UID`/`MAC`/IP fallback) for overrides. -- **`Device` model**: stable SSDP identity (`UDN` / `USN` / MAC / endpoint fallback). -- **SSDP**: UDP multicast, M-SEARCH refresh, NOTIFY parsing, XML descriptor fetch, offline via NOTIFY byebye and TTL-based expiry (`2 × max-age` from `CACHE-CONTROL`, bounded), periodic refresh thread. -- **SSDP rules file** (`config/ssdp_rules.json`): name, information, and type heuristics without recompiling. -- **Additional discovery stacks**: **WSD** (`discovery/wsd.py`, PyPI `WSDiscovery`), **`wsdd`** local daemon cache (`discovery/wsdd_client.py`), **NetBIOS name browse** via **`nmblookup`** (`discovery/netbios.py`); enabled/query knobs under **`discovery.json`** (see [`MAINTENANCE.md`](MAINTENANCE.md)). -- **UI**: list and icon grid, sidebar grouped by type or location (matching arrange mode), details dialogs (**Overview** + protocol fields / raw XML / mDNS **Services** / icon tab), **`utils/details_payload`**: merged **Last seen** deduped; WSD/wsdd/NMB-only detail rows minimized (no noisy Discovery/XAddrs/NetBIOS registration lines). -- **Browser / file-manager open**: **Open** / double-click resolves via **`utils/double_click_open`** (HTTP(S) → SMB → FTP → SSH → Telnet; **`computer`** → **`smb://`** when nothing else matches). No fallback to **Details** on double-click. -- **Tray & session GTK**: **`ui/tray_indicator.py`** (AppIndicator / StatusIcon fallback; tray **Minimize to tray**), **`utils/session_autostart.py`** (XDG autostart `.desktop` with **`--start-minimized-to-tray`**). **View → Preferences**: close-to-tray (default), start minimized to tray, start at login. -- **Window chrome**: with tray active, **`Gtk.HeaderBar`** **Maximize + Close** (minimize via tray menu); **F11** fullscreen for icon-heavy use. -- **Persistence** (per user): `~/.config/netneighbor/ui_prefs.json` (view, filters, overrides, monitored snapshots for restore on next launch — not a full device database file). -- **mDNS (zeroconf)**: real browser/listener, TXT decode, type/category heuristics, host-level service aggregation (single device can expose multiple services), and conditional presentation URL (only when `_http._tcp` is actually present). Aggregation scoring prefers **playback / printer** services (e.g. `_airplay._tcp`, `_raop._tcp`, Sonos/Cast/Spotify Connect, `_ipp._tcp`, `_printer._tcp`) over bare **`_http._tcp`** so representative TXT, type, and icon metadata stabilize sooner on multi-service hosts. -- **`data/device_types.json`**: explicit mDNS keys for common smart-speaker / casting services map to **Smart Speakers** and bundled **`smartspeaker.png`** (user overlay still merges from `~/.config/netneighbor/device_types.json`). -- **Auto location (metadata)**: room-like labels are inferred from SSDP XML / mDNS TXT (including per-service TXT under `metadata["services"]`). Values that look like **SSDP LOCATION / descriptor URLs** (`http…`, `description.xml`, etc.) are rejected so they never populate **location** UI or presets (`utils/location_label.py`). -- **Remote icon persistence**: SSDP/mDNS device icon URLs normalized and cached under `~/.cache/netneighbor/remote_icons/` (raw **`.payload`** per SHA-256 of a **canonical URL**). **Canonicalization** omits default HTTP/HTTPS ports; lookup also tries explicit **`:80` / `:443`** forms when the same logical URL appears with or without a default port. A **host-level RAM cache** and **`~/.cache/netneighbor/remote_icon_index.json`** map **LAN IP → `{canonical_url, payload_sha256, updated_at}`** so the correct **`.payload`** loads immediately at startup even when the representative mDNS port or advertised URL string drifts. UI tries **all** icon URLs from merged service TXT before falling back to bundled / GTK icons. -- **Discovery / UI debugging (optional)**: `logging.json` keys **`mdns`** / **`ssdp`** at **DEBUG** surface manager lines for **location** resolution and **device appearance** (type, icon, `user_location`); **`app`** at **DEBUG** includes **`ui.device_list`** lines for bundled vs remote icon paths and GTK fallbacks. -- **`DiscoveryManager.register_presence_transition_hook`** (internal extension point): optional callbacks when a cached device transitions **online** or **offline** (no hooks registered by core UI yet). Intended for future plugins / scripting; callers may run off the GTK thread. -- **Location stability hardening**: location cache is now preferred and persisted automatically; discovery updates can promote a new plausible room value and trigger cache reapply/persist, reducing `No location` flicker during metadata races. -- **Identity gating (early discovery)**: first-seen SSDP/mDNS rows without stable identity (`UID`/MAC) are briefly held (~3s) before UI publication; immediate release occurs once identity resolves. -- **Release/version unification**: single root `VERSION` file is now consumed by About dialog, build scripts, and desktop entry templating; release artifacts embed `VERSION` explicitly. -- **Packaging quality updates**: `.deb` sets `Installed-Size`; launcher + tray icons ship as **`hicolor/scalable/apps`** **SVG** (see `assets/svg/netneighbor.svg`); **`control`** declares **`Recommends`**: `samba-common-bin` (**`nmblookup`**), **`gir1.2-ayatanaappindicator3-0.1` | `gir1.2-appindicator3-0.1`** (tray GObject bindings — not Samba servers). Manual user-data cleanup helper script retained for optional full local wipe (see [`PACKAGING.md`](PACKAGING.md)). -- **Discovery cache split**: volatile data moved to `~/.cache/netneighbor/discovery-cache.json` (`last_seen`, monitored snapshots metadata, SSDP XML/profile cache), while `ui_prefs.json` keeps UI/user choices. -- **SSDP startup enrichment**: persistent SSDP XML/profile cache reused at startup to improve immediate name/type/details rendering before fresh XML fetches complete. -- **Startup recovery refreshes**: configurable one-shot refreshes after discovery startup via root **`startup_refresh_seconds`** in `discovery.json` (string or array; default `[20, 45, 90]`). - -## In progress / next - -1. **Cross-protocol deduplication hardening** - - Host identity-based override keys are in place (`UID`/`MAC`/IP fallback). - - Recent work improved **same-host mDNS** stability (aggregate representative scoring, host icon index); continue validation on real networks for edge cases (sleep/wake, endpoint shifts, mixed protocol timing, SSDP+mDNS bundle races). - -2. **Runtime mode extensions** - - **Delivered:** single-instance GTK app + optional **systray** + **session autostart** (no standalone systemd daemon). - - **Still deferred:** headless discovery **service** with separate UI attachment, deeper **file-manager** integration — only if cost/benefit is clear. - -3. **Packaging and release** - - **Done for Debian family:** scripted `.deb` + `tar.gz` + `release.sh`, SVG icons, **`Recommends`** for tray + NetBIOS client. - - **Still open:** AppImage (or Flatpak), optional lint/signing/checksum hardening beyond current `SHA256SUMS`. - -4. **Optional UX / data** - - Search / filter bar, quick **copy IP** action, richer **IPv6** surfaces when protocols expose more than link-local inference (today: overview **IPv6 (link-local)** when `fe80::` appears in payloads or device IP). - -## Future — plugins / automation / monitoring (planned, after current next items) - -Goals (examples gathered from design discussion): - -- **Presence monitoring:** react to connects/disconnects (e.g. notify by email when a monitored server drops). -- **Port-triggered actions:** when a known service/port appears on a host, run a **user-configured** shell command with `IP` / `PORT` (e.g. open FTP client, ssh, Telnet UI). -- Prefer a phased approach: stabilize **presence hooks**, then optionally **shell/exec hooks with env vars**, before a fuller dynamic plugin loader if needed. - -Architecture / safety reminders (carry into implementation specs): - -| Topic | Guidance | -|------|----------| -| **Safety** | Never execute payloads from the network. Only configs the user opted into; whitelist identities (IP / UID) where possible. | -| **Stability** | Isolate hook failures (`try`/`except` per hook); timeouts so slow plugins cannot block discovery. Presence hooks today already swallow exceptions and log (`discovery.manager`). | -| **Threading** | Protocol paths can call hooks off the GTK main thread — plugins must marshal UI work via `GLib.idle_add` (see `DiscoveryManager.register_presence_transition_hook` docstring). | -| **Phasing** | (1) stable event vocabulary from core; (2) optional external scripts triggered with fixed env/schema; (3) richer plugin API only if demand is clear. | - -## How to use this file - -- After a major feature lands, add a line under **Done** and adjust **In progress / next**. -- Keep the brief in sync when scope or acceptance criteria change. diff --git a/docs/COMMUNITY_OVERRIDES.md b/docs/contributing/COMMUNITY_OVERRIDES.md similarity index 82% rename from docs/COMMUNITY_OVERRIDES.md rename to docs/contributing/COMMUNITY_OVERRIDES.md index 5d3cf70b..a15573c7 100644 --- a/docs/COMMUNITY_OVERRIDES.md +++ b/docs/contributing/COMMUNITY_OVERRIDES.md @@ -19,11 +19,12 @@ bulk-reset or script defaults; invalid or missing keys fall back to built-in def |----------------|---------| | `close_to_tray` | If true and a tray icon exists, closing the window hides the app instead of exiting (default true). | | `start_minimized_to_tray` | If true and tray works, start hidden to the panel after launch. | -| `start_at_login` | If true, ensures `~/.config/autostart/io.esp3d.netneighbor.desktop` exists (see [`MAINTENANCE.md`](MAINTENANCE.md)). | +| `start_at_login` | If true, ensures `~/.config/autostart/io.esp3d.netneighbor.desktop` exists (see [`MAINTENANCE.md`](../operations/MAINTENANCE.md)). | | `autostart_onboarding_done` | Set after the first-run **session startup** dialog; prevents showing that prompt again. | | `custom_command_template` | Optional shell-like command for **Run custom command** in the device menu; placeholders `{ip}`, `{port}`, `{name}`, `{type}`, `{category}`, `{url}` are expanded (quoted). | | `connect_command_templates` | Optional object keyed by **`http`**, **`https`**, **`smb`**, **`ftp`**, **`ssh`**, **`telnet`**, **`sftp`**: shell-like command for **Open** / double-click for that URL scheme; empty value = system default. Same placeholders as `custom_command_template`. | | `device_commands` | Per-device connection commands (set in the **Options** tab). Object keyed by device identity (`name:source` or `source:ip:port`). Each value is a list of `{scheme, ip, port, mode, label}` where `mode` is `"override"` or `"additional"`. Override entries replace auto-detected defaults for that scheme; additional entries add submenu entries without replacing. | +| `icon_pack` | Active icon pack ID (string). `"builtin"` selects the shipped `assets/icons/netneighbor/` pack; any other value is resolved as a subdirectory name under `~/.config/netneighbor_icon_packs/`. Set from **Preferences → General → Icon pack**. | Other keys store view mode, icon sort, overrides, sidebar width, notification mode, etc.; treat unknown keys as opaque unless you grep the codebase for `save_ui_preferences` / `ui_prefs`. @@ -32,9 +33,11 @@ unknown keys as opaque unless you grep the codebase for `save_ui_preferences` / | File | Merges with | Behaviour | |------|-------------|-----------| -| `device_types.json` | `data/device_types.json` | Deep-merge per `mdns` / `ssdp` service key; shallow merge `fallback`. | +| `device_types.json` | `config/device_types.json` | Deep-merge per `mdns` / `ssdp` service key; shallow merge `fallback`. | +| `icons.json` | `config/icons.json` | Shallow-merge the top-level ``types`` object: each slug maps to an ordered list of **basename** strings for `assets/icons/netneighbor/{N}x{N}/.png` (replaces the shipped list for that slug when you supply it). | | `ssdp_rules.json` | `config/ssdp_rules.json` | Shallow merge `name_rules` and `information_rules` (user keys win). **`type_rules`:** user list is **prepended** (first match wins over shipped rules). | | `mdns_rules.json` | `config/mdns_rules.json` | **`summary_from_txt`:** same label merges `keys` lists (user aliases first, then bundled). **`type_rules`:** user list **prepended**. | +| `wsd_rules.json` | `config/wsd_rules.json` | **`qname_rules`:** user list **prepended** (first match wins). **`precedence`** / **`default`:** replaced when supplied. Rules match on QName attributes (`local_eq` / `local_endswith` / `local_contains_any` / `ns_contains`), not substrings. | ## Partial files @@ -137,10 +140,10 @@ haystack matches. Use **real tokens** from your LAN (inspect device details → raw XML / TXT); replace the placeholder substrings (`myvendor-nas`, `my-upnp-gateway`, …) with strings that appear in the -combined haystack (see [`SSDP.md`](SSDP.md) and [`MDNS.md`](MDNS.md)). +combined haystack (see [`SSDP.md`](../reference/SSDP.md) and [`MDNS.md`](../reference/MDNS.md)). ## Contributing upstream Patterns that help others belong in merge requests updating the bundled `config/` or `data/` -files; see [`CONTRIBUTING_ICONS.md`](CONTRIBUTING_ICONS.md), [`SSDP.md`](SSDP.md), -and [`MDNS.md`](MDNS.md). +files; see [`CONTRIBUTING_ICONS.md`](CONTRIBUTING_ICONS.md), [`SSDP.md`](../reference/SSDP.md), +and [`MDNS.md`](../reference/MDNS.md). diff --git a/docs/contributing/CONTRIBUTING_ICONS.md b/docs/contributing/CONTRIBUTING_ICONS.md new file mode 100644 index 00000000..45454f84 --- /dev/null +++ b/docs/contributing/CONTRIBUTING_ICONS.md @@ -0,0 +1,35 @@ +# Contributing Icons + +## Type → default asset basenames (`config/icons.json`) + +Per logical device type (slug), the **ordered** list of icon **basenames** lives in +**`config/icons.json`** under the ``types`` object. Each name is resolved as:: + + assets/icons/netneighbor/{N}x{N}/.png + +(first existing size wins; see ``ui/icons.bundled_freedesktop_png_side_sizes``). + +- Edit **`config/icons.json`** in the repository to change defaults shipped with the app. +- Optional user override: **`~/.config/netneighbor/icons.json`** with the same ``types`` structure (per-slug lists replace or extend shipped entries for that slug). Documented in [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md). + +There is **no** Freedesktop theme, **no** Windows Shell stock, and **no** ``QStyle`` fallback for types. If no basename matches, **`assets/icons/unknown.png`** is used when present. + +## Multi-size pack layout + +Square folders (`16x16` … `1024x1024`, etc.) under ``netneighbor/`` are auto-discovered. + +## Per-device JSON icons (`config/device_types.json`) + +The ``icon`` field may still name a file under ``assets/icons/`` (e.g. ``router.png``). If that file exists, it is shown before the type pack (device row logic in the UI). + +## User custom PNGs + +``~/.config/netneighbor/custom_icons/*.png`` — picked in GTK/Qt device icon dialogs (ids ``custom:filename.png``). + +## Registering a new device type slug + +1. Add the slug and basename list under ``types`` in ``config/icons.json``. +2. Add matching PNGs under ``netneighbor/{N}x{N}/``. +3. Wire the type in discovery / ``device_types.json`` as today. + +Ensure ``fallback.icon`` remains set to ``unknown.png`` where applicable in ``device_types.json``. diff --git a/docs/I18N.md b/docs/contributing/I18N.md similarity index 100% rename from docs/I18N.md rename to docs/contributing/I18N.md diff --git a/docs/esp3d-overview/context-menu.png b/docs/esp3d-overview/context-menu.png index 636264ac..d1a03e8f 100644 Binary files a/docs/esp3d-overview/context-menu.png and b/docs/esp3d-overview/context-menu.png differ diff --git a/docs/esp3d-overview/index.mdx b/docs/esp3d-overview/index.mdx index 1b7148bc..66ef9265 100644 --- a/docs/esp3d-overview/index.mdx +++ b/docs/esp3d-overview/index.mdx @@ -1,13 +1,13 @@ --- title: NetNeighbor -description: Discover and monitor devices on your local network — a free Linux desktop application. +description: Discover and monitor devices on your local network — free desktop application for Windows, Linux and macOS (Apple Silicon & Intel). --- import { Card, CardGrid, LinkButton, Badge } from '@astrojs/starlight/components'; **Discover and monitor devices on your local network.** -NetNeighbor is a free Linux desktop application that automatically finds all devices +NetNeighbor is a free desktop application that automatically finds all devices on your network and displays them with icons or in a list — printers, NAS drives, cameras, routers, 3D printers, and more. @@ -30,6 +30,10 @@ cameras, routers, 3D printers, and more. Opens HTTP, HTTPS, SMB, SSH, FTP, SFTP and Telnet with a double-click. Configurable per device and per scheme. + + Switch between icon themes. Install community packs or create your own. + Per-device icon override with a visual picker. + Rename devices, tag by location, assign a custom icon or type. Settings are stored locally and survive reboots. @@ -37,6 +41,9 @@ cameras, routers, 3D printers, and more. Runs quietly in the background. Optional autostart at login and minimize to tray. + + Runs on Windows, Linux and macOS. Native SMB credential dialog on Windows. + French, Spanish, German, Italian, Dutch, Japanese, Simplified and Traditional Chinese. @@ -47,12 +54,17 @@ cameras, routers, 3D printers, and more. ## Screenshots +### Main window — icon grid + +![NetNeighbor icon grid view](./overview-hero.png) + +Icon grid with devices grouped by type. Switch to unsorted or list view from the **View** menu. + ### Device list with sidebar ![Device list with sidebar](./main-list.png) -The sidebar groups devices by type or location. Switch between icon grid and list view -from the View menu. +The sidebar groups devices by type or location. Sort by any column in list view. ### Right-click menu @@ -61,6 +73,12 @@ from the View menu. Right-click any device to open it, view its details, rename it, change its type, assign a location, or run a custom command. +### Preferences — General + +![Preferences general tab](./preferences-general.png) + +Switch icon packs, choose a light/dark/auto theme, and manage session autostart. + ### System tray ![System tray menu](./tray-menu.png) @@ -71,24 +89,48 @@ NetNeighbor can minimise to the system tray and start silently at login. ## Download - + + + **Recommended** for Windows 10/11. Installs as a standard application. + + ``` + NetNeighbor-2.0.0-win64-setup.exe + ``` + + > Not code-signed — SmartScreen may warn: click **More info** → **Run anyway**. + + + Drag NetNeighbor to Applications and launch. + + - `NetNeighbor-2.0.0-macos-arm64.dmg` — Apple Silicon (macOS 12+) + - `NetNeighbor-2.0.0-macos-intel.dmg` — Intel (macOS 11+) + + > Not notarized — if Gatekeeper blocks it: right-click → **Open** → **Open**, or run `xattr -cr /Applications/NetNeighbor.app` in Terminal. + **Recommended** for Ubuntu, Linux Mint, and Debian. Dependencies installed automatically. ```bash - sudo dpkg -i netneighbor_1.0.0_amd64.deb + sudo dpkg -i netneighbor_2.0.0_amd64.deb ``` Runs on any Linux distribution. - Requires Python 3 and GTK 3 on the system. ```bash - chmod +x NetNeighbor-1.0.0-x86_64.AppImage - ./NetNeighbor-1.0.0-x86_64.AppImage + chmod +x NetNeighbor-2.0.0-x86_64.AppImage + ./NetNeighbor-2.0.0-x86_64.AppImage + ``` + + + Windows, Linux and macOS. + + ```bash + pip install -r requirements.txt + python main.py ``` @@ -104,21 +146,19 @@ NetNeighbor can minimise to the system tray and start silently at login. ## Requirements -- Linux desktop (Ubuntu 22.04+, Linux Mint 21+, Debian 12+, or equivalent) -- Python 3.10 or later · GTK 3 +| Platform | Requirement | +|----------|-------------| +| **Windows** | Windows 10 or later | +| **Linux** | Ubuntu 22.04+, Linux Mint 21+, Debian 12+, or equivalent | +| **macOS (Apple Silicon)** | macOS 12 (Monterey) or later | +| **macOS (Intel)** | macOS 11 (Big Sur) or later | +| **From source** | Python 3.10+ · PySide6 6.5+ | -For **NetBIOS name resolution** (Windows device names): +For **NetBIOS name resolution** on Linux (Windows device names): ```bash sudo apt install samba-common-bin ``` -For the **system tray icon**: -```bash -sudo apt install gir1.2-ayatanaappindicator3-0.1 -``` - -Both are included automatically when installing the `.deb` package. - --- ## Documentation @@ -127,10 +167,15 @@ Both are included automatically when installing the `.deb` package. Detailed guide covering all features, dialogs, preferences, and troubleshooting. - [Read USER_DOCUMENTATION →](https://github.com/luc-github/NetNeighbor/blob/main/USER_DOCUMENTATION.md) + [Read USER_DOCUMENTATION →](https://github.com/luc-github/NetNeighbor/blob/2.0/docs/USER_DOCUMENTATION.md) + + + How to install community icon packs or create your own. + + [Read CONTRIBUTING_ICONS →](https://github.com/luc-github/NetNeighbor/blob/2.0/docs/contributing/CONTRIBUTING_ICONS.md) - MIT-licensed, contributions welcome. + LGPL-3.0, contributions welcome. [github.com/luc-github/NetNeighbor →](https://github.com/luc-github/NetNeighbor) diff --git a/docs/esp3d-overview/main-list.png b/docs/esp3d-overview/main-list.png index 8f80412a..7b83c607 100644 Binary files a/docs/esp3d-overview/main-list.png and b/docs/esp3d-overview/main-list.png differ diff --git a/docs/esp3d-overview/overview-hero.png b/docs/esp3d-overview/overview-hero.png index ee678dfa..eaf15537 100644 Binary files a/docs/esp3d-overview/overview-hero.png and b/docs/esp3d-overview/overview-hero.png differ diff --git a/docs/esp3d-overview/preferences-general.png b/docs/esp3d-overview/preferences-general.png new file mode 100644 index 00000000..ceeea33c Binary files /dev/null and b/docs/esp3d-overview/preferences-general.png differ diff --git a/docs/esp3d-overview/tray-menu.png b/docs/esp3d-overview/tray-menu.png index db90a2c4..5b3675b4 100644 Binary files a/docs/esp3d-overview/tray-menu.png and b/docs/esp3d-overview/tray-menu.png differ diff --git a/docs/images/3dprinter.png b/docs/images/3dprinter.png deleted file mode 100644 index 2dd51e07..00000000 Binary files a/docs/images/3dprinter.png and /dev/null differ diff --git a/docs/images/badge-light.png b/docs/images/badge-light.png new file mode 100644 index 00000000..71d264b9 Binary files /dev/null and b/docs/images/badge-light.png differ diff --git a/docs/images/cnc.png b/docs/images/cnc.png deleted file mode 100644 index f11350f2..00000000 Binary files a/docs/images/cnc.png and /dev/null differ diff --git a/docs/images/context-menu.png b/docs/images/context-menu.png new file mode 100644 index 00000000..d1a03e8f Binary files /dev/null and b/docs/images/context-menu.png differ diff --git a/docs/images/device-details.png b/docs/images/device-details.png new file mode 100644 index 00000000..26d5c73d Binary files /dev/null and b/docs/images/device-details.png differ diff --git a/docs/images/device-options.png b/docs/images/device-options.png new file mode 100644 index 00000000..e9108279 Binary files /dev/null and b/docs/images/device-options.png differ diff --git a/docs/images/external-applications.png b/docs/images/external-applications.png new file mode 100644 index 00000000..9db0a0fe Binary files /dev/null and b/docs/images/external-applications.png differ diff --git a/docs/images/icon-picker.png b/docs/images/icon-picker.png new file mode 100644 index 00000000..c646f8ef Binary files /dev/null and b/docs/images/icon-picker.png differ diff --git a/docs/images/location-presets.png b/docs/images/location-presets.png new file mode 100644 index 00000000..af3d27b5 Binary files /dev/null and b/docs/images/location-presets.png differ diff --git a/docs/images/main-grid.png b/docs/images/main-grid.png new file mode 100644 index 00000000..e934ae67 Binary files /dev/null and b/docs/images/main-grid.png differ diff --git a/docs/images/main-list.png b/docs/images/main-list.png new file mode 100644 index 00000000..7b83c607 Binary files /dev/null and b/docs/images/main-list.png differ diff --git a/docs/images/menu-tools.png b/docs/images/menu-tools.png new file mode 100644 index 00000000..a77ccb3b Binary files /dev/null and b/docs/images/menu-tools.png differ diff --git a/docs/images/menu-view.png b/docs/images/menu-view.png new file mode 100644 index 00000000..80a009d7 Binary files /dev/null and b/docs/images/menu-view.png differ diff --git a/docs/images/overview-hero.png b/docs/images/overview-hero.png new file mode 100644 index 00000000..eaf15537 Binary files /dev/null and b/docs/images/overview-hero.png differ diff --git a/docs/images/pibot_pendant.png b/docs/images/pibot_pendant.png deleted file mode 100644 index ee256e40..00000000 Binary files a/docs/images/pibot_pendant.png and /dev/null differ diff --git a/docs/images/preferences-general.png b/docs/images/preferences-general.png new file mode 100644 index 00000000..ceeea33c Binary files /dev/null and b/docs/images/preferences-general.png differ diff --git a/docs/images/tray-menu.png b/docs/images/tray-menu.png new file mode 100644 index 00000000..5b3675b4 Binary files /dev/null and b/docs/images/tray-menu.png differ diff --git a/docs/images/type-presets.png b/docs/images/type-presets.png new file mode 100644 index 00000000..7cbd8edc Binary files /dev/null and b/docs/images/type-presets.png differ diff --git a/docs/operations/MAINTENANCE.md b/docs/operations/MAINTENANCE.md new file mode 100644 index 00000000..01df8deb --- /dev/null +++ b/docs/operations/MAINTENANCE.md @@ -0,0 +1,132 @@ +# Maintenance and follow-up + +This complements [`README.md`](../README.md) and the [developer index](README.md) for anyone +keeping the project healthy between releases. + +## Configuration paths + +> **All platforms** (Windows, Linux, macOS) use `~` = `Path.home()` as the base, so paths are +> identical relative to the home directory. On Windows `~` resolves to `C:\Users\`. +> +> **Windows path consistency (fixed in 2.0)** — an earlier version of `utils/device_remote_icon.py` +> computed the icon cache base as `%LOCALAPPDATA%\netneighbor\cache\` on Windows, while +> `utils/app_logging.py` and `utils/discovery_cache.py` both used `Path.home() / ".cache" / +> "netneighbor"`. This caused icon payload files and the index to land in +> `C:\Users\\AppData\Local\netneighbor\cache\remote_icons\` instead of +> `C:\Users\\.cache\netneighbor\remote_icons\` like everything else. +> The fix was to remove the `sys.platform == "win32"` branch from `_netneighbor_cache_dir()` in +> `device_remote_icon.py` so all three modules resolve to the same `~/.cache/netneighbor/` base. +> Users who ran the old version on Windows may have orphaned files in +> `%LOCALAPPDATA%\netneighbor\cache\` — those can be deleted; the app will re-fetch icons into the +> correct location automatically. + +| Path | Content | +|------|---------| +| `~/.config/netneighbor/ui_prefs.json` | UI state + per-device overrides + rules (not a full device DB). Tray-related booleans include **`close_to_tray`** (default true), **`start_minimized_to_tray`**, **`start_at_login`** (writes XDG autostart when enabled). **`custom_command_template`** (**Tools → External applications**) for **Run custom command**; **`connect_command_templates`** overrides **Open** per URL scheme; **`device_commands`** stores per-device connection command lists from the **Options** tab (see [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md)). | +| `~/.config/autostart/io.esp3d.netneighbor.desktop` | Present when **Start NetNeighbor when logging in** is checked in View → Preferences; standard XDG autostart entry. **`Exec=`** appends **`--start-minimized-to-tray`** (tray-only login start) while the **menu** `.desktop` from packaging stays without that flag. Implemented in `utils/session_autostart.py`. | +| `~/.cache/netneighbor/discovery-cache.json` | Volatile discovery cache (`last_seen_overrides`, monitored snapshots metadata, SSDP XML/profile cache). Safe to delete; app rebuilds it. | +| `~/.config/netneighbor/logging.json` | Per-area log levels (`default`, `app`, `ssdp`, `mdns`). Created with defaults on first run if missing. | +| `~/.cache/netneighbor/netneighbor.log` | Log file when file logging is enabled (see `app.py`). | +| `~/.cache/netneighbor/remote_icons/` | On-disk cache for **device-provided** icons fetched from SSDP/mDNS URLs (normalized). Primary file per URL: **`{SHA256(url)}.payload`** raw HTTP body (decoded with GdkPixbuf on load — avoids flaky `savev`). The digest uses a **canonical URL** after rewriting typical LAN hosts (`*.local`, `*.lan`, single-label names) to the **device IP** (stable fetch + hash), then normalizing (lowercased scheme/host, trailing FQDN dot stripped, **default HTTP/HTTPS ports omitted**). Disk lookup also tries **legacy explicit `:80` / `:443`** variants so filenames from older canonicalization rules still resolve. A second lookup tries the **canonical raw URL** (pre-IP rewrite) for older payloads. **HTTPS** to `*.local` / `*.lan` or **RFC1918** hosts uses a relaxed TLS context: certificate verification is disabled (self-signed printer certs) **and** `SECLEVEL=0` is set to allow legacy cipher suites and short keys that older embedded firmware (HP, Canon, Lexmark…) may require. Standard public HTTPS URLs go through the system default SSL context with full verification. Legacy **`.png`** files from older releases are still read if present. Clearing the folder forces a fresh download; if icons look wrong after a firmware change, clear **`remote_icon_index.json`** (see next row) as well. | +| `~/.cache/netneighbor/remote_icon_index.json` | **Host → icon cache index** (version 2 JSON): per **IPv4/IPv6 key** stores **`canonical_url`**, **`payload_sha256`** (same stem as **`remote_icons/{sha256}.payload`**), and **`updated_at`**. Lets the UI load the correct cached icon **on cold start** without waiting for every mDNS TXT variant. Delete this file to drop remembered host→URL mappings (payload files remain until removed manually). | +| `~/.config/netneighbor_icon_packs/` | **User-installed icon packs** (one subfolder per pack). Intentionally outside `~/.config/netneighbor/` so *Reset all application data* does not wipe them. Each subfolder may contain `iconpack.json` (`name`, `owner`, `version`, `license`, `repository` fields; optional) and icon files under `{N}x{N}/` or flat `{N}/` subdirectories. Active pack ID stored in `ui_prefs.json` under `icon_pack`. See `utils/icon_packs.py`. | +| `~/.config/netneighbor/discovery.json` | Discovery toggles + startup refresh schedule. Top-level **`mdns`** / **`ssdp`** with **`enabled`**, **`rules`**, optional **`query`**: SSDP **`interval_seconds`** (periodic M-SEARCH cadence, default 60), **`mx_seconds`** (M-SEARCH **MX** max wait, clamped **5–6**, default 5), **`descriptor_http_min_interval_seconds`** (minimum gap between HTTP GETs for descriptor URLs whose **host is the same IP** (or same hostname if not numeric); avoids duplicate fetches when anticipatory XML and SSDP LOCATION arrive close together; **0** disables; default **5**, max **120**); mDNS **`enumeration_timeout_seconds`** (DNS-SD type scan, **2–3** s, default 2.5), **`enumeration_interval_seconds`** (repeat scan, default 240), **`service_info_timeout_ms`** (`get_service_info`, **2000–3000** ms, default 2500). **`merge.protocol_order`**: ordered protocol **`source`** ids (default **`ssdp`**, **`mdns`**) — earlier = stronger for live-row tie-breaks. **`merge.information_precedence`**: ordered roles (**`user_override`**, **`ssdp_live`**, **`ssdp_profile_cache`**, **`mdns`**) — must list all four exactly once to customize; defaults favour user prefs, then live SSDP, then disk-cache hints on mDNS, then raw mDNS (see `utils/discovery_config.py`). **`startup_refresh_seconds`** at root (comma-separated string or JSON array). | + +## Logging + +- Root logging is configured in `app.py` (console + optional rotating file under cache dir). +- **`logging.json`**: keys `ssdp` and `mdns` apply both to the protocol module (`discovery.ssdp`, `discovery.mdns`) and to manager-side lines for that source (`discovery.manager.ssdp`, `discovery.manager.mdns`), including “Device added/updated”, **location** resolution (`Location: …`), and **device appearance** (type, bundled icon filename, `user_location`). Set **`app`** to **DEBUG** for **`ui.device_list`** messages (remote vs bundled icon path, GTK theme fallback). +- Special levels **`NONE`**, **`OFF`**, **`DISABLED`**, **`SILENT`** turn off that area (no INFO/DEBUG/WARNING from those loggers). +- **`NETNEIGHBOR_LOG_LEVEL`** still overrides the root/default level when set. +- Other useful loggers: `discovery.manager` (start/stop, publishing at DEBUG), `ui`. + +## Systray, window chrome, fullscreen + +- **Tray**: `ui/systray.py` — `NetNeighborTray(QSystemTrayIcon)`. Tray menu: **Show window** / **Hide window** / **Quit**. Left-click toggles window visibility. Created in `app_qt.py` when `QSystemTrayIcon.isSystemTrayAvailable()`. On Linux this requires a desktop environment with a system tray (most include one). +- **Icons**: canonical vector logo — **`assets/svg/netneighbor_icon.svg`**. The installed `.deb` copies the SVG into `/usr/share/icons/hicolor/scalable/apps/` as `io.esp3d.netneighbor.svg`, and the tray SVG as `io.esp3d.netneighbor-tray.svg`. +- **Close-to-tray**: `closeEvent` in `ui/main_window.py` calls `event.ignore()` + `self.hide()` when `close_to_tray` pref is `True` and a tray is available; otherwise normal close. +- **Minimize to tray**: `changeEvent` intercepts `WindowStateChange` + `isMinimized()`; schedules `self.hide()` via `QTimer.singleShot(0, …)`. +- **CLI `--start-minimized-to-tray`**: when set and tray is available, `window.show()` is skipped so the app starts invisible. +- **F11 fullscreen**: handled via `keyPressEvent` in `ui/main_window.py`. +- **Open on PCs**: **Open** / double-click uses `resolve_connect_target` — **HTTP(S)** first, then **SMB** / **FTP** / **SSH** / **SFTP** / **Telnet** from merged mDNS or explicit device URLs; type `computer` with no other target opens `smb://` toward the host IP. The resulting URI is opened via `launch_connect_for_uri` (`utils/connect_launcher.py`) — empty per-scheme template in **View → Preferences… → Applications** keeps the system default. If no target exists, **Open** is inactive. + +## Icon packs + +NetNeighbor supports swappable icon packs for device-type icons. The active pack is selected in **Preferences → General → Icon pack** and stored as `icon_pack` in `ui_prefs.json`. + +- **Resolution**: `utils/qt_device_icons.py` (`_bundled_freedesktop_qicon`) checks the active pack first, then falls back to the built-in `assets/icons/netneighbor/`. Supports both `{N}x{N}/` and flat `{N}/` directory naming. +- **User packs**: `~/.config/netneighbor_icon_packs/{pack_id}/` — survives Reset. Add `iconpack.json` for display name; otherwise the directory name is shown. +- **Cache**: changing the pack invalidates the module-level cache (`utils/icon_packs.invalidate_icon_pack_cache`) and `QPixmapCache` so the view rebuilds immediately. + +## Bundled device icons (netneighbor) + +`assets/icons/netneighbor/` contains PNG fallback icons for ~1 000 +[freedesktop.org](https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html) +icon names, supplied at multiple pixel resolutions. The source tree retains **all** +resolutions (~151 MB total) for archival — they are available for future UI changes or +higher-DPI presets without requiring a new source checkout. + +Packages ship only the **5 sizes** actually used by the Qt icon-view presets: + +| Folder | UI preset | HiDPI equivalent | +|--------|-----------|-----------------| +| `16/` | Small (16 px) | — | +| `32/` | Medium (32 px) | Small @2× | +| `48/` | Large (48 px) | Medium @2× | +| `96/` | Extra large (96 px) | Large @2× | +| `256/` | — | high-DPI launcher / app icon | + +All other resolution directories (24, 64, 128, …) are stripped during the packaging +build step (`packaging/linux/build_*.sh`, `packaging/windows/build.ps1`), saving +~143 MB per artifact. + +`bundled_freedesktop_png_side_sizes()` in `ui/icons.py` discovers the available sizes +dynamically at runtime by scanning for `{N}x{N}` subdirectories, so trimming the +directory has no effect on the runtime code path — it simply resolves to a smaller set. +User packs that use flat `{N}/` directories are handled by `scan_pack_sizes()` / `find_icon_in_pack()` in `utils/icon_packs.py`. + +## Common tasks + +- **Rules tuning**: shipped `config/ssdp_rules.json` / `config/mdns_rules.json`; user overlays in **`~/.config/netneighbor/`** — [`COMMUNITY_OVERRIDES.md`](../contributing/COMMUNITY_OVERRIDES.md). +- **Icons / types**: `config/device_types.json` and [`CONTRIBUTING_ICONS.md`](../contributing/CONTRIBUTING_ICONS.md); optional user merge from `~/.config/netneighbor/device_types.json` ([`COMMUNITY_OVERRIDES.md`](../contributing/COMMUNITY_OVERRIDES.md)). Icons loaded from SSDP/mDNS URLs are persisted under **`~/.cache/netneighbor/remote_icons/`** with a **`remote_icon_index.json`** host map (see table above). +- **Translations**: `app/locale/*/LC_MESSAGES/netneighbor.po`, compile with `msgfmt`; see [`I18N.md`](../contributing/I18N.md) for full workflow. + +## Discovery extension hooks + +- **`DiscoveryManager.register_presence_transition_hook` / `unregister_presence_transition_hook`** (`discovery/manager.py`): optional observers for **`"online"`** / **`"offline"`** transitions per device identity row (not wired in core UI). Callbacks run on the same thread as the discovery update — use `GLib.idle_add` before touching GTK. Failures are logged and do not stop discovery. Planned use: future plugins / alerting. Extension code may import `DiscoveryManager`, `PresenceTransitionHook`, and `PresenceTransitionKind` from the **`discovery`** package (`from discovery import …`). + +## Debugging discovery issues + +1. Confirm only **one** app instance (SSDP bind + multicast). +2. Check firewall allows UDP 1900 inbound / multicast. +3. Inspect SSDP details in the UI for `LOCATION`, `USN`, XML presence. +4. Compare logs for “XML fetched” vs failures (timeouts, parse errors). +5. **Location looks like a URL / `description.xml`**: should no longer happen; if prefs were polluted earlier, open **Location presets** or edit **`ui_prefs.json`** — invalid URL-like presets are stripped on load. **`utils/location_label.py`** documents the rejection rules. +6. **Wrong or delayed device icon**: confirm **`remote_icons/*.payload`** and **`remote_icon_index.json`** together; bump **`mdns`** / **`app`** to **DEBUG** to trace aggregate + icon load path. +7. **Device details (first tab)**: duplicate **Last seen** rows are collapsed to the latest timestamp; bundled WSD/wsdd/NMB-only rows omit legacy **Discovery** / **WSD XAddrs** / **NetBIOS registration** lines (overview + protocol fields stay minimal). **IPv6 (link-local)** in the overview only appears when a `fe80::` address is inferred from device IP or WSD/wsdd payloads — many Windows PCs only advertise IPv4 in WSD URLs, so an empty IPv6 line there is expected. + +## Changelog / release notes + +Archived in [`archive/CHANGELOG.md`](../archive/CHANGELOG.md) (up to **0.8.0**). New release notes go in the repository changelog or release tags. + +## Suggested additional docs (optional) + +| Document | When to add | +|----------|-------------| +| `TESTING.md` | Once you have automated tests or a repeatable manual checklist per release. | +| `PACKAGING.md` | When AppImage / `.deb` pipeline is scripted (commands, deps, smoke test). | +| `TROUBLESHOOTING.md` | User-facing FAQ distilled from GitHub issues (short). | + +Architecture Decision Records (ADR): optional short files under `docs/adr/` for major choices +(why GTK3, why in-memory store first, etc.) if the team grows. + +## Release checklist (minimal) + +- [ ] **`VERSION`** bumped. +- [ ] `README.md` and `USER_DOCUMENTATION.md` aligned with new behavior. +- [ ] `docs/operations/MAINTENANCE.md`, `docs/operations/PACKAGING.md`, and `docs/contributing/COMMUNITY_OVERRIDES.md` updated if behavior or deps changed. +- [ ] `docs/ROADMAP.md` updated (move done items, add new known issues). +- [ ] Translation catalogs merged (`msgmerge`) and `.mo` files compiled. +- [ ] Smoke run: start app, discovery, details, tray hide/show, **CLI** `--start-minimized-to-tray`, optional autostart toggle, monitored device restart. +- [ ] Test Open / double-click with Override and Additional device commands. +- [ ] Packaging smoke: `./packaging/linux/build_deb.sh`, install in VM, verify icons + `Recommends` (tray + `nmblookup`). diff --git a/docs/operations/PACKAGING.md b/docs/operations/PACKAGING.md new file mode 100644 index 00000000..c25c8953 --- /dev/null +++ b/docs/operations/PACKAGING.md @@ -0,0 +1,291 @@ +# Packaging + +NetNeighbor 2.0 ships platform-specific build scripts under `packaging/` — all targets use **PySide6** (`app_qt.py`). + +Layout: [`packaging/README.md`](../packaging/README.md). + +--- + +## Linux (`packaging/linux/`) + +### Prerequisites (build machine) + +- Debian/Ubuntu-like environment +- `git`, `dpkg-deb`, `tar` +- Optional: `msgfmt` (`gettext`) for `.po` → `.mo` +- Optional (AppImage): [appimagetool](https://github.com/AppImage/AppImageKit/releases) or `bash packaging/linux/build_appimage.sh --download-tool` + +### Build + +From repository root: + +```bash +chmod +x packaging/linux/*.sh +./packaging/linux/release.sh +``` + +Or individual targets: + +```bash +./packaging/linux/build_deb.sh +./packaging/linux/build_tarball.sh +./packaging/linux/build_appimage.sh # optional; needs appimagetool +``` + +Version defaults to the first line of `VERSION`; override with `./packaging/linux/release.sh 2.0.0`. + +### Outputs (`dist/`) + +| Artifact | Description | +|----------|-------------| +| `netneighbor__.deb` | System install under `/usr/share/netneighbor` | +| `netneighbor-.tar.gz` | Portable tree + `run.sh` | +| `NetNeighbor--.AppImage` | Optional; skipped if appimagetool missing | +| `SHA256SUMS-.txt` | Checksums (via `packaging/linux/checksums.sh`) | + +### Runtime dependencies (`.deb`) + +**Depends:** `python3 (>= 3.10)`, `python3-pip`, `samba-common-bin` (NetBIOS name resolution). +PySide6, zeroconf, and WSDiscovery are installed via pip into the package prefix — no system GUI library dependencies. + +See `packaging/linux/build_deb.sh` for the full file list and icon layout. + +### Bundled icon set — size trimming + +`assets/icons/netneighbor/` is ~151 MB in the source tree (10 resolution +directories). All three Linux build scripts automatically trim the directory to the +5 sizes used by the Qt icon-view presets (16, 32, 48, 96, 256), reducing the packaged +size by ~143 MB. The Windows build does the same after the PyInstaller `onedir` step. +See [`MAINTENANCE.md`](MAINTENANCE.md#bundled-device-icons-netneighbor) for details. + +### Install / cleanup + +```bash +sudo apt install ./dist/netneighbor__amd64.deb +netneighbor +sudo apt remove netneighbor +``` + +```bash +sudo bash packaging/linux/cleanup.sh +bash packaging/linux/cleanup-user-data.sh +``` + +Tarball: extract, `./run.sh`, optional `./install-desktop.sh`. + +--- + +## Windows (`packaging/windows/`) + +### Prerequisites + +- Windows 10/11, Python 3.10+ +- `pip install -r requirements.txt pyinstaller` +- **Inno Setup 6** (`ISCC.exe` on `PATH`, or `winget install JRSoftware.InnoSetup --source winget`) +- **VC++ Redistributable** on end-user machines (PySide6 requires it; Windows 10/11 typically ship it already) + +### Build + +```powershell +.\packaging\windows\build.ps1 +.\packaging\windows\build_installer.ps1 +``` + +Optional: `-Version 2.0.0` on both scripts. Uses `.venv\Scripts\python.exe` when present, else `python`. + +### Outputs (`dist/`) + +| Artifact | Description | +|----------|-------------| +| `NetNeighbor/` | PyInstaller onedir folder | +| `NetNeighbor--win64.zip` | Zipped folder | +| `NetNeighbor--win64-setup.exe` | Inno Setup installer | + +PyInstaller spec: `packaging/windows/netneighbor.spec` — entry `app/main.py`, `pathex` includes `app/`. + +--- + +### ⚠️ CRITICAL — Windows PyInstaller gotchas (read before any build) + +Two bugs that make the frozen app behave like malware if not addressed. Both are fixed +in the current codebase; **do not remove or move these fixes**. + +#### Bug 1 — `multiprocessing.freeze_support()` missing → hundreds of windows + +**Symptom:** Launching the `.exe` immediately opens dozens or hundreds of semi-transparent +windows that cannot be closed. Task Manager shows the process tree growing out of control. +Killing the main process leaves orphaned child-process windows on screen. + +**Root cause:** On Windows, PyInstaller frozen apps use the `spawn` multiprocessing start +method. When any dependency (zeroconf, ThreadPoolExecutor, …) spawns a child process, +Windows re-executes the frozen `.exe` from scratch. Without `freeze_support()` the child +re-runs the full application — which spawns another child — infinitely. + +**Fix (in `main.py`):** +```python +import multiprocessing + +if __name__ == "__main__": + multiprocessing.freeze_support() # ← MUST be first, before any other code + from app_qt import main + raise SystemExit(main()) +``` + +`freeze_support()` detects the special command-line token that PyInstaller injects for +child processes and calls `sys.exit()` immediately, preventing the full app from running. + +**Rule:** `freeze_support()` must remain the very first statement inside +`if __name__ == "__main__":`, before any import or application code. + +--- + +#### Bug 2 — `subprocess` calls without `CREATE_NO_WINDOW` → console window spam + +**Symptom:** Many black or semi-transparent console (terminal) windows flash on screen +every few seconds while the app is running. Each window appears and disappears rapidly. + +**Root cause:** When a frozen app built with `console=False` calls `subprocess.run()` or +`subprocess.Popen()` without `creationflags=subprocess.CREATE_NO_WINDOW`, Windows creates +a visible console window for every subprocess. NetNeighbor looks up MAC addresses via +`arp -a` for each discovered device on every UI refresh — potentially 10–30 calls per +cycle — producing a storm of console flashes. + +**Fix (in `utils/neighbor_mac.py`):** +```python +_cflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) +proc = subprocess.run([...], creationflags=_cflags, ...) +``` + +A 850 ms cache on the `arp -a` output also prevents redundant subprocess calls within +the same refresh cycle (one `arp -a` covers all devices). + +**Rule:** Every `subprocess.run()` / `Popen()` call in Windows-reachable code paths must +pass `creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)`. The `getattr` fallback +keeps the code portable (the constant is Windows-only). `discovery/netbios.py` already +uses `_subprocess_no_window_kwargs()` for this — follow the same pattern. + +--- + +## macOS (`packaging/macos/`) + +Two separate builds are produced: one for Apple Silicon (arm64) and one for Intel (x86_64). + +### Prerequisites + +**Homebrew** (required for `create-dmg` — both architectures) : + +```bash +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" +brew install create-dmg +``` + +Homebrew requires Xcode Command Line Tools; the installer will prompt to install them automatically if missing. + +--- + +**Apple Silicon (arm64) — macOS 12+** +- Homebrew + `create-dmg` (see above) +- Python 3.10+, `pip install -r requirements.txt pyinstaller` + +**Intel (x86_64) — macOS 11 Big Sur+** +- Homebrew + `create-dmg` (see above) +- **Python 3.11.x** — PySide6 6.5.x requires Python < 3.12; Python 3.12+ can only install PySide6 6.6+ which requires macOS 12+. Download from [python.org](https://www.python.org/downloads/). +- `pip install "PySide6>=6.5,<6.6" -r requirements.txt pyinstaller` + PySide6 6.5.x is the last series supporting macOS 11. PySide6 6.6+ requires macOS 12+. + +CI uses `macos-15-intel` runner (Intel x86_64, macOS 15) — faster queue than the deprecated `macos-13`. + +### Build + +```bash +# Apple Silicon +bash packaging/macos/build_app.sh 2.0.0 arm64 + +# Intel (run on an Intel Mac or macos-13 CI runner) +bash packaging/macos/build_app.sh 2.0.0 x86_64 + +# Native arch (detects automatically) +bash packaging/macos/build_app.sh 2.0.0 +``` + +### DMG background images + +`packaging/macos/dmg_background.png` (560×300 px) and `dmg_background@2x.png` (1120×600 px) are the drag-to-Applications background shown in the Finder window. + +**Important — macOS DPI:** these files must be saved at **72 DPI** (not 96 DPI which is the Windows/Linux default). At 96 DPI macOS renders the image at 75% of its pixel size (560 px → 420 px), leaving a gray border around the background. Most image editors have a resolution/DPI setting in the export dialog — set it to 72. + +To verify or fix on macOS: +```bash +sips -g dpiWidth packaging/macos/dmg_background.png # must show 72.000 +# Fix if needed (sips -s takes px/cm, not DPI: 72 DPI = 28.346 px/cm): +sips -s dpiWidth 28.346 -s dpiHeight 28.346 packaging/macos/dmg_background.png +sips -s dpiWidth 56.693 -s dpiHeight 56.693 packaging/macos/dmg_background@2x.png +``` + +### Outputs (`dist/`) + +| Artifact | Description | +|----------|-------------| +| `NetNeighbor.app` | Application bundle (intermediate, deleted by CI after smoke test) | +| `NetNeighbor--macos-arm64.dmg` | Apple Silicon installer DMG (macOS 12+) | +| `NetNeighbor--macos-intel.dmg` | Intel installer DMG (macOS 11 Big Sur+) | + +### Local testing on a Big Sur Intel VM (VirtualBox) + +The Intel build can be built and tested directly on a Big Sur machine: + +```bash +# 1. Install Homebrew (includes Xcode Command Line Tools if missing) +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" +brew install create-dmg + +# 2. Install Python 3.11 from python.org, then: +python3.11 -m venv .venv +source .venv/bin/activate +pip install --upgrade pip +pip install "PySide6>=6.5,<6.6" -r requirements.txt pyinstaller + +# 3. Build +bash packaging/macos/build_app.sh 2.0.0 x86_64 +# → dist/NetNeighbor-2.0.0-macos-intel.dmg +``` + +Code signing (Apple notarization) is not planned — cost prohibitive for an open-source project. Users may see an OS security warning on first run; this is expected and harmless. + +--- + +## Checksums (all platforms) + +```bash +packaging/linux/checksums.sh [basename ...] +``` + +Without basenames, includes known patterns already in `dist/`. Linux `release.sh` calls this automatically. + +--- + +## GitHub Actions (release tags) + +Workflow [`.github/workflows/release.yml`](../.github/workflows/release.yml) runs on tags `v*` (e.g. `v2.0.0`): + +- **Linux** — full `packaging/linux/release.sh`, assets attached to the GitHub Release +- **Windows / macOS** — PyInstaller skeleton builds (`continue-on-error: true` until validated locally) + +Push a tag to trigger: + +```bash +git tag v2.0.0 +git push origin v2.0.0 +``` + +--- + +## 2.0 migration note + +Do not expect Windows/macOS CI builds to be production-ready until: + +1. UI port is complete (`app.py`, systray, notification history). +2. [`packaging/POST_PORT.md`](../packaging/POST_PORT.md) checklist is done (`app_qt.py` removed). +3. Local builds pass on each OS; then tighten CI (`continue-on-error: false`). + +Linux `.deb` / `tar.gz` / AppImage will switch from GTK to PySide6 in the same pass. diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/reference/BACKEND_ARCHITECTURE.md similarity index 76% rename from docs/BACKEND_ARCHITECTURE.md rename to docs/reference/BACKEND_ARCHITECTURE.md index a408b4d6..5d64e347 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/reference/BACKEND_ARCHITECTURE.md @@ -4,7 +4,9 @@ The backend is built around a single `DiscoveryManager` instance that owns the in-memory device store and all user overrides. Protocol modules run in their own threads and emit -normalized payloads; the manager applies overrides and notifies UI listeners via `GLib.idle_add`. +normalized payloads; the manager applies overrides and notifies UI listeners on caller threads. +The desktop shell passes **`schedule_on_main_thread`** (GTK: `GLib.idle_add`, Qt: queued slot) +so heavy UI updates and mDNS browser registration run on the toolkit main thread. ``` ┌────────────────────────────────────────────────────────┐ @@ -22,7 +24,7 @@ normalized payloads; the manager applies overrides and notifies UI listeners via │ merge protocols │ │ _notify(devices) │ └────────────┬───────────┘ - │ listener(devices) [GLib.idle_add] + │ listener(devices) [marshal via UI hook] ▼ ┌────────────────────────┐ │ MainWindow / UI │ @@ -101,6 +103,40 @@ Optional hooks registered via `register_presence_transition_hook`: called on `"online"` / `"offline"` transitions. Callbacks run on the discovery thread — use `GLib.idle_add` before touching GTK. +### Reachability probe & offline removal + +Passive discovery alone cannot tell a brutally disconnected host (power loss, +cable pull) from a quiet one — mDNS/SSDP records only expire after their TTL, +which can be tens of minutes. Two active probes close that gap: + +- **Startup TCP probe** (`_start_tcp_probes_for_cached_devices`): on `start()`, + every cached online endpoint with a usable port is TCP-probed (1.5 s timeout). + Gives the UI a clean picture within ~5 s without waiting for live discovery. +- **Periodic ICMP probe** (`_start_ping_probes_for_live_devices`): every + `_PERIODIC_PROBE_INTERVAL_S` (180 s) each online device's IP is pinged + (`utils/tcp_probe.ping_host`, no admin rights needed). Works regardless of + port. On Windows, exit code `0` is insufficient — a router answering + *"Destination host unreachable"* for an offline LAN target also exits `0`, so + the probe additionally requires `TTL=` in the output (only present in a + genuine reply from the target). + +Both probes only flip a device offline if no protocol confirmed it online since +the probe started (`last_seen > probe_start` guard), avoiding races with live +discovery. All mutations are marshalled to the main thread via +`schedule_on_main_thread`. + +**Offline removal policy** — when a device that was online transitions to +offline (via a probe, or an mDNS byebye/SSDP byebye through +`add_or_update_device` with `prev_online is True`): + +- **Monitored** (followed) devices stay in the list, greyed out. +- **Non-monitored** devices are dropped from `_devices` immediately — a device + returning from sleep is re-discovered automatically by mDNS/SSDP or on the + next user refresh, so no deferred grace timer is needed. + +Devices restored from the disk cache as offline at startup (`prev_online is +None`) are kept, so the startup probe / live discovery can confirm them. + --- ## Protocol modules @@ -118,7 +154,7 @@ use `GLib.idle_add` before touching GTK. - Uses `zeroconf` library (passive browsing + DNS-SD enumeration) - Aggregates per-service payloads into per-host entries - URL only set when `_http._tcp` is actually advertised -- **Grace period on removal**: `remove_service` callbacks are delayed 180 s when the host is still alive, absorbing mDNS TTL jitter that would otherwise cause false offline flaps +- **Grace period on removal**: `remove_service` callbacks are delayed 120 s when the host is still alive, absorbing mDNS TTL jitter that would otherwise cause false offline flaps. After a user `refresh()` the pending grace-removes are rescheduled to a short 15 s window so a stale device disappears quickly if it does not re-announce - **Refresh = full Zeroconf restart**: `refresh()` closes and reopens the `Zeroconf` instance to clear its DNS cache, then recreates all `ServiceBrowser` objects. This ensures PTR queries go out without *known-answer suppression* headers (RFC 6762 §7.1), so devices that stopped announcing (TTL expired) will respond and repopulate the device list - See [`MDNS.md`](MDNS.md) for full details @@ -194,8 +230,8 @@ All devices with a loopback IP address (`ipaddress.ip_address(ip).is_loopback`) |------|---------| | `config/ssdp_rules.json` | SSDP name / info / type classification rules | | `config/mdns_rules.json` | mDNS TXT → summary mapping + type rules | -| `config/default_commands.json` | Default command templates per URL scheme (used by Tools → External applications) | -| `data/device_types.json` | Icon, display name, and mDNS service type → device type mapping | +| `config/default_commands.json` | Default command templates per URL scheme and OS (`linux` / `darwin` / `win32` objects; legacy flat map still supported). Used by Tools → External applications. Optional `{ip_raw}` (see `utils/custom_command.py`) for templates where quoting breaks UNC paths. | +| `config/device_types.json` | Icon, display name, and mDNS service type → device type mapping | | `~/.config/netneighbor/discovery.json` | Discovery toggles, intervals, merge order | | `~/.config/netneighbor/ui_prefs.json` | All user overrides + UI state | @@ -211,8 +247,10 @@ All devices with a loopback IP address (`ipaddress.ip_address(ip).is_loopback`) ## See also -- [`UI_ARCHITECTURE.md`](UI_ARCHITECTURE.md) — GTK frontend +- [`UI_ARCHITECTURE.md`](../archive/UI_ARCHITECTURE.md) — GTK frontend (archived) - [`SSDP.md`](SSDP.md) — SSDP protocol detail - [`MDNS.md`](MDNS.md) — mDNS protocol detail -- [`COMMUNITY_OVERRIDES.md`](COMMUNITY_OVERRIDES.md) — user config overlays -- [`MAINTENANCE.md`](MAINTENANCE.md) — config paths, logging, debugging +- [`WSD.md`](WSD.md) — WS-Discovery protocol detail +- [`NETBIOS.md`](NETBIOS.md) — NetBIOS discovery detail +- [`COMMUNITY_OVERRIDES.md`](../contributing/COMMUNITY_OVERRIDES.md) — user config overlays +- [`MAINTENANCE.md`](../operations/MAINTENANCE.md) — config paths, logging, debugging diff --git a/docs/reference/MDNS.md b/docs/reference/MDNS.md new file mode 100644 index 00000000..36651789 --- /dev/null +++ b/docs/reference/MDNS.md @@ -0,0 +1,179 @@ +# mDNS in NetNeighbor + +## Protocol overview + +**mDNS** (multicast DNS / DNS-SD) advertises services on the local network under `*.local.` names. +NetNeighbor uses `zeroconf` browsing callbacks; it does not perform an active LAN scan. + +Typical service types discovered: + +| Type | Meaning | +|------|---------| +| `_http._tcp` | Web UI | +| `_smb._tcp`, `_microsoft-ds._tcp` | File sharing | +| `_ssh._tcp` | SSH | +| `_ftp._tcp` | FTP | +| `_telnet._tcp` | Telnet | +| `_esp3d._tcp` | ESP3D firmware | + +## Code map + +| Area | File / symbol | Role | +|------|---------------|------| +| Provider | `discovery/mdns.py` | `MDNSDiscovery` — zeroconf browser/listener, TXT decode, host aggregation | +| Contract | `discovery/base.py` | `BaseDiscovery._emit("device", payload)` → normalized dict to manager | +| Orchestration | `discovery/manager.py` | Receives `mdns` payloads, applies overrides, stores and notifies | +| Mapping hints | `config/device_types.json` | Per-service defaults (`type`, `icon`, `default_port`) | +| UI payload | `utils/details_payload.py` | `build_mdns_payload` — per-service sections for the Services tab | +| Rules | `config/mdns_rules.json` | TXT → summary line mappings and optional `type_rules` | + +## Browse strategy + +- Service types from `config/device_types.json` (`mdns` section) are browsed immediately. +- **DNS-SD enumeration** (`_services._dns-sd._udp`) runs in background to catch unlisted types. +- Enumeration repeats on a timer and on `refresh()` — no types need to be listed statically. + +## Host-level aggregation + +mDNS announces per-service. NetNeighbor aggregates services to one logical host entry: + +1. Track per-service payloads `(service_type, instance_name)` +2. Map each service to a host key — the **SRV target** (`ServiceInfo.server`, e.g. + `DESKTOP-LUCTW.local.`), unique per machine; fallback to IP, then instance hostname +3. Emit an aggregated payload with all services under `metadata["services"]` + +A device like ESP3D exposing both `_esp3d._tcp` and `_telnet._tcp` appears as one entry +with both services visible in the Details dialog. + +## Multi-homed hosts and the local machine + +An important real-world case (hit on the PC hosting NetNeighbor itself — see +`utils/local_host.py`): a Windows host with several network interfaces advertises **all** +its addresses in one mDNS record — real LAN NIC (DHCP), VirtualBox/Hyper-V host-only +switches (`192.168.56.1`, `192.168.53.1`, …), and APIPA `169.254.x.x` fallbacks on +disconnected adapters. Two consequences the pipeline must absorb: + +- **Unstable address ordering.** zeroconf returns A/AAAA records in no guaranteed order, + so trusting `addresses[0]` makes the same host flap between its interfaces across + resolutions. Each flap used to materialise as a *distinct* device row (device keys are + endpoint-based), so one PC showed up 3–4 times — and since hide/monitor prefs match by + `host:name:` when no MAC/UID is available, hiding one row hid them all. + Fix: `choose_best_address()` ranks candidates (routable LAN IPv4 → virtual-switch IPv4 → + routable IPv6 → link-local) with a deterministic tie-break, both when building a + per-service payload and across rows when aggregating a host. +- **Partial record sets.** Ranking alone is not enough: a zeroconf resolution can + momentarily surface *only* the APIPA A record, so the "best" of that set is still + link-local. Each such flap retired the LAN endpoint (offline) — and since offline + non-monitored rows are dropped, the host vanished from the UI between flips. Fix: + `_sticky_host_ip()` remembers the last rank-0 (routable) address per host for + `_STICKY_HOST_IP_TTL_S` (10 min) and refuses to downgrade the aggregate endpoint while + that memory is fresh; a *new* routable address (DHCP renewal) still replaces it + immediately, and a host that genuinely lost its LAN falls back after the TTL. +- **Host key must not be the IP.** Keying hosts by IP split a multi-homed machine into one + aggregate per interface and the stale-endpoint retirement in `_on_service_change` never + fired. Keying by the SRV target keeps one aggregate; when the chosen endpoint changes + (e.g. DHCP renewal), the previous endpoint is emitted offline and replaced. + +The **local machine** is a further special case: Windows never answers WSD probes sent +from the host itself (verified with `fdrespub` running and a Private network profile — +remote hosts answer, the local stack does not), and NetBIOS browsing does not return the +local host either. Its only discovery rows are incidental mDNS adverts from user apps +(e.g. Spotify's `_spotify-connect._tcp`, which carries no host identity and would leave +the PC in "Unknown Devices" with a speaker icon). The manager therefore classifies any +still-unknown device whose IP belongs to a local interface as `computer` +(`_apply_local_host_identity` in `discovery/manager.py`, flag `metadata["local_host"]`); +explicit user type overrides still win. + +## Legacy-unicast resolution fallback + +Another real-world case (hit on "LUC-NAS", a Samba host with an embedded mDNS responder): +some responders announce PTRs — or their PTRs keep echoing through other clients' +known-answer sections — but **never answer standard multicast queries**, neither QM nor QU. +`zc.get_service_info()` then always returns `None` and the host silently never appears, +even though "discovery messages" for it are visible in the logs. Such responders do answer +**one-shot legacy queries** (RFC 6762 §6.7): a query sent from an ephemeral port gets a +unicast reply, recognisable by its TTL ≤ 10. + +`_legacy_unicast_service_info()` handles this: when `get_service_info()` fails, the +instance label (must look like a hostname — no spaces/punctuation) is resolved as +`