SmsGora.psm1

#Requires -Version 5.1
Set-StrictMode -Version Latest

$script:SmsGoraBaseUrl = 'https://tekservix.com/smsgora/api/v1'
$script:SmsGoraApiKey = $null

function Connect-SmsGora {
    <#
    .SYNOPSIS
    Sets the SMS Gora API key used by the other SmsGora commands in this session.
    .DESCRIPTION
    Create a key in your Tekservix dashboard under SMS Gora > API keys (it starts with sgk_).
    You can also set the SMSGORA_API_KEY environment variable instead of calling this command.
    No account yet? Start at https://tekservix.com/smsgora
    .EXAMPLE
    Connect-SmsGora -ApiKey $env:SMSGORA_API_KEY
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$ApiKey,
        [string]$BaseUrl = 'https://tekservix.com/smsgora/api/v1'
    )
    $script:SmsGoraApiKey = $ApiKey
    $script:SmsGoraBaseUrl = $BaseUrl.TrimEnd('/')
}

function Invoke-SmsGoraApi {
    <#
    .SYNOPSIS
    Calls any SMS Gora API endpoint with your API key and returns the "data" part of the answer.
    .EXAMPLE
    Invoke-SmsGoraApi -Path '/devices'
    .LINK
    https://tekservix.com/smsgora/docs/
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Path,
        [ValidateSet('GET', 'POST', 'PUT', 'PATCH', 'DELETE')][string]$Method = 'GET',
        [object]$Body,
        [hashtable]$Query
    )
    $key = if ($script:SmsGoraApiKey) { $script:SmsGoraApiKey } else { $env:SMSGORA_API_KEY }
    if (-not $key) {
        throw 'No SMS Gora API key. Run Connect-SmsGora -ApiKey <key> or set SMSGORA_API_KEY. Create a key at https://tekservix.com/smsgora'
    }
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

    $uri = $script:SmsGoraBaseUrl + '/' + $Path.TrimStart('/')
    if ($Query) {
        $pairs = foreach ($k in $Query.Keys) {
            $v = $Query[$k]
            if ($null -ne $v -and "$v" -ne '') { [uri]::EscapeDataString($k) + '=' + [uri]::EscapeDataString("$v") }
        }
        if ($pairs) { $uri += '?' + ($pairs -join '&') }
    }

    $params = @{
        Uri         = $uri
        Method      = $Method
        Headers     = @{ 'x-api-key' = $key; 'Accept' = 'application/json' }
        ErrorAction = 'Stop'
    }
    if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) {
        $json = $Body | ConvertTo-Json -Depth 10 -Compress
        $params.Body = [Text.Encoding]::UTF8.GetBytes($json)
        $params.ContentType = 'application/json; charset=utf-8'
    }

    try {
        $response = Invoke-RestMethod @params
    }
    catch {
        $status = $null
        $message = $_.Exception.Message
        $raw = $null
        if ($_.Exception.PSObject.Properties['Response'] -and $_.Exception.Response) {
            try { $status = [int]$_.Exception.Response.StatusCode } catch { $status = $null }
            try {
                $stream = $_.Exception.Response.GetResponseStream()
                if ($stream) { $raw = (New-Object IO.StreamReader($stream)).ReadToEnd() }
            }
            catch { $raw = $null }
        }
        if (-not $raw -and $_.ErrorDetails -and $_.ErrorDetails.Message) { $raw = $_.ErrorDetails.Message }
        if ($raw) {
            try {
                $parsed = $raw | ConvertFrom-Json
                if ($parsed.PSObject.Properties['message'] -and $parsed.message) { $message = $parsed.message }
            }
            catch { $message = $raw }
        }
        $prefix = if ($status) { "SMS Gora API error $status" } else { 'SMS Gora API error' }
        throw "${prefix}: $message"
    }

    if ($null -ne $response -and $response.PSObject.Properties['data']) { return $response.data }
    return $response
}

function Send-SmsGoraSms {
    <#
    .SYNOPSIS
    Sends an SMS from one of your Android phones to one or more numbers.
    .PARAMETER To
    Phone numbers in international format, for example +250788123456 (up to 1,000).
    .PARAMETER DeviceId
    The phone that sends the SMS. Leave it out to use your best online phone.
    .PARAMETER SimSlot
    0 for SIM 1, 1 for SIM 2.
    .PARAMETER ScheduleAt
    Send later instead of now.
    .EXAMPLE
    Send-SmsGoraSms -To '+250788123456' -Message 'Your order has shipped.'
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)][string[]]$To,
        [Parameter(Mandatory)][ValidateLength(1, 1600)][string]$Message,
        [int]$DeviceId,
        [ValidateSet(0, 1)][int]$SimSlot,
        [datetime]$ScheduleAt
    )
    $body = @{ recipients = @($To); message = $Message }
    if ($PSBoundParameters.ContainsKey('SimSlot')) { $body.sim_slot = $SimSlot }
    if ($PSBoundParameters.ContainsKey('ScheduleAt')) { $body.schedule_at = $ScheduleAt.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') }
    $path = if ($PSBoundParameters.ContainsKey('DeviceId')) { "/devices/$DeviceId/send-sms" } else { '/send-sms' }
    if ($PSCmdlet.ShouldProcess(($To -join ', '), 'Send SMS')) {
        Invoke-SmsGoraApi -Path $path -Method POST -Body $body
    }
}

