AdobeGenP.psm1

<#
    .NOTES
    --------------------------------------------------------------------------------
     Code generated by: SAPIEN Technologies, Inc., PowerShell Studio 2023 v5.8.232
     Generated on: 05-Oct-23 18:34
     Generated by: chixus
     Organization: CHXOFT
    --------------------------------------------------------------------------------
    .DESCRIPTION
        Script generated by PowerShell Studio 2023
#>



    <#
        .SYNOPSIS
            Adobe GenP tool handling
         
        .DESCRIPTION
            Download, install, update, start Adobe GenP.
         
        .PARAMETER GetVersion
            Get version of installed GenP on your PC
         
        .PARAMETER GetOnlineVersion
            Get latest version on the web.
         
        .PARAMETER Update
            Update to latest version, if there is no new version nothing will happend.
         
        .PARAMETER Uninstall
            Uninstall and completly delete GenP from PC.
         
        .EXAMPLE
                    PS C:\> Start-GenP
         
        .NOTES
            © 2023. All rights reserved.
    #>

    function Start-GenP
    {
        [CmdletBinding(ConfirmImpact = 'None',
                       SupportsShouldProcess = $true)]
        [OutputType([Microsoft.Win32.SafeHandles.SafeMemoryMappedFileHandle])]
        param
        (
            [switch]$GetVersion,
            [switch]$GetOnlineVersion,
            [switch]$Update,
            [Parameter(Mandatory = $false)]
            [switch]$Uninstall
        )
        
        function Invoke-FileDNL
        {
            param
            (
                [Parameter(Mandatory = $true,
                           Position = 1,
                           HelpMessage = 'Provide correct URL like www.google.com')]
                [uri]$URL,
                [Parameter(Mandatory = $true,
                           Position = 2,
                           HelpMessage = 'Enter filename to search on website, you can use wilcards like: file*name*.jpg')]
                [SupportsWildcards()]
                [string]$Filename,
                [Parameter(HelpMessage = 'Enter full download path to folder.')]
                [string]$Path,
                [switch]$GetLink,
                [switch]$ListFoundedFiles,
                [Parameter(HelpMessage = 'Enter full alternate filename with exstension.')]
                [string]$NewFileName,
                [switch]$SearchWebLink
            )
            
            function Get-ValidLink
            {
                [OutputType([string])]
                param
                (
                    [Parameter(Mandatory = $true)]
                    [system.Uri]$Uri
                )
                
                if ($Uri.IsAbsoluteUri)
                {
                    if (!(Test-WebLink -Uri $Uri)) { return }
                }
                else
                {
                    $test = Test-WebLink -Uri $Uri -GetLink
                    if (!$test) { return }
                    else { $Uri = $test }
                }
                return $Uri.AbsoluteUri
            }
            function Test-WebLink
            {
                [OutputType([bool])]
                param
                (
                    [Parameter(Mandatory = $true)]
                    [ValidateNotNullOrEmpty()]
                    [System.Uri]$Uri,
                    [Parameter(DontShow = $true)]
                    [switch]$GetLink
                )
                
                $ProgressPreference = 'SilentlyContinue'
                $ErrorActionPreference = 'SilentlyContinue'
                function Get-UriParentLeafQualifier
                {
                    [CmdletBinding()]
                    [OutputType([hashtable])]
                    param
                    (
                        [Parameter(Mandatory = $true)]
                        [ValidateNotNullOrEmpty()]
                        [string]$UriTest
                    )
                    
                    $UriQualifier = Split-Path -Path $UriTest -Qualifier -ErrorAction SilentlyContinue
                    $UriLeaf = Split-Path -Path $UriTest -Leaf -ErrorAction SilentlyContinue
                    $UriParent = Split-Path -Path $UriTest -Parent -ErrorAction SilentlyContinue
                    if ($UriParent -eq '') { $UriParent = $null }
                    if ($UriParent)
                    {
                        if ($UriParent) { $UriParentTest = $UriParent.Split('*\*')[0] }
                        if ($UriLeaf -eq $UriParentTest) { $UriLeaf = $null }
                        if ($UriParent -clike '*\\*') { $UriParent = $UriParent.Split('\')[2] }
                        if (($UriParent -clike '*\*') -or ($UriParent -like '*\')) { $UriParent = $UriParent.Split('\')[0] }
                    }
                    else { $UriParent = $UriLeaf; $UriLeaf = $null }
                    if ($UriLeaf) { $RestOfLeaf = $UriTest -split $UriLeaf; $UriLeaf = $UriLeaf + $RestOfLeaf[1] }
                    $Hashtable = @{
                        UriQualifier = $UriQualifier
                        UriParent    = $UriParent
                        UriLeaf         = $UriLeaf
                    }
                    return $Hashtable
                }
                function Test-NotFoundError
                {
                    [CmdletBinding()]
                    [OutputType([System.Collections.ArrayList], [System.Boolean])]
                    param
                    (
                        [Parameter(Mandatory = $true)]
                        [string]$URL,
                        [switch]$ShowQuerry
                    )
                    
                    BEGIN
                    {
                        $queries = New-Object System.Collections.ArrayList
                        function Test-Website
                        {
                            param
                            (
                                [string]$Site
                            )
                            
                            try { $request = Invoke-WebRequest -Uri $Site }
                            catch [System.Net.WebException]
                            {
                                if ([int]$_.Exception.Response.StatusCode -eq 404) { $request = [PSCustomObject]@{ Site = $site; ReturnCode = [int]$_.Exception.Response.StatusCode } }
                                else { $request = [PSCustomObject]@{ Site = $site; ReturnCode = 'another_thing' } }
                            }
                            catch { $request = [PSCustomObject]@{ Site = $site; ReturnCode = 'request_failure' } }
                            if ($request.StatusCode) { $response = $request.StatusCode }
                            else { $response = $request.ReturnCode }
                            return [PSCustomObject]@{ Site = $Site; Response = $response }
                        }
                    }
                    PROCESS
                    {
                        $404Test = Test-Website -Site $URL
                        $queries.Add($404Test) | Out-Null
                        if ($ShowQuerry) { $queries }
                    }
                    END
                    {
                        if ($queries.Response -eq 404) { return [boolean]$false }
                        else { return [boolean]$true }
                    }
                }
                if ($Uri.AbsoluteUri) { $TestOK = Test-NotFoundError -URL $Uri; if ($TestOK -eq [boolean]$true) { return [bool]$true } }
                elseif (!$Uri.PathAndQuery)
                {
                    $TempUri = Get-UriParentLeafQualifier -UriTest $Uri
                    $UriQualifier = $TempUri.UriQualifier
                    $UriParent = $TempUri.UriParent
                    $UriLeaf = $TempUri.UriLeaf
                }
                else { $UriParent = $Uri.Authority; $UriLeaf = $Uri.LocalPath }
                $TestDNS = Resolve-DnsName -Name $UriParent -Type ANY -QuickTimeout
                if (!($TestDNS)) { return [bool]$false }
                $Resolve = (Invoke-WebRequest -Uri $UriParent -UseBasicParsing -TimeoutSec 5 -ErrorAction SilentlyContinue).BaseResponse.ResponseUri.AbsoluteUri
                if (!($Resolve)) { return [bool]$false }
                else { $UriQualifier = $UriQualifier = $Uri.Scheme }
                $URLexist = Test-NotFoundError -URL $Resolve
                if (!($URLexist)) { return [bool]$false }
                if ($UriQualifier) { $UriTest = Join-Path -Path $UriParent -ChildPath $UriLeaf }
                if ($UriQualifier) { $right = Split-Path -Path $Resolve -Qualifier; if ($UriQualifier -ne $right) { $Link = "$right\\$UriTest" } }
                else { $Link = "$Resolve$UriLeaf" }
                $Err404TestPassed = Test-NotFoundError -URL $Link
                if (!$Err404TestPassed) { return [bool]$false }
                if ($GetLink) { return $Link }
                else { return [bool]$true }
            }
            function Get-UrlStatusCode
            {
                param
                (
                    [Parameter(Mandatory = $true)]
                    [uri]$TestURL
                )
                
                try { (Invoke-WebRequest -Uri $TestURL -UseBasicParsing -DisableKeepAlive -ErrorAction SilentlyContinue).StatusCode }
                catch [Net.WebException] { [int]$_.Exception.Response.StatusCode }
            }
            if (($Filename -eq "*") -or ($Filename -eq "*.*")) { return Write-Warning 'Cannot provide only wildcard.' }
            if (($GetLink) -and ([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Filename))) { return Write-Warning '-GetLink switch must be used with exact filename without wildcards.' }
            if ($Filename.Substring(0, 1) -ne "*") { $Filename = "*" + $Filename }
            if (!$Path) { $Path = Get-Location }
            $DownloadWebPage = (Invoke-WebRequest $URL).AllElements
            $FilesFinded = $DownloadWebPage.href -like $Filename
            if (!$FilesFinded) { return Write-Warning "No files found like $Filename" }
            $FileSelection = Split-Path -Path $FilesFinded -Leaf
            if ($FilesFinded.Count -gt 1) { $WEBPath = $FilesFinded.Split([Environment]::NewLine) | Select-Object -First 1 }
            else { $WEBPath = $FilesFinded }
            $WEBPath = Get-ValidLink -Uri "$WEBPath"
            $statusCode = Get-UrlStatusCode -TestURL $WEBPath -ErrorAction SilentlyContinue
            if (($statusCode -eq 0) -or (!$statusCode))
            {
                $WEBPath = "$URL" + $WEBPath
                $statusCode = Get-UrlStatusCode -TestURL $WEBPath
                if (($statusCode -eq 0) -or (!$statusCode)) { return Write-Error "Cannot find download link for searched file on the $URL" -Category InvalidResult }
            }
            if ($NewFileName) { $Filename = $NewFileName }
            else { $Filename = Split-Path $WEBPath -Leaf }
            $FullFilePath = Join-Path -Path $Path -ChildPath $Filename
            if ($GetLink -and $ListFoundedFiles) { Write-Warning "-GetLink switch should be used without -ListFoundedFiles switch." }
            if ($GetLink -and (!$ListFoundedFiles))
            {
                $CleanPath = Invoke-WebRequest -Uri $WEBPath -MaximumRedirection 0 -ErrorAction SilentlyContinue
                $WEBPath = $CleanPath.Headers.Values | Select-String -SimpleMatch $Filename
                return $WEBPath
            }
            elseif ($ListFoundedFiles) { return $FileSelection }
            if ($SearchWebLink) { return $WEBPath }
            else { Invoke-WebRequest -Uri $WEBPath -OutFile $FullFilePath -Method Get; return Write-Output "Download path: $FullFilePath" }
        }
        function Open-GenP
        {
            param
            (
                [Parameter(Mandatory = $true)]
                [ValidateNotNull()]
                [string]$Path2EXE
            )
            
            $EXE = Resolve-Path -Path $Path2EXE
            Start-Process -FilePath $EXE -WindowStyle Normal -Wait
        }
        function Get-LatestGenP
        {
            param
            (
                [Parameter(Mandatory = $false)]
                [string]$FolderPath,
                [switch]$GetVersion
            )
            
            $ProgressPreference = 'Continue'
            if ($GetVersion)
            {
                if ($FolderPath) { return Write-Error -Message 'Cannot define path for getting version' }
                $ProgressPreference = 'SilentlyContinue'
            }
            else
            {
                if (!$FolderPath) { return Write-Error -Message 'Path not defined!' }
            }
            $Counter = 6
            $ActDown = "DOwnloading latest GenP to $FolderPath"
            $ActOnst = "Installing GenP to $FolderPath"
            Write-Progress -Activity $ActDown -Status 'Getting weblink to file' -PercentComplete (($counter/12) * 100); $Counter++
            [System.Uri]$DownloadLink = ((Invoke-WebRequest -Uri 'https://www.cybermania.ws/apps/adobe-genp/').Links.href -clike '*GenP-*.7z*')[0]
            Write-Progress -Activity $ActDown -Status "Downloading from $DowloadLik" -PercentComplete (($counter/12) * 100); $Counter++
            [system.String]$FileName = ($DownloadLink -split ('/')) -clike '*.7z' -join ''
            $ver = (($FileName -split '-') -clike '*.7z') -replace '.7z', ''
            if ($GetVersion) { return $ver }
            Write-Progress -Activity $ActOnst -Status 'Downloading' -PercentComplete (($counter/12) * 100); $Counter++
            $GenP7z = Resolve-Path -Path ((Invoke-FileDNL -URL $DownloadLink -Filename $FileName -Path $env:TEMP) -replace 'Download path: ', '')
            Write-Progress -Activity $ActOnst -Status 'Installing' -PercentComplete (($counter/12) * 100); $Counter++
            Expand-7Zip -ArchiveFileName $GenP7z -TargetPath $FolderPath
            Write-Progress -Activity $ActOnst -Status 'Deleting installation' -PercentComplete (($counter/12) * 100); $Counter++
            Remove-Item -Path $GenP7z -Force
            Write-Output "GenP version $ver installed at $FolderPath"
            Write-Progress -Activity $ActOnst -Status 'Installation finished' -PercentComplete (($counter/12) * 100) -Completed
        }
        
        $ProgressPreference = 'SilentlyContinue'
        $Path = "$env:ProgramData\GenP"
        $GenPexe = "$Path\Release\AdobeGenP.exe"
        if (!(Test-Path -Path $Path -PathType Container))
        {
            if ($Update) { Write-Warning -Message 'GenP not installed.' }
            $Path = Resolve-Path -Path (New-Item -Path $env:ProgramData -ItemType Directory -Name 'GenP' -Force)
            Write-Warning -Message "GenP folder $Path does not exist, getting latest GenP"
            Get-LatestGenP -FolderPath $Path
        }
        else
        {
            $Path = Resolve-Path -Path (New-Item -Path $env:ProgramData -ItemType Directory -Name 'GenP' -Force)
        }
        if (!(Test-Path -Path $GenPexe -PathType Leaf))
        {
            if ($Update) { Write-Warning -Message 'GenP not installed.' }
            Write-Warning -Message "GenP exeutable not found, getting latest GenP"
            Get-LatestGenP -FolderPath $Path
        }
        if ($Uninstall)
        {
            Remove-Item -Path $Path -Recurse -Force
            return Write-Output "GenP uninstalled, removed folder: $Path"
        }
        if ($GetVersion) { return ((((Get-ChildItem -Path $Path -Depth 5 -Include '*.AU3')[0]) -replace '.AU3', '') -split '-')[1] }
        if ($GetOnlineVersion) { return Get-LatestGenP -GetVersion }
        if ($Update)
        {
            $Latest = (Get-LatestGenP -GetVersion)
            $Current = ((((Get-ChildItem -Path $Path -Depth 5 -Include '*.AU3')[0]) -replace '.AU3', '') -split '-')[1]
            if ($Latest -gt $Current)
            {
                Write-Output 'New version available:'
                Write-Output -InputObject $Latest
                Write-Output 'Current version:'
                Write-Output -InputObject $Current
                Write-Output 'Updating to latest version'
                Remove-Item -Path $Path -Recurse -Force
                Get-LatestGenP -FolderPath $Path
                return Write-Output 'Adobe GenP updated.'
            }
            else
            {
                Write-Output 'No update availabe.'
                Write-Output 'Current version:'
                Write-Output -InputObject $Current
                Write-Output 'Online version:'
                return Write-Output -InputObject $Latest
            }
        }
        Open-GenP -Path2EXE $GenPexe
    }