-
Notifications
You must be signed in to change notification settings - Fork 68
/
ApiListener.ps1
84 lines (56 loc) · 2.33 KB
/
ApiListener.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Param (
[Parameter()]
[String] $SharedFile, #complete path
#[String] $SharedFile='C:\Users\admin\Desktop\Megaminer\ApiShared34474029.tmp',
[Parameter()]
[Int] $Port = 9999,
[Parameter()]
[String] $Url = "",
[Parameter()]
[System.Net.AuthenticationSchemes] $Auth = [System.Net.AuthenticationSchemes]::IntegratedWindowsAuthentication
)
$ErrorActionPreference = "Stop"
if ($Url.Length -gt 0 -and -not $Url.EndsWith('/')) {
$Url += "/"
}
$Host.UI.RawUI.WindowTitle = "MM API Listener"
$listener = New-Object System.Net.HttpListener
$prefix = "http://*:$Port/$Url"
$listener.Prefixes.Add($prefix)
$listener.AuthenticationSchemes = $Auth
$listener.Start()
Write-Warning "Megaminer Api Listening on port $port......."
Write-Warning "Don´t close this window while you want to use API."
while ($true) {
$statusCode = 200
$context = $listener.GetContext()
Write-Warning "Received request $(get-date)"
$request = $context.Request
$command = $request.QueryString.Item("command")
if ($command -eq "exit") {
Write-Warning "Received command to exit listener"
break
}
try{$commandOutput = get-content -path $SharedFile -raw } catch{$commandOutput=""}
if ($commandOutput -ne $null -and $commandOutput -ne "") {
$A=(get-date)
$B=([datetime]($commandOutput |convertfrom-json).RefreshDate)
$Ago = $A - $B
if ($Ago.TotalSeconds -gt 20) {$commandOutput=""} #check info refresh date
if ($Ago.TotalSeconds -gt 300) {break} #check info refresh date
}
$response = $context.Response
$response.StatusCode = $statusCode
$Response.ContentEncoding = [System.Text.Encoding]::utf8
$Response.ContentType = "text/plain; charset=utf-8"
if (!$commandOutput) {$commandOutput = [string]::Empty}
$buffer = [System.Text.Encoding]::utf8.GetBytes($commandOutput)
$response.ContentLength64 = $buffer.Length
$output = $response.OutputStream
try {
$output.Write($buffer,0,$buffer.Length)
$output.Close()
} catch{}
}
$listener.Stop()
stop-process -Id $PID