-
-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathHelpers.swift
More file actions
279 lines (243 loc) · 9.4 KB
/
Helpers.swift
File metadata and controls
279 lines (243 loc) · 9.4 KB
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
//
// Helpers.swift
// MeetingBar
//
// Created by Andrii Leitsius on 12.06.2020.
// Copyright © 2020 Andrii Leitsius. All rights reserved.
//
import AppKit
import Cocoa
import Defaults
import EventKit
import Foundation
struct Bookmark: Codable, Defaults.Serializable, Hashable {
var name: String
var service: MeetingServices
var url: URL
}
struct ProcessedEvent: Codable, Defaults.Serializable, Hashable {
var id: String
var lastModifiedDate: Date?
var eventEndDate: Date
}
/**
* this method will extract m365 safe links if any of these links are found in the given text..
* The method will extract the real url from safe links and decode it, so that the following regex logic can detect the meeting service.
*
* The original link looks like this
*https://nam12.safelinks.protection.outlook.com/ap/t-59584e83/?url=https%3A%2F%2Fteams.microsoft.com%2Fl%2Fmeetup-join%2F19%253ameeting_[obfuscated]&data=[obfuscated]
*
* and the method will extract it to https://teams.microsoft.com/l/meetup-join/19%3ameeting_[obfuscated]
* If no m365 links are found, the original text is returned.
*
*/
func cleanupOutlookSafeLinks(rawText: String) -> String {
var text = rawText
autoreleasepool {
var links = UtilsRegex.outlookSafeLinkRegex.matches(in: text, range: NSRange(text.startIndex..., in: text))
if !links.isEmpty {
repeat {
let urlRange = links[0].range(at: 1)
let safeLinks = links.map { String(text[Range($0.range, in: text)!]) }
if !safeLinks.isEmpty {
let serviceUrl = (text as NSString).substring(with: urlRange)
if let decodedServiceURL = serviceUrl.decodeUrl() {
text = text.replacingOccurrences(of: safeLinks[0], with: decodedServiceURL)
}
}
links = UtilsRegex.outlookSafeLinkRegex.matches(in: text, range: NSRange(text.startIndex..., in: text))
} while !links.isEmpty
}
}
return text
}
func getMatch(text: String, regex: NSRegularExpression) -> String? {
var match: String?
autoreleasepool {
let resultsIterator = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
let resultsMap = resultsIterator.map { String(text[Range($0.range, in: text)!]) }
if !resultsMap.isEmpty {
match = resultsMap[0]
}
}
return match
}
func cleanUpNotes(_ notes: String) -> String {
let zoomSeparator = "\n──────────"
let meetSeparator = "-::~:~::~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~::~:~::-"
let cleanNotes = notes
.components(separatedBy: zoomSeparator)[0]
.components(separatedBy: meetSeparator)[0]
.htmlTagsStripped()
return cleanNotes
}
func compareVersions(_ versionX: String, _ versionY: String) -> Bool {
versionX.compare(versionY, options: .numeric) == .orderedDescending
}
func addInstalledBrowser() {
let existingBrowsers = Defaults[.browsers]
var appUrls = LSCopyApplicationURLsForURL(URL(string: "https:")! as CFURL, .all)?.takeRetainedValue() as? [URL]
if !appUrls!.isEmpty {
appUrls = appUrls?.sorted { $0.path.fileName() < $1.path.fileName() }
appUrls?.forEach {
let browser = Browser(name: $0.path.fileName(), path: $0.path)
if !existingBrowsers.contains(where: { $0.name == browser.path.fileName() }) {
Defaults[.browsers].append(browser)
}
}
}
}
func hexStringToUIColor(hex: String) -> NSColor {
var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if cString.hasPrefix("#") {
cString.remove(at: cString.startIndex)
}
if (cString.count) != 6 {
return NSColor.gray
}
var rgbValue: UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return NSColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
@MainActor func createNSViewFromText(text: String) -> NSView {
// Create views
let paddingView = NSView()
let textView = NSTextView()
paddingView.addSubview(textView)
// Text styling
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
textView.textStorage?.setAttributedString(
text.splitWithNewLineAttributedString(
with: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: NSFont.systemFont(ofSize: 14)
],
maxWidth: 300.0
)
.withLinksEnabled()
)
textView.backgroundColor = .clear
textView.textColor = .textColor
// Adjust frame layout for padding
if let textContainer = textView.textContainer {
textView.layoutManager?.ensureLayout(for: textContainer)
if let frame = textView.layoutManager?.usedRect(for: textContainer) {
// There's 10pt of padding seemingly built into the left side,
// no such thing on the right so we go 20pt to match the left side
textView.frame = NSRect(x: 10.0, y: 0.0, width: frame.width, height: frame.height)
paddingView.frame = NSRect(x: 0.0, y: 0.0, width: frame.width + 20, height: frame.height)
} else {
// Backup layout if we couldn't calculate frame
textView.autoresizingMask = [.width, .height]
}
} else {
// Backup layout if we couldn't calculate frame
textView.autoresizingMask = [.width, .height]
}
return paddingView
}
func getInstallationDate() -> Date? {
let urlToDocumentsFolder: URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
return try? FileManager.default.attributesOfItem(atPath: (urlToDocumentsFolder?.path)!)[.creationDate] as? Date
}
/*
* -----------------------
* MARK: - Fantastical
* ------------------------
*/
func checkIsFantasticalInstalled() -> Bool {
NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.flexibits.fantastical2.mac") != nil
}
func openInFantastical(startDate: Date, title: String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let queryItems = [URLQueryItem(name: "date", value: dateFormatter.string(from: startDate)), URLQueryItem(name: "title", value: title)]
var fantasticalUrlComp = URLComponents()
fantasticalUrlComp.scheme = "x-fantastical3"
fantasticalUrlComp.host = "show"
fantasticalUrlComp.queryItems = queryItems
let fantasticalUrl = fantasticalUrlComp.url!
fantasticalUrl.openInDefaultBrowser()
}
/*
* -----------------------
* MARK: - Clipboard
* ------------------------
*/
func openLinkFromClipboard() {
let pasteboard = NSPasteboard.general
let clipboardContent = pasteboard.string(forType: .string) ?? ""
if !clipboardContent.isEmpty {
let meetingLink = detectMeetingLink(clipboardContent)
if let meetingLink = meetingLink {
openMeetingURL(meetingLink.service, meetingLink.url, nil)
} else {
let validUrl = NSURL(string: clipboardContent)
if validUrl != nil {
URL(string: clipboardContent)?.openInDefaultBrowser()
} else {
sendNotification("No valid url",
"Clipboard has no meeting link, so the meeting cannot be started")
}
}
} else {
sendNotification("Clipboard is empty",
"Clipboard has no content, so the meeting cannot be started...")
}
}
func generateFakeEvent() -> MBEvent {
let calendar = MBCalendar(title: "Fake calendar", id: "fake_cal", source: nil, email: nil, color: .black)
let event = MBEvent(
id: "test_event",
lastModifiedDate: nil,
title: "Test event",
status: .confirmed,
notes: nil,
location: nil,
url: URL(string: "https://zoom.us/j/5551112222")!,
organizer: nil,
startDate: Calendar.current.date(byAdding: .minute, value: 3, to: Date())!,
endDate: Calendar.current.date(byAdding: .minute, value: 33, to: Date())!,
isAllDay: false,
recurrent: false,
calendar: calendar
)
return event
}
extension Data {
init?(base64URL urlString: String) {
var st = urlString.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let pad = 4 - st.count % 4
if pad < 4 { st.append(String(repeating: "=", count: pad)) }
self.init(base64Encoded: st)
}
}
extension NSImage {
/// Returns a copy tinted with macOS disabled text colour.
func tintedDisabled() -> NSImage {
let copy = self.copy() as! NSImage
copy.lockFocus()
NSColor.disabledControlTextColor
.withAlphaComponent(0.4)
.set()
let rect = NSRect(origin: .zero, size: copy.size)
rect.fill(using: .sourceAtop) // keep alpha, replace colour
copy.unlockFocus()
return copy
}
}
extension DateFormatter {
static let yyyyMMdd: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}