summary history branches tags files
commit:b1dbbba75b075aaf422502caf88c76cd34941f35
author:Trevor Bentley
committer:Trevor Bentley
date:Tue Apr 11 11:48:53 2017 +0200
parents:d02f05230b92b510d14922e3fee27f60ec0db564
Optional DeviceId support in commands
diff --git a/src/main.rs b/src/main.rs
line changes: +2/-0
index 43d0e20..0b15a28
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,8 @@ fn main() {
         uris: Some(vec!["one".to_string(), "two".to_string()]),
         offset: Some(offset),
     };
+    spotify.play(Some("deviceid".to_string()), Some(&ctx));
+    spotify.pause(Some("deviceid".to_string()));
     spotify.play(None, Some(&ctx));
     spotify.pause(None);
     spotify.play(None, None);

diff --git a/src/webapi/mod.rs b/src/webapi/mod.rs
line changes: +24/-10
index 0840da9..234c38b
--- a/src/webapi/mod.rs
+++ b/src/webapi/mod.rs
@@ -95,6 +95,28 @@ impl Default for PlayContext {
     fn default() -> PlayContext { PlayContext { context_uri: None, uris: None, offset: None } }
 }
 
+fn append_to_json_string<T>(json: String, key: String, value: T) -> String
+    where T: ToJson {
+    // Highly wasteful implementation.  struct -> string -> obj -> string
+    let jdata = Json::from_str(&json).unwrap();
+    let mut jobj = jdata.into_object().unwrap();
+    jobj.insert(key, value.to_json());
+    Json::Object(jobj).to_string()
+}
+
+fn append_device_id(json: String, device: Option<DeviceId>) -> String {
+    match device {
+        Some(x) => {
+            // Convert empty string to empty JSON
+            let json = match json.len() {
+                0 => "{}".to_string(),
+                _ => json
+            };
+            append_to_json_string(json, "device_id".to_string(), x)
+        },
+        None => json
+    }
+}
 
 impl SpotifyConnectr {
     pub fn new(settings: settings::Settings) -> SpotifyConnectr {
@@ -117,21 +139,13 @@ impl SpotifyConnectr {
     }
     pub fn play(&self, device: Option<DeviceId>, context: Option<&PlayContext>) {
         let query = match context {
-            Some(x) => {
-                //json::encode(x).unwrap()
-                let jstr = json::encode(x).unwrap();
-                let jdata = Json::from_str(&jstr).unwrap();
-                let jobj = jdata.into_object().unwrap();
-                jobj.insert("device".to_string(), device.unwrap().to_json());
-                String::new()
-            },
+            Some(x) => append_device_id(json::encode(x).unwrap(), device),
             None => String::new(),
         };
-        println!("PUT query: {}", query);
         let _ = http::http(spotify_api::PLAY, &query, http::HttpMethod::PUT, Some(&self.access_token));
     }
     pub fn pause(&self, device: Option<DeviceId>) {
-        let query = String::new();
+        let query = append_device_id(String::new(), device);
         let _ = http::http(spotify_api::PAUSE, &query, http::HttpMethod::PUT, Some(&self.access_token));
     }
 }