1import UIKit
2
3/// Connect to Server, as Files and the Finder offer it: an `smb://` address, then a guest
4/// or an account whose password goes in the Keychain, then a folder to open — or, when
5/// `editing` a server notebook, a new address and folder to relocate it to while keeping
6/// its local changes.
7final class ServerViewController: UITableViewController, UITextFieldDelegate {
8 private static let lastKey = "server"
9
10 private let editingNotebook: Notebook?
11 private let address = UITextField()
12 private let name = UITextField()
13 private let password = UITextField()
14 private let guest = UISegmentedControl(items: ["Guest", "Registered User"])
15 private var connecting = false
16 var onOpen: ((Notebook) -> Void)?
17 var onUpdate: ((@escaping () -> Void) -> Void)?
18
19 init(editing notebook: Notebook? = nil) {
20 self.editingNotebook = notebook
21 super.init(style: .insetGrouped)
22 title = notebook == nil ? "Connect to Server" : "Change Server Address"
23 }
24
25 required init?(coder: NSCoder) { fatalError() }
26
27 override func viewDidLoad() {
28 super.viewDidLoad()
29 navigationItem.leftBarButtonItem = UIBarButtonItem(
30 systemItem: .cancel, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
31 navigationItem.rightBarButtonItem = UIBarButtonItem(
32 title: "Connect", primaryAction: UIAction { [weak self] _ in self?.connect() })
33 address.placeholder = "smb://server/share"
34 address.keyboardType = .URL
35 address.autocapitalizationType = .none
36 address.autocorrectionType = .no
37 address.clearButtonMode = .whileEditing
38 name.placeholder = "Name"
39 name.textContentType = .username
40 name.autocapitalizationType = .none
41 name.autocorrectionType = .no
42 password.placeholder = "Password"
43 password.textContentType = .password
44 password.isSecureTextEntry = true
45 for field in [address, name, password] {
46 field.delegate = self
47 field.returnKeyType = field === password || field === address ? .go : .next
48 }
49 if case .server(let current) = editingNotebook?.source {
50 address.text = current.url
51 guest.selectedSegmentIndex = current.user.isEmpty ? 0 : 1
52 name.text = current.user
53 password.text = current.user.isEmpty ? nil : Keychain.password(current)
54 } else {
55 address.text = UserDefaults.standard.string(forKey: Self.lastKey)
56 guest.selectedSegmentIndex = 1
57 }
58 guest.addAction(UIAction { [weak self] _ in self?.tableView.reloadData() }, for: .valueChanged)
59 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "field")
60 }
61
62 override func viewDidAppear(_ animated: Bool) {
63 super.viewDidAppear(animated)
64 address.becomeFirstResponder()
65 }
66
67 func textFieldShouldReturn(_ field: UITextField) -> Bool {
68 if field === name {
69 password.becomeFirstResponder()
70 } else {
71 connect()
72 }
73 return false
74 }
75
76 private var registered: Bool { guest.selectedSegmentIndex == 1 }
77
78 /// `smb://user@host:port/share/folder`, or the same without a scheme.
79 private func server() -> Server? {
80 Server.parse(address.text ?? "", registered: registered, username: name.text ?? "")
81 }
82
83 private func connect() {
84 guard !connecting else { return }
85 guard let server = server() else {
86 return alert("Enter a Server Address", "Use the form smb://server/share.")
87 }
88 let secret = registered ? password.text ?? "" : ""
89 connecting = true
90 navigationItem.rightBarButtonItem?.isEnabled = false
91 let spinner = UIActivityIndicatorView(style: .medium)
92 spinner.startAnimating()
93 navigationItem.titleView = spinner
94 background({ () -> (Int, String?) in
95 var error: UnsafeMutablePointer<CChar>?
96 let share = sb_share_connect(server.host, server.share, server.user, secret, "", &error)
97 return (Int(bitPattern: share), take(error))
98 }) { [weak self] share, _ in
99 guard let self else { return }
100 connecting = false
101 navigationItem.rightBarButtonItem?.isEnabled = true
102 navigationItem.titleView = nil
103 guard let share = OpaquePointer(bitPattern: share) else {
104 return alert(
105 "Can’t Connect", "Check the address, name and password, and that the server is on this network.")
106 }
107 if registered { Keychain.save(secret, for: server) }
108 if editingNotebook == nil { UserDefaults.standard.set(address.text, forKey: Self.lastKey) }
109 let browser = ShareViewController(
110 share: SharedConnection(share), server: server, path: server.root, editing: editingNotebook)
111 browser.onOpen = onOpen
112 browser.onUpdate = onUpdate
113 navigationController?.pushViewController(browser, animated: true)
114 }
115 }
116
117 override func numberOfSections(in tableView: UITableView) -> Int { registered ? 2 : 1 }
118
119 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 2 }
120
121 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
122 let cell = tableView.dequeueReusableCell(withIdentifier: "field", for: indexPath)
123 cell.contentView.subviews.forEach { $0.removeFromSuperview() }
124 cell.selectionStyle = .none
125 let view: UIView =
126 switch (indexPath.section, indexPath.row) {
127 case (0, 0): address
128 case (0, _): guest
129 case (_, 0): name
130 default: password
131 }
132 view.translatesAutoresizingMaskIntoConstraints = false
133 cell.contentView.addSubview(view)
134 let margins = cell.contentView.layoutMarginsGuide
135 NSLayoutConstraint.activate([
136 view.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
137 view.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
138 view.topAnchor.constraint(equalTo: margins.topAnchor),
139 view.bottomAnchor.constraint(equalTo: margins.bottomAnchor),
140 view.heightAnchor.constraint(greaterThanOrEqualToConstant: 32),
141 ])
142 return cell
143 }
144}
145
146/// A share connection the browser's folders share, closed with the last of them.
147final class SharedConnection {
148 let handle: OpaquePointer
149 init(_ handle: OpaquePointer) { self.handle = handle }
150 deinit { sb_share_free(handle) }
151}
152
153/// A folder on a share: its folders to go into, and Open where it holds a notebook.
154final class ShareViewController: UITableViewController {
155 private struct Listing: Decodable {
156 let notebook: Bool
157 let folders: [String]
158 let sections: [String]
159 }
160
161 private let share: SharedConnection
162 private let server: Server
163 private let path: String
164 private let editingNotebook: Notebook?
165 private var listing: Listing?
166 private var updating = false
167 var onOpen: ((Notebook) -> Void)?
168 var onUpdate: ((@escaping () -> Void) -> Void)?
169
170 init(share: SharedConnection, server: Server, path: String, editing notebook: Notebook? = nil) {
171 self.share = share
172 self.server = server
173 self.path = path
174 self.editingNotebook = notebook
175 super.init(style: .insetGrouped)
176 title = path.split(separator: "/").last.map(String.init) ?? server.share
177 }
178
179 required init?(coder: NSCoder) { fatalError() }
180
181 override func viewDidLoad() {
182 super.viewDidLoad()
183 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "entry")
184 let open = UIBarButtonItem(
185 title: editingNotebook == nil ? "Open" : "Update",
186 primaryAction: UIAction { [weak self] _ in self?.open() })
187 open.style = .done
188 open.isEnabled = false
189 navigationItem.rightBarButtonItem = open
190 var loading = UIContentUnavailableConfiguration.loading()
191 loading.text = "Loading…"
192 contentUnavailableConfiguration = loading
193 let (handle, path) = (Int(bitPattern: share.handle), path)
194 background({
195 decode(Listing.self, sb_share_list(OpaquePointer(bitPattern: handle), path))
196 }) { [weak self] listing in
197 guard let self else { return }
198 self.listing = listing
199 tableView.reloadData()
200 open.isEnabled = listing.map { $0.notebook || !$0.sections.isEmpty } ?? false
201 var empty = UIContentUnavailableConfiguration.empty()
202 if listing == nil {
203 empty.text = "Can’t Read Folder"
204 empty.secondaryText = "Check that this account can open it."
205 if !self.path.isEmpty {
206 var button = UIButton.Configuration.bordered()
207 button.title = "Browse “\(self.server.share)”"
208 empty.button = button
209 empty.buttonProperties.primaryAction = UIAction { [weak self] _ in
210 guard let self else { return }
211 let root = ShareViewController(
212 share: self.share, server: self.server, path: "", editing: self.editingNotebook)
213 root.onOpen = self.onOpen
214 root.onUpdate = self.onUpdate
215 self.navigationController?.pushViewController(root, animated: true)
216 }
217 }
218 } else {
219 empty.text = "No Folders"
220 empty.secondaryText = "OneNote notebooks are folders with sections in them."
221 }
222 contentUnavailableConfiguration =
223 listing.map { $0.folders.isEmpty && $0.sections.isEmpty } ?? true ? empty : nil
224 }
225 }
226
227 private func open() {
228 guard !updating else { return }
229 var server = server
230 server.root = path
231 guard let notebook = editingNotebook else {
232 onOpen?(Notebook(name: server.folderName, source: .server(server)))
233 return
234 }
235 updating = true
236 navigationItem.rightBarButtonItem?.isEnabled = false
237 navigationItem.hidesBackButton = true
238 navigationController?.isModalInPresentation = true
239 let spinner = UIActivityIndicatorView(style: .medium)
240 spinner.startAnimating()
241 navigationItem.titleView = spinner
242 notebook.relocate(to: server) { [weak self] problem, restore in
243 guard let self else { return }
244 updating = false
245 navigationItem.rightBarButtonItem?.isEnabled = true
246 navigationItem.hidesBackButton = false
247 navigationController?.isModalInPresentation = false
248 navigationItem.titleView = nil
249 if let problem {
250 return alert("Can’t Update Server", problem)
251 }
252 onUpdate?(restore)
253 }
254 }
255
256 override func numberOfSections(in tableView: UITableView) -> Int { 2 }
257
258 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
259 section == 0 ? listing?.folders.count ?? 0 : listing?.sections.count ?? 0
260 }
261
262 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
263 section == 1 && !(listing?.sections.isEmpty ?? true) ? "Sections" : nil
264 }
265
266 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
267 let cell = tableView.dequeueReusableCell(withIdentifier: "entry", for: indexPath)
268 var content = cell.defaultContentConfiguration()
269 if indexPath.section == 0 {
270 content.text = listing?.folders[indexPath.row]
271 content.image = UIImage(systemName: "folder.fill")
272 cell.accessoryType = .disclosureIndicator
273 cell.selectionStyle = .default
274 } else {
275 content.text = listing.map { URL(fileURLWithPath: $0.sections[indexPath.row]).deletingPathExtension().lastPathComponent }
276 content.image = UIImage(systemName: "rectangle.portrait.fill")
277 content.imageProperties.tintColor = .secondaryLabel
278 content.textProperties.color = .secondaryLabel
279 cell.accessoryType = .none
280 cell.selectionStyle = .none
281 }
282 cell.contentConfiguration = content
283 return cell
284 }
285
286 override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
287 indexPath.section == 0 ? indexPath : nil
288 }
289
290 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
291 guard let folder = listing?.folders[indexPath.row] else { return }
292 let child = ShareViewController(
293 share: share, server: server, path: path.isEmpty ? folder : "\(path)/\(folder)", editing: editingNotebook)
294 child.onOpen = onOpen
295 child.onUpdate = onUpdate
296 navigationController?.pushViewController(child, animated: true)
297 }
298}