Helpers.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Foundation
  2. import CryptoKit
  3. func topicUrl(baseUrl: String, topic: String) -> String {
  4. return "\(baseUrl)/\(topic)"
  5. }
  6. func topicShortUrl(baseUrl: String, topic: String) -> String {
  7. return shortUrl(url: topicUrl(baseUrl: baseUrl, topic: topic))
  8. }
  9. func topicAuthUrl(baseUrl: String, topic: String) -> String {
  10. return "\(baseUrl)/\(topic)/auth"
  11. }
  12. func topicHash(baseUrl: String, topic: String) -> String {
  13. let data = Data(topicUrl(baseUrl: baseUrl, topic: topic).utf8)
  14. let digest = SHA256.hash(data: data)
  15. return digest.compactMap { String(format: "%02x", $0)}.joined()
  16. }
  17. func shortUrl(url: String) -> String {
  18. return url
  19. .replacingOccurrences(of: "http://", with: "")
  20. .replacingOccurrences(of: "https://", with: "")
  21. }
  22. func parseAllTags(_ tags: String?) -> [String] {
  23. return (tags?.components(separatedBy: ",") ?? [])
  24. .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
  25. }
  26. func parseEmojiTags(_ tags: String?) -> [String] {
  27. return parseEmojiTags(parseAllTags(tags))
  28. }
  29. func parseEmojiTags(_ tags: [String]?) -> [String] {
  30. guard let tags = tags else { return [] }
  31. var emojiTags: [String] = []
  32. for tag in tags {
  33. if let emoji = EmojiManager.shared.getEmojiByAlias(alias: tag) {
  34. emojiTags.append(emoji.getUnicode())
  35. }
  36. }
  37. return emojiTags
  38. }
  39. func parseNonEmojiTags(_ tags: String?) -> [String] {
  40. return parseAllTags(tags)
  41. .filter { EmojiManager.shared.getEmojiByAlias(alias: $0) == nil }
  42. }
  43. func formatSize(_ size: Int64) -> String {
  44. if (size < 1000) { return "\(size) bytes" }
  45. let exp = Int(log2(Double(size)) / log2(1000.0))
  46. let unit = ["KB", "MB", "GB", "TB", "PB", "EB"][exp - 1]
  47. let number = Double(size) / pow(1000, Double(exp))
  48. return String(format: "%.1f %@", number, unit)
  49. }
  50. func timeExpired(_ expires: Int64?) -> Bool {
  51. guard let expires = expires else { return false }
  52. return expires > 0 && TimeInterval(expires) < NSDate().timeIntervalSince1970
  53. }
  54. extension Data {
  55. func mimeType() -> String {
  56. var b: UInt8 = 0
  57. self.copyBytes(to: &b, count: 1)
  58. switch b {
  59. case 0xFF:
  60. return "image/jpeg"
  61. case 0x89:
  62. return "image/png"
  63. case 0x47:
  64. return "image/gif"
  65. default:
  66. return "application/octet-stream"
  67. }
  68. }
  69. func guessExtension() -> String {
  70. switch mimeType() {
  71. case "image/jpeg":
  72. return ".jpg"
  73. case "image/png":
  74. return ".png"
  75. case "image/gif":
  76. return ".gif"
  77. default:
  78. return ".bin"
  79. }
  80. }
  81. }