Private/MonsterCore.psm1
|
# ============================================================================== # MONSTER SCRIPT ENTERPRISE - CORE MODULE # Файл: Private\MonsterCore.psm1 # Назначение: Инфраструктурный фундамент (Логирование, Event Log, Диалоги, Safety) # ============================================================================== # Глобальные переменные модуля для хранения состояния логирования $script:LogFile = $null $script:LogContext = "CORE" $script:VerboseMode = $false # Вспомогательная функция определения текущей директории модуля/скрипта function Get-MonsterScriptDir { $dir = $PSScriptRoot if (-not $dir -and $MyInvocation.MyCommand.Path) { $dir = Split-Path -Parent $MyInvocation.MyCommand.Path } if (-not $dir) { $dir = (Get-Location).Path } return $dir } # ------------------------------------------------------------------------------ # 1. ПОДСИСТЕМА ЛОГИРОВАНИЯ И EVENT VIEWER # ------------------------------------------------------------------------------ function Initialize-MonsterLogging { param( [Parameter(Mandatory = $true)] [string]$ScriptName, [switch]$VerboseLogging ) $script:VerboseMode = $VerboseLogging $scriptDir = Get-MonsterScriptDir # Определяем безопасный путь для логов: в AppData для установленного модуля, либо в корне проекта при разработке if ($scriptDir -like "*Program Files*") { $logsDir = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) "MonsterScript\Logs" } else { $moduleRoot = Split-Path (Split-Path $scriptDir -Parent) -Parent $logsDir = Join-Path $moduleRoot "Logs" if (-not (Test-Path $logsDir)) { $logsDir = Join-Path $scriptDir "Logs" # Запасной вариант рядом } } if (-not (Test-Path $logsDir)) { try { New-Item -ItemType Directory -Path $logsDir -Force | Out-Null } catch { $logsDir = [System.IO.Path]::GetTempPath() } } $timestamp = (Get-Date).ToString("yyyyMMdd") $suffix = if ($script:VerboseMode) { "_verbose.log" } else { ".log" } $script:LogFile = Join-Path $logsDir "$ScriptName$suffix" # Инициализация Event Log источника в журнале "Monster" $sourceName = "Monster_$ScriptName" try { if (-not [System.Diagnostics.EventLog]::SourceExists($sourceName)) { New-EventLog -LogName "Monster" -Source $sourceName -ErrorAction Stop } } catch { Write-Verbose "Не удалось зарегистрировать источник EventLog [$sourceName]: $_" } } function Write-Log { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateSet("INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL", "VERBOSE")] [string]$Level, [Parameter(Mandatory = $true)] [string]$Message, [string]$Context = "" ) if (-not $script:LogContext) { $script:LogContext = "CORE" } $activeContext = if (-not [string]::IsNullOrWhiteSpace($Context)) { $Context } else { $script:LogContext } if ($Level -eq "VERBOSE" -and -not $script:VerboseMode) { return } $dateTime = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss") $logLine = "[$dateTime] [$Level] [$activeContext] $Message" # 1. Запись в файл if ($script:LogFile) { try { Add-Content -Path $script:LogFile -Value $logLine -Encoding UTF8 -ErrorAction SilentlyContinue } catch {} } # 2. Вывод в консоль switch ($Level) { "SUCCESS" { Write-Host $logLine -ForegroundColor Green } "WARNING" { Write-Host $logLine -ForegroundColor Yellow } "ERROR" { Write-Host $logLine -ForegroundColor Red } "CRITICAL" { Write-Host $logLine -ForegroundColor DarkRed -BackgroundColor White } "VERBOSE" { Write-Host $logLine -ForegroundColor Gray } default { Write-Host $logLine -ForegroundColor Cyan } } # 3. Интеграция с Windows Event Viewer $sourceName = "Monster_launcher" try { if ([System.Diagnostics.EventLog]::SourceExists($sourceName)) { $eventType = switch ($Level) { "SUCCESS" { [System.Diagnostics.EventLogEntryType]::Information } "WARNING" { [System.Diagnostics.EventLogEntryType]::Warning } "ERROR" { [System.Diagnostics.EventLogEntryType]::Error } "CRITICAL" { [System.Diagnostics.EventLogEntryType]::Error } default { [System.Diagnostics.EventLogEntryType]::Information } } if ($script:VerboseMode -or $Level -ne "VERBOSE") { Write-EventLog -LogName "Monster" -Source $sourceName -EventId 1000 -EntryType $eventType -Message "$($activeContext): $Message" -ErrorAction SilentlyContinue } } } catch {} } # ------------------------------------------------------------------------------ # 2. ИНТЕРАКТИВНЫЕ ДИАЛОГИ (REQUEST-USERCONSENT) # ------------------------------------------------------------------------------ function Request-UserConsent { param( [Parameter(Mandatory = $true)] [string]$Message, [int]$TimeoutSeconds = 10, [bool]$DefaultActionIfTimeout = $false, [string]$ActionYesLabel = "Да (Y)", [string]$ActionNoLabel = "Нет / Отмена (N)" ) if (-not [Environment]::UserInteractive) { Write-Log -Level "INFO" -Message "Неинтерактивный режим. Автоматический выбор дефолта: $DefaultActionIfTimeout" -Context "CORE" return $DefaultActionIfTimeout } Write-Host "`n==============================================" -ForegroundColor Yellow Write-Host " [MONSTER SYSTEM NOTICE]" -ForegroundColor Yellow Write-Host "==============================================" -ForegroundColor Yellow Write-Host "$Message" -ForegroundColor White Write-Host "----------------------------------------------" -ForegroundColor Gray Write-Host "Таймаут: $TimeoutSeconds сек. По умолчанию: $(if($DefaultActionIfTimeout){'ДА'}else{'НЕТ'})" -ForegroundColor DarkGray Write-Host "Нажмите [Y] - $ActionYesLabel | [N] - $ActionNoLabel" -ForegroundColor Cyan $sw = [Diagnostics.Stopwatch]::StartNew() while ($sw.ElapsedMilliseconds -lt ($TimeoutSeconds * 1000)) { if ([Console]::KeyAvailable) { $key = [Console]::ReadKey($true) if ($key.Key -eq 'Y') { Write-Host "`n[Выбор пользователя]: ДА" -ForegroundColor Green return $true } if ($key.Key -eq 'N' -or $key.Key -eq 'Escape') { Write-Host "`n[Выбор пользователя]: НЕТ" -ForegroundColor Red return $false } } Start-Sleep -Milliseconds 100 } Write-Host "`n[Таймаут истек]. Применен выбор по умолчанию: $(if($DefaultActionIfTimeout){'ДА'}else{'НЕТ'})" -ForegroundColor DarkYellow return $DefaultActionIfTimeout } # ------------------------------------------------------------------------------ # 3. ИНТЕЛЛЕКТУАЛЬНЫЕ ПРОВЕРКИ (DND & ACTIVE HOURS) # ------------------------------------------------------------------------------ function Test-MonsterActiveHours { try { $currentHour = (Get-Date).Hour $startHour = $null $endHour = $null $policyPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" if (Test-Path $policyPath) { $pStart = (Get-ItemProperty -Path $policyPath -Name "ActiveHoursStart" -ErrorAction SilentlyContinue).ActiveHoursStart $pEnd = (Get-ItemProperty -Path $policyPath -Name "ActiveHoursEnd" -ErrorAction SilentlyContinue).ActiveHoursEnd if ($null -ne $pStart -and $null -ne $pEnd) { $startHour = [int]$pStart $endHour = [int]$pEnd } } if ($null -eq $startHour) { $uxPath = "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" if (Test-Path $uxPath) { $uStart = (Get-ItemProperty -Path $uxPath -Name "ActiveHoursStart" -ErrorAction SilentlyContinue).ActiveHoursStart $uEnd = (Get-ItemProperty -Path $uxPath -Name "ActiveHoursEnd" -ErrorAction SilentlyContinue).ActiveHoursEnd if ($null -ne $uStart -and $null -ne $uEnd) { $startHour = [int]$uStart $endHour = [int]$uEnd } } } if ($null -eq $startHour -or $null -eq $endHour) { return $false } if ($startHour -le $endHour) { return ($currentHour -ge $startHour -and $currentHour -lt $endHour) } else { return ($currentHour -ge $startHour -or $currentHour -lt $endHour) } } catch { Write-Log -Level "VERBOSE" -Message "Ошибка при проверке Active Hours: $_" -Context "CORE" return $false } } function Test-MonsterDndState { $isDndActive = $false try { $pathW11 = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings" $dndVal = (Get-ItemProperty -Path $pathW11 -Name "NOC_GLOBAL_SETTING_DND" -ErrorAction Stop).NOC_GLOBAL_SETTING_DND if ($dndVal -eq 1) { $isDndActive = $true } } catch {} if (-not $isDndActive) { try { $pathW10 = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\FocusAssist" $stateVal = (Get-ItemProperty -Path $pathW10 -Name "State" -ErrorAction Stop).State if ($stateVal -gt 0) { $isDndActive = $true } } catch {} } return $isDndActive } # ------------------------------------------------------------------------------ # 4. ГЛАВНАЯ ФУНКЦИЯ ПРОВЕРКИ ОКРУЖЕНИЯ (ASSERT-MONSTERSAFETY) # ------------------------------------------------------------------------------ function Assert-MonsterExecutionSafety { [CmdletBinding()] param( [switch]$IsAutoStart ) $isInteractive = [Environment]::UserInteractive # 1. Проверка прав Администратора $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $isAdmin) { Write-Log -Level "CRITICAL" -Message "Скрипт запущен без прав Администратора! Обслуживание системы невозможно." -Context "CORE" return $false } # Вспомогательный блок для вызова task_manager.ps1 (надежный поиск рядом в Private) $triggerReschedule = { param([int]$DelayMinutes = 60) $scriptDir = Get-MonsterScriptDir $managerScript = Join-Path $scriptDir "task_manager.ps1" if (Test-Path $managerScript) { Write-Log -Level "INFO" -Message "Запрос репланирования Auto-задачи через task_manager.ps1 (сдвиг на $DelayMinutes минут)..." -Context "CORE" & $managerScript -Reschedule -Minutes $DelayMinutes } else { Write-Log -Level "ERROR" -Message "Не найден task_manager.ps1 по пути: $managerScript" -Context "CORE" } } # ============================================================================== # УРОВЕНЬ 1: ПРОВЕРКА АКТИВНЫХ ЧАСОВ (ACTIVE HOURS) # ============================================================================== $isActiveHours = Test-MonsterActiveHours if ($isActiveHours) { Write-Log -Level "WARNING" -Message "Обнаружены активные рабочие часы системы (Active Hours)." -Context "CORE" if ($IsAutoStart -or -not $isInteractive) { # Авторежим: тихо уходим в реплан Write-Log -Level "INFO" -Message "Автозапуск в Active Hours. Отмена сеанса и перепланировка." -Context "CORE" & $triggerReschedule 60 return $false } else { # Ручной/интерактивный запуск: спрашиваем единый раз $consent = Request-UserConsent ` -Message "Внимание! Сейчас идут активные часы системы. Вы хотите запустить обслуживание?" ` -TimeoutSeconds 15 ` -DefaultActionIfTimeout $false ` -ActionYesLabel "Принудительно начать" ` -ActionNoLabel "Отменить" if (-not $consent) { # Ручной отказ — завершаемся молча без реплана Write-Log -Level "INFO" -Message "Пользователь отменил запуск во время активных часов. Выход без реплана." -Context "CORE" return $false } # ВАЖНО: Если пользователь сказал «ДА» — выходим сразу с $true! # Проверка DND полностью ИГНОРИРУЕТСЯ, чтобы не задавать повторных вопросов. Write-Log -Level "SUCCESS" -Message "Получен принудительный мандат пользователя. Автоматический обход проверки DND." -Context "CORE" return $true } } # ============================================================================== # УРОВЕНЬ 2: ПРОВЕРКА DND / FOCUS ASSIST # Выполняется ТОЛЬКО если Active Hours неактивны (пользователь с мандатом сюда не доходит) # ============================================================================== $isDndActive = Test-MonsterDndState if ($isDndActive) { Write-Log -Level "WARNING" -Message "Обнаружен активный режим концентрации (DND / Focus Assist)." -Context "CORE" if ($IsAutoStart -or -not $isInteractive) { # Авторежим: тихо уходим в реплан Write-Log -Level "INFO" -Message "Автозапуск при активном DND. Отмена сеанса и перепланировка." -Context "CORE" & $triggerReschedule 30 return $false } else { # Ручной запуск: спрашиваем только про DND (так как Active Hours были чисты) $consent = Request-UserConsent ` -Message "Внимание! В системе включен режим DND (концентрация/игра). Запустить очистку?" ` -TimeoutSeconds 15 ` -DefaultActionIfTimeout $false ` -ActionYesLabel "Запустить всё равно" ` -ActionNoLabel "Отложить" if (-not $consent) { Write-Log -Level "INFO" -Message "Пользователь отложил запуск из-за DND. Выход без реплана." -Context "CORE" return $false } } } Write-Log -Level "SUCCESS" -Message "Все проверки безопасности и окружения успешно пройдены." -Context "CORE" return $true } # Экспорт публичных функций модуля Export-ModuleMember -Function Initialize-MonsterLogging, Write-Log, Request-UserConsent, Test-MonsterActiveHours, Test-MonsterDndState, Assert-MonsterExecutionSafety |