Files
powershell-scripts/ApiGit/Users/userListNotifics.ps1
T
marco.locatelli@steamware.net f11d2ac73a creazione script gitlab user list
2026-05-05 16:27:56 +02:00

193 lines
6.9 KiB
PowerShell

<#
.SYNOPSIS
Recupera utenti GitLab per ID 1-100 e scrive output in C:\Steamware\Logs\Gitlab\GitlabUsers.log
#>
#importo file contenente configurazioni
. .\ApiGit\ApiGitResources\ApiScriptsConfig.ps1
#importo file contenente funzioni
. .\ApiGit\ApiGitResources\ApiScriptsFunctions.ps1
$GitlabUrl = "gitlab.steamware.net"
$PrivateToken = $tokenGitlab
# Configurazione
$StartId = 1
$EndId = 31
$LogDir = "C:\Steamware\Logs\Gitlab"
$LogFile = Join-Path -Path $LogDir -ChildPath "GitlabUsers.log"
# Crea cartella log se non esiste
try {
if (-not (Test-Path -Path $LogDir)) {
New-Item -Path $LogDir -ItemType Directory -Force | Out-Null
}
}
catch {
Write-Error "Impossibile creare la cartella di log $LogDir. Errore: $($_.Exception.Message)"
exit 1
}
# Helper: serializza in JSON su singola riga compatibile PS5/PS7
function ToSingleLineJson {
param($Object, $Depth = 10)
$json = $Object | ConvertTo-Json -Depth $Depth
return ($json -replace "`r?`n", " " -replace "\s{2,}", " ").Trim()
}
# Normalizza baseUrl per includere schema se mancante
if ($GitlabUrl -notmatch '^https?://') {
$baseUrl = "https://$GitlabUrl".TrimEnd('/')
}
else {
$baseUrl = $GitlabUrl.TrimEnd('/')
}
# Header autenticazione
$headers = @{ "PRIVATE-TOKEN" = $PrivateToken }
# Inizializza file di log (sovrascrive se esiste)
$startLine = "INFO [{0}] Starting GitLab users retrieval for IDs {1}-{2}" -f (Get-Date -Format o), $StartId, $EndId
$startLine | Out-File -FilePath $LogFile -Encoding UTF8
$retrieved = 0
$errors = 0
# inizializza contatore per numeratore
$counter = 1
$total = $EndId - $StartId + 1
for ($id = $StartId; $id -le $EndId; $id++) {
$url = "$baseUrl/api/v4/users/$id"
# crea prefisso numerato e separatore (es. ----- 001/100 -----)
$num = "{0:D3}" -f $counter
$separator = "----- $num/$total -----"
try {
# Recupera dati utente
$user = Invoke-RestMethod -Uri $url -Headers $headers -Method Get -ErrorAction Stop
$userJson = ToSingleLineJson -Object $user -Depth 10
# --- Recupero impostazioni notifiche robusto ---
$notif = $null
$notifLevel = "unavailable"
$notifDetails = ""
$err1 = $null; $err2 = $null; $err3 = $null
# 1) Prova endpoint per user specifico: /users/:id/notification_settings
try {
$notifUrlUser = "$baseUrl/api/v4/users/$id/notification_settings"
$notif = Invoke-RestMethod -Uri $notifUrlUser -Headers $headers -Method Get -ErrorAction Stop
}
catch {
$notif = $null
$err1 = $_
}
# 2) Se nulla, prova query param ?sudo=<id> su /notification_settings
if ($notif -eq $null) {
try {
$notifUrlSudoParam = "$baseUrl/api/v4/notification_settings?sudo=$id"
$notif = Invoke-RestMethod -Uri $notifUrlSudoParam -Headers $headers -Method Get -ErrorAction Stop
}
catch {
$notif = $null
$err2 = $_
}
}
# 3) Se ancora nulla, prova header Sudo (copia headers per non modificare l'originale)
if ($notif -eq $null) {
try {
$headersWithSudo = @{}
foreach ($k in $headers.Keys) { $headersWithSudo[$k] = $headers[$k] }
$headersWithSudo["Sudo"] = [string]$id
$notifUrlSudoHeader = "$baseUrl/api/v4/notification_settings"
$notif = Invoke-RestMethod -Uri $notifUrlSudoHeader -Headers $headersWithSudo -Method Get -ErrorAction Stop
}
catch {
$notif = $null
$err3 = $_
}
}
# Analizza risultato o logga dettagli diagnostici
if ($notif -ne $null) {
if ($notif.PSObject.Properties.Name -contains "level") {
$notifLevel = $notif.level
}
elseif ($notif.PSObject.Properties.Name -contains "notification_level") {
$notifLevel = $notif.notification_level
}
else {
$notifLevel = "found_object"
}
if ($notifLevel -eq "custom" -and $notif.email_events -ne $null) {
$notifDetails = ToSingleLineJson -Object $notif.email_events -Depth 5
}
else {
$notifDetails = ToSingleLineJson -Object $notif -Depth 5
}
}
else {
# dettaglio diagnostico: registra gli status code e body di eventuali errori
$diag = @()
foreach ($e in @($err1, $err2, $err3)) {
if ($null -ne $e) {
$status = "unknown"
$body = ""
try {
if ($e.Exception.Response -ne $null) {
$status = $e.Exception.Response.StatusCode.value__
$stream = $e.Exception.Response.GetResponseStream()
if ($stream -ne $null) {
$sr = New-Object System.IO.StreamReader($stream)
$body = $sr.ReadToEnd()
$sr.Close()
}
}
} catch {}
$diag += @{ status = $status; message = ($e.Exception.Message -replace "`r?`n"," "); body = $body }
}
}
$diagJson = ($diag | ConvertTo-Json -Depth 5) -replace "`r?`n"," "
$notifLevel = "unavailable"
$notifDetails = "diag=" + $diagJson
}
# --- fine recupero notifiche ---
# Scrive riga log con separatore, dati utente e livello notifiche
$line = "{0} `nINFO [{1}] USER_FOUND id={2} notif_level={3} notif_details={4} data={5}" -f $separator, (Get-Date -Format o), $id, $notifLevel, $notifDetails, $userJson
$line | Out-File -FilePath $LogFile -Encoding UTF8 -Append
$retrieved++
}
catch {
$status = "unknown"
try {
if ($_.Exception.Response -ne $null) {
$status = $_.Exception.Response.StatusCode.value__
}
} catch { $status = "unknown" }
if ($status -eq 404) {
$line = "{0} `nWARN [{1}] USER_NOT_FOUND id={2} status=404 message=Not Found" -f $separator, (Get-Date -Format o), $id
}
else {
$msg = $_.Exception.Message -replace "`r?`n", " "
$line = "{0} `nERROR [{1}] USER_ERROR id={2} status={3} message={4}" -f $separator, (Get-Date -Format o), $id, $status, $msg
}
$line | Out-File -FilePath $LogFile -Encoding UTF8 -Append
$errors++
}
$counter++
Start-Sleep -Milliseconds 200
}
$endLine = "INFO [{0}] Completed. Retrieved={1} Errors={2}" -f (Get-Date -Format o), $retrieved, $errors
$endLine | Out-File -FilePath $LogFile -Encoding UTF8 -Append
Write-Host "Fatto. Log salvato in $LogFile. Utenti recuperati: $retrieved. Errori: $errors."