forked from glushchenko/fsnotes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShareViewController.swift
361 lines (293 loc) · 13.6 KB
/
ShareViewController.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//
// ShareViewController.swift
// FSNotes iOS Share
//
// Created by Oleksandr Glushchenko on 3/18/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import UIKit
import MobileCoreServices
import Social
import NightNight
import Kanna
@objc(ShareViewController)
class ShareViewController: SLComposeServiceViewController {
private var notes: [Note]?
private var projects: [Project]?
private var imagesFound = false
private var urlPreview: String?
private var instagram: Data?
public var currentProject: Project?
public let projectItem = SLComposeSheetConfigurationItem()
public let appendItem = SLComposeSheetConfigurationItem()
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
_ = NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { (_) in
if let layoutContainerView = self.view.subviews.last {
layoutContainerView.frame.size.height += 45
}
}
}
preferredContentSize = CGSize(width: 300, height: 300)
navigationController!.navigationBar.topItem!.rightBarButtonItem!.title = NSLocalizedString("New note", comment: "")
navigationController?.navigationBar.backgroundColor = Colors.Header.normalResource
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.barTintColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 20))
let font = UserDefaultsManagement.noteFont.italic().bold().withSize(16)
label.text = "FSNotes"
label.font = font
label.textColor = UIColor.white
navigationController?.navigationBar.topItem?.titleView = label
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.setContentOffset(.zero, animated: true)
if let table = textView.superview?.superview?.superview as? UITableView {
let length = table.numberOfRows(inSection: 0)
table.scrollToRow(at: IndexPath(row: length - 1, section: 0), at: .bottom, animated: true)
for item in 0...2 {
if let cell = table.cellForRow(at: IndexPath(item: item, section: 0)) {
cell.textLabel?.textColor = UIColor(red:0.19, green:0.38, blue:0.57, alpha:1.0)
}
}
}
if let font = self.textView.font, #available(iOSApplicationExtension 11.0, *) {
let fontMetrics = UIFontMetrics(forTextStyle: .largeTitle)
self.textView.font = fontMetrics.scaledFont(for: font).italic()
self.textView.textColor = UIColor.darkGray
}
}
override func loadPreviewView() -> UIView! {
urlPreview = self.textView.text
if let context = self.extensionContext,
let input = context.inputItems as? [NSExtensionItem] {
for row in input {
if let attach = row.attachments {
for attachRow in attach {
if attachRow.hasItemConformingToTypeIdentifier(kUTTypeImage as String) || attachRow.hasItemConformingToTypeIdentifier(kUTTypeJPEG as String){
imagesFound = true
textView.text = ""
return super.loadPreviewView()
}
if attachRow.hasItemConformingToTypeIdentifier(kUTTypeURL as String) {
attachRow.loadItem(forTypeIdentifier: kUTTypeURL as String, options: nil, completionHandler: { (url, error) in
guard let url = url as? URL else { return }
guard !url.absoluteString.startsWith(string: "file:///") else {
if let fileContent = try? Data(contentsOf: url), let text = String(data: fileContent, encoding: String.Encoding.utf8) {
DispatchQueue.main.async {
self.textView.text = text
}
}
return
}
let data = url as NSURL
self.checkInstagram(data: data)
DispatchQueue.main.async {
let preview = self.urlPreview ?? String()
self.textView.text = "\(preview)\n\n\(url.absoluteString)".trimmingCharacters(in: .whitespacesAndNewlines)
}
})
}
}
}
}
}
return UIView()
}
override func isContentValid() -> Bool {
return true
}
override func didSelectPost() {
save()
}
override func configurationItems() -> [Any]! {
let storage = Storage.sharedInstance()
var urls = [URL]()
if let inbox = UserDefaultsManagement.storageUrl {
urls.append(inbox)
}
if let archive = UserDefaultsManagement.archiveDirectory {
urls.append(archive)
}
urls.append(contentsOf: UserDefaultsManagement.projects)
storage.loadProjects(from: urls)
projectItem?.title = NSLocalizedString("Project", comment: "")
projectItem?.tapHandler = {
let controller = ProjectListController()
controller.delegate = self
let projects = storage.getProjects()
controller.setProjects(projects: projects)
self.pushConfigurationViewController(controller)
}
appendItem?.title = NSLocalizedString("Append to", comment: "")
DispatchQueue.global().async {
if let projectURL = UserDefaultsManagement.lastSelectedURL,
let project = storage.getProjectBy(url: projectURL)
{
self.currentProject = project
self.loadNotesFrom(project: project)
}
DispatchQueue.main.async {
self.projectItem?.value = self.currentProject?.label
}
if let note = self.notes?.first {
note.load()
note.loadPreviewInfo()
DispatchQueue.main.async {
self.appendItem?.value = note.getName()
self.appendItem?.tapHandler = {
self.save(note: note)
}
}
}
}
guard let select = SLComposeSheetConfigurationItem() else { return [] }
select.title = NSLocalizedString("Choose for append", comment: "")
select.tapHandler = {
if let notes = self.notes {
let controller = NotesListController()
controller.delegate = self
controller.setNotes(notes: notes)
self.pushConfigurationViewController(controller)
}
}
return [self.projectItem!, self.appendItem!, select]
}
public func save(note: Note? = nil) {
guard let context = self.extensionContext,
let input = context.inputItems as? [NSExtensionItem] else { return }
let note = note ?? Note(project: self.currentProject)
Storage.sharedInstance().add(note)
var started = 0
var finished = 0
var urls = UserDefaultsManagement.importURLs
urls.insert(note.url, at: 0)
UserDefaultsManagement.importURLs = urls
if let instagram = self.instagram {
note.append(image: instagram)
note.append(string: NSMutableAttributedString(string: "\n\n" + self.textView.text))
note.write()
self.close()
return
}
for item in input {
if let a = item.attachments {
for provider in a {
if provider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
started = started + 1
provider.loadItem(forTypeIdentifier: kUTTypeImage as String, options: nil, completionHandler: { (data, error) in
var imageData = data as? Data
if let image = data as? UIImage {
imageData = image.jpegData(compressionQuality: 1)
} else if let url = data as? URL {
imageData = try? Data.init(contentsOf: url)
}
let url = data as? URL
if let data = imageData {
note.append(image: data, url: url)
}
finished = finished + 1
if started == finished {
if self.textView.text.count > 0 {
note.append(string: NSMutableAttributedString(string: "\n\n" + self.textView.text))
}
note.write()
self.close()
return
}
})
} else if provider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) {
if !imagesFound, let contentText = self.contentText {
guard let url = URL(string: contentText) else {
// File URL provided, but text is loaded in textView
note.append(string: NSMutableAttributedString(string: contentText))
note.write()
self.close()
return
}
let data = try? Data(contentsOf: url)
if let data = data, let image = UIImage(data: data), image.size.width > 0 {
note.append(image: data)
} else {
let prefix = self.getPrefix(for: note)
let string = NSMutableAttributedString(string: "\(prefix)\(contentText)")
note.append(string: string)
}
note.write()
self.close()
return
}
} else if provider.hasItemConformingToTypeIdentifier(kUTTypeText as String) {
if !imagesFound, let contentText = self.contentText {
let prefix = self.getPrefix(for: note)
let string = NSMutableAttributedString(string: "\(prefix)\(contentText)")
note.append(string: string)
note.write()
self.close()
return
}
}
}
}
}
self.close()
}
// private func checkImage() -> UIImage {
// attachRow.loadItem(forTypeIdentifier: kUTTypeURL as String, options: nil, completionHandler: { (url, error) in
//
// })
// }
public func close() {
if let context = self.extensionContext {
context.completeRequest(returningItems: context.inputItems, completionHandler: nil)
}
}
private func getPrefix(for note: Note) -> String {
if note.content.length == 0 {
return String()
}
return "\n\n"
}
public func loadNotesFrom(project: Project) {
let storage = Storage.sharedInstance()
if storage.getNotesBy(project: project).count == 0 {
storage.loadNotes(project)
}
let notes = storage.noteList.filter({$0.project == project })
self.notes = storage.sortNotes(noteList: notes, filter: "")
if let notes = self.notes {
DispatchQueue.main.async {
if let note = notes.first {
note.load()
note.loadPreviewInfo()
self.appendItem?.value = note.title
}
}
}
}
private func checkInstagram(data: NSURL) {
if let path = data.absoluteString, path.starts(with: "https://www.instagram.com") {
let html = try? String(contentsOf: data as URL)
if let doc = try? Kanna.HTML(html: html!, encoding: String.Encoding.utf8) {
if let metaSet = doc.head?.css("meta") {
for meta in metaSet {
if let property = meta["property"]?.lowercased {
if property().hasPrefix("og:image"), let imagePath = meta["content"] {
if let imURL = URL(string: imagePath), let instaData = try? Data(contentsOf: imURL) {
self.instagram = instaData
DispatchQueue.main.async {
self.textView.text = imURL.path
}
}
break
}
}
}
}
}
}
}
}