<commit_before>//
//  Request.swift
//  ThreeSixtyCamera
//
//  Created by <NAME> on 4/18/17.
//  Copyright © 2017 Tappollo Inc. All rights reserved.
//

import Foundation
import SwiftyyJSON
import PromiseKit
import AwaitKit

enum Endpoint {
    case info
    case state

    case execute
    case status

    var path: String {
        switch self {
        case .execute: return "/osc/commands/execute"
        case .status: return "/osc/commands/status"
        case .info: return "/osc/info"
        case .state: return "/osc/state"
        }
    }

    var method: String {
        switch self {
        case .execute, .state, .status: return "POST"
        case .info: return "GET"
        }
    }
}

private class DummyURLSessionDelegate: NSObject, URLSessionDelegate, URLSessionDownloadDelegate {

    let (promise, fulfill, reject) = Promise<URL>.pending()

    let progress: ((Double) -> Void)?

    init(progress: ((Double) -> Void)?) {
        self.progress = progress
    }

    var bytesPreviouslyWritten: Int64 = 0

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let totalBytesWritten = bytesWritten + bytesPreviouslyWritten
        progress?(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite))
        bytesPreviouslyWritten = totalBytesWritten
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        progress?(1)
        fulfill(location)
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error { reject(error) }
    }

}

extension OSCKit {
    func assembleRequest(endPoint: Endpoint = .execute, params json: JSON? = nil) -> URLRequest {
        var request = URLRequest(url: URL(string: "http://192.168.1.1\(endPoint.path)")!)
        request.httpMethod = endPoint.method
        request.addValue("application/json;charset=utf-8", forHTTPHeaderField: "Content-Type")
        if let json = json {
            request.httpBody = json.encode()
        }
        return request
    }

    func requestJSON(endPoint: Endpoint = .execute, params json: JSON? = nil) -> Promise<JSON> {
        var request = assembleRequest(endPoint: endPoint, params: json)
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        return URLSession.shared.dataTask(with: request).then(execute: { data -> JSON in
            let anyObject = try JSONSerialization.jsonObject(with: data, options: [])
            return JSON(value: anyObject as? NSObject)
        })
    }

    func requestData(command: Command) -> Promise<Data> {
        return async {
            let request = self.assembleRequest(params: command.json)
            return try await(URLSession.shared.dataTask(with: request))
        }
    }

    func download(command: Command, to: URL, progress: ((Double) -> Void)? = nil) -> Promise<URL> {
        let request = self.assembleRequest(params: command.json)
        return download(request: request, to: to, progress: progress)
    }

    func download(request: URLRequest, to: URL, progress: ((Double) -> Void)? = nil) -> Promise<URL> {
        let dummyDelegate = DummyURLSessionDelegate(progress: progress)
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: dummyDelegate, delegateQueue: nil)

        let task = session.downloadTask(with: request)
        task.resume()
        return dummyDelegate.promise
    }

    func requestData(url: String) -> Promise<Data> {
        let request = URLRequest(url: URL(string: url)!)
        return URLSession.shared.dataTask(with: request)
    }

    func execute(command: Command) -> Promise<JSON> {
        return self.requestJSON(endPoint: .execute, params: command.json)
    }
}
<commit_msg>Converting to target location<commit_after>//
//  Request.swift
//  ThreeSixtyCamera
//
//  Created by <NAME> on 4/18/17.
//  Copyright © 2017 Tappollo Inc. All rights reserved.
//

import Foundation
import SwiftyyJSON
import PromiseKit
import AwaitKit

enum Endpoint {
    case info
    case state

    case execute
    case status

    var path: String {
        switch self {
        case .execute: return "/osc/commands/execute"
        case .status: return "/osc/commands/status"
        case .info: return "/osc/info"
        case .state: return "/osc/state"
        }
    }

    var method: String {
        switch self {
        case .execute, .state, .status: return "POST"
        case .info: return "GET"
        }
    }
}

private class DummyURLSessionDelegate: NSObject, URLSessionDelegate, URLSessionDownloadDelegate {

    let (promise, fulfill, reject) = Promise<URL>.pending()

    let progress: ((Double) -> Void)?

    let targetLocation: URL

    init(progress: ((Double) -> Void)?, targetLocation: URL) {
        self.progress = progress
        self.targetLocation = targetLocation
    }

    var bytesPreviouslyWritten: Int64 = 0

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let totalBytesWritten = bytesWritten + bytesPreviouslyWritten
        progress?(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite))
        bytesPreviouslyWritten = totalBytesWritten
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        progress?(1)
        do {
            try FileManager.default.moveItem(at: location, to: self.targetLocation)
            fulfill(self.targetLocation)
        } catch (let error) {
            reject(error)
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error { reject(error) }
    }

}

extension OSCKit {
    func assembleRequest(endPoint: Endpoint = .execute, params json: JSON? = nil) -> URLRequest {
        var request = URLRequest(url: URL(string: "http://192.168.1.1\(endPoint.path)")!)
        request.httpMethod = endPoint.method
        request.addValue("application/json;charset=utf-8", forHTTPHeaderField: "Content-Type")
        if let json = json {
            request.httpBody = json.encode()
        }
        return request
    }

    func requestJSON(endPoint: Endpoint = .execute, params json: JSON? = nil) -> Promise<JSON> {
        var request = assembleRequest(endPoint: endPoint, params: json)
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        return URLSession.shared.dataTask(with: request).then(execute: { data -> JSON in
            let anyObject = try JSONSerialization.jsonObject(with: data, options: [])
            return JSON(value: anyObject as? NSObject)
        })
    }

    func requestData(command: Command) -> Promise<Data> {
        return async {
            let request = self.assembleRequest(params: command.json)
            return try await(URLSession.shared.dataTask(with: request))
        }
    }

    func download(command: Command, to: URL, progress: ((Double) -> Void)? = nil) -> Promise<URL> {
        let request = self.assembleRequest(params: command.json)
        return download(request: request, to: to, progress: progress)
    }

    func download(request: URLRequest, to: URL, progress: ((Double) -> Void)? = nil) -> Promise<URL> {
        let dummyDelegate = DummyURLSessionDelegate(progress: progress, targetLocation: to)
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: dummyDelegate, delegateQueue: nil)

        let task = session.downloadTask(with: request)
        task.resume()
        return dummyDelegate.promise
    }

    func requestData(url: String) -> Promise<Data> {
        let request = URLRequest(url: URL(string: url)!)
        return URLSession.shared.dataTask(with: request)
    }

    func execute(command: Command) -> Promise<JSON> {
        return self.requestJSON(endPoint: .execute, params: command.json)
    }
}

{'fraction_non_alphanumeric': 0.10696365193978705, 'fraction_numerical': 0.006853506302778117, 'mean_word_length': 2.898854961832061, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4398650', 'n_tokens_mistral': 2328, 'n_tokens_neox': 2227, 'n_words': 600}