function Send-SmsGoraBulkSms {
    <#
    .SYNOPSIS
    Sends different texts to different people in one call (up to 5,000 recipients).
    .PARAMETER Messages
    A list of hashtables with Recipients (numbers) and an optional own Message.
    .PARAMETER MessageTemplate
    Text used for every entry that has no message of its own.
    .EXAMPLE
    Send-SmsGoraBulkSms -DeviceId 12 -MessageTemplate 'Your parcel is ready.' -Messages @(
        @{ Recipients = '+250788123456'; Message = 'Hi Aline, parcel #1042 is ready.' }
        @{ Recipients = '+250722000000', '+250733000000' }
    )
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)][int]$DeviceId,
        [Parameter(Mandatory)][hashtable[]]$Messages,
        [string]$MessageTemplate
    )
    $entries = foreach ($m in $Messages) {
        $entry = @{ recipients = @($m.Recipients) }
        if ($m.ContainsKey('Message') -and $m.Message) { $entry.message = $m.Message }
        elseif (-not $MessageTemplate) { throw 'Every entry needs a Message when no -MessageTemplate is given.' }
        $entry
    }
    $body = @{ messages = @($entries) }
    if ($MessageTemplate) { $body.messageTemplate = $MessageTemplate }
    if ($PSCmdlet.ShouldProcess("$(@($entries).Count) entries", 'Send bulk SMS')) {
        Invoke-SmsGoraApi -Path "/devices/$DeviceId/send-bulk-sms" -Method POST -Body $body
    }
}

function Get-SmsGoraMessage {
    <#
    .SYNOPSIS
    Gets one message by ID, or lists messages (newest first) with optional filters.
    .EXAMPLE
    Get-SmsGoraMessage -Id 1873
    .EXAMPLE
    Get-SmsGoraMessage -Direction out -Status failed -Limit 20
    #>

    [CmdletBinding(DefaultParameterSetName = 'List')]
    param(
        [Parameter(Mandatory, ParameterSetName = 'ById')][int]$Id,
        [Parameter(ParameterSetName = 'List')][ValidateSet('in', 'out')][string]$Direction,
        [Parameter(ParameterSetName = 'List')][ValidateSet('scheduled', 'queued', 'dispatched', 'sent', 'delivered', 'failed', 'cancelled', 'received')][string]$Status,
        [Parameter(ParameterSetName = 'List')][string]$Phone,
        [Parameter(ParameterSetName = 'List')][datetime]$Since,
        [Parameter(ParameterSetName = 'List')][ValidateRange(1, 100)][int]$Limit = 50,
        [Parameter(ParameterSetName = 'List')][int]$Page = 1
    )
    if ($PSCmdlet.ParameterSetName -eq 'ById') { return Invoke-SmsGoraApi -Path "/messages/$Id" }
    $q = @{ direction = $Direction; status = $Status; phone = $Phone; limit = $Limit; page = $Page }
    if ($PSBoundParameters.ContainsKey('Since')) { $q.since = $Since.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') }
    $result = Invoke-SmsGoraApi -Path '/messages' -Query $q
    if ($null -ne $result -and $result.PSObject.Properties['data']) { return $result.data }
    $result
}

function Stop-SmsGoraMessage {
    <#
    .SYNOPSIS
    Cancels a message that is still queued or scheduled.
    .EXAMPLE
    Stop-SmsGoraMessage -Id 1873
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory, ValueFromPipelineByPropertyName)][int]$Id)
    process {
        if ($PSCmdlet.ShouldProcess("message $Id", 'Cancel')) {
            Invoke-SmsGoraApi -Path "/messages/$Id/cancel" -Method POST
        }
    }
}

