-
Notifications
You must be signed in to change notification settings - Fork 0
/
TweetArchiveStore.swift
296 lines (226 loc) · 6.25 KB
/
TweetArchiveStore.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
//
// TweetArchiveStore.swift
// VisaViz
//
// Created by Felix Akira Green on 8/25/22.
//
import Foundation
@MainActor
class TweetArchiveStore: ObservableObject {
@Published
var allTweets: [Tweet] = []
@Published
var replyCount: [String: Int] = [:]
@Published
var account = Account(
username: "",
accountId: "",
createdAt: Date(),
accountDisplayName: ""
)
@Published var archivePath: URL?
@Published var isLoaded: Bool = false
var isNotLoaded: Bool {
!isLoaded
}
@Published var anyError: Error?
enum ArchiveError: Error {
case fileNotFound
case invalidString
case invalidData
case createURLFailure
case tweetJSNotFound
case archivePathNotFound
}
private func fileURL(name: String) throws -> URL {
guard let url = Bundle.main.url(forResource: name, withExtension: "js") else {
throw ArchiveError.fileNotFound
}
return url
}
func load() async {
do {
let fileURL = try fileURL(name: "tweet500")
await loadFileURL(file: fileURL)
}
catch {
print("error: \(error)")
}
}
// TODO: function for pulling data/tweet.js
// data/account.js
// func load
func loadArchive(path: URL) async {
archivePath = path
print("loadArchive", path)
do {
// let url = try tweetURL(path: path)
// print("url...", url.absoluteString)
// This is not working...
// let doesFileExist = FileManager.default.fileExists(atPath: url.absoluteString)
// print("doesFileExist", doesFileExist)
// await loadFileURL(file: url)
try await loadAccount()
try await loadAllTweets()
isLoaded = true
}
catch {
anyError = error
print("error: \(error)")
}
}
func loadFileURL(file: URL) async {
do {
let (data, _) = try await URLSession.shared.data(from: file)
let decodedData = try await decodeTweetData(data: data)
allTweets = decodedData.sorted(by: { $0.createdAt < $1.createdAt })
}
catch {
print("error: \(error)")
}
}
//
// Tweets (data/tweet.js, data/tweet-part1.js, +)
//
func loadAllTweets() async throws {
guard let archivePath else {
throw ArchiveError.archivePathNotFound
}
let url = try tweetURL(path: archivePath)
// print("url", url)
try await loadTweets(url: url)
var i = 1
while let partUrl = tweetPartitionedURL(path: archivePath, part: i), i < 20 {
// print("partUrl", partUrl)
do {
try await loadTweets(url: partUrl)
i += 1
} catch {
break
}
}
// sort all at the end
allTweets = allTweets.sorted(by: { $0.createdAt < $1.createdAt })
}
func loadTweets(url: URL) async throws {
// print("loadTweets:", url)
let (data, _) = try await URLSession.shared.data(from: url)
let decodedData = try await decodeTweetData(data: data)
allTweets.append(contentsOf: decodedData)
}
private func tweetURL(path: URL) throws -> URL {
guard let url = URL(string: "data/tweet.js", relativeTo: path) else {
throw ArchiveError.createURLFailure
}
return url
}
private func tweetPartitionedURL(path: URL, part: Int) throws -> URL {
guard let url = URL(string: "data/tweet-part\(part).js", relativeTo: path) else {
throw ArchiveError.createURLFailure
}
return url
}
private func tweetPartitionedURL(path: URL, part: Int) -> URL? {
guard let url = URL(string: "data/tweet-part\(part).js", relativeTo: path) else {
return nil
}
return url
}
private func decodeTweetData(data: Data) async throws -> [Tweet] {
let string = String(decoding: data, as: UTF8.self)
guard let jsonBeginIndex = string.firstIndex(of: "[") else {
throw ArchiveError.invalidString
}
let jsonString = String(string[jsonBeginIndex...])
// let jsonString = string.dropFirst(jsonBeginIndex)
guard let jsonData = jsonString.data(using: .utf8) else {
throw ArchiveError.invalidData
}
// print("jsonString", jsonString)
// print("jsonData", jsonData)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .formatted(DateFormatter.tweet)
let decodedData = try decoder.decode([Tweet].self, from: jsonData)
return decodedData
}
//
// Account (data/account.js)
//
func loadAccount() async throws {
guard archivePath != nil else {
throw ArchiveError.archivePathNotFound
}
let url = try accountURL(path: archivePath!)
let (data, _) = try await URLSession.shared.data(from: url)
let decodedData = try await decodeAccountData(data: data)
account = decodedData
}
private func accountURL(path: URL) throws -> URL {
guard let url = URL(string: "data/account.js", relativeTo: path) else {
throw ArchiveError.createURLFailure
}
return url
}
private func decodeAccountData(data: Data) async throws -> Account {
let string = String(decoding: data, as: UTF8.self)
guard let jsonBeginIndex = string.firstIndex(of: "[") else {
throw ArchiveError.invalidString
}
let jsonString = String(string[jsonBeginIndex...])
// let jsonString = string.dropFirst(jsonBeginIndex)
guard let jsonData = jsonString.data(using: .utf8) else {
throw ArchiveError.invalidData
}
// print("jsonString", jsonString)
// print("jsonData", jsonData)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso)
let decodedData = try decoder.decode([Account].self, from: jsonData)
return decodedData[0]
}
//
// visualizations
//
func generateReplies() {
/// mutating directly cause the view to be updated 9000+ times
var _replyCount: [String: Int] = [:]
for tweetIndex in allTweets.indices {
if let repliedTo = allTweets[tweetIndex].replyUserName {
if _replyCount[repliedTo] == nil {
_replyCount[repliedTo] = 1
}
else {
_replyCount[repliedTo]! += 1
}
}
}
/// doing it this way means it only happens once
replyCount = _replyCount
}
func computeMax() -> Int {
var _max: Int = 0
for tweet in allTweets {
let val = tweet.popularity
if val > _max {
_max = val
}
}
return _max
}
func computeHistogram() -> [Int: Int] {
let max = computeMax()
var _histogram: [Int: Int] = [:]
for tweet in allTweets {
let lit = tweet.computeLit(max: max)
if _histogram[lit] == nil {
_histogram[lit] = 1
}
else {
_histogram[lit]! += 1
}
}
return _histogram
}
}