-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataSource.fs
63 lines (53 loc) · 1.86 KB
/
DataSource.fs
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
module VpnGateConnect.DataSource
open System.IO
open FSharp.Data
let private downloadVpnListCsv apiUrl =
try
let result = Http.Request(apiUrl, silentHttpErrors=true)
match result.StatusCode with
| 200 -> Ok result
| code -> Error <| UnexpectedStatusCode code
with ex -> Error <| WebError ex.Message
/// Extracts the text body from an HTTP response, or returns an Error result if not text.
let private expectTextResponse response =
match response.Body with
| Text body -> Ok body
| _ -> Error UnexpectedContentType
/// VPN Gate CSV has some unnecessary lines that trip up the CSV parser.
/// This function returns true for the header, column list, and footer lines.
let private isJunkLine (x : string) =
x.Trim() = "*vpn_servers" ||
x.StartsWith("#HostName") ||
x.Trim() = "*"
/// Removes extraneous lines from VPN Gate CSV gateway list.
let private normalizeVpnGateCsv (csv : string) =
match csv with
| "" ->
Error EmptyCsv
| _ ->
csv.Split('\n')
|> Array.filter (not << isJunkLine)
|> String.concat "\n"
|> Ok
let private stringToVpnList csv =
try
csv |> VpnList.ParseRows |> Ok
with
| ex -> CsvParseError ex.Message |> Error
let private (>>=) a b = Result.bind b a
let private getLocalData path =
if File.Exists(path) |> not then
Error <| InvalidPath path
else
try
File.ReadAllText path |> Ok
with ex -> Error (CannotOpenFileBecause ex.Message)
let private getRemoteData url =
url |> downloadVpnListCsv >>= expectTextResponse
/// Takes a data source tuple, connects to it, and returns the resulting list of VPNs.
let connect dataSource =
match dataSource with
| Cli.RemoteUrl, url -> getRemoteData url
| Cli.LocalPath, path -> getLocalData path
>>= normalizeVpnGateCsv
>>= stringToVpnList