aboutsummaryrefslogtreecommitdiff
path: root/Sources
diff options
context:
space:
mode:
authorBen Beltran <ben@nsovocal.com>2017-05-20 09:40:30 -0500
committerBen Beltran <ben@nsovocal.com>2017-05-20 09:40:30 -0500
commit29a566fada656091bf92456f6fb0f1bea5b6dca3 (patch)
treeca3abc17d3b5077db6b6a1e6d70e4702613eb427 /Sources
parent85d0536f2e9a3d4596c01b263d76b2b8d9ba70ae (diff)
parentd852b84edc24f1f1bbf4c34aa359447970e732b0 (diff)
Merge branch 'feature/rbdr-document-and-cleanup' into develop
Diffstat (limited to 'Sources')
-rw-r--r--Sources/arguments_source.swift21
-rw-r--r--Sources/configuration.swift50
-rw-r--r--Sources/lyricli.swift37
-rw-r--r--Sources/lyrics_engine.swift86
-rw-r--r--Sources/main.swift123
-rw-r--r--Sources/source_manager.swift40
-rw-r--r--Sources/source_protocol.swift2
-rw-r--r--Sources/track.swift6
8 files changed, 225 insertions, 140 deletions
diff --git a/Sources/arguments_source.swift b/Sources/arguments_source.swift
index c07c952..9615318 100644
--- a/Sources/arguments_source.swift
+++ b/Sources/arguments_source.swift
@@ -1,17 +1,18 @@
-/// Source that deals with command line
+// Source that reads track artist and name from the command line
class ArgumentsSource: Source {
- public var currentTrack: Track? {
- get {
- if CommandLine.arguments.count >= 3 {
- // expected usage: $ ./lyricli <artist> <name>
+ // Returns a track based on the arguments. It assumes the track artist
+ // will be the first argument, and the name will be the second, excluding
+ // any flags.
+ var currentTrack: Track? {
- let trackName: String = CommandLine.arguments[2]
- let trackArtist: String = CommandLine.arguments[1]
+ if CommandLine.arguments.count >= 3 {
+ // expected usage: $ ./lyricli <artist> <name>
+ let trackName: String = CommandLine.arguments[2]
+ let trackArtist: String = CommandLine.arguments[1]
- return Track(withName: trackName, andArtist: trackArtist)
- }
- return nil
+ return Track(withName: trackName, andArtist: trackArtist)
}
+ return nil
}
}
diff --git a/Sources/configuration.swift b/Sources/configuration.swift
index f5e4b0f..f1a1ee1 100644
--- a/Sources/configuration.swift
+++ b/Sources/configuration.swift
@@ -1,34 +1,38 @@
import Foundation
-/// Handles reading and writing the configuration
-public class Configuration {
-
- let configurationPath = NSString(string: "~/.lyricli.conf").expandingTildeInPath
-
- // The defaults are added here
+// Reads and writes the configuration. Config keys are accessed as a dictionary.
+class Configuration {
+ // Location of the global configuration file
+ private let configurationPath = NSString(string: "~/.lyricli.conf").expandingTildeInPath
+ // Default options, will be automatically written to the global config if
+ // not found.
private var configuration: [String: Any] = [
- "enabled_sources": ["arguments"],
- "default": true
+ "enabled_sources": ["arguments"]
]
- static let sharedInstance: Configuration = Configuration()
+ // The shared instance of the object
+ static let shared: Configuration = Configuration()
private init() {
- // Read the config file and attempt toset any of the values. Otherwise
- // Don't do anything.
- // IMPROVEMENT: Enable a debug mode
+ // Read the config file and attempt to set any of the values. Otherwise
+ // don't do anything.
if let data = try? NSData(contentsOfFile: configurationPath) as Data {
- if let parsedConfig = try? JSONSerialization.jsonObject(with: data) as! [String:Any] {
- for (key, value) in parsedConfig {
+ if let parsedConfig = try? JSONSerialization.jsonObject(with: data) {
+ if let parsedConfig = parsedConfig as? [String: Any] {
+ for (key, value) in parsedConfig {
- if key == "enabled_sources" {
- configuration[key] = value as! [String]
- }
- else {
- configuration[key] = value as! String
+ if key == "enabled_sources" {
+ if let value = value as? [String] {
+ configuration[key] = value
+ }
+ } else {
+ if let value = value as? String {
+ configuration[key] = value
+ }
+ }
}
}
}
@@ -37,18 +41,22 @@ public class Configuration {
writeConfiguration()
}
+ // Write the configuration back to the file
private func writeConfiguration() {
var error: NSError?
if let outputStream = OutputStream(toFileAtPath: configurationPath, append: false) {
outputStream.open()
- JSONSerialization.writeJSONObject(configuration, to: outputStream, options: [JSONSerialization.WritingOptions.prettyPrinted], error: &error)
+ JSONSerialization.writeJSONObject(configuration,
+ to: outputStream,
+ options: [JSONSerialization.WritingOptions.prettyPrinted],
+ error: &error)
outputStream.close()
}
}
- // Allow access as an object
+ // Allow access to the config properties as a dictionary
subscript(index: String) -> Any? {
get {
return configuration[index]
diff --git a/Sources/lyricli.swift b/Sources/lyricli.swift
index c44a7f4..e7d14b9 100644
--- a/Sources/lyricli.swift
+++ b/Sources/lyricli.swift
@@ -1,15 +1,20 @@
-/// The main Lyricli interface
-public class Lyricli {
- public static var version = "0.0.0-feature/option-parsing"
+// The main class, handles all the actions that the executable will call
+class Lyricli {
- public static var showTitle = false
+ // Version of the application
+ static var version = "0.0.0"
- public static func printLyrics() {
+ // Flag that controls whether we should show the track artist and name before
+ // the lyrics
+ static var showTitle = false
+
+ // Obtains the name of the current track from a source, fetches the lyrics
+ // from an engine and prints them
+ static func printLyrics() {
let sourceManager = SourceManager()
if let currentTrack = sourceManager.currentTrack {
-
let engine = LyricsEngine(withTrack: currentTrack)
if let lyrics = engine.lyrics {
@@ -18,33 +23,37 @@ public class Lyricli {
}
print(lyrics)
- }
- else {
+ } else {
print("Lyrics not found :(")
}
- }
- else {
+ } else {
print("No Artist/Song could be found :(")
}
}
- public static func printSources() {
+ // Print the currently available sources
+ static func printSources() {
print("Listing Sources: Not yet implemented")
}
- public static func enableSource(_ sourceName: String) {
+ // Runs the enable method of a source and writes the configuration to set it
+ // as enabled
+ static func enableSource(_ sourceName: String) {
print("Enable source \(sourceName): Not yet implemented")
}
- public static func disableSource(_ sourceName: String) {
+ // Remove a source from the enabled sources configuration
+ static func disableSource(_ sourceName: String) {
print("Disable source \(sourceName): Not yet implemented")
}
- public static func resetSource(_ sourceName: String) {
+ // Removes any configuration for a source, and disables it
+ static func resetSource(_ sourceName: String) {
print("Reset source \(sourceName): Not yet implemented")
}
+ // Prints the track artist and name
private static func printTitle(_ track: Track) {
print("\(track.artist) - \(track.name)")
}
diff --git a/Sources/lyrics_engine.swift b/Sources/lyrics_engine.swift
index d6b1985..85e4735 100644
--- a/Sources/lyrics_engine.swift
+++ b/Sources/lyrics_engine.swift
@@ -1,80 +1,87 @@
import Foundation
import HTMLEntities
-/// Looks for lyrics on the internet
+// Given a track, attempts to fetch the lyrics from lyricswiki
class LyricsEngine {
+ // URL of the API endpoint to use
private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson"
+
+ // Method used to call the API
private let apiMethod = "GET"
+
+ // Regular expxression used to find the lyrics in the lyricswiki HTML
private let lyricsMatcher = "class='lyricbox'>(.+)<div"
+ // The track we'll be looking for
private let track: Track
// Fetches the lyrics and returns if found
-
var lyrics: String? {
- get {
- var lyrics: String?
+ var lyrics: String?
- if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
- if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
- if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
+ // Encode the track artist and name and finish building the API call URL
- // We'll lock until the async call is finished
+ if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
+ if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
+ if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
- var requestFinished = false
- let asyncLock = NSCondition()
- asyncLock.lock()
+ // We'll lock until the async call is finished
- // Call the API and unlock when you're done
+ var requestFinished = false
+ let asyncLock = NSCondition()
+ asyncLock.lock()
- fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
- if let lyricsResult = lyricsResult {
- lyrics = lyricsResult
- requestFinished = true
- asyncLock.signal()
- }
- })
+ // Call the API and unlock when you're done
- while(!requestFinished) {
- asyncLock.wait()
+ fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
+ if let lyricsResult = lyricsResult {
+ lyrics = lyricsResult
+ requestFinished = true
+ asyncLock.signal()
}
- asyncLock.unlock()
+ })
+
+ while !requestFinished {
+ asyncLock.wait()
}
+ asyncLock.unlock()
}
}
-
- return lyrics
}
+
+ return lyrics
}
+ // Initializes with a track
init(withTrack targetTrack: Track) {
track = targetTrack
}
- // Fetch the lyrics from the API and request / parse the page
-
+ // Fetch the lyrics URL from the API, triggers the request to fetch the
+ // lyrics page
private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
var apiRequest = URLRequest(url: url)
apiRequest.httpMethod = "GET"
- let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, response, error -> Void in
+ let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
// If the response is parseable JSON, and has a url, we'll look for
// the lyrics in there
if let data = data {
- let jsonResponse = try? JSONSerialization.jsonObject(with: data) as! [String: Any]
- if let jsonResponse = jsonResponse {
- if let lyricsUrlString = jsonResponse["url"] as? String {
- if let lyricsUrl = URL(string: lyricsUrlString) {
+ if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
+ if let jsonResponse = jsonResponse as? [String: Any] {
+ if let lyricsUrlString = jsonResponse["url"] as? String {
+ if let lyricsUrl = URL(string: lyricsUrlString) {
- // At this point we have a valid wiki url
- self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
- return
+ // At this point we have a valid wiki url
+ self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
+ return
+ }
}
}
}
@@ -85,14 +92,13 @@ class LyricsEngine {
task.resume()
}
- // Fetch the lyrics from the page and parse the page
-
+ // Fetch the lyrics from the page and send it to the parser
private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
var pageRequest = URLRequest(url: url)
pageRequest.httpMethod = "GET"
- let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, response, error -> Void in
+ let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
// If the response is parseable JSON, and has a url, we'll look for
// the lyrics in there
@@ -109,10 +115,11 @@ class LyricsEngine {
task.resume()
}
- // Parses the wiki to obtain the lyrics
-
+ // Parses the wiki to find the lyrics, decodes the lyrics object
private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
+ // Look for the lyrics lightbox
+
if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
@@ -133,7 +140,6 @@ class LyricsEngine {
}
// Escapes the HTML entities
-
private func decodeLyrics(_ lyrics: String) -> String {
let unescapedLyrics = lyrics.htmlUnescape()
diff --git a/Sources/main.swift b/Sources/main.swift
index e4b2760..9d46e92 100644
--- a/Sources/main.swift
+++ b/Sources/main.swift
@@ -1,11 +1,44 @@
import CommandLineKit
import Foundation
+// Entry point of the application. This is the main executable
+private func main() {
+ let (flags, parser) = createParser()
+
+ do {
+ try parser.parse()
+ } catch {
+ parser.printUsage(error)
+ exit(EX_USAGE)
+ }
+
+ // Boolean Options
+
+ checkHelpFlag(flags["help"], withParser: parser)
+ checkVersionFlag(flags["version"], withParser: parser)
+ checkListSourcesFlag(flags["listSources"], withParser: parser)
+ checkTitleFlag(flags["title"], withParser: parser)
+
+ // String Options
+
+ checkEnableSourceFlag(flags["enableSource"], withParser: parser)
+ checkDisableSourceFlag(flags["disableSource"], withParser: parser)
+ checkResetSourceFlag(flags["resetSource"], withParser: parser)
+
+ // Remove any flags so anyone after this gets the unprocessed values
+
+ let programName: [String] = [CommandLine.arguments[0]]
+ CommandLine.arguments = programName + parser.unparsedArguments
+
+ // Run Lyricli
+
+ Lyricli.printLyrics()
+}
+
/// Sets up and returns a new options parser
///
/// - Returns: A Dictionary of Options, and a new CommandLineKit instance
-func createParser() -> ([String:Option], CommandLineKit) {
-
+private func createParser() -> ([String:Option], CommandLineKit) {
let parser = CommandLineKit()
var flags: [String:Option] = [:]
@@ -21,74 +54,98 @@ func createParser() -> ([String:Option], CommandLineKit) {
parser.addOptions(Array(flags.values))
- return (flags, parser)
-}
+ parser.formatOutput = {parseString, type in
-func main() {
+ var formattedString: String
- let (flags, parser) = createParser()
+ switch type {
+ case .About:
+ formattedString = "\(parseString) [<artist_name> <song_name>]"
+ break
+ default:
+ formattedString = parseString
+ }
- do {
- try parser.parse()
- }
- catch {
- parser.printUsage(error)
- exit(EX_USAGE)
+ return parser.defaultFormat(formattedString, type: type)
}
- if let helpFlag = flags["help"] as? BoolOption {
- if helpFlag.value == true {
+ return (flags, parser)
+}
+
+// Handle the Help flag
+
+private func checkHelpFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let helpFlag = flag as? BoolOption {
+ if helpFlag.value {
parser.printUsage()
exit(0)
}
}
+}
+
+// Handle the version flag
- if let versionFlag = flags["version"] as? BoolOption {
- if versionFlag.value == true {
+private func checkVersionFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let versionFlag = flag as? BoolOption {
+ if versionFlag.value {
print(Lyricli.version)
exit(0)
}
}
+}
+
+// Handle the list sources flag
- if let listSourcesFlag = flags["listSources"] as? BoolOption {
- if listSourcesFlag.value == true {
+private func checkListSourcesFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let listSourcesFlag = flag as? BoolOption {
+ if listSourcesFlag.value {
Lyricli.printSources()
exit(0)
}
}
+}
+
+// Handle the title flag
+
+private func checkTitleFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let titleFlag = flag as? BoolOption {
+ if titleFlag.value {
+ Lyricli.showTitle = true
+ }
+ }
+}
- if let enableSourceFlag = flags["enableSource"] as? StringOption {
+// Handle the enable source flag
+
+private func checkEnableSourceFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let enableSourceFlag = flag as? StringOption {
if let source = enableSourceFlag.value {
Lyricli.enableSource(source)
exit(0)
}
}
+}
- if let disableSourceFlag = flags["disableSource"] as? StringOption {
+// Handle the disable source flag
+
+private func checkDisableSourceFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let disableSourceFlag = flag as? StringOption {
if let source = disableSourceFlag.value {
Lyricli.disableSource(source)
exit(0)
}
}
+}
- if let resetSourceFlag = flags["resetSource"] as? StringOption {
+// Handle the reset source flag
+
+private func checkResetSourceFlag(_ flag: Option?, withParser parser: CommandLineKit) {
+ if let resetSourceFlag = flag as? StringOption {
if let source = resetSourceFlag.value {
Lyricli.resetSource(source)
exit(0)
}
}
-
- if let titleFlag = flags["title"] as? BoolOption {
- if titleFlag.value == true {
- Lyricli.showTitle = true
- }
- }
-
- // Remove any flags so anyone after this gets the unprocessed values
- let programName: [String] = [CommandLine.arguments[0]]
- CommandLine.arguments = programName + parser.unparsedArguments
-
- Lyricli.printLyrics()
}
main()
diff --git a/Sources/source_manager.swift b/Sources/source_manager.swift
index dd956ad..5ee1305 100644
--- a/Sources/source_manager.swift
+++ b/Sources/source_manager.swift
@@ -1,52 +1,50 @@
-/// Manages the different sources. Keeps track of them, lists and toggles
+// Collect and manage the available and enabled source
class SourceManager {
+ // List of sources enabled for the crurent platform
private var availableSources: [String: Source] = [
"arguments": ArgumentsSource()
]
+ // Iterate over the sources until we find a track or run out of sources
var currentTrack: Track? {
- get {
-
- for source in enabledSources {
- if let currentTrack = source.currentTrack {
- return currentTrack
- }
+ for source in enabledSources {
+ if let currentTrack = source.currentTrack {
+ return currentTrack
}
-
- return nil
}
+
+ return nil
}
+ // Return the list of enabled sources based on the configuration
var enabledSources: [Source] {
// Checks the config and returns an array of sources based on the
// enabled and available ones
- get {
- var sources = [Source]()
+ var sources = [Source]()
- if let sourceNames = Configuration.sharedInstance["enabled_sources"] as? [String]{
- for sourceName in sourceNames {
- if let source = availableSources[sourceName] {
- sources.append(source)
- }
+ if let sourceNames = Configuration.shared["enabled_sources"] as? [String] {
+ for sourceName in sourceNames {
+ if let source = availableSources[sourceName] {
+ sources.append(source)
}
}
-
- return sources
}
+
+ return sources
}
+ // Given a source name, it will enable it and add it to the enabled sources config
func enable(sourceName: String) {
}
+ // Given a source name, it will remove it from the enabled sources config
func disable(sourceName: String) {
}
+ // Given a source name, it removes any stored configuration and disables it
func reset(sourceName: String) {
}
-
- func getSources(sourceName: String) {
- }
}
diff --git a/Sources/source_protocol.swift b/Sources/source_protocol.swift
index ee9350c..0885994 100644
--- a/Sources/source_protocol.swift
+++ b/Sources/source_protocol.swift
@@ -1,3 +1,5 @@
+// All sources should comply with this protocol. The currentTrack computed
+// property will return a track if the conditions are met
protocol Source {
var currentTrack: Track? { get }
}
diff --git a/Sources/track.swift b/Sources/track.swift
index d2a9047..ead4359 100644
--- a/Sources/track.swift
+++ b/Sources/track.swift
@@ -1,6 +1,10 @@
-/// Contains the artist and name of a track
+// Holds the name and artist of a track
class Track {
+
+ // The name of the track to search for
let name: String
+
+ // The name of the artist
let artist: String
init(withName trackName: String, andArtist trackArtist: String) {