2022-12-17 12:37:46 +00:00
|
|
|
import Foundation
|
|
|
|
import HTML2Markdown
|
2022-12-26 07:24:55 +00:00
|
|
|
import SwiftSoup
|
2022-12-17 12:37:46 +00:00
|
|
|
import SwiftUI
|
|
|
|
|
|
|
|
public typealias HTMLString = String
|
|
|
|
|
2023-01-17 10:36:01 +00:00
|
|
|
public extension HTMLString {
|
|
|
|
var asMarkdown: String {
|
2022-12-17 12:37:46 +00:00
|
|
|
do {
|
|
|
|
let dom = try HTMLParser().parse(html: self)
|
|
|
|
return dom.toMarkdown()
|
2023-01-12 05:58:04 +00:00
|
|
|
// Add space between hashtags and mentions that follow each other
|
|
|
|
.replacingOccurrences(of: ")[", with: ") [")
|
2022-12-17 12:37:46 +00:00
|
|
|
} catch {
|
|
|
|
return self
|
|
|
|
}
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
|
|
|
var asRawText: String {
|
2022-12-26 07:24:55 +00:00
|
|
|
do {
|
|
|
|
let document: Document = try SwiftSoup.parse(self)
|
|
|
|
return try document.text()
|
|
|
|
} catch {
|
|
|
|
return self
|
|
|
|
}
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
|
|
|
func findStatusesURLs() -> [URL]? {
|
2022-12-27 06:51:44 +00:00
|
|
|
do {
|
|
|
|
let document: Document = try SwiftSoup.parse(self)
|
|
|
|
let links: Elements = try document.select("a")
|
2022-12-30 15:55:13 +00:00
|
|
|
var URLs: [URL] = []
|
2022-12-27 06:51:44 +00:00
|
|
|
for link in links {
|
|
|
|
let href = try link.attr("href")
|
2022-12-30 15:55:13 +00:00
|
|
|
if let url = URL(string: href),
|
2023-01-17 10:36:01 +00:00
|
|
|
let _ = Int(url.lastPathComponent)
|
|
|
|
{
|
2022-12-30 15:55:13 +00:00
|
|
|
URLs.append(url)
|
2022-12-27 06:51:44 +00:00
|
|
|
}
|
|
|
|
}
|
2022-12-30 15:55:13 +00:00
|
|
|
return URLs
|
2022-12-27 06:51:44 +00:00
|
|
|
} catch {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2023-01-17 10:36:01 +00:00
|
|
|
|
|
|
|
var asSafeAttributedString: AttributedString {
|
2022-12-17 12:37:46 +00:00
|
|
|
do {
|
2022-12-20 13:35:47 +00:00
|
|
|
let options = AttributedString.MarkdownParsingOptions(allowsExtendedAttributes: true,
|
|
|
|
interpretedSyntax: .inlineOnlyPreservingWhitespace)
|
2023-01-13 13:11:21 +00:00
|
|
|
return try AttributedString(markdown: self, options: options)
|
2022-12-17 12:37:46 +00:00
|
|
|
} catch {
|
|
|
|
return AttributedString(stringLiteral: self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|