From c305ec28e6768d8cb81a8b7a73d47d4d0b3401f7 Mon Sep 17 00:00:00 2001 From: Daniil Vinogradov Date: Mon, 29 Jul 2024 21:55:10 +0200 Subject: [PATCH] Sonar: Reduce code duplication --- .../Rss/Details/RssDetailsViewModel.swift | 49 +++++++++++-------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/iTorrent/Screens/Rss/Details/RssDetailsViewModel.swift b/iTorrent/Screens/Rss/Details/RssDetailsViewModel.swift index 8bb5bbdc..8cf0a7bc 100644 --- a/iTorrent/Screens/Rss/Details/RssDetailsViewModel.swift +++ b/iTorrent/Screens/Rss/Details/RssDetailsViewModel.swift @@ -45,8 +45,9 @@ class RssDetailsViewModel: BaseViewModelWith { private extension RssDetailsViewModel { func prepareDownload() async { - if let link = rssModel.link, - let magnet = MagnetURI(with: link) + // MARK: - Try download magnet + if let magnet = MagnetURI(with: rssModel.enclosure?.url) ?? // Check enclosure + MagnetURI(with: rssModel.link) // Otherwise check link { guard !TorrentService.shared.checkTorrentExists(with: magnet.infoHashes) else { downloadType = .added @@ -61,31 +62,23 @@ private extension RssDetailsViewModel { return } - if let link = rssModel.link, - let file = await TorrentFile(remote: link) - { - guard !TorrentService.shared.checkTorrentExists(with: file.infoHashes) else { - downloadType = .added - return - } - downloadType = .torrent - download = { [unowned self] in - navigate(to: TorrentAddViewModel.self, with: .init(torrentFile: file, completion: { [weak self] added in - guard added else { return } - self?.downloadType = .added - }), by: .present(wrapInNavigation: true)) - } - return - } + // MARK: - Try download file + let file: TorrentFile? - if let link = rssModel.enclosure?.url, - let file = await TorrentFile(remote: link) - { + // Check enclosure + if let temp = await TorrentFile(remote: rssModel.enclosure?.url) { file = temp } + // Otherwise check link + else if let temp = await TorrentFile(remote: rssModel.link) { file = temp } + // Otherwise nothing to download + else { file = nil } + + if let file { guard !TorrentService.shared.checkTorrentExists(with: file.infoHashes) else { downloadType = .added return } + downloadType = .torrent download = { [unowned self] in navigate(to: TorrentAddViewModel.self, with: .init(torrentFile: file, completion: { [weak self] added in @@ -97,3 +90,17 @@ private extension RssDetailsViewModel { } } } + +private extension TorrentFile { + convenience init?(remote url: URL?) async { + guard let url else { return nil } + await self.init(remote: url) + } +} + +private extension MagnetURI { + convenience init?(with url: URL?) { + guard let url else { return nil } + self.init(with: url) + } +}