Gitea.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\Gitea.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName Gitea.Import.DoDotSource -Fallback $false
if ($Gitea_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName Gitea.Import.IndividualFiles -Fallback $false
if ($Gitea_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }

function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
 
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
 
            This provides a central location to react to files being imported, if later desired
 
        .PARAMETER Path
            The path to the file to load
 
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
 
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )

    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }

    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }

    # Import all internal classes
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\classes" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }

    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }

    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }

    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'Gitea' -Language 'en-US'

function Get-EncodedParameterString {
    <#
    .SYNOPSIS
    Converts a hashtable to GET Parameters
 
    .DESCRIPTION
    Converts a hashtable to GET Parameters.
 
    .PARAMETER parameter
    Hashtable with the GET Parameters
 
    .EXAMPLE
    Get-EncodedParameterString -parameter @{key1="value1";key2="value2"}
    Returns the string: key1=value1&key2=value2
 
    .NOTES
    General notes
    #>


    param (
        [parameter(Mandatory,Position=1)]
        [Hashtable]$parameter
    )
    $getParameter = @()
    if ($parameter) {
        foreach ($key in $parameter.Keys) {
            $value = $parameter[$key]
            if ($value) {
                switch ($value.GetType()) {
                    bool { $value = $value.ToString() }
                    Default { }
                }
                $valueEncoded = [System.Web.HttpUtility]::UrlEncode($value)
                $getParameter += "$key=$valueEncoded"
            }
        }
    }
    return ($getParameter -join "&")
}

function Get-GiteaServerRoot {
<#
.SYNOPSIS
Cleans a given URL to be used as a server-root.
 
.DESCRIPTION
Cleans a given URL to be used as a server-root.
 
.PARAMETER Url
A FQDN/URL or the server
 
.EXAMPLE
Get-DracoonServerRoot "my.server.de"
Get-DracoonServerRoot "my.server.de/"
Get-DracoonServerRoot "http://my.server.de"
Get-DracoonServerRoot "http://my.server.de/"
All versions return "https://my.server.de"
 
.NOTES
General notes
#>

    param (
        [parameter(mandatory = $true, Position=0)]
        [string]$Url
    )
    Write-PSFMessage "Getting Server-Root for $Url"
    # Strip leading /
    $serverRoot = $Url.Trim("/")
    # Strip Prefix protocoll
    $serverRoot = $serverRoot -replace "^.*:\/\/"
    $serverRoot="https://$serverRoot"
    Write-PSFMessage "Result: $serverRoot"
    $serverRoot
}

function Remove-NullFromHashtable {
    <#
    .SYNOPSIS
    Funktion zum Entfernen von $null Werten aus HashTables.
 
    .DESCRIPTION
    Funktion zum Entfernen von $null Werten aus HashTables. Dazu wird die HashTable in einen json String umgewandelt
    und anschließend per RegEx alle null-Werte entfernt. Falls InputHashmap -eq $null dann wird nichts zurückgegeben.
 
    .PARAMETER InputHashmap
    Die Eingabe-HashTable
 
    .PARAMETER Json
    Wird der Parameter gesetzt, so wird anstatt einer neuen HashTable der modifizierte json String zurück geliefert
 
    .EXAMPLE
    $hash=@{
        Name="Max"
        Surname="Mustermann"
        MiddleName=$null
        kids=@(
            @{
                Name="Maxi"
                MiddleName=$null
                Surname="Mustermann"
            },
            @{
                Name="Maxine"
                MiddleName="Christine"
        Surname="Mustermann"
            }
        )
    }
    $newHash=$hash | Remove-NullFromHashtable
    .NOTES
    General notes
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
    param (
        [Parameter(ValueFromPipeline)]
        [hashtable]$InputHashmap,
        [switch]$Json
    )

    process {
        if ($InputHashmap) {
            $tempString = $InputHashmap | ConvertTo-Json -Depth 15
            Write-PSFMessage -Level Debug "Entferne null Values aus $tempString"
            $tempString = $tempString -replace '"\w+?"\s*:\s*null,?'
            Write-PSFMessage -Level Debug "Ergebnis: $tempString"
            if ($Json) { $tempString }else {
                Write-PSFMessage -Level Debug "Erzeuge HashTable"
                $newHashmap = $tempString | ConvertFrom-Json
                $newHashmap
            }
        }
    }
}

