<commit_before>//
//  BrowserViewControllerExtension.swift
//  Client
//
//  Created by Sahakyan on 4/28/16.
//  Copyright © 2016 Mozilla. All rights reserved.
//

import Foundation
import JavaScriptCore

extension BrowserViewController: ControlCenterViewDelegate {

	func loadInitialURL() {
		if let urlString = self.initialURL,
		   let url = NSURL(string: urlString) {
			self.navigateToURL(url)
            if let tab = tabManager.selectedTab {
                tab.url = url
            }
			self.initialURL = nil
		}
	}

    func askForNewsNotificationPermissionIfNeeded () {
        if (NewsNotificationPermissionHelper.sharedInstance.shouldAskForPermission() ){
            let controller = UINavigationController(rootViewController: NewsNotificationPermissionViewController())
            if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
                controller.preferredContentSize = CGSize(width: NewsNotificationPermissionViewControllerUX.Width, height: NewsNotificationPermissionViewControllerUX.Height)
                controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
            }
            
            self.presentViewController(controller, animated: true, completion: {
                self.urlBar.leaveOverlayMode()
            })
        }
    }

	func downloadVideoFromURL(url: String, sourceRect: CGRect) {
		if let filepath = NSBundle.mainBundle().pathForResource("main", ofType: "js") {
			do {
                let hudMessage = NSLocalizedString("Retrieving video information", tableName: "Cliqz", comment: "HUD message displayed while youtube downloader grabing the download URLs of the video")
                FeedbackUI.showLoadingHUD(hudMessage)
				let jsString = try NSString(contentsOfFile:filepath, encoding: NSUTF8StringEncoding)
				let context = JSContext()
				let httpRequest = XMLHttpRequest()
				httpRequest.extendJSContext(context)
				context.exceptionHandler = { context, exception in
					debugPrint("JS Error: \(exception)")
				}
				context.evaluateScript(jsString as String)
				let callback: @convention(block)([AnyObject])->()  = { [weak self] (urls) in
                    self?.downloadVideoOfSelectedFormat(urls, sourceRect: sourceRect)
				}
				let callbackName = "URLReceived"
				context.setObject(unsafeBitCast(callback, AnyObject.self), forKeyedSubscript: callbackName)
				context.evaluateScript("window.ytdownloader.getUrls('\(url)', \(callbackName))")
			} catch {
				debugPrint("Couldn't load file")
			}
		}
	}
	
	func downloadVideoOfSelectedFormat(urls: [AnyObject], sourceRect: CGRect) {
		if urls.count > 0 {
			TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("page_load", "is_downloadable", "true"))
		} else {
			TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("page_load", "is_downloadable", "false"))
		}
        FeedbackUI.dismissHUD()
        let title = NSLocalizedString("Video quality", tableName: "Cliqz", comment: "Youtube downloader action sheet title")
        let message = NSLocalizedString("Please select video quality", tableName: "Cliqz", comment: "Youtube downloader action sheet message")
 		let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
		for url in urls {
			if let f = url["label"] as? String, u = url["url"] as? String {
				actionSheet.addAction(UIAlertAction(title: f, style: .Default, handler: { _ in
					YoutubeVideoDownloader.downloadFromURL(u)
                    TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("click", "target", f.replace(" ", replacement: "_")))
				}))
			}
		}
        actionSheet.addAction(UIAlertAction(title: UIConstants.CancelString, style: .Cancel, handler: { _ in
            TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("click", "target", "cancel"))
        }))
        
        if let popoverPresentationController = actionSheet.popoverPresentationController {
            popoverPresentationController.sourceView = view
            let center = self.view.center
            popoverPresentationController.sourceRect = CGRectMake(center.x, center.y, 1, 1)
            popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        }
		self.presentViewController(actionSheet, animated: true, completion: nil)
	}
	
	func SELBadRequestDetected(notification: NSNotification) {
		dispatch_async(dispatch_get_main_queue()) {
			
			if let tabId = notification.object as? Int where self.tabManager.selectedTab?.webView?.uniqueId == tabId {
                let newCount = (self.tabManager.selectedTab?.webView?.unsafeRequests)!
                self.urlBar.updateTrackersCount(newCount)
                if newCount > 0 && InteractiveIntro.sharedInstance.shouldShowAntitrackingHint {
                    self.showHint(.Antitracking)
                }
			}
			
		}
	}
    
	func urlBarDidClickAntitracking(urlBar: URLBarView, trackersCount: Int, status: String) {
        
        if let controlCenter = self.controlCenterController {
            if controlCenter.visible == true {
                self.controlCenterController?.closeControlCenter()
                self.controlCenterController?.visible = false
                
                // log telemetry signal
                let customData : [String: AnyObject] = ["tracker_count": trackersCount, "status": status, "state": "open"]
                logToolbarSignal("click", target: "control_center", customData: customData)
                
                return
            }
        }
        
        if let tab = self.tabManager.selectedTab, webView = tab.webView, url = webView.URL {
        
            let panelLayout = OrientationUtil.controlPanelLayout()
            
            let controlCenterVC = ControlCenterViewController(webViewID: webView.uniqueId, url:url, privateMode: tab.isPrivate)
            controlCenterVC.delegate = self
            controlCenterVC.controlCenterDelegate = self
            self.addChildViewController(controlCenterVC)
            self.controlCenterController = controlCenterVC
            
            let toolbarHeight: CGFloat = 44.0
            
            if (panelLayout != .LandscapeRegularSize){
                var r = self.view.bounds
                r.origin.y = -r.size.height
                r.size.height = r.size.height - toolbarHeight
                controlCenterVC.view.frame = r
            }
            else{
                var r = self.view.frame
                r.origin.x = r.size.width<commit_msg>[IB-1114] CC in Reader Mode shows localhost instead of the domain<commit_after>//
//  BrowserViewControllerExtension.swift
//  Client
//
//  Created by Sahakyan on 4/28/16.
//  Copyright © 2016 Mozilla. All rights reserved.
//

import Foundation
import JavaScriptCore

extension BrowserViewController: ControlCenterViewDelegate {

	func loadInitialURL() {
		if let urlString = self.initialURL,
		   let url = NSURL(string: urlString) {
			self.navigateToURL(url)
            if let tab = tabManager.selectedTab {
                tab.url = url
            }
			self.initialURL = nil
		}
	}

    func askForNewsNotificationPermissionIfNeeded () {
        if (NewsNotificationPermissionHelper.sharedInstance.shouldAskForPermission() ){
            let controller = UINavigationController(rootViewController: NewsNotificationPermissionViewController())
            if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
                controller.preferredContentSize = CGSize(width: NewsNotificationPermissionViewControllerUX.Width, height: NewsNotificationPermissionViewControllerUX.Height)
                controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
            }
            
            self.presentViewController(controller, animated: true, completion: {
                self.urlBar.leaveOverlayMode()
            })
        }
    }

	func downloadVideoFromURL(url: String, sourceRect: CGRect) {
		if let filepath = NSBundle.mainBundle().pathForResource("main", ofType: "js") {
			do {
                let hudMessage = NSLocalizedString("Retrieving video information", tableName: "Cliqz", comment: "HUD message displayed while youtube downloader grabing the download URLs of the video")
                FeedbackUI.showLoadingHUD(hudMessage)
				let jsString = try NSString(contentsOfFile:filepath, encoding: NSUTF8StringEncoding)
				let context = JSContext()
				let httpRequest = XMLHttpRequest()
				httpRequest.extendJSContext(context)
				context.exceptionHandler = { context, exception in
					debugPrint("JS Error: \(exception)")
				}
				context.evaluateScript(jsString as String)
				let callback: @convention(block)([AnyObject])->()  = { [weak self] (urls) in
                    self?.downloadVideoOfSelectedFormat(urls, sourceRect: sourceRect)
				}
				let callbackName = "URLReceived"
				context.setObject(unsafeBitCast(callback, AnyObject.self), forKeyedSubscript: callbackName)
				context.evaluateScript("window.ytdownloader.getUrls('\(url)', \(callbackName))")
			} catch {
				debugPrint("Couldn't load file")
			}
		}
	}
	
	func downloadVideoOfSelectedFormat(urls: [AnyObject], sourceRect: CGRect) {
		if urls.count > 0 {
			TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("page_load", "is_downloadable", "true"))
		} else {
			TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("page_load", "is_downloadable", "false"))
		}
        FeedbackUI.dismissHUD()
        let title = NSLocalizedString("Video quality", tableName: "Cliqz", comment: "Youtube downloader action sheet title")
        let message = NSLocalizedString("Please select video quality", tableName: "Cliqz", comment: "Youtube downloader action sheet message")
 		let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
		for url in urls {
			if let f = url["label"] as? String, u = url["url"] as? String {
				actionSheet.addAction(UIAlertAction(title: f, style: .Default, handler: { _ in
					YoutubeVideoDownloader.downloadFromURL(u)
                    TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("click", "target", f.replace(" ", replacement: "_")))
				}))
			}
		}
        actionSheet.addAction(UIAlertAction(title: UIConstants.CancelString, style: .Cancel, handler: { _ in
            TelemetryLogger.sharedInstance.logEvent(.YoutubeVideoDownloader("click", "target", "cancel"))
        }))
        
        if let popoverPresentationController = actionSheet.popoverPresentationController {
            popoverPresentationController.sourceView = view
            let center = self.view.center
            popoverPresentationController.sourceRect = CGRectMake(center.x, center.y, 1, 1)
            popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        }
		self.presentViewController(actionSheet, animated: true, completion: nil)
	}
	
	func SELBadRequestDetected(notification: NSNotification) {
		dispatch_async(dispatch_get_main_queue()) {
			
			if let tabId = notification.object as? Int where self.tabManager.selectedTab?.webView?.uniqueId == tabId {
                let newCount = (self.tabManager.selectedTab?.webView?.unsafeRequests)!
                self.urlBar.updateTrackersCount(newCount)
                if newCount > 0 && InteractiveIntro.sharedInstance.shouldShowAntitrackingHint {
                    self.showHint(.Antitracking)
                }
			}
			
		}
	}
    
	func urlBarDidClickAntitracking(urlBar: URLBarView, trackersCount: Int, status: String) {
        
        if let controlCenter = self.controlCenterController {
            if controlCenter.visible == true {
                self.controlCenterController?.closeControlCenter()
                self.controlCenterController?.visible = false
                
                // log telemetry signal
                let customData : [String: AnyObject] = ["tracker_count": trackersCount, "status": status, "state": "open"]
                logToolbarSignal("click", target: "control_center", customData: customData)
                
                return
            }
        }
        
        if let tab = self.tabManager.selectedTab, webView = tab.webView, url = self.urlBar.currentURL {
        
            let panelLayout = OrientationUtil.controlPanelLayout()
            
            let controlCenterVC = ControlCenterViewController(webViewID: webView.uniqueId, url:url, privateMode: tab.isPrivate)
            controlCenterVC.delegate = self
            controlCenterVC.controlCenterDelegate = self
            self.addChildViewController(controlCenterVC)
            self.controlCenterController = controlCenterVC
            
            let toolbarHeight: CGFloat = 44.0
            
            if (panelLayout != .LandscapeRegularSize){
                var r = self.view.bounds
                r.origin.y = -r.size.height
                r.size.height = r.size.height - toolbarHeight
                controlCenterVC.view.frame = r
            }
            else{
                var r = self.view.frame
                r.origin.x = r.size.width
{'fraction_non_alphanumeric': 0.09308692676249145, 'fraction_numerical': 0.0030420564301467793, 'mean_word_length': 2.8104897131266298, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '15927', 'n_tokens_mistral': 3787, 'n_tokens_neox': 3407, 'n_words': 721}