<commit_before>import Vapor
import S4

var workDir: String {
    let parent = #file.characters.split(separator: "/").map(String.init).dropLast().joined(separator: "/")
    let path = "/\(parent)/"
    return path
}

let config = Config(seed: JSON.object(["port": "8000"]), workingDirectory: workDir)
let app = Application(workDir: workDir, config: config)

//MARK: Basic

app.get("/") { request in
    return try app.view("welcome.html")
}

app.get("test") { request in
    print("Request: \(request)")
    return "123"
}

// Create NSData object
//NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
//    dataUsingEncoding:NSUTF8StringEncoding];
//
//// Get NSString from NSData object in Base64
//NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
//
//// Print the Base64 encoded string
//NSLog(@"Encoded: %@", base64Encoded);
//
//// Let's go the other way...
//
//// NSData from the Base64 encoded str
//NSData *nsdataFromBase64String = [[NSData alloc]
//    initWithBase64EncodedString:base64Encoded options:0];
//
//// Decoded NSString from the NSData
//NSString *base64Decoded = [[NSString alloc]
//    initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
//NSLog(@"Decoded: %@", base64Decoded);
import Foundation
import SHA1

extension String {
    // TODO: Fewer foundation deps
    func makeWebSocketSecKeyExchange() -> String {
        // UUID defined here: https://tools.ietf.org/html/rfc6455#section-1.3
        let HashKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        let combined = self.trim() + HashKey
        let shaBytes = SHA1.calculate(combined)
        let endMarker = NSData(bytes: shaBytes, length: shaBytes.count)
        let hashed = endMarker.base64EncodedString(.encoding64CharacterLineLength)
        return hashed
    }
    func toBase64() -> String {
        let d = data(using: NSUTF8StringEncoding)
        return d!.base64EncodedString(.encoding64CharacterLineLength)
//        return d!.base64EncodedData(NSDataBase64EncodingOptions.encoding64CharacterLineLength)
    }

    static func fromBase64(_ string: String) -> String {
        let d = NSData.init(base64Encoded: string, options: .ignoreUnknownCharacters)
        return String.init(data: d!, encoding: NSUTF8StringEncoding)!
    }
}

// TODO: Do test from RFC
//let HashKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
//let combined = "dGhlIHNhbXBsZSBub25jZQ==" + HashKey
//let shaBytes = SHA1.calculate(combined)
//var endMarker = NSData(bytes: shaBytes, length: shaBytes.count)
//let hashed = endMarker.base64EncodedString(.encoding64CharacterLineLength)
//print("HASHED: \(hashed)")
//print("")