function Connect-Gitea {
    <#
    .SYNOPSIS
    Creates a new Connection Object to a Gitea Server instance.
 
    .DESCRIPTION
    Creates a new Connection Object to a Gitea Server instance.
 
    For connecting you always need the -Url as the function needs to know where the Server is located. As a
    minimum additional information you have to provide an authorization, either as -Credential or as -AccessToken.
    The usage of a credential object as the only information is *deprecated* and should be replaces in favor of
    an OAuth workflow. For OAuth you need to configure an application within the Web-UI. For more information
    see about_Gitea.
 
    .PARAMETER Credential
    Credential-Object for direct login.
 
    .PARAMETER Url
    The server root URL.
 
    .PARAMETER RefreshToken
    Neccessary for OAuth Login: Refresh-Token. Can be created with Request-OAuthRefreshToken.
 
    .PARAMETER AccessToken
    Neccessary for OAuth Login: Access-Token. Can be created with Request-OAuthRefreshToken.
 
    .PARAMETER AuthToken
    Neccessary for OAuth Login: Auth-Token. Can be created with Request-OAuthRefreshToken.
 
    .PARAMETER ClientID
    Neccessary for OAuth Login: The Id of the OAauth Client.
 
    .PARAMETER ClientSecret
    Neccessary for OAuth Login: The Secret of the OAauth Client.
 
    .PARAMETER EnableException
    Should Exceptions been thrown?
 
    .EXAMPLE
    $connection=Connect-Gitea -Url $url -ClientID $clientId -ClientSecret $clientSecret -Credential $cred
    Connect directly with OAuth and a Credential-Object
 
 
    .NOTES
    #>


    # [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')]
    # [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
    [CmdletBinding(DefaultParameterSetName = "AccessToken")]
    Param (
        [parameter(mandatory = $true, ParameterSetName = "BasicAuth")]
        [parameter(mandatory = $true, ParameterSetName = "AccessToken")]
        # [PSFramework.TabExpansion.PsfArgumentCompleterAttribute("Gitea.url")]
        [string]$Url,
        [parameter(mandatory = $true, ParameterSetName = "BasicAuth")]
        [pscredential]$Credential,
        [parameter(mandatory = $true, ParameterSetName = "AccessToken")]
        [string]$AccessToken,
        [switch]$EnableException
    )
    $connection = [GiteaConnection]::new()
    Write-PSFMessage "ParameterSetName=$($PSCmdlet.ParameterSetName)"
    $connection.serverRoot = Get-GiteaServerRoot -Url $Url
    $connection.WebServiceRoot = "$($connection.serverRoot)/api"
    # $connection.Headers.add("accept", "application/json")
    Write-PSFMessage "Stelle Verbindung her zu $($connection.serverRoot)" -Target $connection.serverRoot
    if ($PSCmdlet.ParameterSetName -eq 'BasicAuth') {
        Write-PSFMessage "Basic Auth"
        $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credential.UserName):$($Credential.GetNetworkCredential().Password)"))
        $connection.Headers.add("Authorization", "Basic $encodedCreds")
    }
    elseif ($PSCmdlet.ParameterSetName -eq 'AccessToken') {
        Write-PSFMessage "AccessToken"
        $connection.Headers.add("Authorization", "token $AccessToken")
    }
    Invoke-PSFProtectedCommand -Action "Connecting to Gitea" -Target $Url -ScriptBlock {
        $result = Get-GiteaCurrentAccount -Connection $Connection
        $connection.AuthenticatedUser = $result.login
    } -PSCmdlet $PSCmdlet  -EnableException $EnableException
    if (Test-PSFFunctionInterrupt) { return }
    Write-PSFMessage "Successfully connected with user $($connection.AuthenticatedUser)"
    $connection
}

function Get-GiteaCurrentAccount {
    <#
    .SYNOPSIS
    Retrieves all information regarding the current user’s account. API-GET /v1/user
 
    .DESCRIPTION
    Retrieves all information regarding the current user’s account. API-GET /v1/user
 
    .PARAMETER Connection
    Parameter description
 
    .EXAMPLE
    To be added
    in the Future
 
    .NOTES
    General notes
    #>

    param (
        [parameter(Mandatory)]
        [GiteaConnection]$Connection
    )
    $apiCallParameter = @{
        Connection      = $Connection
        method          = "Get"
        Path            = "/v1/user"
        # EnableException = $true
    }

    Invoke-GiteaAPI @apiCallParameter
}

function Invoke-GiteaAPI {
    <#
    .SYNOPSIS
    Generic API Call to the Dracoon API.
 
    .DESCRIPTION
    Generic API Call to the Dracoon API.
 
    .PARAMETER Connection
    Object of Class [Dracoon], stores the authentication Token and the API Base-URL
 
    .PARAMETER Path
    API Path to the REST function
 
    .PARAMETER Body
    Parameter for the API call; Converted to the POST body
 
    .PARAMETER UrlParameter
    Parameter for the API call; Converted to the GET URL parameter set
 
    .PARAMETER Method
    HTTP Method
 
    .PARAMETER ContentType
    HTTP-ContentType, defaults to "application/json;charset=UTF-8"
 
    .PARAMETER InFile
    File which should be transfered during the Request.
 
    .PARAMETER HideParameters
    If set to $true the password is hidden from logging
 
    .PARAMETER EnablePaging
    Wenn die API mit Paging arbeitet, kann über diesn Parameter ein automatisches Handling aktivieren.
    Dann werden alle Pages abgehandelt und nur die items zurückgeliefert.
 
    .PARAMETER EnableException
    If set to true, inner exceptions will be rethrown. Otherwise the an empty result will be returned.
 
    .EXAMPLE
    $result = Invoke-DracoonAPI -connection $this -path "/v4/auth/login" -method POST -body @{login = $credentials.UserName; password = $credentials.GetNetworkCredential().Password; language = "1"; authType = "sql" } -hideparameters $true
    Login to the service
 
    .NOTES
    General notes
    #>


    param (
        [parameter(Mandatory)]
        $Connection,
        [parameter(Mandatory)]
        [string]$Path,
        [parameter(Mandatory)]
        [Microsoft.Powershell.Commands.WebRequestMethod]$Method,
        [Hashtable]$Body,
        [Hashtable]$UrlParameter,
        [bool]$HideParameters = $false,
        [string]$ContentType = "application/json;charset=UTF-8",
        [string]$InFile,
        [bool]$EnableException = $true,
        [bool]$EnablePaging = $false
    )
    $uri = $connection.webServiceRoot + $path
    if ($UrlParameter) {
        Write-PSFMessage "Wandle URL Parameter in String um und hänge diese an die URI"
        $parameterString = (Get-EncodedParameterString($UrlParameter))
        $uri = $uri + '?' + $parameterString.trim("?")
    }
    $restAPIParameter = @{
        Uri         = $Uri
        method      = $Method
        body        = ($Body | Remove-NullFromHashtable -Json)
        Headers     = $connection.headers
        ContentType = $ContentType
    }
    If ($Body) {
        $restAPIParameter.body = ($Body | Remove-NullFromHashtable -Json)
    }
    If ($InFile) {
        $restAPIParameter.InFile = $InFile
    }
    Write-PSFMessage -Message "$(("$Method").ToUpper()) $uri" -Target $connection

    $tempBody = $body
    if ($hideParameters) {
        if ($tempBody.ContainsKey("password")) { $tempBody.set_Item("password", "*****") }
    }
    if ($tempBody) {
        Write-PSFMessage ("Rufe {0} mit {1} auf" -f $uri, ($tempBody  | Remove-NullFromHashtable -Json))
    }
    else {
        Write-PSFMessage ("Rufe {0} auf" -f $uri)
    }

    try {
        Write-PSFMessage -Level Debug "restAPIParameter= $($restAPIParameter|ConvertTo-Json -Depth 5)"
        $result = Invoke-RestMethod @restAPIParameter
        Write-PSFMessage -Level Debug "result= $($result|ConvertTo-Json -Depth 5)"
        if ($EnablePaging -and ($result -is [array])) {
            Write-PSFMessage "Paging enabled, aber keine Range zurückgeliefert" -Level Warning
        }
        elseif ($EnablePaging) {
            Write-PSFMessage "Paging enabled, starte Schleife, result.range=$($result.range)"
            $allItems = ($result.items)
            write-psfmessage "Anzahl ermittelter Items: $($allItems.count)"
            $UrlParameter.limit = $result.range.limit
            $UrlParameter.offset = $result.range.offset
            while ($result.range.total -gt $allItems.count) {
                Write-PSFMessage "result.range.total=$($result.range.total) -gt allItems.count=$($allItems.count)"
                $UrlParameter.offset = $allItems.count
                $nextParameter = @{
                    Connection     = $Connection
                    Path           = $Path
                    Body           = $Body
                    UrlParameter   = $UrlParameter
                    Method         = $Method
                    HideParameters = $HideParameters
                }
                write-psfmessage "Rufe API auf mit $($nextParameter|convertto-json -depth 10)" -Level Debug
                write-psfmessage "Rufe API auf mit URL Params auf $($UrlParameter|convertto-json -depth 10)"

                $result = Invoke-DracoonAPI @nextParameter
                $allItems += ($result.items)
            }
            return $allItems
        }
    }
    catch {
        $result = $_.errordetails
        Write-PSFMessage "$result" -Level Critical
        If ($EnableException) {
            throw $_#$result.Message
        }
        else {
            return
        }
    }
    return $result
}

