72 lines
1.8 KiB
Swift
72 lines
1.8 KiB
Swift
|
|
|
||
|
|
import SwiftUI
|
||
|
|
import Foundation
|
||
|
|
|
||
|
|
struct BlockedCount: View {
|
||
|
|
@State private var txtRecord: String = "..."
|
||
|
|
|
||
|
|
var body: some View {
|
||
|
|
Text(txtRecord)
|
||
|
|
.onAppear {
|
||
|
|
fetchTXTRecord()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func parseResponse(data: Data) -> String? {
|
||
|
|
// This is a DNS wire format response and we make a lot of assumptions
|
||
|
|
// It is not critical functionality so just let it fail if it fails
|
||
|
|
|
||
|
|
guard data.count > 44 else { return nil }
|
||
|
|
|
||
|
|
let startIndex = 44
|
||
|
|
let subData = data.suffix(from: startIndex)
|
||
|
|
|
||
|
|
// Find the first space character (ASCII 32)
|
||
|
|
var endIndex: Int?
|
||
|
|
for (offset, byte) in subData.enumerated() {
|
||
|
|
if byte == 32 { // Space character
|
||
|
|
endIndex = offset
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
guard let foundEndIndex = endIndex else { return nil }
|
||
|
|
|
||
|
|
// Extract bytes between start and space
|
||
|
|
let numberData = subData.prefix(foundEndIndex)
|
||
|
|
|
||
|
|
return String(decoding: numberData, as: UTF8.self)
|
||
|
|
}
|
||
|
|
|
||
|
|
func fetchTXTRecord() {
|
||
|
|
let dohURL = URL(string: "https://dns.sr2.uk/dns-query?dns=DoQBAAABAAAAAAAABXN0YXRzB2ludmFsaWQAABAAAQ")!
|
||
|
|
|
||
|
|
let request = URLRequest(url: dohURL)
|
||
|
|
|
||
|
|
URLSession.shared.dataTask(with: request) { data, response, error in
|
||
|
|
DispatchQueue.main.async {
|
||
|
|
if error != nil {
|
||
|
|
txtRecord = "Error"
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
guard let data = data else {
|
||
|
|
txtRecord = "Error"
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
guard let count = parseResponse(data: data) else {
|
||
|
|
txtRecord = "Error"
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
txtRecord = count
|
||
|
|
}
|
||
|
|
}.resume()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#Preview {
|
||
|
|
BlockedCount()
|
||
|
|
}
|