function Get-SmsGoraReceivedSms {
    <#
    .SYNOPSIS
    Lists SMS received by your phones, newest first.
    .EXAMPLE
    Get-SmsGoraReceivedSms -DeviceId 12 -Limit 10
    #>

    [CmdletBinding()]
    param(
        [int]$DeviceId,
        [string]$Phone,
        [datetime]$Since,
        [ValidateRange(1, 100)][int]$Limit = 50,
        [int]$Page = 1
    )
    $q = @{ phone = $Phone; limit = $Limit; page = $Page }
    if ($PSBoundParameters.ContainsKey('Since')) { $q.since = $Since.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') }
    $path = if ($PSBoundParameters.ContainsKey('DeviceId')) { "/devices/$DeviceId/get-received-sms" } else { '/received-sms' }
    $result = Invoke-SmsGoraApi -Path $path -Query $q
    if ($null -ne $result -and $result.PSObject.Properties['data']) { return $result.data }
    $result
}

function Get-SmsGoraDevice {
    <#
    .SYNOPSIS
    Lists the Android phones linked to your account, or gets one by ID.
    .EXAMPLE
    Get-SmsGoraDevice | Select-Object id, name, status, battery
    #>

    [CmdletBinding()]
    param([int]$Id)
    if ($PSBoundParameters.ContainsKey('Id')) { return Invoke-SmsGoraApi -Path "/devices/$Id" }
    Invoke-SmsGoraApi -Path '/devices'
}

function Get-SmsGoraAccount {
    <#
    .SYNOPSIS
    Gets your SMS Gora plan, limits and usage.
    #>

    [CmdletBinding()]
    param()
    Invoke-SmsGoraApi -Path '/account'
}

function New-SmsGoraWebhook {
    <#
    .SYNOPSIS
    Registers a webhook URL for SMS events. Keep the returned secret to check signatures.
    .EXAMPLE
    New-SmsGoraWebhook -Url 'https://example.com/sms' -Events sms.received
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)][uri]$Url,
        [ValidateSet('sms.received', 'sms.sent', 'sms.delivered', 'sms.failed', 'device.online', 'device.offline')][string[]]$Events = @('sms.received'),
        [int]$DeviceId
    )
    $body = @{ url = "$Url"; events = @($Events) }
    if ($PSBoundParameters.ContainsKey('DeviceId')) { $body.device_id = $DeviceId }
    if ($PSCmdlet.ShouldProcess("$Url", 'Register webhook')) {
        Invoke-SmsGoraApi -Path '/webhooks' -Method POST -Body $body
    }
}

function Get-SmsGoraWebhook {
    <#
    .SYNOPSIS
    Lists your webhooks.
    #>

    [CmdletBinding()]
    param()
    Invoke-SmsGoraApi -Path '/webhooks'
}

function Remove-SmsGoraWebhook {
    <#
    .SYNOPSIS
    Deletes a webhook.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory, ValueFromPipelineByPropertyName)][int]$Id)
    process {
        if ($PSCmdlet.ShouldProcess("webhook $Id", 'Delete')) {
            Invoke-SmsGoraApi -Path "/webhooks/$Id" -Method DELETE
        }
    }
}

function Test-SmsGoraWebhookSignature {
    <#
    .SYNOPSIS
    Checks the X-SmsGora-Signature header of a webhook call (HMAC-SHA256 of the raw body).
    .PARAMETER RawBody
    The request body exactly as received.
    .PARAMETER Signature
    The X-SmsGora-Signature header value, for example sha256=5d3c...
    .PARAMETER Secret
    The secret returned when the webhook was created.
    .EXAMPLE
    Test-SmsGoraWebhookSignature -RawBody $body -Signature $headers['X-SmsGora-Signature'] -Secret $secret
    #>

    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)][AllowEmptyString()][string]$RawBody,
        [Parameter(Mandatory)][AllowEmptyString()][string]$Signature,
        [Parameter(Mandatory)][string]$Secret
    )
    if (-not $Signature) { return $false }
    $hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList (, [Text.Encoding]::UTF8.GetBytes($Secret))
    try {
        $hash = $hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($RawBody))
    }
    finally { $hmac.Dispose() }
    $expected = 'sha256=' + (($hash | ForEach-Object { $_.ToString('x2') }) -join '')
    if ($expected.Length -ne $Signature.Length) { return $false }
    $diff = 0
    for ($i = 0; $i -lt $expected.Length; $i++) { $diff = $diff -bor ([int][char]$expected[$i] -bxor [int][char]$Signature[$i]) }
    return ($diff -eq 0)
}

Export-ModuleMember -Function Connect-SmsGora, Invoke-SmsGoraApi, Send-SmsGoraSms, Send-SmsGoraBulkSms, Get-SmsGoraMessage, Stop-SmsGoraMessage, Get-SmsGoraReceivedSms, Get-SmsGoraDevice, Get-SmsGoraAccount, New-SmsGoraWebhook, Get-SmsGoraWebhook, Remove-SmsGoraWebhook, Test-SmsGoraWebhookSignature