function New-GiteaAccessToken {
    <#
    .SYNOPSIS
    Creates a new access token. API-POST /v1/users/{username}/tokens
 
    .DESCRIPTION
    Creates a new access token. API-POST /v1/users/{username}/tokens
 
    .PARAMETER Connection
    Connection Object
 
    .PARAMETER Name
    Name for the new access token
 
    .PARAMETER UserName
    Name of the user for whom the token should get generated. If not set then the current user will be used
 
    .PARAMETER whatIf
    If enabled it does not execute the backend API call.
 
    .PARAMETER confirm
    If enabled the backend API Call has to be confirmed
 
    .EXAMPLE
    To be added
    in the Future
 
    .NOTES
    General notes
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param (
        [parameter(Mandatory)]
        [GiteaConnection]$Connection,
        [parameter(Mandatory)]
        [string]$Name,
        [string]$UserName
    )
    if (!$UserName) {
        $UserName = $Connection.AuthenticatedUser
    }
    $apiCallParameter = @{
        Connection = $Connection
        method     = "Post"
        Path       = "/v1/users/$Username/tokens"
        Body       = @{
            name = $Name
        }
    }
    Invoke-PSFProtectedCommand -Action "Create AccessToken $Name for user $Username" -Target "$Name" -ScriptBlock {

        $result = Invoke-GiteaAPI @apiCallParameter
        Write-PSFMessage "AccessToken created"
        $result
    } -PSCmdlet $PSCmdlet
}

function Remove-GiteaAccessToken {
    <#
    .SYNOPSIS
    Deletes an existing access token. API-DELETE /v1/users/{username}/tokens/{token}
 
    .DESCRIPTION
    Deletes an existing access token. API-DELETE /v1/users/{username}/tokens/{token}
 
    .PARAMETER Connection
    Connection Object
 
    .PARAMETER AccessToken
    Name/ID of the access token
 
    .PARAMETER UserName
    Name of the user for whom the token should get generated. If not set then the current user will be used
 
    .PARAMETER whatIf
    If enabled it does not execute the backend API call.
 
    .PARAMETER confirm
    If enabled the backend API Call has to be confirmed
 
    .EXAMPLE
    To be added
    in the Future
 
    .NOTES
    General notes
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param (
        [parameter(Mandatory)]
        [GiteaConnection]$Connection,
        [parameter(Mandatory)]
        [string]$AccessToken,
        [string]$UserName
    )
    if (!$UserName) {
        $UserName = $Connection.AuthenticatedUser
    }
    $apiCallParameter = @{
        Connection = $Connection
        method     = "Delete"
        Path       = "/v1/users/$Username/tokens/$AccessToken"
    }
    Invoke-PSFProtectedCommand -Action "Delete AccessToken $AccessToken for user $Username" -Target "$Name" -ScriptBlock {
        $result = Invoke-GiteaAPI @apiCallParameter
        Write-PSFMessage "AccessToken deleted"
        $result
    } -PSCmdlet $PSCmdlet
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'Gitea' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'Gitea' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'Gitea' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'Gitea.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "Gitea.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name Gitea.alcohol
#>


New-PSFLicense -Product 'Gitea' -Manufacturer 'b10057231' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-02-07") -Text @"
Copyright (c) 2021 b10057231
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code