File size: 8,699 Bytes
2d8be8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

import Tauri
import UserNotifications

enum NotificationError: LocalizedError {
  case triggerRepeatIntervalTooShort
  case attachmentFileNotFound(path: String)
  case attachmentUnableToCreate(String)
  case pastScheduledTime
  case invalidDate(String)

  var errorDescription: String? {
    switch self {
    case .triggerRepeatIntervalTooShort:
      return "Schedule interval too short, must be a least 1 minute"
    case .attachmentFileNotFound(let path):
      return "Unable to find file \(path) for attachment"
    case .attachmentUnableToCreate(let error):
      return "Failed to create attachment: \(error)"
    case .pastScheduledTime:
      return "Scheduled time must be *after* current time"
    case .invalidDate(let date):
      return "Could not parse date \(date)"
    }
  }
}

func makeNotificationContent(_ notification: Notification) throws -> UNNotificationContent {
  let content = UNMutableNotificationContent()
  content.title = NSString.localizedUserNotificationString(
    forKey: notification.title, arguments: nil)
  if let body = notification.body {
    content.body = NSString.localizedUserNotificationString(
      forKey: body,
      arguments: nil)
  }

  var userInfo: [String: Any] = [:]
  
  if let extra = notification.extra {
    userInfo["__EXTRA__"] = extra
  }
  
  if let schedule = notification.schedule {
    userInfo["__SCHEDULE__"] = scheduleToDictionary(schedule)
  }
  
  content.userInfo = userInfo

  if let actionTypeId = notification.actionTypeId {
    content.categoryIdentifier = actionTypeId
  }

  if let threadIdentifier = notification.group {
    content.threadIdentifier = threadIdentifier
  }

  if let summaryArgument = notification.summary {
    content.summaryArgument = summaryArgument
  }

  if let sound = notification.sound {
    content.sound = UNNotificationSound(named: UNNotificationSoundName(sound))
  }

  if let attachments = notification.attachments {
    content.attachments = try makeAttachments(attachments)
  }

  return content
}

func scheduleToDictionary(_ schedule: NotificationSchedule) -> [String: Any] {
  switch schedule {
  case .at(let date, let repeating):
    return [
      "type": "at",
      "date": date,
      "repeating": repeating
    ]
  case .interval(let interval):
    return [
      "type": "interval",
      "interval": scheduleIntervalToDictionary(interval)
    ]
  case .every(let interval, let count):
    return [
      "type": "every",
      "interval": interval.rawValue,
      "count": count
    ]
  }
}

func scheduleIntervalToDictionary(_ interval: ScheduleInterval) -> [String: Any] {
  var dict: [String: Any] = [:]
  
  if let year = interval.year {
    dict["year"] = year
  }
  if let month = interval.month {
    dict["month"] = month
  }
  if let day = interval.day {
    dict["day"] = day
  }
  if let weekday = interval.weekday {
    dict["weekday"] = weekday
  }
  if let hour = interval.hour {
    dict["hour"] = hour
  }
  if let minute = interval.minute {
    dict["minute"] = minute
  }
  if let second = interval.second {
    dict["second"] = second
  }
  
  return dict
}

func makeAttachments(_ attachments: [NotificationAttachment]) throws -> [UNNotificationAttachment] {
  var createdAttachments = [UNNotificationAttachment]()

  for attachment in attachments {

    guard let urlObject = makeAttachmentUrl(attachment.url) else {
      throw NotificationError.attachmentFileNotFound(path: attachment.url)
    }

    let options = attachment.options != nil ? makeAttachmentOptions(attachment.options!) : nil

    do {
      let newAttachment = try UNNotificationAttachment(
        identifier: attachment.id, url: urlObject, options: options)
      createdAttachments.append(newAttachment)
    } catch {
      throw NotificationError.attachmentUnableToCreate(error.localizedDescription)
    }
  }

  return createdAttachments
}

func makeAttachmentUrl(_ path: String) -> URL? {
  return URL(string: path)
}

