2021-04-01 08:39:15 +02:00
|
|
|
//
|
|
|
|
// MastodonField.swift
|
|
|
|
// Mastodon
|
|
|
|
//
|
|
|
|
// Created by MainasuK Cirno on 2021-3-30.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import ActiveLabel
|
|
|
|
|
|
|
|
enum MastodonField {
|
|
|
|
|
2021-05-27 07:56:55 +02:00
|
|
|
static func parse(field string: String, emojiDict: MastodonStatusContent.EmojiDict) -> ParseResult {
|
|
|
|
// use content parser get emoji entities
|
|
|
|
let value = string
|
|
|
|
|
|
|
|
var string = string
|
|
|
|
var entities: [ActiveEntity] = []
|
|
|
|
|
|
|
|
do {
|
|
|
|
let contentParseresult = try MastodonStatusContent.parse(content: string, emojiDict: emojiDict)
|
|
|
|
string = contentParseresult.trimmed
|
|
|
|
entities.append(contentsOf: contentParseresult.activeEntities)
|
|
|
|
} catch {
|
|
|
|
// assertionFailure(error.localizedDescription)
|
|
|
|
}
|
|
|
|
|
2021-04-14 09:59:29 +02:00
|
|
|
let mentionMatches = string.matches(pattern: "(?:@([a-zA-Z0-9_]+)(@[a-zA-Z0-9_.-]+)?)")
|
2021-04-01 08:39:15 +02:00
|
|
|
let hashtagMatches = string.matches(pattern: "(?:#([^\\s.]+))")
|
|
|
|
let urlMatches = string.matches(pattern: "(?i)https?://\\S+(?:/|\\b)")
|
|
|
|
|
|
|
|
|
|
|
|
for match in mentionMatches {
|
|
|
|
guard let text = string.substring(with: match, at: 0) else { continue }
|
|
|
|
let entity = ActiveEntity(range: match.range, type: .mention(text, userInfo: nil))
|
|
|
|
entities.append(entity)
|
|
|
|
}
|
|
|
|
|
|
|
|
for match in hashtagMatches {
|
|
|
|
guard let text = string.substring(with: match, at: 0) else { continue }
|
|
|
|
let entity = ActiveEntity(range: match.range, type: .hashtag(text, userInfo: nil))
|
|
|
|
entities.append(entity)
|
|
|
|
}
|
|
|
|
|
|
|
|
for match in urlMatches {
|
|
|
|
guard let text = string.substring(with: match, at: 0) else { continue }
|
|
|
|
let entity = ActiveEntity(range: match.range, type: .url(text, trimmed: text, url: text, userInfo: nil))
|
|
|
|
entities.append(entity)
|
|
|
|
}
|
|
|
|
|
2021-05-27 07:56:55 +02:00
|
|
|
return ParseResult(value: value, trimmed: string, activeEntities: entities)
|
2021-04-01 08:39:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
extension MastodonField {
|
|
|
|
struct ParseResult {
|
|
|
|
let value: String
|
2021-05-27 07:56:55 +02:00
|
|
|
let trimmed: String
|
2021-04-01 08:39:15 +02:00
|
|
|
let activeEntities: [ActiveEntity]
|
|
|
|
}
|
|
|
|
}
|