IceCubesApp/Packages/Models/Sources/Models/Alias/HTMLString.swift

58 lines
1.4 KiB
Swift
Raw Normal View History

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()
// 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")
var URLs: [URL] = []
2022-12-27 06:51:44 +00:00
for link in links {
let href = try link.attr("href")
if let url = URL(string: href),
2023-01-17 10:36:01 +00:00
let _ = Int(url.lastPathComponent)
{
URLs.append(url)
2022-12-27 06:51:44 +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)
}
}
}