func makeAttachmentOptions(_ options: NotificationAttachmentOptions) -> [AnyHashable: Any] {
  var opts: [AnyHashable: Any] = [:]

  if let value = options.iosUNNotificationAttachmentOptionsTypeHintKey {
    opts[UNNotificationAttachmentOptionsTypeHintKey] = value
  }
  if let value = options.iosUNNotificationAttachmentOptionsThumbnailHiddenKey {
    opts[UNNotificationAttachmentOptionsThumbnailHiddenKey] = value
  }
  if let value = options.iosUNNotificationAttachmentOptionsThumbnailClippingRectKey {
    opts[UNNotificationAttachmentOptionsThumbnailClippingRectKey] = value
  }
  if let value = options
    .iosUNNotificationAttachmentOptionsThumbnailTimeKey

  {
    opts[UNNotificationAttachmentOptionsThumbnailTimeKey] = value
  }
  return opts
}

func handleScheduledNotification(_ schedule: NotificationSchedule) throws
  -> UNNotificationTrigger?
{
  switch schedule {
  case .at(let date, let repeating):
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

    if let at = dateFormatter.date(from: date) {
      let dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: at)

      if dateInfo.date! < Date() {
        throw NotificationError.pastScheduledTime
      }

      let dateInterval = DateInterval(start: Date(), end: dateInfo.date!)

      // Notifications that repeat have to be at least a minute between each other
      if repeating && dateInterval.duration < 60 {
        throw NotificationError.triggerRepeatIntervalTooShort
      }

      return UNTimeIntervalNotificationTrigger(
        timeInterval: dateInterval.duration, repeats: repeating)

    } else {
      throw NotificationError.invalidDate(date)
    }
  case .interval(let interval):
    let dateComponents = getDateComponents(interval)
    return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
  case .every(let interval, let count):
    if let repeatDateInterval = getRepeatDateInterval(interval, count) {
      // Notifications that repeat have to be at least a minute between each other
      if repeatDateInterval.duration < 60 {
        throw NotificationError.triggerRepeatIntervalTooShort
      }

      return UNTimeIntervalNotificationTrigger(
        timeInterval: repeatDateInterval.duration, repeats: true)
    }
  }

  return nil
}

/// Given our schedule format, return a DateComponents object
/// that only contains the components passed in.

func getDateComponents(_ at: ScheduleInterval) -> DateComponents {
  // var dateInfo = Calendar.current.dateComponents(in: TimeZone.current, from: Date())
  // dateInfo.calendar = Calendar.current
  var dateInfo = DateComponents()

  if let year = at.year {
    dateInfo.year = year
  }
  if let month = at.month {
    dateInfo.month = month
  }
  if let day = at.day {
    dateInfo.day = day
  }
  if let hour = at.hour {
    dateInfo.hour = hour
  }
  if let minute = at.minute {
    dateInfo.minute = minute
  }
  if let second = at.second {
    dateInfo.second = second
  }
  if let weekday = at.weekday {
    dateInfo.weekday = weekday
  }
  return dateInfo
}

/// Compute the difference between the string representation of a date
/// interval and today. For example, if every is "month", then we
/// return the interval between today and a month from today.

func getRepeatDateInterval(_ every: ScheduleEveryKind, _ count: Int) -> DateInterval? {
  let cal = Calendar.current
  let now = Date()
  switch every {
  case .year:
    let newDate = cal.date(byAdding: .year, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .month:
    let newDate = cal.date(byAdding: .month, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .twoWeeks:
    let newDate = cal.date(byAdding: .weekOfYear, value: 2 * count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .week:
    let newDate = cal.date(byAdding: .weekOfYear, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .day:
    let newDate = cal.date(byAdding: .day, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .hour:
    let newDate = cal.date(byAdding: .hour, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .minute:
    let newDate = cal.date(byAdding: .minute, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  case .second:
    let newDate = cal.date(byAdding: .second, value: count, to: now)!
    return DateInterval(start: now, end: newDate)
  }
}