Migrate the chapter importer to Swift.
This commit is contained in:
1 parent
514ab21fb7
commit
23f626be9f
10 files changed
+317
-44
No files matched your search
@@ -0,0 +1,18 @@
|
||||
//
|
||||
// ChapterSearchController.swift
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/07/2017.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
|
||||
class ChapterSearchController: NSWindowController {
|
||||
|
||||
override func windowDidLoad() {
|
||||
super.windowDidLoad()
|
||||
|
||||
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//
|
||||
// ChapterDB.swift
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/07/2017.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class ChapterDB : ChapterService {
|
||||
|
||||
func search(title: String, duration: UInt64) -> [ChapterResult] {
|
||||
|
||||
guard let url = URL(string: "http://www.chapterdb.org/chapters/search?title=\(title.urlEncoded())"),
|
||||
let data = fetch(url: url)
|
||||
else { return [] }
|
||||
|
||||
let delta: UInt64 = 10000
|
||||
return parse(data: data).filter { $0.duration < (duration + delta) && $0.duration > (duration - delta) }
|
||||
}
|
||||
|
||||
private func fetch(url: URL) -> Data? {
|
||||
let header = ["ApiKey": "ETET7TXFJH45YNYW0I4A"]
|
||||
return SBMetadataHelper.downloadData(from: url, httpMethod: "GET", httpBody: nil, headerOptions: header, cachePolicy: .default)
|
||||
}
|
||||
|
||||
private func title(node: XMLNode) -> String? {
|
||||
guard let nodes = try? node.nodes(forXPath: "./*:title") else { return nil }
|
||||
return nodes.first?.stringValue
|
||||
}
|
||||
|
||||
private func confirmations(node: XMLNode) -> UInt? {
|
||||
guard let nodes = try? node.nodes(forXPath: "./@confirmations"),
|
||||
let confirmations = nodes.first?.stringValue else { return nil }
|
||||
return UInt(confirmations)
|
||||
}
|
||||
|
||||
private func duration(node: XMLNode) -> UInt64? {
|
||||
guard let nodes = try? node.nodes(forXPath: "./*:source/*:duration"),
|
||||
let duration = nodes.first?.stringValue else { return nil }
|
||||
return TimeFromString(duration, 1000)
|
||||
}
|
||||
|
||||
private func parse(node: XMLNode) -> ChapterResult? {
|
||||
guard let title = title(node: node),
|
||||
let confirmations = confirmations(node: node),
|
||||
let duration = duration(node: node),
|
||||
let times = try? node.nodes(forXPath: "./*:chapters/*:chapter/@time"),
|
||||
let names = try? node.nodes(forXPath: "./*:chapters/*:chapter/@name") else { return nil }
|
||||
|
||||
var currentTime: UInt64 = 0
|
||||
var chapters: [Chapter] = Array()
|
||||
|
||||
for (time, name) in zip(times.flatMap { $0.stringValue }, names.flatMap { $0.stringValue }) {
|
||||
let timestamp = TimeFromString(time, 1000)
|
||||
|
||||
if timestamp < currentTime {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
currentTime = timestamp
|
||||
}
|
||||
|
||||
let chapter = Chapter(name: name, timestamp: timestamp)
|
||||
chapters.append(chapter)
|
||||
}
|
||||
|
||||
if chapters.count > 0 {
|
||||
let result = ChapterResult(title: title, duration: duration, confimations: confirmations, chapters: chapters)
|
||||
return result
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
private func parse(data: Data) -> [ChapterResult] {
|
||||
guard let document = try? XMLDocument(data: data, options: []),
|
||||
let children = try? document.nodes(forXPath: "//*:chapterInfo") else { return [] }
|
||||
|
||||
return children.flatMap { parse(node: $0) }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//
|
||||
// ChapterImporter.swift
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/07/2017.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol ChapterService {
|
||||
func search(title: String, duration: UInt64) -> [ChapterResult]
|
||||
}
|
||||
|
||||
public enum ChapterSearch {
|
||||
case movieSeach(service: ChapterService, title: String, duration: UInt64)
|
||||
|
||||
public func search(completionHandler: @escaping ([ChapterResult]) -> Void) -> MetadataSearchTask {
|
||||
switch self {
|
||||
case let .movieSeach(service, title, duration):
|
||||
return MetadataSearchInternalTask(search: service.search(title: title, duration: duration),
|
||||
completionHandler: completionHandler)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// ChapterResult.swift
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/07/2017.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public struct Chapter {
|
||||
let name: String
|
||||
let timestamp: UInt64
|
||||
}
|
||||
|
||||
public struct ChapterResult {
|
||||
let title: String
|
||||
let duration: UInt64
|
||||
let confimations: UInt
|
||||
let chapters: [Chapter]
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//
|
||||
// MetadataHelper.swift
|
||||
// Subler
|
||||
//
|
||||
// Created by Damiano Galassi on 31/07/2017.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
public protocol MetadataSearchTask {
|
||||
func runAsync() -> MetadataSearchTask
|
||||
func run() -> MetadataSearchTask
|
||||
func cancel()
|
||||
}
|
||||
|
||||
class MetadataSearchInternalTask<T> : MetadataSearchTask {
|
||||
|
||||
private var cancelled: Bool = false
|
||||
private let search: () -> T
|
||||
private let completionHandler: (T) -> Void
|
||||
|
||||
init(search: @escaping @autoclosure () -> T, completionHandler: @escaping (T) -> Void) {
|
||||
self.search = search
|
||||
self.completionHandler = completionHandler
|
||||
}
|
||||
|
||||
public func runAsync() -> MetadataSearchTask {
|
||||
DispatchQueue.global(priority: .background).async {
|
||||
_ = self.run()
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func run() -> MetadataSearchTask {
|
||||
let results = self.search()
|
||||
if self.cancelled == false {
|
||||
self.completionHandler(results)
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func cancel() {
|
||||
self.cancelled = true
|
||||
}
|
||||
}
|
||||
|
||||
public protocol MetadataSearchCancelToken {
|
||||
func cancel()
|
||||
var sessionTask: URLSessionTask? { get set }
|
||||
}
|
||||
|
||||
// MARK: - Filename
|
||||
|
||||
enum FilenameType {
|
||||
case movie(title: String)
|
||||
case tvShow(seriesName: String, season: Int?, episode: Int?)
|
||||
}
|
||||
|
||||
private func parseAnimeFilename(_ filename: String) -> FilenameType? {
|
||||
|
||||
guard let regex = try? NSRegularExpression(pattern: "^\\[(.+)\\](?:(?:\\s|_)+)?([^()]+)(?:(?:\\s|_)+)(?:(?:-\\s|-_|Ep)+)([0-9]+)", options: [.caseInsensitive]) else { return nil }
|
||||
|
||||
var result: FilenameType?
|
||||
|
||||
regex.enumerateMatches(in: filename, options: [],
|
||||
range: NSRange(filename.startIndex..., in: filename)) {
|
||||
(match, flags, stop) in
|
||||
|
||||
if let seriesNameRange = match?.range(at: 2), let episodeRange = match?.range(at: 3) {
|
||||
let seriesName = (filename as NSString).substring(with: seriesNameRange)
|
||||
let episode = Int((filename as NSString).substring(with: episodeRange))
|
||||
|
||||
if seriesName.count > 0 {
|
||||
result = FilenameType.tvShow(seriesName: seriesName, season: 1, episode: episode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private func parseFilename(_ filename: String) -> FilenameType? {
|
||||
guard let path = Bundle(for: MP42File.self).path(forResource: "ParseFilename", ofType: "") else { return nil }
|
||||
|
||||
let stdOut = Pipe()
|
||||
let stdOutWrite = stdOut.fileHandleForWriting
|
||||
|
||||
// Use the ParseFilename perl script
|
||||
let task = Process()
|
||||
task.launchPath = "/usr/bin/perl"
|
||||
task.arguments = ["-I\(path)/lib", "\(path)/ParseFilename.pl", filename]
|
||||
task.standardOutput = stdOutWrite
|
||||
|
||||
task.launch()
|
||||
task.waitUntilExit()
|
||||
stdOutWrite.closeFile()
|
||||
|
||||
let outputData = stdOut.fileHandleForReading.readDataToEndOfFile()
|
||||
let outputString = String(describing: outputData)
|
||||
let lines = outputString.components(separatedBy: "\n")
|
||||
|
||||
if lines.count > 0 {
|
||||
if lines.first == "tv" {
|
||||
if lines.count >= 4 {
|
||||
let newSeriesName = lines[1].replacingOccurrences(of: ".", with: " ")
|
||||
return FilenameType.tvShow(seriesName: newSeriesName, season: Int(lines[2]), episode: Int(lines[3]))
|
||||
}
|
||||
}
|
||||
else if lines.first == "movie" {
|
||||
if lines.count >= 2 {
|
||||
let newTitle = lines[1].replacingOccurrences(of: ".", with: " ")
|
||||
.replacingOccurrences(of: "(", with: " ")
|
||||
.replacingOccurrences(of: ")", with: " ")
|
||||
.replacingOccurrences(of: "[", with: " ")
|
||||
.replacingOccurrences(of: "]", with: " ")
|
||||
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
|
||||
return FilenameType.movie(title: newTitle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
extension String {
|
||||
|
||||
func parsedAsFilename() -> FilenameType? {
|
||||
if let parsed = parseAnimeFilename(self) {
|
||||
return parsed
|
||||
}
|
||||
else if let parsed = parseFilename(self) {
|
||||
return parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - URL Utilities
|
||||
|
||||
extension String {
|
||||
|
||||
func urlEncoded() -> String {
|
||||
return self.precomposedStringWithCompatibilityMapping.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
|
||||
}
|
||||
|
||||
}
|
||||
@@ -78,7 +78,6 @@ public enum MetadataNameSearch {
|
||||
return MetadataSearchInternalTask(search: service.search(TVSeries: tvSeries, language: language),
|
||||
completionHandler: completionHandler)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -109,40 +108,3 @@ public enum MetadataSearch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public protocol MetadataSearchTask {
|
||||
func runAsync() -> MetadataSearchTask
|
||||
func run() -> MetadataSearchTask
|
||||
func cancel()
|
||||
}
|
||||
|
||||
private class MetadataSearchInternalTask<T> : MetadataSearchTask {
|
||||
|
||||
private var cancelled: Bool = false
|
||||
private let search: () -> T
|
||||
private let completionHandler: (T) -> Void
|
||||
|
||||
fileprivate init(search: @escaping @autoclosure () -> T, completionHandler: @escaping (T) -> Void) {
|
||||
self.search = search
|
||||
self.completionHandler = completionHandler
|
||||
}
|
||||
|
||||
public func runAsync() -> MetadataSearchTask {
|
||||
DispatchQueue.global(priority: .background).async {
|
||||
_ = self.run()
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func run() -> MetadataSearchTask {
|
||||
let results = self.search()
|
||||
if self.cancelled == false {
|
||||
self.completionHandler(results)
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
public func cancel() {
|
||||
self.cancelled = true
|
||||
}
|
||||
}
|
||||
@@ -237,7 +237,7 @@ final public class TheMovieDBService {
|
||||
// MARK: - Service calls
|
||||
|
||||
public func search(movie: String, language: String) -> [TMDBMovieSearchResult] {
|
||||
let encodedName = SBMetadataHelper.urlEncoded(movie)
|
||||
let encodedName = movie.urlEncoded()
|
||||
|
||||
guard let url = URL(string: basePath + "search/movie?api_key=" + key + "&query=" + encodedName + "&language=" + language),
|
||||
let result = sendJSONRequest(url: url, language: language, type: Wrapper<[TMDBMovieSearchResult]>.self)
|
||||
@@ -255,7 +255,7 @@ final public class TheMovieDBService {
|
||||
}
|
||||
|
||||
public func search(series: String, language: String) -> [TMDBTVSearchResult] {
|
||||
let encodedName = SBMetadataHelper.urlEncoded(series)
|
||||
let encodedName = series.urlEncoded()
|
||||
|
||||
guard let url = URL(string: basePath + "search/tv?api_key=" + key + "&query=" + encodedName + "&language=" + language),
|
||||
let result = sendJSONRequest(url: url, language: language, type: Wrapper<[TMDBTVSearchResult]>.self)
|
||||
|
||||
@@ -254,7 +254,7 @@ final public class TheTVDBService {
|
||||
// MARK: - Service calls
|
||||
|
||||
public func fetch(series: String, language: String) -> [SeriesSearchResult] {
|
||||
let encodedName = SBMetadataHelper.urlEncoded(series)
|
||||
let encodedName = series.urlEncoded()
|
||||
|
||||
guard let url = URL(string: basePath + "search/series?name=" + encodedName),
|
||||
let result = sendJSONRequest(url: url, language: language, type: Wrapper<[SeriesSearchResult]>.self)
|
||||
|
||||
@@ -241,11 +241,11 @@ public struct iTunesStore: MetadataService {
|
||||
// Determine artistId/collectionId
|
||||
guard let url = { () -> URL? in
|
||||
if let seasonNum = seasonNum {
|
||||
let searchTerm = SBMetadataHelper.urlEncoded("\(seriesName) \(store.season) \(seasonNum)")
|
||||
let searchTerm = "\(seriesName) \(store.season) \(seasonNum)".urlEncoded()
|
||||
return URL(string: "https://itunes.apple.com/search?country=\(store.country2)&lang=\(store.language2.lowercased())&term=\(searchTerm)&attribute=tvSeasonTerm&entity=tvSeason&limit=250")
|
||||
}
|
||||
else {
|
||||
let searchTerm = SBMetadataHelper.urlEncoded(seriesName)
|
||||
let searchTerm = seriesName.urlEncoded()
|
||||
return URL(string: "https://itunes.apple.com/search?country=\(store.country2)&lang=\(store.language2.lowercased())&term=\(searchTerm)&attribute=showTerm&entity=tvShow&limit=250")
|
||||
}
|
||||
}()
|
||||
@@ -363,7 +363,7 @@ public struct iTunesStore: MetadataService {
|
||||
|
||||
public func search(movie: String, language: String) -> [SBMetadataResult] {
|
||||
guard let store = iTunesStore.store(language: language),
|
||||
let url = URL(string: "https://itunes.apple.com/search?country=\(store.country2)&lang=\(store.language2)&term=\(SBMetadataHelper.urlEncoded(movie))&entity=movie&limit=150"),
|
||||
let url = URL(string: "https://itunes.apple.com/search?country=\(store.country2)&lang=\(store.language2)&term=\(movie.urlEncoded())&entity=movie&limit=150"),
|
||||
let results = sendJSONRequest(url: url, type: Wrapper<Track>.self)
|
||||
else { return [] }
|
||||
|
||||
|
||||
Reference in new issue
Block a user