Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [CmdletBinding()]
- param
- (
- [Parameter(Mandatory=$true, Position=0)]
- [uri] $Url,
- [Parameter(Mandatory=$true, Position=1)]
- [string]$BearerToken
- )
- $messageQueue = New-Object -TypeName "System.Collections.Generic.List[string]" -ArgumentList 1024
- $receivedObjects = New-Object -TypeName "System.Collections.Generic.List[object]" -ArgumentList 100
- Function Process-Lines([ref]$Queue, [ref]$List)
- {
- $index = 0
- $lastEventIndex = -1
- for ($i = 0; $i -lt $Queue.Value.Count; $i++)
- {
- $line = $Queue.Value[$i]
- if ([string]::IsNullOrWhiteSpace($line))
- {
- continue
- }
- $line = $line.Trim()
- if ($line -like "event:*")
- {
- $lastEvent = [pscustomobject]@{
- Name = $line -replace "event:", ""
- Data = $null
- }
- }
- elseif ($line -like "data:*")
- {
- if ($null -eq $lastEvent)
- {
- continue
- }
- $lastEvent.Data = $line -replace 'data:', ''
- $List.Value.Add($lastEvent)
- Write-Host "`nFound event: $index"
- Write-Host "Name: $($lastEvent.Name)"
- Write-Host "Data: $($lastEvent.Data)"
- $index++
- $lastEventIndex = $i
- }
- }
- if ($lastEventIndex -ge 0)
- {
- $Queue.Value.RemoveRange(0, $lastEventIndex)
- }
- }
- Function Push-Text([string]$text, [ref]$Queue, [ref]$List)
- {
- if ([string]::IsNullOrWhiteSpace($text))
- {
- return
- }
- $lines = $text.Trim() -split "`n"
- $Queue.Value.AddRange($lines)
- if ($text -like "*data:*")
- {
- Process-Lines -Queue $Queue -List $List
- }
- }
- Function Read-StreamForever([System.IO.Stream]$Stream, [ref]$Queue, [ref]$List)
- {
- $encoding = [System.Text.Encoding]::UTF8
- [byte[]]$buffer = New-Object byte[] 2048
- while ($true)
- {
- if ($Stream.CanRead)
- {
- $length = $Stream.Read($buffer, 0, 2048)
- if ($length -gt 0)
- {
- $text = $encoding.GetString($buffer, 0, $length)
- Push-Text -Text $text -Queue $Queue -List $List
- }
- }
- }
- }
- Function Open-SSEStream([uri]$Url, [string]$token, [ref]$Queue, [ref]$List)
- {
- $request = [System.Net.WebRequest]::CreateHttp($Url)
- $request.Headers.Add("Authorization", "Bearer $token")
- $request.AllowReadStreamBuffering = $false
- $response = $request.GetResponse()
- $stream = $response.GetResponseStream()
- Read-StreamForever -Queue $Queue -Stream $stream -List $List
- return $stream
- }
- Write-Host "Attempting to open stream"
- $response = Open-SSEStream -Url $Url -Token $BearerToken -Queue ([ref]$messageQueue) -List ([ref]$receivedObjects)
- if ($?)
- {
- Write-Host "`nSuccess!"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement