forked from TelegramMessenger/Telegram-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTodayViewController.swift
242 lines (199 loc) · 8.76 KB
/
TodayViewController.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
import UIKit
import TelegramCore
import SwiftSignalKit
import Postbox
import NotificationCenter
private var installedSharedLogger = false
private func setupSharedLogger(_ path: String) {
if !installedSharedLogger {
installedSharedLogger = true
Logger.setSharedLogger(Logger(basePath: path))
}
}
private let auxiliaryMethods = AccountAuxiliaryMethods(updatePeerChatInputState: { _, _ in
return nil
}, fetchResource: { _, _, _, _ in
return nil
}, fetchResourceMediaReferenceHash: { _ in
return .single(nil)
}, prepareSecretThumbnailData: { _ in
return nil
})
class TodayViewController: UIViewController, NCWidgetProviding {
private var initializedInterface = false
private let disposable = MetaDisposable()
deinit {
self.disposable.dispose()
}
private var snapshotView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
self.snapshotView?.removeFromSuperview()
let snapshotView = UIImageView()
if let path = self.getSnapshotPath(), let image = UIImage(contentsOfFile: path) {
snapshotView.image = image
}
self.snapshotView = snapshotView
self.view.addSubview(snapshotView)
if self.initializedInterface {
return
}
self.initializedInterface = true
let appBundleIdentifier = Bundle.main.bundleIdentifier!
guard let lastDotRange = appBundleIdentifier.range(of: ".", options: [.backwards]) else {
return
}
let apiId: Int32 = BuildConfig.shared().apiId
let languagesCategory = "ios"
let appGroupName = "group.\(appBundleIdentifier[..<lastDotRange.lowerBound])"
let maybeAppGroupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName)
guard let appGroupUrl = maybeAppGroupUrl else {
return
}
let rootPath = rootPathForBasePath(appGroupUrl.path)
performAppGroupUpgrades(appGroupPath: appGroupUrl.path, rootPath: rootPath)
TempBox.initializeShared(basePath: rootPath, processType: "widget", launchSpecificId: arc4random64())
let logsPath = rootPath + "/today-logs"
let _ = try? FileManager.default.createDirectory(atPath: logsPath, withIntermediateDirectories: true, attributes: nil)
setupSharedLogger(logsPath)
let account: Signal<Account, NoError>
let appVersion = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "unknown"
initializeAccountManagement()
let accountManager = AccountManager(basePath: rootPath + "/accounts-metadata")
account = currentAccount(allocateIfNotExists: false, networkArguments: NetworkInitializationArguments(apiId: apiId, languagesCategory: languagesCategory, appVersion: appVersion, voipMaxLayer: 0), supplementary: true, manager: accountManager, rootPath: rootPath, auxiliaryMethods: auxiliaryMethods)
|> mapToSignal { account -> Signal<Account, NoError> in
if let account = account {
switch account {
case .upgrading:
return .complete()
case let .authorized(account):
return .single(account)
case .unauthorized:
return .complete()
}
} else {
return .complete()
}
}
let applicationInterface = account
|> deliverOnMainQueue
|> afterNext { [weak self] account in
let _ = (recentPeers(account: account)
|> deliverOnMainQueue).start(next: { peers in
if let strongSelf = self {
switch peers {
case let .peers(peers):
strongSelf.setPeers(account: account, peers: peers.filter { !$0.isDeleted })
case .disabled:
strongSelf.setPeers(account: account, peers: [])
}
}
})
}
self.disposable.set(applicationInterface.start())
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
completionHandler(.newData)
}
@available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
}
private var peers: [Peer]?
private func setPeers(account: Account, peers: [Peer]) {
self.peers = peers
self.peerViews.forEach {
$0.removeFromSuperview()
}
self.peerViews = []
for peer in peers {
let peerView = PeerView(account: account, peer: peer, tapped: { [weak self] in
if let strongSelf = self {
if let url = URL(string: "\(BuildConfig.shared().appSpecificUrlScheme)://localpeer?id=\(peer.id.toInt64())") {
strongSelf.extensionContext?.open(url, completionHandler: nil)
}
}
})
self.view.addSubview(peerView)
self.peerViews.append(peerView)
}
self.validSnapshotSize = nil
if let size = self.validLayout {
self.updateLayout(size: size)
}
}
private var validLayout: CGSize?
private var validSnapshotSize: CGSize?
private var peerViews: [PeerView] = []
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.updateLayout(size: self.view.bounds.size)
}
private func updateLayout(size: CGSize) {
self.validLayout = size
if let image = self.snapshotView?.image {
let scale = UIScreen.main.scale
self.snapshotView?.frame = CGRect(origin: CGPoint(), size: CGSize(width: image.size.width / scale, height: image.size.height / scale))
}
let peerSize = CGSize(width: 70.0, height: 100.0)
var peerFrames: [CGRect] = []
var offset: CGFloat = 0.0
for _ in self.peerViews {
let peerFrame = CGRect(origin: CGPoint(x: offset, y: 10.0), size: peerSize)
offset += peerFrame.size.width
if peerFrame.maxX > size.width {
break
}
peerFrames.append(peerFrame)
}
var totalSize: CGFloat = 0.0
for i in 0 ..< peerFrames.count {
totalSize += peerFrames[i].width
}
let spacing: CGFloat = floor((size.width - totalSize) / CGFloat(peerFrames.count))
offset = floor(spacing / 2.0)
for i in 0 ..< peerFrames.count {
let peerView = self.peerViews[i]
peerView.frame = CGRect(origin: CGPoint(x: offset, y: 20.0), size: peerFrames[i].size)
peerView.updateLayout(size: peerFrames[i].size)
offset += peerFrames[i].width + spacing
}
if self.peers != nil {
self.snapshotView?.removeFromSuperview()
if self.validSnapshotSize != size {
self.validSnapshotSize = size
self.updateSnapshot()
}
}
}
private func updateSnapshot() {
if let path = self.getSnapshotPath() {
DispatchQueue.main.async {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0.0)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image, let data = UIImagePNGRepresentation(image) {
let _ = try? FileManager.default.removeItem(atPath: path)
do {
try data.write(to: URL(fileURLWithPath: path))
} catch let e {
print("\(e)")
}
}
}
}
}
private func getSnapshotPath() -> String? {
let appBundleIdentifier = Bundle.main.bundleIdentifier!
guard let lastDotRange = appBundleIdentifier.range(of: ".", options: [.backwards]) else {
return nil
}
let appGroupName = "group.\(appBundleIdentifier[..<lastDotRange.lowerBound])"
let maybeAppGroupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupName)
guard let appGroupUrl = maybeAppGroupUrl else {
return nil
}
let rootPath = rootPathForBasePath(appGroupUrl.path)
return rootPath + "/widget-snapshot.png"
}
}