Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName System.IO.Compression Add-Type -AssemblyName System.IO.Compression.FileSystem # CRC32 compilado em C#: muito mais rapido que loops byte a byte em PowerShell. Add-Type -TypeDefinition @' using System; using System.IO; public static class CalliuCrc { static readonly uint[] Table = Build(); static uint[] Build() { var t = new uint[256]; for (uint i=0; i<256; i++) { uint c=i; for(int j=0;j<8;j++) c=(c&1)!=0 ? (c>>1)^0xEDB88320u : c>>1; t[i]=c; } return t; } public static string Hash(string path) { uint crc=0xffffffffu; using(var s=new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072)) { byte[] b=new byte[131072]; int n; while((n=s.Read(b,0,b.Length))>0) for(int i=0;i>8)^Table[(crc^b[i])&255]; } return (~crc).ToString("x8"); } } '@ $form = New-Object Windows.Forms.Form $form.Text = 'Gerador Update CalliuWS - Independente RAPIDO' $form.Width = 760; $form.Height = 510; $form.StartPosition = 'CenterScreen' $form.Font = New-Object Drawing.Font('Segoe UI', 10) $form.BackColor = [Drawing.Color]::FromArgb(25,32,43) $form.ForeColor = [Drawing.Color]::White $lbl = New-Object Windows.Forms.Label $lbl.Text = 'Pasta dos arquivos do cliente (Atualizacao):'; $lbl.Location = New-Object Drawing.Point(18,16); $lbl.AutoSize = $true $form.Controls.Add($lbl) $txt = New-Object Windows.Forms.TextBox $txt.Location = New-Object Drawing.Point(18,45); $txt.Width = 560 $txt.Text = 'C:\AppServ\www\Gerador de Update\Atualização' $form.Controls.Add($txt) $browse = New-Object Windows.Forms.Button $browse.Text = 'Selecionar'; $browse.Location = New-Object Drawing.Point(590,42); $browse.Size = New-Object Drawing.Size(120,32) $form.Controls.Add($browse) $browse.Add_Click({ $dlg = New-Object Windows.Forms.FolderBrowserDialog if ([IO.Directory]::Exists($txt.Text)) { $dlg.SelectedPath = $txt.Text } if ($dlg.ShowDialog() -eq 'OK') { $txt.Text = $dlg.SelectedPath } }) $note = New-Object Windows.Forms.Label $note.Text = '1) VERIFICAR lista arquivos rapidamente. 2) GERAR UPDATE compacta apenas arquivos novos/alterados.' $note.Location = New-Object Drawing.Point(18,85); $note.Size = New-Object Drawing.Size(700,40) $form.Controls.Add($note) $scan = New-Object Windows.Forms.Button $scan.Text = '1 - VERIFICAR'; $scan.Location = New-Object Drawing.Point(18,132) $scan.Size = New-Object Drawing.Size(195,44) $form.Controls.Add($scan) $generate = New-Object Windows.Forms.Button $generate.Text = '2 - GERAR UPDATE'; $generate.Location = New-Object Drawing.Point(225,132) $generate.Size = New-Object Drawing.Size(235,44); $generate.BackColor = [Drawing.Color]::FromArgb(0,140,75) $generate.ForeColor = [Drawing.Color]::White; $generate.Enabled = $false $form.Controls.Add($generate) $progress = New-Object Windows.Forms.ProgressBar $progress.Location = New-Object Drawing.Point(18,193); $progress.Size = New-Object Drawing.Size(692,24) $form.Controls.Add($progress) $status = New-Object Windows.Forms.Label $status.Text = 'Selecione uma COPIA da pasta Atualizacao e clique em VERIFICAR.' $status.Location = New-Object Drawing.Point(18,225); $status.Size = New-Object Drawing.Size(700,35) $form.Controls.Add($status) $log = New-Object Windows.Forms.TextBox $log.Location = New-Object Drawing.Point(18,265); $log.Size = New-Object Drawing.Size(692,180) $log.Multiline = $true; $log.ReadOnly = $true; $log.ScrollBars = 'Vertical' $form.Controls.Add($log) $script:files = @(); $script:root = '' $scan.Add_Click({ try { $root = [IO.Path]::GetFullPath($txt.Text).TrimEnd('\') if (-not [IO.Directory]::Exists($root)) { throw 'Pasta inexistente.' } if ($root -match '(?i)\\upload$') { throw 'Selecione Atualizacao, nao upload.' } $upload = Join-Path $root 'upload' $status.Text = 'Listando arquivos...'; $form.Refresh() $script:files = @([IO.Directory]::EnumerateFiles($root,'*',[IO.SearchOption]::AllDirectories) | Where-Object { -not $_.StartsWith(($upload + '\'), [StringComparison]::OrdinalIgnoreCase) -and -not $_.Substring($root.Length+1).StartsWith('_calliuws_gerando_', [StringComparison]::OrdinalIgnoreCase) -and -not $_.EndsWith('.calliuws-backup',[StringComparison]::OrdinalIgnoreCase) -and [IO.Path]::GetFileName($_) -ne 'ListaPatch.txt' } | Sort-Object) if ($script:files.Count -eq 0) { throw 'Nenhum arquivo encontrado.' } $script:root = $root $generate.Enabled = $true $progress.Value = 0 $status.Text = "Verificacao concluida: $($script:files.Count) arquivos. Clique GERAR UPDATE." $log.Text = "Pasta: $root`r`nArquivos encontrados: $($script:files.Count)`r`n" } catch { $generate.Enabled = $false; [Windows.Forms.MessageBox]::Show($_.Exception.Message,'Erro ao verificar') | Out-Null } }) # Processamento em pequenos lotes no timer do WinForms. # Eventos rodam na thread da interface: nao exigem Runspace em thread separada. $timer = New-Object Windows.Forms.Timer $timer.Interval = 20 $script:state = $null function Finish-Generation([string]$errorMessage) { $timer.Stop() $scan.Enabled = $true; $browse.Enabled = $true; $txt.Enabled = $true; $generate.Enabled = $true $st = $script:state if ($null -ne $st) { if ([IO.Directory]::Exists($st.Stage)) { try { [IO.Directory]::Delete($st.Stage,$true) } catch { } } } $script:state = $null if ($errorMessage) { $status.Text = 'Erro: ' + $errorMessage [Windows.Forms.MessageBox]::Show($errorMessage,'Falha ao gerar update') | Out-Null } else { $progress.Value = 100 $message = "Concluido! Alterados: $($st.Changed) | Reutilizados: $($st.Reused) | Total: $($st.Files.Count)" $status.Text = $message $log.AppendText("`r`n"+$message+"`r`n") [Windows.Forms.MessageBox]::Show($message,'CalliuWS') | Out-Null } } $timer.Add_Tick({ $st = $script:state if ($null -eq $st) { $timer.Stop(); return } try { # Um arquivo por ciclo permite que a janela continue respondendo. if ($st.Index -lt $st.Files.Count) { $path = [string]$st.Files[$st.Index] $f = New-Object IO.FileInfo($path) if (-not $f.Exists) { throw "Arquivo desapareceu: $path" } $rel = $path.Substring($st.Root.Length+1).Replace('\','/') if ($rel.Contains([char]9) -or $rel.Contains([char]10) -or $rel.Contains([char]13)) { throw "Nome nao suportado: $rel" } $destZip = Join-Path $st.Upload ($rel.Replace('/','\')+'.zip') $stamp = $f.LastWriteTimeUtc.Ticks.ToString() $cached = $st.Old[$rel] $same = ($null -ne $cached -and $cached[1] -eq $f.Length.ToString() -and $cached[2] -eq $stamp -and [IO.File]::Exists($destZip)) if ($same) { $crc = $cached[3]; $st.Reused++ } else { $crc = [CalliuCrc]::Hash($path) $zipPath = Join-Path $st.Stage ($rel.Replace('/','\')+'.zip') [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($zipPath)) | Out-Null $zip = [IO.Compression.ZipFile]::Open($zipPath,[IO.Compression.ZipArchiveMode]::Create) try { [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$path,$rel,[IO.Compression.CompressionLevel]::Fastest) | Out-Null } finally { $zip.Dispose() } $st.Changed++ } $st.Manifest.Add(('{0} {1} {2}' -f $rel,$crc,$f.Length)) $st.Cache.Add(($rel,$f.Length,$stamp,$crc -join "`t")) $st.Index++ $progress.Value = [Math]::Min(99,[int](($st.Index*99)/$st.Files.Count)) $status.Text = "Preparando $($st.Index)/$($st.Files.Count) | Alterados: $($st.Changed) | Reutilizados: $($st.Reused)" } else { $timer.Stop() [IO.File]::WriteAllLines((Join-Path $st.Stage 'ListaPatch.txt'),$st.Manifest.ToArray(),(New-Object Text.UTF8Encoding($false))) [IO.Directory]::CreateDirectory($st.Upload) | Out-Null foreach ($zipFile in [IO.Directory]::EnumerateFiles($st.Stage,'*.zip',[IO.SearchOption]::AllDirectories)) { $relativeZip = $zipFile.Substring($st.Stage.Length+1) $dest = Join-Path $st.Upload $relativeZip [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($dest)) | Out-Null [IO.File]::Copy($zipFile,$dest,$true) } # Publicar a lista por ultimo: so anuncia novos patches apos copiar ZIPs. [IO.File]::Copy((Join-Path $st.Stage 'ListaPatch.txt'),(Join-Path $st.Upload 'ListaPatch.txt'),$true) [IO.File]::WriteAllLines((Join-Path $st.Upload '_calliuws_cache.tsv'),$st.Cache.ToArray(),(New-Object Text.UTF8Encoding($false))) Finish-Generation '' } } catch { Finish-Generation $_.Exception.Message } }) $generate.Add_Click({ if ($timer.Enabled) { return } try { $root = $script:root if (-not [IO.Directory]::Exists($root)) { throw 'Pasta inexistente.' } $upload = Join-Path $root 'upload' $stage = Join-Path $root ('_calliuws_gerando_' + [Guid]::NewGuid().ToString('N')) [IO.Directory]::CreateDirectory($stage) | Out-Null $old = @{} $cachePath = Join-Path $upload '_calliuws_cache.tsv' if ([IO.File]::Exists($cachePath)) { foreach ($line in [IO.File]::ReadAllLines($cachePath)) { $c = $line.Split([char]9) if ($c.Length -eq 4) { $old[$c[0]] = $c } } } $script:state = [pscustomobject]@{ Root=$root; Upload=$upload; Stage=$stage; Files=[string[]]$script:files; Old=$old; Cache=(New-Object 'System.Collections.Generic.List[string]'); Manifest=(New-Object 'System.Collections.Generic.List[string]'); Index=0; Changed=0; Reused=0 } $scan.Enabled = $false; $generate.Enabled = $false; $browse.Enabled = $false; $txt.Enabled = $false $progress.Value = 0; $status.Text = 'Gerando atualizacoes...' $timer.Start() } catch { Finish-Generation $_.Exception.Message } }) [void]$form.ShowDialog()