<commit_before>//
//  BackgroundDownloader.swift
//  TwentyOne
//
//  Created by <NAME> on 11/11/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import UIKit

public class BackgroundDownloader: NSObject, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate
{
	var completionHandler:(UIBackgroundFetchResult) -> Void

	public init(completionHandler:(UIBackgroundFetchResult) -> Void)
	{
		self.completionHandler = completionHandler
	}

	public func updateBlockList()
	{
		Logger.log("Beginning background download...");

		let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(Constants.BackgroundSessionID)
		configuration.sessionSendsLaunchEvents = true
		configuration.sharedContainerIdentifier = Constants.AppGroupID

		let session = NSURLSession.init(configuration:configuration, delegate:self, delegateQueue:nil)
		let downloadTask = session.downloadTaskWithRequest(NSURLRequest.init(URL:Constants.BlockListURL))
		downloadTask.resume()
	}

	public func URLSession(session:NSURLSession, task:NSURLSessionTask, didCompleteWithError error:NSError?)
	{
		if error != nil {
			self.completionHandler(.Failed)
		}
	}

	public func URLSession(session:NSURLSession, downloadTask:NSURLSessionDownloadTask, didFinishDownloadingToURL temporaryURL:NSURL)
	{
		Logger.log("Finished downloading");
		let newData = NSData.init(contentsOfURL:temporaryURL)

		/* See if block list has changed */
		var uncoordinatedURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Constants.AppGroupID)!;
		uncoordinatedURL = uncoordinatedURL.URLByAppendingPathComponent(Constants.BlockListFilename)
		let fileCoordinator = NSFileCoordinator.init(filePresenter:nil)
		var error:NSError?
		var operationDidFinish:Bool = false
		var theSame = false
		fileCoordinator.coordinateReadingItemAtURL(uncoordinatedURL, options:.ResolvesSymbolicLink, error:&error, byAccessor:{(readingURL) in
			let oldData = NSData.init(contentsOfURL:readingURL)
			theSame = (oldData == newData)
			operationDidFinish = true
		});

		if error != nil {
			Logger.log("ERROR (comparing data): \(error)")
			self.completionHandler(.Failed)
			return
		}

		if operationDidFinish != true {
			Logger.log("ERROR (comparing data): Operation did not finish")
			self.completionHandler(.Failed)
			return
		}

		if (theSame) {
			Logger.log("Data was the same, not re-writing")
			self.completionHandler(.NoData)
		} else {
			Logger.log("Data was different, writing")
			BackgroundDownloader.saveBlockListWithData(newData)
			self.completionHandler(.NewData)
		}
	}

	private static func saveBlockListWithData(data:NSData?)
	{
		if data == nil {
			Logger.log("ERROR (saving file): data was nil")
			return
		}

		let fileCoordinator = NSFileCoordinator.init(filePresenter:nil)
		var uncoordinatedURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Constants.AppGroupID)!;
		uncoordinatedURL = uncoordinatedURL.URLByAppendingPathComponent(Constants.BlockListFilename)
		var error:NSError?
		var operationDidFinish:Bool = false
		fileCoordinator.coordinateWritingItemAtURL(uncoordinatedURL, options:.ForReplacing, error:&error, byAccessor:{(writingURL) in
			let fileManager = NSFileManager.init()
			if fileManager.fileExistsAtPath(writingURL.path!) {
				do {
					try fileManager.replaceItemAtURL(writingURL, withItemAtURL:uncoordinatedURL, backupItemName:nil, options:.UsingNewMetadataOnly, resultingItemURL:nil)
				}
				catch let error as NSError {
					operationDidFinish = false
					Logger.log("ERROR: \(error.localizedDescription)")
				}
			} else {
				operationDidFinish = data!.writeToURL(writingURL, atomically:true)
			}
		})

		if error != nil {
			Logger.log("ERROR (saving file): \(error?.localizedDescription)")
			return
		}

		if operationDidFinish != true {
			Logger.log("ERROR (saving file): Operation did not complete successfully")
			return
		}
	}
}<commit_msg>Use default file manager.<commit_after>//
//  BackgroundDownloader.swift
//  TwentyOne
//
//  Created by <NAME> on 11/11/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import UIKit

