Public/Send-ADUsersToBB.ps1

Function Send-ADUsersToBB {
    <#
    .SYNOPSIS
        Get the user information from the pipeline that is already converted to a GoBright Meet-Work-Visit object, and send it to the GoBright Meet-Work-Visit system
    .DESCRIPTION
        The pipeline should contain the converted user information
    .PARAMETER BrightBookingApiUrl
        Address of the GoBright Meet-Work-Visit API, e.g.: https://t1b.gobright.cloud/ (please get this from the 'General Settings' page of the portal)
    .PARAMETER BrightBookingApiKey
        API key of the user to use to process the import
    .PARAMETER BrightBookingIntegrationName
        Name of the integration to link the users to
    .PARAMETER UserRoleNameForNewUsers
        Name of the GoBright userrole to link new users to
    .PARAMETER DeactivateExistingUsersInSameIntegrationThatAreNotLoaded
        Deactivate users that exist in the platform in the same integration but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on)
    .EXAMPLE
        Get-ADUsersForBB -Filter * | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get all users in the Active Directory and let GoBright Meet-Work-Visit process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter * -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which are member of the given group and let GoBright Meet-Work-Visit process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter { memberOf -RecursiveMatch "CN=Administrators,DC=Company,DC=com" } -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport -ADUserPincodePropertyName PersonnelNumber | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which in the specified SearchBase path, and use the custom property 'PersonnelNumber' as pincode and let GoBright Meet-Work-Visit process it directly
    .LINK
        https://support.gobright.com/
    #>


    [CmdletBinding()]
    Param(
      [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
       [System.Object[]]$pipelineConvertedADUsers,

      [Parameter(Mandatory=$True)]
       [string]$BrightBookingApiUrl,

      [Parameter(Mandatory=$True)]
       [string]$BrightBookingApiKey,

      [Parameter(Mandatory=$True)]
       [string]$BrightBookingIntegrationName,
       
      [Parameter(Mandatory=$False)]
       [string]$UserRoleNameForNewUsers,
      
      [Parameter(Mandatory=$False)]
       [bool]$SyncIncludesUserNFCId,
      
      [Parameter(Mandatory=$False)]
       [bool]$SyncIncludesUserPincode,
       
      [switch]$DeactivateExistingUsersInSameIntegrationThatAreNotLoaded      
    )
    
    Begin {
        $convertedUsers = @()
    }

    Process {
        Foreach ($user in $pipelineConvertedADUsers)
        {
            $convertedUsers += $user
        }
    }
    
    End {
        Write-Output "Loading..."
        
        $countConvertedUsers = $convertedUsers | Measure-Object | Select-Object -ExpandProperty Count;        
        Write-Output "Will process $countConvertedUsers users from retreived AD data..."
                
        Write-Output "Connecting to the GoBright Meet-Work-Visit API..."
        Write-Output ""
        
        # get an access token
        $access_token = Get-BBAccessToken -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiKey $BrightBookingApiKey
        
        # check if we can start a new session at all
        $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false -ValidateCanStartNew $true
        
        If ($DeactivateExistingUsersInSameIntegrationThatAreNotLoaded.IsPresent -eq $True) 
        {
            # get active users to compare
            $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/synchronize-get-data")        

            $GetQueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
            $GetQueryParameters['integrationname'] = $BrightBookingIntegrationName
                    
            $GetRequest  = [System.UriBuilder]($resturi)
            $GetRequest.Query = $GetQueryParameters.ToString()

            $GetHdrs = @{}
            $GetHdrs.Add("Authorization", "Bearer "+ $access_token)
            
            $usersViewForSync = $null
            Try
            {
                Write-Output "Getting comparison data (this might take a while)..."            
                $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $GetRequest.Uri -Method Get -Headers $GetHdrs -UseBasicParsing
                        
                If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201)
                {                
                    $usersViewForSync = ConvertFrom-Json $([String]::new($response.Content))
                    # will proceed below...
                }
                Else
                {
                    throw "Could not get comparison data, unexpected statuscode $response.StatusCode"
                }
            } 
            Catch 
            {
                $statusCode = $_.Exception.Response.StatusCode.Value__
                $responseText = $_.ErrorDetails.Message
                
                Try
                {
                    If ($responseText)
                    {
                        $jsonresponse = $responseText | ConvertFrom-Json
                        If ($jsonresponse.SyncRoot)
                        {
                            $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                        }
                        Else
                        {
                            $statusMessage = $responseText
                        }
                    }
                } 
                Catch 
                {
                    $statusMessage = $responseText
                }
                
                # we want to use write-output, so it can be catched easily in to e.g. a file, but this means we need a special way of setting the color for error output
                # save the current color
                $outputOriginalForegroundColor = $host.UI.RawUI.ForegroundColor
                $outputOriginalBackgroundColor = $host.UI.RawUI.BackgroundColor
                # set the new color
                $host.UI.RawUI.ForegroundColor = 'Red'
                $host.UI.RawUI.BackgroundColor = 'Yellow'
        
                Write-Output "Could not get comparison data"
                Write-Output "Statuscode: $statusCode"
                If ($statusMessage)
                {
                    Write-Output "Statusdetails:"
                    $statusMessage = $statusMessage.Trim()
                    Write-Output $statusMessage
                }
                
                # restore the original color
                $host.UI.RawUI.ForegroundColor = $outputOriginalForegroundColor
                $host.UI.RawUI.BackgroundColor = $outputOriginalBackgroundColor
                
                throw "Could not get comparison data"
            }
            
            ##
            # process comparison
            Write-Output "Comparing..."
            
            If ($usersViewForSync)
            {
                If ($usersViewForSync.ActiveUsersInIntegration) 
                {
                    $amountToBeDeactivated = 0;
                    # compare to get the users which are now not in the resultset from AD, and are still active in the platform -> so must be disabled
                    Foreach ($activeUserInIntegration in $usersViewForSync.ActiveUsersInIntegration)
                    {
                        $activeUserInIntegrationFound = $false;
                        # exists this one in the $convertedUsers?
                        Foreach ($convertedUser in $convertedUsers)
                        {
                            $found = ((-Not [string]::IsNullOrEmpty($convertedUser.UniqueImportID)) -And ($convertedUser.UniqueImportID -ceq $activeUserInIntegration.UUI)) -Or ((-Not [string]::IsNullOrEmpty($convertedUser.EmailAddress)) -And ($convertedUser.EmailAddress -eq $activeUserInIntegration.EA));
                            
                            If ($found)
                            {
                                $activeUserInIntegrationFound = $true;
                                break;
                            }                        
                        }
                        
                        If (-Not $activeUserInIntegrationFound) 
                        {
                            # should be disabled
                            $outputUserPropertiesHash = [ordered]@{
                                EmailAddress              = $activeUserInIntegration.EA                            
                                UniqueImportID            = $activeUserInIntegration.UII
                                Active                    = $false
                            }

                            $outputUser = New-Object PSObject -Property $outputUserPropertiesHash
                            $convertedUsers += $outputUser
                            
                            $amountToBeDeactivated++;
                        }
                    }
                    
                    Write-Output "Will deactivate $amountToBeDeactivated users..."
                }
            }
        } Else {
            Write-Output "Skipping checking for deactivation of users that exist in the platform but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on). Please use the -DeactivateExistingUsersInSameIntegrationThatAreNotLoaded switch parameter to enable deactivation checking."
        }
        Write-Output ""
        
        # generate the csv file contents, generate to string
        $csvtext = $convertedUsers | ConvertTo-Csv -NoTypeInformation | Out-String        
        # convert the text so the encoding is correct to handle special characters
        $csvtext = [System.Text.Encoding]::UTF8.GetBytes($csvtext)
        
        # post stuff to the api
        $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/synchronize-direct-csv")            

        $QueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
        $QueryParameters['integrationname'] = $BrightBookingIntegrationName
        $QueryParameters['userrolename'] = $UserRoleNameForNewUsers
                
        If ($SyncIncludesUserPincode) {
            Write-Output "Sync does include user pincodes..."
            $QueryParameters['syncincludesuserpincode'] = "true"                
        } else {
            $QueryParameters['syncincludesuserpincode'] = "false"                
        }
        
        If ($SyncIncludesUserNFCId) {
            Write-Output "Sync does include user NFC ids..."
            $QueryParameters['syncincludesusernfcid'] = "true"                
        } else {
            $QueryParameters['syncincludesusernfcid'] = "false"                
        }
        
        $Request  = [System.UriBuilder]($resturi)
        $Request.Query = $QueryParameters.ToString()

        $body = $csvtext

        $hdrs = @{}
        $hdrs.Add("Authorization", "Bearer "+ $access_token)
        
        Try
        {
            Write-Output "Processing users in GoBright Meet-Work-Visit (this might take a while)..."    
            Write-Output ""
            
            $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $Request.Uri -Method Post -Body $body -ContentType 'application/text' -Headers $hdrs -UseBasicParsing
        
            If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201)
            {
                Write-Output "Succesfully started user synchronization to GoBright Meet-Work-Visit"
                Write-Output "Processing..."

                # wait for processing finished
                $keepprocessing = $true
                $waitseconds = 30
                $totalwaitedseconds = 0
                While ($keepprocessing) {
                    Start-Sleep -Seconds $waitseconds
                    $totalwaitedseconds = $totalwaitedseconds + $waitseconds

                    $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false
                    If ($status.IsCurrentlyProcessing) {
                        Write-Output "Processing..."

                        If ($waitseconds -lt 60) {
                            $waitseconds = $waitseconds +5;
                        }
                    } Else {
                        # finished processing
                        break
                    }
                }
                
                # sleep another 32 seconds to overcome the 30 sec limit that is neccessary to do a next call (doing 2 sec extra for clockskew)
                Start-Sleep -Seconds 32

                # get the result status
                $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $true

                If ($status.LastResult.Succeeded) {
                    Write-Output "Finished synchronizing users to GoBright Meet-Work-Visit successfully"
                } Else {
                    Write-Error "Synchronizing users to GoBright Meet-Work-Visit failed"
                }
                Write-Output "Results:"
                
                Write-Output $(' Created users: {0}' -f $status.LastResult.AmountCreated)
                Write-Output $(' Updated users: {0}' -f $status.LastResult.AmountUpdated)
                Write-Output $(' Ignored users: {0}' -f $status.LastResult.AmountIgnored)
                Foreach ($ignoredUser in $status.LastResult.IgnoredUsers) {
                    Write-Output $(' - Ignored user: {0}' -f $ignoredUser.Identifier)
                    Write-Output $(' - Validation errors:')
                    Foreach ($validationError in $ignoredUser.ValidationErrors) {
                        Write-Output $(' -> Property: {0}' -f $validationError.Property)
                        Write-Output $(' -> ErrorCode: {0}' -f $validationError.ErrorCode)
                        Write-Output $(' -> Value: {0}' -f $validationError.Value)
                    }
                }
                
                If ((-not $status.LastResult.Succeeded) -or ($status.LastResult.AmountIgnored -ge 0))
                {
                    exit 1
                }
                Else
                {
                    exit 0
                }
            }
            Else
            {
                Write-Output "Could not start synchronization of users to GoBright Meet-Work-Visit, unexpected statuscode $response.StatusCode"
            }
        } 
        Catch 
        {
            $statusCode = $_.Exception.Response.StatusCode.Value__
            $responseText = $_.ErrorDetails.Message
            
            Try
            {
                If ($responseText)
                {
                    $jsonresponse = $responseText | ConvertFrom-Json
                    If ($jsonresponse.SyncRoot)
                    {
                        $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                    }
                    Else
                    {
                        $statusMessage = $responseText
                    }
                }
            } 
            Catch 
            {
                $statusMessage = $responseText
            }
            
            # we want to use write-output, so it can be catched easily in to e.g. a file, but this means we need a special way of setting the color for error output
            # save the current color
            $outputOriginalForegroundColor = $host.UI.RawUI.ForegroundColor
            $outputOriginalBackgroundColor = $host.UI.RawUI.BackgroundColor
            # set the new color
            $host.UI.RawUI.ForegroundColor = 'Black'
            $host.UI.RawUI.BackgroundColor = 'Yellow'
    
            Write-Output "Synchronizing users to GoBright Meet-Work-Visit failed, please check the user data you have selected from your AD"
            Write-Output "Statuscode: $statusCode"
            If ($statusMessage)
            {
                Write-Output "Statusdetails:"
                $statusMessage = $statusMessage.Trim()
                Write-Output $statusMessage
            }
            
            # restore the original color
            $host.UI.RawUI.ForegroundColor = $outputOriginalForegroundColor
            $host.UI.RawUI.BackgroundColor = $outputOriginalBackgroundColor
            
            throw "Synchronizing users failed"
        }
    }
}