Загрузка данных


[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Set-Location $PSScriptRoot

# =====================================================================
# НАСТРОЙКИ: ВСТАВЛЯЙ ССЫЛКУ И КАТЕГОРИЮ ТОЛЬКО СЮДА
# =====================================================================

# 1. Вставь полную ссылку на раздел, который открыт в браузере
$startUrl = "https://main.atb.su/normdocs/Lists/Docs/ByCategory.aspx" 

# 2. Вставь категорию, которую сейчас ищем (например: "Порядок", "Инструкция", "Положение")
$targetCategory = "Порядок" 

# =====================================================================

# Создаем папку под конкретную категорию, чтобы они не перемешались
$downloadDir = "downloads_$targetCategory"
if (!(Test-Path $downloadDir)) { New-Item -ItemType Directory -Path $downloadDir | Out-Null }

# Вычисляем базовый домен из твоей ссылки (чтобы не писать вручную)
$uri = [System.Uri]$startUrl
$baseDomain = "$($uri.Scheme)://$($uri.Host)"

$currentUrl = $startUrl
$pageNum = 1

Write-Host "===================================================" -ForegroundColor Cyan
Write-Host " РЕЖИМ СБОРА ДОКУМЕНТОВ" -ForegroundColor Cyan
Write-Host " Категория: $targetCategory" -ForegroundColor Cyan
Write-Host " Сохраняем в папку: $downloadDir" -ForegroundColor Cyan
Write-Host "===================================================" -ForegroundColor Cyan

# Цикл: будет работать, пока есть кнопка "Следующая страница"
while ($currentUrl) {
    Write-Host "`n[ Страница $pageNum ] Сканирую список..." -ForegroundColor Yellow
    
    try {
        # Прикидываемся браузером и запрашиваем страницу
        $page = Invoke-WebRequest -Uri $currentUrl -UseDefaultCredentials -TimeoutSec 30
    } catch {
        Write-Host "  [!] Ошибка загрузки страницы: $($_.Exception.Message)" -ForegroundColor Red
        break
    }

    # Ищем все строки таблицы (<tr>), которые относятся к документам
    $rows = [regex]::Matches($page.Content, '(?is)<tr[^>]*class="[^"]*ms-itmhover[^"]*"[^>]*>(.*?)</tr>')
    
    $downloadedOnPage = 0
    foreach ($row in $rows) {
        $rowHtml = $row.Groups[1].Value
        
        # --- ПРОВЕРКА 1: Статус "Действителен" ---
        if ($rowHtml -notmatch "Действителен") { continue }
        
        # --- ПРОВЕРКА 2: Совпадение категории ---
        if ($rowHtml -notmatch $targetCategory) { continue }
        
        # --- ПРОВЕРКА 3: Ищем прямую ссылку на файл (Attachments) ---
        if ($rowHtml -match 'href="([^"]*?Attachments/[^"]+)"' -or $rowHtml -match 'href="([^"]+?\.(pdf|docx?|xlsx?))"') {
            $link = [System.Web.HttpUtility]::HtmlDecode($matches[1])
            
            # Собираем правильную ссылку
            if ($link -match "^http") {
                $fileUrl = $link
            } else {
                if (-not $link.StartsWith("/")) { $link = "/$link" }
                $fileUrl = "$baseDomain$link"
            }

            # Достаем красивое имя файла из ссылки
            $fileName = [System.Web.HttpUtility]::UrlDecode($fileUrl.Split('/')[-1])
            $savePath = Join-Path $downloadDir $fileName

            # Проверяем, не скачали ли мы его уже (чтобы не качать дубликаты)
            if (-not (Test-Path $savePath)) {
                Write-Host "  [+] Скачиваю: $fileName" -ForegroundColor Green
                try {
                    Invoke-WebRequest -Uri $fileUrl -OutFile $savePath -UseDefaultCredentials
                    $downloadedOnPage++
                } catch {
                    Write-Host "  [!] Ошибка скачивания файла: $fileName" -ForegroundColor Red
                }
            } else {
                Write-Host "  [-] Уже скачан, пропускаю: $fileName" -ForegroundColor DarkGray
            }
        }
    }
    
    Write-Host "Скачано файлов на этой странице: $downloadedOnPage" -ForegroundColor Cyan

    # --- ИЩЕМ ПЕРЕХОД НА СЛЕДУЮЩУЮ СТРАНИЦУ ---
    # SharePoint прячет ссылку на следующую страницу в параметре Paged=TRUE (и без PagedPrev)
    $nextPageMatch = [regex]::Match($page.Content, 'href="([^"]*Paged=TRUE(?:(?!PagedPrev).)*?)"')
    if ($nextPageMatch.Success) {
        $nextUrlRaw = [System.Web.HttpUtility]::HtmlDecode($nextPageMatch.Groups[1].Value)
        
        if ($nextUrlRaw -match "^http") {
            $currentUrl = $nextUrlRaw
        } elseif ($nextUrlRaw.StartsWith("?")) {
            $currentUrl = $startUrl.Split('?')[0] + $nextUrlRaw
        } else {
            if (-not $nextUrlRaw.StartsWith("/")) { $nextUrlRaw = "/$nextUrlRaw" }
            $currentUrl = "$baseDomain$nextUrlRaw"
        }
        $pageNum++
    } else {
        Write-Host "`n[КНОПКА 'ДАЛЕЕ' НЕ НАЙДЕНА] Все страницы пройдены." -ForegroundColor Green
        $currentUrl = $null # Останавливаем цикл
    }
}

Write-Host "`n--- СБОР ДОКУМЕНТОВ ПОЛНОСТЬЮ ЗАВЕРШЕН ---" -ForegroundColor White
Read-Host "Нажмите Enter для закрытия окна"