import Foundation import DevPlaceSwiftSDK enum NotificationRoute { case post(PostDestination) case conversation(User) case web(URL) case ownProfile } extension NotificationRoute { private static let webBaseUrl = "https://devplace.net" private static let notificationsPath = "/notifications" init?(redirect: String) { if let destination = Self.postDestination(fromRedirect: redirect) { self = .post(destination) } else if let url = Self.webUrl(fromRedirect: redirect) { self = .web(url) } else { return nil } } private static func webUrl(fromRedirect redirect: String) -> URL? { guard redirect.hasPrefix("/"), redirect != notificationsPath else { return nil } return URL(string: webBaseUrl + redirect) } private static func postDestination(fromRedirect redirect: String) -> PostDestination? { guard let slug = postSlug(from: redirect) else { return nil } let scrollToCommentId = commentUid(from: redirect).map { "comment:" + $0 } return PostDestination(slug: slug, scrollToCommentId: scrollToCommentId) } private static func postSlug(from url: String) -> String? { guard let components = URLComponents(string: url) else { return nil } let segments = components.path.split(separator: "/").map(String.init) guard let postsIndex = segments.firstIndex(of: "posts"), postsIndex + 1 < segments.count else { return nil } return segments[postsIndex + 1] } private static func commentUid(from url: String) -> String? { guard let components = URLComponents(string: url) else { return nil } if let fragment = components.fragment, let uid = commentUid(fromToken: fragment) { return uid } let commentQueryNames = ["comment", "comment_id", "commentId", "comment_uid"] if let value = components.queryItems?.first(where: { commentQueryNames.contains($0.name) })?.value, !value.isEmpty { return value } let segments = components.path.split(separator: "/").map(String.init) if let commentsIndex = segments.firstIndex(of: "comments"), commentsIndex + 1 < segments.count { return segments[commentsIndex + 1] } return nil } private static func commentUid(fromToken token: String) -> String? { let prefixes = ["comment-", "comment_", "comment:", "comment"] for prefix in prefixes where token.hasPrefix(prefix) { let uid = String(token.dropFirst(prefix.count)) return uid.isEmpty ? nil : uid } return nil } }