app.get("socket") { request in
    print("Get socket: \(request)")
    func socketHandler(_ socket: Stream) throws {
        print("About to send\n\n")
        try socket.send(Data([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
        print("Sent ---\n\n Receiving --- \n\n")
        let received = try socket.receive(upTo: 1024)
        let msg = try MessageParser.parseInput(Data(received))
        print("Received message: \(msg)")
        print("\n\nPayload: \(try msg.payload.toString())\n\n")
        print("")
//        let msg = Message
//        print("Received raw: \(received)")
//        print("received: \(try received.toString())")
        return
    }

    let secReturn = request.headers["Sec-WebSocket-Key"]!.makeWebSocketSecKeyExchange()
//    let combined = inputKey + HashKey
//    let hashed = combined.toBase64()
//    HTTP/1.1 101 Switching Protocols
//    Upgrade: websocket
//    Connection: Upgrade
//    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
//    Sec-WebSocket-Protocol: chat
    var headers: Headers = [:]<commit_msg>repeated firing working successfully from client to server<commit_after>import Vapor
import S4

var workDir: String {
    let parent = #file.characters.split(separator: "/").map(String.init).dropLast().joined(separator: "/")
    let path = "/\(parent)/"
    return path
}

let config = Config(seed: JSON.object(["port": "8000"]), workingDirectory: workDir)
let app = Application(workDir: workDir, config: config)

//MARK: Basic

app.get("/") { request in
    return try app.view("welcome.html")
}

app.get("test") { request in
    print("Request: \(request)")
    return "123"
}

// Create NSData object
//NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
//    dataUsingEncoding:NSUTF8StringEncoding];
//
//// Get NSString from NSData object in Base64
//NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];
//
//// Print the Base64 encoded string
//NSLog(@"Encoded: %@", base64Encoded);
//
//// Let's go the other way...
//
//// NSData from the Base64 encoded str
//NSData *nsdataFromBase64String = [[NSData alloc]
//    initWithBase64EncodedString:base64Encoded options:0];
//
//// Decoded NSString from the NSData
//NSString *base64Decoded = [[NSString alloc]
//    initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
//NSLog(@"Decoded: %@", base64Decoded);
import Foundation
import SHA1

extension String {
    // TODO: Fewer foundation deps
    func makeWebSocketSecKeyExchange() -> String {
        // UUID defined here: https://tools.ietf.org/html/rfc6455#section-1.3
        let HashKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        let combined = self.trim() + HashKey
        let shaBytes = SHA1.calculate(combined)
        let endMarker = NSData(bytes: shaBytes, length: shaBytes.count)
        let hashed = endMarker.base64EncodedString(.encoding64CharacterLineLength)
        return hashed
    }
    func toBase64() -> String {
        let d = data(using: NSUTF8StringEncoding)
        return d!.base64EncodedString(.encoding64CharacterLineLength)
//        return d!.base64EncodedData(NSDataBase64EncodingOptions.encoding64CharacterLineLength)
    }

    static func fromBase64(_ string: String) -> String {
        let d = NSData.init(base64Encoded: string, options: .ignoreUnknownCharacters)
        return String.init(data: d!, encoding: NSUTF8StringEncoding)!
    }
}

// TODO: Do test from RFC
//let HashKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
//let combined = "dGhlIHNhbXBsZSBub25jZQ==" + HashKey
//let shaBytes = SHA1.calculate(combined)
//var endMarker = NSData(bytes: shaBytes, length: shaBytes.count)
//let hashed = endMarker.base64EncodedString(.encoding64CharacterLineLength)
//print("HASHED: \(hashed)")
//print("")


app.get("socket") { request in
    print("Get socket: \(request)")
    func socketHandler(_ socket: Stream) throws {
        print("About to send\n\n")
        try socket.send(Data([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
        print("Sent ---\n\n Receiving --- \n\n")
        let received = try socket.receive(upTo: 1024)
        let msg = try MessageParser.parseInput(Data(received))
        print("Received message: \(msg)")
        print("\n\nPayload: \(try msg.payload.toString())\n\n")
        print("")

        try socket.send(Data([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))
        try socket.send(Data([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f]))

        while true {
            let next = try socket.receive(upTo: 1024)
            guard !next.isEmpty else { continue }
            let newMsg = try MessageParser.parseInput(Data(next))
            let str = try newMsg.payload.toString()
            print("\n\n[MSG]:\n\n\t\(str)\n\n")
        }
//        let msg = Message
//        print("Received raw: \(received)")
//        print("received: \(try received.toString())")
        return
    }

    let secReturn = request.headers["Sec-WebSocket-Key"]!.makeWebSocketSecKeyExchange()
//    let combined = inputKey + HashKey
//    let hashed = combined.toBase64()
//    HTTP/1.1 101 Switching Protocols
//    Upgrade: websocket
//    Connection: Upgrade
//    Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
//    Sec-WebSocket-Protocol: chat
    var headers: Headers = [:]
{'fraction_non_alphanumeric': 0.1406646372399797, 'fraction_numerical': 0.04058853373921867, 'mean_word_length': 3.2483836206896552, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2337052', 'n_tokens_mistral': 2775, 'n_tokens_neox': 2543, 'n_words': 591}