|
| 1 | +#[macro_use] |
| 2 | +extern crate cpython; |
| 3 | +extern crate tokio_core; |
| 4 | +extern crate librespot; |
| 5 | + |
| 6 | +use std::cell::RefCell; |
| 7 | +use cpython::{PyResult, PyObject}; |
| 8 | +use tokio_core::reactor::Core; |
| 9 | + |
| 10 | +thread_local! { |
| 11 | + pub static CORE: RefCell<Core> = RefCell::new(Core::new().unwrap()); |
| 12 | +} |
| 13 | + |
| 14 | +py_class!(class Session |py| { |
| 15 | + data session : librespot::session::Session; |
| 16 | + |
| 17 | + def __new__(_cls, username: String, password: String) -> PyResult<Session> { |
| 18 | + use librespot::session::Config; |
| 19 | + use librespot::authentication::Credentials; |
| 20 | + |
| 21 | + CORE.with(|core| { |
| 22 | + let mut core = core.borrow_mut(); |
| 23 | + let handle = core.handle(); |
| 24 | + |
| 25 | + let config = Config::default(); |
| 26 | + let credentials = Credentials::with_password(username, password); |
| 27 | + let session = core.run(librespot::session::Session::connect(config, credentials, None, handle)).unwrap(); |
| 28 | + |
| 29 | + Session::create_instance(py, session) |
| 30 | + }) |
| 31 | + } |
| 32 | + |
| 33 | + def player(&self) -> PyResult<Player> { |
| 34 | + let backend = librespot::audio_backend::find(None).unwrap(); |
| 35 | + let session = self.session(py).clone(); |
| 36 | + |
| 37 | + let player = librespot::player::Player::new(session, None, move || (backend)(None)); |
| 38 | + Player::create_instance(py, player) |
| 39 | + } |
| 40 | +}); |
| 41 | + |
| 42 | +py_class!(class Player |py| { |
| 43 | + data player : librespot::player::Player; |
| 44 | + |
| 45 | + def play(&self, track: SpotifyId) -> PyResult<PyObject> { |
| 46 | + CORE.with(|core| { |
| 47 | + let mut core = core.borrow_mut(); |
| 48 | + let player = self.player(py); |
| 49 | + let track = *track.id(py); |
| 50 | + |
| 51 | + core.run(player.load(track, true, 0)).unwrap(); |
| 52 | + |
| 53 | + Ok(py.None()) |
| 54 | + }) |
| 55 | + } |
| 56 | +}); |
| 57 | + |
| 58 | +py_class!(class SpotifyId |py| { |
| 59 | + data id : librespot::util::SpotifyId; |
| 60 | + |
| 61 | + def __new__(_cls, base62: &str) -> PyResult<SpotifyId> { |
| 62 | + let id = librespot::util::SpotifyId::from_base62(base62); |
| 63 | + SpotifyId::create_instance(py, id) |
| 64 | + } |
| 65 | +}); |
| 66 | + |
| 67 | +py_module_initializer!(librespot, initlibrespot, PyInit_librespot, |py, m| { |
| 68 | + m.add_class::<Session>(py)?; |
| 69 | + m.add_class::<SpotifyId>(py)?; |
| 70 | + Ok(()) |
| 71 | +}); |
0 commit comments