-
Notifications
You must be signed in to change notification settings - Fork 0
/
QRScanViewController.swift
191 lines (166 loc) · 10.1 KB
/
QRScanViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//
// QRScanViewController.swift
// fastSwift
//
// Created by Adrian on 16.09.17.
// Copyright © 2017 Adrian. All rights reserved.
//
import UIKit
import AVFoundation
import AudioToolbox
class QRScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var video = AVCaptureVideoPreviewLayer()
var session = AVCaptureSession()
@IBOutlet weak var denied: UILabel!
static var relaunched = false
// -------------------------------------------------------------------------
// MARK: UIViewController
// -------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
AppDelegate.shared.qrScanner = self
let device = AVCaptureDevice.default(for: AVMediaType.video)
if device != nil {
do {
let input = try AVCaptureDeviceInput(device: device!)
session.addInput(input)
} catch let error {
print("Error: \(error)")
}
var cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch cameraAuthorizationStatus {
case .denied:
view.viewWithTag(1)!.isHidden = true
case .authorized:
showCam() // Show cam only if user has authorized it
case .restricted: break
case .notDetermined: // If the user hasn't putted anything, wait for it
print("Not determined!")
let _ = Repea.t(all: 0.2, seconds: { (timer) in
if cameraAuthorizationStatus == .notDetermined {
cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
} else if !QRScanViewController.relaunched {
let launchScreen = AppViewControllers().launchScreen
launchScreen.menu = AppViewControllers().menu
launchScreen.menu.loadedStore = AppDelegate.shared.menu.loadedStore
launchScreen.menu.mainVCIndex = AppDelegate.shared.menu.mainVCIndex
QRScanViewController.relaunched = true
AppDelegate.shared.window?.rootViewController = launchScreen
}
})
}
}
view.backgroundColor = AppDelegate.shared.theme.color
denied.textColor = AppDelegate.shared.theme.textColor
}
// -------------------------------------------------------------------------
// MARK: Camera
// -------------------------------------------------------------------------
func showCam() {
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.init(label: "qr"))
output.metadataObjectTypes = [AVMetadataMachineReadableCodeObject.ObjectType.qr]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.frame
view.layer.addSublayer(video)
session.startRunning()
view.bringSubview(toFront: view.viewWithTag(1)!)
}
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects.isEmpty {
return
}
if let _ = presentedViewController as? UIAlertController {
return
}
if let terminal = AppDelegate.shared.topViewController() as? NMTerminalViewController { // Send text to terminal
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
if object.type == .qr {
if let str = object.stringValue?.replacingOccurrences(of: "\n", with: "") {
if terminal.session.isConnected {
if terminal.session.isAuthorized {
if !terminal.terminal.text.hasSuffix(str) {
DispatchQueue.main.async {
if terminal.terminal.isEditable {
AudioServicesPlaySystemSound(1307)
terminal.terminal.text = terminal.terminal.text+str
return
}
}
}
}
}
}
}
}
}
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
if object.type == .qr {
if let str = object.stringValue {
if str.hasPrefix("$SERVER=") { // is server
AudioServicesPlaySystemSound(1307)
let server = str.replacingOccurrences(of: "$SERVER=", with: "")
if let userName = server.components(separatedBy: "@").first {
if let address = server.components(separatedBy: "@").last?.components(separatedBy: ";").first {
if let password = server.components(separatedBy: ";").last {
DispatchQueue.main.async {
AlertManager.shared.presentAlert(withTitle: "Detected Server!", message: "Do you want to use server '\(userName)@\(address)' with password '\(password)'?", style: .alert, actions: [UIAlertAction.init(title: "Cancel", style: .cancel, handler: { (action) in
self.session.startRunning()
}), AlertManager.shared.ok(handler: { (action) in
UserDefaults.standard.set(address, forKey: "hostname")
UserDefaults.standard.set(userName, forKey: "username")
UserDefaults.standard.set(password, forKey: "password")
UserDefaults.standard.set(true, forKey: "custom_server")
self.session.startRunning()
AppDelegate.shared.menu.showSettings()
})], inside: self, animated: true, completion: nil)
}
}
}
}
} else if str.hasPrefix("$CODE=") { // is a script
AudioServicesPlaySystemSound(1307)
let script = str.replacingOccurrences(of: "$CODE=", with: "")
if let url = URL(string:script) {
DispatchQueue.main.async {
AlertManager.shared.presentAlert(withTitle: "Detected script!", message: "Do you want to run this script?", style: .alert, actions: [UIAlertAction.init(title: "Cancel", style: .cancel, handler: { (action) in
}), UIAlertAction.init(title: "Ok", style: .default, handler: { (alert) in
let activity = ActivityViewController(message: "Downloading...")
self.present(activity, animated: true, completion: nil)
URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
if error == nil {
if url != nil {
let finalURL = url!.deletingLastPathComponent().appendingPathComponent(response!.suggestedFilename!)
do {
try FileManager.default.moveItem(at: url!, to: finalURL)
self.dismiss(animated: true, completion: {
let _ = AppDelegate.shared.application(UIApplication.shared, open: finalURL)
})
} catch let error {
self.dismiss(animated: true, completion: {
AlertManager.shared.presentAlert(withTitle: "Error moving file!", message: error.localizedDescription, style: .alert, actions: [AlertManager.shared.cancel], inside: self, animated: true, completion: nil)
})
}
} else {
self.dismiss(animated: true, completion: {
AlertManager.shared.presentAlert(withTitle: "Error downloading file!", message: "Returned data is empty", style: .alert, actions: [AlertManager.shared.cancel], inside: self, animated: true, completion: nil)
})
}
} else {
self.dismiss(animated: true, completion: {
AlertManager.shared.present(error: error!, withTitle: "Error downloading file!", inside: self)
})
}
}).resume()
})], inside: self, animated: true, completion: nil)
}
}
} else {
AudioServicesPlaySystemSound(1102)
}
}
}
}
}
}