-
Notifications
You must be signed in to change notification settings - Fork 0
/
PostPreview.swift
528 lines (526 loc) · 23.7 KB
/
PostPreview.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//
// PostPreview.swift
// wasteof.money
//
// Created by Oren Lindsey on 11/26/23.
//
import SwiftUI
import RichText
import AlertToast
struct PostPreview: View {
@Environment(\.colorScheme) var colorScheme
@EnvironmentObject var session: Session
let _id: String
var content: String
let time: Int
let comments: Int
@State var loves: Int
let reposts: Int
let poster: Poster
let revisions: [Revision]
let edited: Optional<Int>
let repost: Optional<PostType>
let navigation: Bool
let pinType: Bool
@State var recursion: Int
@State private var isPresentingConfirm: Bool = false
@State var deleted = false
@State var reportReasonShowing = false
@State var reason = ""
@State var dateShown = false
@State var loved = false //hook this up to the api
@State var showingEdits = false
@State var newPostId = ""
@State var showPopup = false
@State var showPinPopup = false
var body: some View {
let posttime: Date = Date(timeIntervalSince1970: TimeInterval(time / 1000))
let pictureurl = URL(string: "https://api.wasteof.money/users/\(poster.name)/picture")
let userLocale = Locale.autoupdatingCurrent
var profileColor: Color {
switch poster.color {
case "red":
return Color.red
case "orange":
return Color.orange
case "yellow":
return Color.yellow
case "green":
return Color.green
case "teal":
return Color.teal
case "blue":
return Color.blue
case "indigo":
return Color.indigo
case "violet":
return Color.purple
case "fuchsia":
return Color.pink
case "pink":
return Color.pink
case "gray":
return Color.gray
case "rainbow":
return Color.gray
default:
return Color.green
}
}
if !deleted {
ScrollView {
VStack {
HStack {
NavigationStack {
NavigationLink {
User(name: poster.name, navigationType: "stack").environmentObject(session)
} label: {
HStack {
AsyncImage(
url: pictureurl,
transaction: Transaction(animation: .easeInOut)
) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image
.resizable()
.transition(.scale(scale: 0.1, anchor: .center))
case .failure:
VStack {
Spacer()
HStack {
Spacer()
WebView(url: pictureurl!).frame(width:40,height:40)
}
}
@unknown default:
EmptyView()
}
}
.frame(width: 40, height: 40)
.background(Color.white)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(profileColor, lineWidth: 4)
)
.clipShape(RoundedRectangle(cornerRadius: 8))
Text("@\(poster.name)").tint(colorScheme == .light ? Color.black: Color.white)
.font(.title2)
}.padding(6)
}.buttonStyle(PlainButtonStyle()).background(.regularMaterial,in: RoundedRectangle(cornerRadius: 8, style: .continuous))
}
Spacer()
VStack {
HStack {
Text(dateShown ? posttime.description(with: userLocale) : posttime.formatted(date: .numeric, time: .shortened))
.onTapGesture {
dateShown.toggle()
if dateShown {
let pasteboard = UIPasteboard.general
pasteboard.string = posttime.description(with: userLocale)
}
}
.font(Font.body.italic())
.foregroundColor(.secondary)
}//.padding()
}
}
RichText(html: content).multilineTextAlignment(.leading)
if repost != nil {
if recursion < 4 {
if navigation {
NavigationStack {
NavigationLink {
Post(commentsState: CommentsObject(), _id: repost!._id, content: repost!.content, time: repost!.time, comments: repost!.comments, loves: repost!.loves, reposts: repost!.reposts, poster: repost!.poster, revisions: repost!.revisions, edited: repost?.edited, repost: repost?.repost, pinType: true).environmentObject(session)
} label: {
PostPreview(_id: repost!._id, content: repost!.content, time: repost!.time, comments: repost!.comments, loves: repost!.loves, reposts: repost!.reposts, poster: repost!.poster, revisions: repost!.revisions, edited: repost?.edited, repost: repost?.repost, navigation: true, pinType: true, recursion: recursion + 1).environmentObject(session)
}
}
} else {
PostPreview(_id: repost!._id, content: repost!.content, time: repost!.time, comments: repost!.comments, loves: repost!.loves, reposts: repost!.reposts, poster: repost!.poster, revisions: repost!.revisions, edited: repost?.edited, repost: repost?.repost, navigation: false, pinType: true, recursion: recursion + 1).environmentObject(session)
}
} else {
Button {
recursion = 1
} label: {
Text("Show Reposts")
}.buttonStyle(.bordered).tint(profileColor)
}
}
//.padding([.bottom])
if revisions.count > 1 {
HStack {
Button {
showingEdits = true
} label: {
Text("Edited")
//.padding([.bottom])
.font(Font.body.italic())
.tint(profileColor)
}
.popover(isPresented: $showingEdits) {
ScrollView {
Text("Edits")
.font(.title)
ForEach(revisions.reversed(), id: \.self) { revision in
let time: Date = Date(timeIntervalSince1970: TimeInterval(revision.time / 1000))
VStack {
Text("Time: \(time.formatted(date: .abbreviated, time: .complete))")
.font(.headline)
if revision.current != nil {
if revision.current == true {
Text("Current")
.font(Font.body.italic())
.padding([.top], 2)
}
}
RichText(html:revision.content)
}.padding().background(.regularMaterial,in: RoundedRectangle(cornerRadius: 8, style: .continuous))
}
}.padding([.horizontal, .top])
}
Spacer()
}
}
HStack {
Spacer()
HStack {
//Spacer()
loveButton
CommentEditor(id: _id, color: profileColor, parent: nil, poster: CommentPoster(name: poster.name, id: poster.id, color: nil), type: String(comments))
PostEditor(newid: $newPostId, type: "repost", reposts: reposts, postId: _id, customColor: profileColor).environmentObject(session)
Spacer()
}.onChange(of: newPostId) {
showPopup.toggle()
print("Posted successfully")
}.toast(isPresenting: $showPopup) {
AlertToast(displayMode: .hud, type: .systemImage("checkmark.bubble", .accentColor), title: "Posted!") // this doesn't show, and i can't figure out why :(
}.toast(isPresenting: $showPinPopup) {
AlertToast(displayMode: .hud, type: .systemImage("checkmark.bubble", .accentColor), title: "Pinned!") // this doesn't show either
}
Spacer()
.frame(width: 5)
Menu {
ShareLink(item: URL(string: "https://wasteof.money/posts/\(_id)")!, message: Text("Post by @\(poster.name)"))
if session.name == poster.name {
if pinType {
Button {
pinPost(_id: _id, token: session.token) { (res) in
if res {
showPinPopup.toggle()
}
}
} label: {
Label("Pin to Profile", systemImage: "pin")
}
} else {
Button {
unpinPost(_id: _id, token: session.token) { (res) in
if res {
showPinPopup.toggle()
}
}
} label: {
Label("Unpin from Profile", systemImage: "pin.slash")
}
}
}
Button(role: .destructive) {
reportReasonShowing = true
} label: {
Label("Report Post", systemImage: "exclamationmark.bubble")
}
if session.name == poster.name {
Button(role: .destructive) {
isPresentingConfirm = true
} label: {
Label("Delete Post", systemImage: "trash")
}
}
} label: {
Label("", systemImage: "ellipsis.circle.fill").tint(profileColor)
}.confirmationDialog("Are you sure?", isPresented: $isPresentingConfirm) {
Button("Delete Post", role: .destructive) {
deletePost(id: _id, token: session.token) { (success) in
if success {
deleted = true
}
}
}
}
}.alert("Reason for reporting", isPresented: $reportReasonShowing) {
TextField("Enter your reason", text: $reason)
Button("OK") {
reportPost(id: _id, token: session.token, reason: reason)
}
} message: {
Text("Enter your reason for reporting this post.")
}
}.padding()
.background(.regularMaterial,in: RoundedRectangle(cornerRadius: 8, style: .continuous))
}.contentShape(Rectangle())
} else {
Text("Post deleted :(")
}
}
@ViewBuilder private var loveButton: some View {
var profileColor: Color {
switch poster.color {
case "red":
return Color.red
case "orange":
return Color.orange
case "yellow":
return Color.yellow
case "green":
return Color.green
case "teal":
return Color.teal
case "blue":
return Color.blue
case "indigo":
return Color.indigo
case "violet":
return Color.purple
case "fuchsia":
return Color.pink
case "pink":
return Color.pink
case "gray":
return Color.gray
case "rainbow":
return Color.gray
default:
return Color.green
}
}
if loved {
Button {
lovePost(_id: _id, token: session.token) { (response) in
loves = response.new.loves
loved = response.new.isLoving
}
} label: {
VStack {
Image(systemName: "heart.fill")
Text("\(loves)")
}
}.tint(profileColor).buttonStyle(.borderedProminent).onAppear() {
checkLoved(_id: _id, token: session.token, name: session.name) { (res) in
if res {
loved = true
} else {
loved = false
}
}
}
} else {
Button {
lovePost(_id: _id, token: session.token) { (response) in
loves = response.new.loves
loved = response.new.isLoving
}
} label: {
VStack {
Image(systemName: "heart")
Text("\(loves)")
}
}.tint(profileColor).buttonStyle(.bordered).onAppear() {
checkLoved(_id: _id, token: session.token, name: session.name) { (res) in
if res {
loved = true
} else {
loved = false
}
}
}
}
}
}
struct CheckLovedResponse: Decodable {
let loved: Bool
}
func checkLoved(_id: String, token: String, name: String, callback: @escaping (Bool) -> ()) {
let url = URL(string: "https://api.wasteof.money/posts/\(_id)/loves/\(name)")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "GET"
request.addValue(token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
} else {
if let data = data, let dataString = String(data: data, encoding: .utf8) {
if dataString == "true" {
callback(true)
} else {
callback(false)
}
}
}
}
task.resume()
}
struct New: Decodable {
let isLoving: Bool
let loves: Int
}
struct LoveResponse: Decodable {
let ok: String
let new: New
}
func lovePost(_id: String, token: String, callback: ((LoveResponse) -> ())? = nil) {
//var result: LoginResponse = LoginResponse(ok: "false", new: New(isLoving: false, loves: 0))
let url = URL(string: "https://api.wasteof.money/posts/\(_id)/loves")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
//let postString = "username=\(username)&password=\(password)"
/*struct LoginData: Hashable, Codable {
let username: String
let password: String
}*/
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
//result = LoginResponse(ok: "error.localizedDescription", new: New(isLoving: false, loves: 0))
} else {
if let data = data, let dataString = String(data: data, encoding: .utf8) {
let jsonData = dataString.data(using: .utf8)!
var response: LoveResponse = LoveResponse(ok: "false", new: New(isLoving: false, loves: 0))
//print(response)
do {
response = try JSONDecoder().decode(LoveResponse.self, from: jsonData)
if response.ok == "unloved" || response.ok == "loved" {
/*loves = response.new.loves
loved = response.new.isLoving*/
callback!(response)
}
} catch DecodingError.keyNotFound(_, _) {
print("something went wrong, key not found")
print("error: \(jsonData)")
} catch {
print("something went wrong")
print(jsonData)
}
}
}
}
task.resume()
}
func pinPost(_id: String, token: String, callback: ((Bool) -> ())? = nil) {
let url = URL(string: "https://api.wasteof.money/posts/\(_id)/pin")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
callback!(false)
} else {
callback!(true)
}
}
task.resume()
}
func unpinPost(_id: String, token: String, callback: ((Bool) -> ())? = nil) {
let url = URL(string: "https://api.wasteof.money/posts/\(_id)/unpin")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
callback!(false)
} else {
callback!(true)
}
}
task.resume()
}
func reportPost(id: String, token: String, reason: String) {
let url = URL(string: "https://api.wasteof.money/posts/\(id)/report")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
//let postString = "username=\(username)&password=\(password)"
/*struct LoginData: Hashable, Codable {
let username: String
let password: String
}*/
struct ReportBody: Hashable, Codable {
let reason: String
let type: String
}
struct ReportResponse: Hashable, Codable {
let ok: String
}
let report = ReportBody(reason: reason, type: "aaa")
let finalBody = try? JSONEncoder().encode(report)
request.httpBody = finalBody
request.addValue(token, forHTTPHeaderField: "Authorization")
var res: ReportResponse = ReportResponse(ok: "no")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
//result = LoginResponse(ok: "error.localizedDescription", new: New(isLoving: false, loves: 0))
} else {
if let data = data, let dataString = String(data: data, encoding: .utf8) {
let jsonData = dataString.data(using: .utf8)!
do {
res = try JSONDecoder().decode(ReportResponse.self, from: jsonData)
print(res.ok)
} catch DecodingError.keyNotFound(_, _) {
print("something went wrong, key not found")
print("error: \(String(decoding: jsonData, as: UTF8.self))")
} catch {
print("something went wrong")
print(String(decoding: jsonData, as: UTF8.self))
}
//print(response)
/*if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
print("successfully reported")
}
}*/
}
}
}
task.resume()
}
func deletePost(id: String, token: String, callback: ((Bool) -> ())? = nil) {
let url = URL(string: "https://api.wasteof.money/posts/\(id)")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "DELETE"
//let postString = "username=\(username)&password=\(password)"
/*struct LoginData: Hashable, Codable {
let username: String
let password: String
}*/
request.addValue(token, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
} else {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
print("successfully deleted")
callback!(true)
}
}
}
}
task.resume()
}
/*#Preview {
PostPreview()
}*/