public class BackgroundDownloader: NSObject, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate
{
	var completionHandler:(UIBackgroundFetchResult) -> Void

	public init(completionHandler:(UIBackgroundFetchResult) -> Void)
	{
		self.completionHandler = completionHandler
	}

	public func updateBlockList()
	{
		Logger.log("Beginning background download...");

		let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(Constants.BackgroundSessionID)
		configuration.sessionSendsLaunchEvents = true
		configuration.sharedContainerIdentifier = Constants.AppGroupID

		let session = NSURLSession.init(configuration:configuration, delegate:self, delegateQueue:nil)
		let downloadTask = session.downloadTaskWithRequest(NSURLRequest.init(URL:Constants.BlockListURL))
		downloadTask.resume()
	}

	public func URLSession(session:NSURLSession, task:NSURLSessionTask, didCompleteWithError error:NSError?)
	{
		if error != nil {
			self.completionHandler(.Failed)
		}
	}

	public func URLSession(session:NSURLSession, downloadTask:NSURLSessionDownloadTask, didFinishDownloadingToURL temporaryURL:NSURL)
	{
		Logger.log("Finished downloading");
		let newData = NSData.init(contentsOfURL:temporaryURL)

		/* See if block list has changed */
		var uncoordinatedURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Constants.AppGroupID)!;
		uncoordinatedURL = uncoordinatedURL.URLByAppendingPathComponent(Constants.BlockListFilename)
		let fileCoordinator = NSFileCoordinator.init(filePresenter:nil)
		var error:NSError?
		var operationDidFinish:Bool = false
		var theSame = false
		fileCoordinator.coordinateReadingItemAtURL(uncoordinatedURL, options:.ResolvesSymbolicLink, error:&error, byAccessor:{(readingURL) in
			let oldData = NSData.init(contentsOfURL:readingURL)
			theSame = (oldData == newData)
			operationDidFinish = true
		});

		if error != nil {
			Logger.log("ERROR (comparing data): \(error)")
			self.completionHandler(.Failed)
			return
		}

		if operationDidFinish != true {
			Logger.log("ERROR (comparing data): Operation did not finish")
			self.completionHandler(.Failed)
			return
		}

		if (theSame) {
			Logger.log("Data was the same, not re-writing")
			self.completionHandler(.NoData)
		} else {
			Logger.log("Data was different, writing")
			BackgroundDownloader.saveBlockListWithData(newData)
			self.completionHandler(.NewData)
		}
	}

	private static func saveBlockListWithData(data:NSData?)
	{
		if data == nil {
			Logger.log("ERROR (saving file): data was nil")
			return
		}

		let fileCoordinator = NSFileCoordinator.init(filePresenter:nil)
		var uncoordinatedURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(Constants.AppGroupID)!;
		uncoordinatedURL = uncoordinatedURL.URLByAppendingPathComponent(Constants.BlockListFilename)
		var error:NSError?
		var operationDidFinish:Bool = false
		fileCoordinator.coordinateWritingItemAtURL(uncoordinatedURL, options:.ForReplacing, error:&error, byAccessor:{(writingURL) in
			let fileManager = NSFileManager.defaultManager()
			if fileManager.fileExistsAtPath(writingURL.path!) {
				do {
					try fileManager.replaceItemAtURL(writingURL, withItemAtURL:uncoordinatedURL, backupItemName:nil, options:.UsingNewMetadataOnly, resultingItemURL:nil)
				}
				catch let error as NSError {
					operationDidFinish = false
					Logger.log("ERROR: \(error.localizedDescription)")
				}
			} else {
				operationDidFinish = data!.writeToURL(writingURL, atomically:true)
			}
		})

		if error != nil {
			Logger.log("ERROR (saving file): \(error?.localizedDescription)")
			return
		}

		if operationDidFinish != true {
			Logger.log("ERROR (saving file): Operation did not complete successfully")
			return
		}
	}
}
{'fraction_non_alphanumeric': 0.09727479182437547, 'fraction_numerical': 0.0025233409033560434, 'mean_word_length': 5.408245755860954, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4023654', 'n_tokens_mistral': 2619, 'n_tokens_neox': 2269, 'n_words': 449}