[
  {
    "path": ".gitignore",
    "content": "/target\n/profiling\nconfig.ron\nprofile.json\n/.vscode"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"pulseshitter\"\nversion = \"3.0.0\"\nedition = \"2021\"\n\n[profile.profiling]\ninherits = \"release\"\ndebug = true\n\n[profile.release]\nlto = true\ncodegen-units = 1\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nreqwest = { version = \"0.12.4\", features = [\"json\"] }\nringbuf = \"0.3.3\"\nserde = \"1.0.156\"\nserde_json = \"1.0.96\"\nron = \"0.8.0\"\ncrossbeam = \"0.8.2\"\nsongbird = \"0.3.2\"\nserenity = { version = \"0.11.5\", default-features = false, features = [\n  \"builder\",\n  \"cache\",\n  \"client\",\n  \"voice\",\n] }\ntokio = { version = \"1.26.0\", features = [\"full\"] }\nlibpulse-binding = \"2.28.1\"\ntui = \"0.19\"\ntui-textarea = \"0.2.0\"\ncrossterm = \"0.25\"\nenum-iterator = \"1.4.0\"\nregex = \"1.7.3\"\nlazy_static = \"1.4.0\"\nparking_lot = \"0.12\"\nmultiversion = \"0.7.1\"\nstrsim = \"0.10.0\"\nthiserror = \"1.0.56\"\n"
  },
  {
    "path": "LICENSE",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in\n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0.\n"
  },
  {
    "path": "README.md",
    "content": "# pulseshitter\n\n[![License](https://img.shields.io/github/license/Enitoni/pulseshitter.svg?style=flat)](https://github.com/Enitoni/pulseshitter/blob/main/LICENSE)\n\n![Screenshot of pulseshitter](preview.gif)\n\npulseshitter is a shitty solution to a shitty problem.\n\nyou see, it all started back in 2015, when discord announced discord, an instant messaging social platform for gamers, until they decided that it was for everyone too.\n\nhowever, they clearly don't support everyone because they hate us blessed linux users. to this day, discord still [doesn't support](https://support.discord.com/hc/en-us/community/posts/360050971374-Linux-Screen-Share-Sound-Support) sharing audio via screen sharing on linux.\n\n## what is this?\n\nthis overengineered project is a workaround to make it possible to share audio via a **bot**. ***it does not pipe your audio through your microphone.*** this has two advantages:\n\n- other people can mute your stream without muting you\n- the audio is stereo (ＷＩＤＥ)\n\n## features\n\n- shits your audio into a voice channel\n- based text-based user interface\n- automatically reconnects to an application when parec stops streaming it (it does that a lot)\n- cool good sound meter™️\n- follows you around so you can always bother your friends\n- says fuck you to discord (fuck you discord)\n- 🚀 blazingly fa-- \n\n## caveats\n\n- you need a bot in a server to use it\n- linux audio sources are very inconsistent so it's not guaranteed it will reconnect properly, or even show a meaningful name, but you can always just select the app you want to stream again\n\n## usage\n\n### prerequisites\n\n- [linux](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git) (duh)\n- [pulseaudio](https://www.freedesktop.org/wiki/Software/PulseAudio/) or [pipewire](https://pipewire.org)\n- [discord bot](https://google.com/search?q=discord+bot+token+generator)\n\n\n[download latest release](https://github.com/Enitoni/pulseshitter/releases/latest) and run the binary in your terminal. you can also add it to path for easy access.\n\n```shell\n./pulseshitter\n```\n\n----\n\n## faq (you)\n\n### Is this a joke?\nParts of this README, yes. The project itself, no. It's actually something I worked really hard on and it is actually a successor to [pulsecord](https://github.com/itsMapleLeaf/pulsecord) which my friend was using. It had some issues, and that's what led to this project.\n\n### Why can't I stream Spotify?\nSpotify streaming is disabled by default due to me not wanting to get in trouble for distributing a binary that allows you to bypass the measures Discord has in place to stop you from streaming Spotify through their service.\n\nYou can enable it by compiling the project yourself with the `ALLOW_SPOTIFY_STREAMING` environment variable set to `true`.\n\n### Are you open to suggestions/bug reports?\nYes. Please make a GitHub issue if you want to report a bug or suggest a feature.\n\n\n---\n\n## build\n\n### prerequisites\n\n- [rust](https://www.rust-lang.org/)\n- pulseaudio / pipewire\n- libopus\n\ncompile it by typing this in your terminal:\n```shell\ncargo build --release\n```\n\nthen you're done (wow!)\n\n\n## license\n\n[MPL-2 license](https://www.mozilla.org/en-US/MPL/2.0/) (very original do not steal)\n"
  },
  {
    "path": "src/app.rs",
    "content": "use crate::{\n    audio::{pulse::PulseClientError, AudioSystem, Source},\n    dickcord::{self, DiscordSystem},\n    interface::{Dashboard, Interface, Setup, Splash},\n    state::{Config, ReadOnlyConfig},\n};\nuse crossbeam::channel::{unbounded, Receiver, Sender};\nuse parking_lot::Mutex;\nuse reqwest::ClientBuilder;\nuse serde::Deserialize;\nuse std::{sync::Arc, thread};\nuse thiserror::Error;\nuse tokio::runtime::{Builder, Runtime};\n\npub const VERSION: &str = env!(\"CARGO_PKG_VERSION\");\nconst LATEST_RELEASE_URL: &str =\n    \"https://api.github.com/repos/enitoni/pulseshitter/releases/latest\";\n\npub struct App {\n    rt: Arc<Runtime>,\n    interface: Interface,\n    audio: Arc<AudioSystem>,\n    discord: Arc<DiscordSystem>,\n\n    events: Sender<AppEvent>,\n    state: Arc<Mutex<AppState>>,\n\n    config: Arc<Mutex<Option<Config>>>,\n    update_available: Arc<Mutex<Option<String>>>,\n}\n\n#[derive(Clone)]\npub struct AppContext {\n    events: Sender<AppEvent>,\n    audio: Arc<AudioSystem>,\n    discord: Arc<DiscordSystem>,\n    config: Arc<Mutex<Option<Config>>>,\n    update_available: Arc<Mutex<Option<String>>>,\n}\n\n#[derive(Debug, Clone)]\nenum AppState {\n    Exiting,\n    Idle,\n}\n\n#[derive(Error, Debug)]\npub enum AppError {\n    #[error(transparent)]\n    PulseClient(#[from] PulseClientError),\n}\n\n#[derive(Debug, Clone)]\npub enum AppAction {\n    SetConfig(Config),\n    SetAudioSource(Source),\n    ToggleScreenshareOnly,\n    ToggleMeter,\n    StopStream,\n    RedoSetup,\n    Exit,\n}\n\n#[allow(clippy::large_enum_variant)]\npub enum AppEvent {\n    DiscordStateUpdate(dickcord::State),\n    Action(AppAction),\n}\n\nimpl App {\n    pub fn new() -> Result<Arc<Self>, AppError> {\n        let rt: Arc<_> = Builder::new_multi_thread()\n            .worker_threads(1)\n            .max_blocking_threads(1)\n            .enable_all()\n            .thread_name(\"pulseshitter-async\")\n            .build()\n            .unwrap()\n            .into();\n\n        let (sender, receiver) = unbounded();\n\n        let config = Config::restore();\n        let audio = AudioSystem::new().map_err(AppError::PulseClient)?;\n        let discord = DiscordSystem::new(rt.clone(), sender.clone(), audio.stream());\n        let interface = Interface::new(Splash, sender.clone());\n\n        let app = Arc::new(Self {\n            rt,\n            audio,\n            discord,\n            interface,\n            events: sender,\n            state: Arc::new(AppState::Idle.into()),\n            config: Arc::new(Mutex::new(config)),\n            update_available: Default::default(),\n        });\n\n        spawn_poll_thread(app.clone(), receiver);\n\n        app.check_for_update();\n        app.restore();\n        Ok(app)\n    }\n\n    pub fn run_tui(&self) {\n        let result = self.interface.run();\n\n        if let Err(err) = result {\n            eprintln!(\"Render error: {}\", err)\n        }\n    }\n\n    fn restore(&self) {\n        let config = Config::restore();\n\n        if let Some(config) = config {\n            self.discord.connect(&config);\n            self.interface.set_view(Dashboard::new(self.context()))\n        } else {\n            self.interface.set_view(Setup::new(self.context()))\n        }\n    }\n\n    fn context(&self) -> AppContext {\n        AppContext {\n            events: self.events.clone(),\n            audio: self.audio.clone(),\n            discord: self.discord.clone(),\n            config: self.config.clone(),\n            update_available: self.update_available.clone(),\n        }\n    }\n\n    fn exit(&self) {\n        self.set_state(AppState::Exiting);\n\n        if let dickcord::State::Connected(_, _) = self.discord.state() {\n            self.discord.disconnect();\n        } else {\n            self.interface.stop();\n        }\n    }\n\n    fn handle_event(&self, event: AppEvent) {\n        match event {\n            AppEvent::Action(action) => self.handle_action(action),\n            AppEvent::DiscordStateUpdate(new_state) => self.handle_discord_state_update(new_state),\n        }\n    }\n\n    fn handle_discord_state_update(&self, new_state: dickcord::State) {\n        if let dickcord::State::Connected(_, _) = new_state {\n            self.save_config();\n            self.interface.set_view(Dashboard::new(self.context()))\n        }\n\n        if let dickcord::State::Idle = new_state {\n            if let AppState::Exiting = self.state() {\n                self.interface.stop();\n            }\n        }\n    }\n\n    fn handle_action(&self, action: AppAction) {\n        match action {\n            AppAction::SetConfig(config) => {\n                self.discord.connect(&config);\n                self.set_config(config);\n            }\n            AppAction::RedoSetup => {\n                self.discord.disconnect();\n                self.interface.set_view(Setup::new(self.context()));\n            }\n            AppAction::ToggleScreenshareOnly => {\n                self.edit_config(|config| {\n                    config.screen_share_only = !config.screen_share_only;\n                });\n\n                self.discord.set_config(self.read_only_config());\n            }\n            AppAction::ToggleMeter => {\n                self.edit_config(|config| {\n                    config.show_meter = !config.show_meter;\n                });\n            }\n            AppAction::SetAudioSource(source) => {\n                self.audio.select(Some(source.clone()));\n                self.discord.announce_source_streaming(Some(source));\n            }\n            AppAction::StopStream => {\n                self.audio.select(None);\n                self.discord.announce_source_streaming(None);\n            }\n            AppAction::Exit => self.exit(),\n        }\n    }\n\n    fn set_state(&self, state: AppState) {\n        *self.state.lock() = state;\n    }\n\n    fn state(&self) -> AppState {\n        self.state.lock().clone()\n    }\n\n    fn set_config(&self, config: Config) {\n        let mut previous_config = self.config.lock();\n        *previous_config = Some(config);\n    }\n\n    fn save_config(&self) {\n        let config = self.config.lock();\n\n        if let Some(config) = config.as_ref() {\n            config.save();\n        }\n    }\n\n    fn edit_config(&self, cb: impl FnOnce(&mut Config)) {\n        let mut config = self.config.lock();\n\n        if let Some(config) = config.as_mut() {\n            cb(config);\n            config.save();\n        }\n    }\n\n    fn read_only_config(&self) -> ReadOnlyConfig {\n        let config = self.config.lock();\n\n        config\n            .as_ref()\n            .expect(\"Config is set when config() is called on AppContext\")\n            .read_only()\n    }\n\n    fn check_for_update(&self) {\n        let update_available = self.update_available.clone();\n\n        self.rt.spawn(async move {\n            let new_version = fetch_update().await;\n\n            if let Some(new_version) = new_version {\n                *update_available.lock() = Some(new_version);\n            }\n        });\n    }\n}\n\nfn spawn_poll_thread(app: Arc<App>, receiver: Receiver<AppEvent>) {\n    let run = move || loop {\n        if let Ok(event) = receiver.recv() {\n            app.handle_event(event)\n        }\n    };\n\n    thread::Builder::new()\n        .name(\"pulseshitter-polling\".to_string())\n        .spawn(run)\n        .unwrap();\n}\n\nimpl AppContext {\n    pub fn dispatch_action(&self, action: AppAction) {\n        self.events.send(AppEvent::Action(action)).unwrap()\n    }\n\n    pub fn sources(&self) -> Vec<Source> {\n        self.audio.sources()\n    }\n\n    pub fn current_source(&self) -> Option<Source> {\n        self.audio.current_source()\n    }\n\n    pub fn selected_source(&self) -> Option<Source> {\n        self.audio.selected_source()\n    }\n\n    pub fn meter_value_ranged(&self) -> (f32, f32) {\n        self.audio.meter_value_ranged()\n    }\n\n    pub fn discord_state(&self) -> dickcord::State {\n        self.discord.state()\n    }\n\n    pub fn config(&self) -> ReadOnlyConfig {\n        let config = self.config.lock();\n\n        config\n            .as_ref()\n            .expect(\"Config is set when config() is called on AppContext\")\n            .read_only()\n    }\n\n    pub fn update_available(&self) -> Option<String> {\n        self.update_available.lock().clone()\n    }\n}\n\n#[derive(Debug, Deserialize)]\nstruct LatestRelease {\n    tag_name: String,\n}\n\nasync fn fetch_update() -> Option<String> {\n    let client = ClientBuilder::new()\n        .user_agent(\"enitoni/pulseshitter\")\n        .build()\n        .unwrap();\n\n    let release: LatestRelease = client\n        .get(LATEST_RELEASE_URL)\n        .send()\n        .await\n        .ok()?\n        .json()\n        .await\n        .ok()?;\n\n    if release.tag_name != format!(\"v{}\", VERSION) {\n        return Some(release.tag_name);\n    }\n\n    None\n}\n"
  },
  {
    "path": "src/audio/analysis.rs",
    "content": "use std::{sync::Arc, thread, time::Duration};\n\nuse crossbeam::atomic::AtomicCell;\nuse multiversion::multiversion;\nuse parking_lot::Mutex;\n\nuse crate::interface::TARGET_FPS;\n\nuse super::{Sample, SAMPLE_IN_BYTES, SAMPLE_RATE};\n\n/// Measures dBFS of a single channel\npub struct Meter {\n    window_size: AtomicCell<usize>,\n\n    current_value: AtomicCell<f32>,\n\n    buffer: Mutex<Vec<f32>>,\n}\n\nimpl Meter {\n    const DEFAULT_WINDOW_SIZE: usize = SAMPLE_RATE / 24;\n    const DB_RANGE: f32 = 100.;\n\n    /// The smoothing modifiers. Higher values equals less smoothing.\n    const MAX_SMOOTHING: f32 = 0.1 / 2.;\n    const MIN_SMOOTHING: f32 = 0.2;\n\n    /// The minimum smoothing boundary\n    const SMOOTHING_BOUNDARY: f32 = 0.5;\n\n    pub fn new() -> Self {\n        Self {\n            window_size: Self::DEFAULT_WINDOW_SIZE.into(),\n            current_value: Default::default(),\n            buffer: Default::default(),\n        }\n    }\n\n    pub fn write(&self, buf: &[u8]) {\n        let mut buffer = self.buffer.lock();\n        let window_size = self.window_size.load();\n\n        let samples = raw_samples_from_bytes(buf);\n\n        buffer.extend_from_slice(&samples);\n\n        let overflow = buffer.len() as isize + -(window_size as isize);\n        let overflow = overflow.max(0) as usize;\n\n        if overflow > 0 {\n            buffer.drain(..overflow);\n        }\n    }\n\n    pub fn drain(&self, amount: usize) {\n        let mut buffer = self.buffer.lock();\n\n        buffer.extend(vec![0.; amount]);\n        buffer.drain(..amount);\n    }\n\n    pub fn process(&self) {\n        process_multiversioned(self)\n    }\n\n    pub fn value(&self) -> f32 {\n        self.current_value.load()\n    }\n\n    pub fn dbfs(&self) -> f32 {\n        self.value().log10() * 20.\n    }\n\n    pub fn value_ranged(&self) -> f32 {\n        let ranged = (Self::DB_RANGE + self.dbfs()) / Self::DB_RANGE;\n        ranged.max(0.).powf(2.)\n    }\n}\n\n#[multiversion(targets(\"x86_64+avx2\"))]\nfn process_multiversioned(meter: &Meter) {\n    let buffer = meter.buffer.lock();\n\n    let current_value = meter.current_value.load();\n    let max_value = buffer\n        .iter()\n        .fold(0f32, |acc, x| faster_max(acc, (*x).abs()));\n\n    let difference = (current_value - max_value).abs();\n\n    if max_value > current_value {\n        meter.current_value.store(max_value);\n    } else {\n        let max_smoothing =\n            (1. - Meter::MAX_SMOOTHING) + Meter::MAX_SMOOTHING * Meter::SMOOTHING_BOUNDARY;\n\n        let min_smoothing =\n            (1. - Meter::MIN_SMOOTHING) + Meter::MIN_SMOOTHING * Meter::SMOOTHING_BOUNDARY;\n\n        let flipped_difference = (-difference) + 1.;\n        let smoothing_factor = flipped_difference * max_value.powf(0.1);\n\n        let smoothing = min_smoothing + (max_smoothing - min_smoothing) * smoothing_factor;\n        let result = current_value * smoothing;\n\n        meter.current_value.store(result);\n    }\n}\n\npub struct StereoMeter {\n    left: Meter,\n    right: Meter,\n}\n\nimpl StereoMeter {\n    pub fn new() -> Self {\n        Self {\n            left: Meter::new(),\n            right: Meter::new(),\n        }\n    }\n\n    pub fn write(&self, buf: &[u8]) {\n        let samples = buf.chunks_exact(SAMPLE_IN_BYTES * 2);\n\n        let mut left = vec![];\n        let mut right = vec![];\n\n        for chunk in samples {\n            left.extend_from_slice(&chunk[..SAMPLE_IN_BYTES]);\n            right.extend_from_slice(&chunk[SAMPLE_IN_BYTES..]);\n        }\n\n        self.left.write(&left);\n        self.right.write(&right);\n    }\n\n    pub fn process(&self) {\n        self.left.process();\n        self.right.process();\n    }\n\n    pub fn drain(&self, amount: usize) {\n        self.left.drain(amount);\n        self.right.drain(amount);\n    }\n\n    pub fn value_ranged(&self) -> (f32, f32) {\n        (self.left.value_ranged(), self.right.value_ranged())\n    }\n}\n\nimpl Default for StereoMeter {\n    fn default() -> Self {\n        Self::new()\n    }\n}\n\nfn faster_max(a: f32, b: f32) -> f32 {\n    if a > b {\n        a\n    } else {\n        b\n    }\n}\n\n/// Converts a slice of bytes into a vec of [Sample].\npub fn raw_samples_from_bytes(bytes: &[u8]) -> Vec<Sample> {\n    bytes\n        .chunks_exact(SAMPLE_IN_BYTES)\n        .map(|b| {\n            let arr: [u8; SAMPLE_IN_BYTES] = [b[0], b[1], b[2], b[3]];\n            Sample::from_le_bytes(arr)\n        })\n        .collect()\n}\n\npub fn spawn_analysis_thread(meter: Arc<StereoMeter>) {\n    let run = move || {\n        let tick_rate = 1. / TARGET_FPS as f32;\n        let samples_to_drain = (SAMPLE_RATE as f32 * tick_rate) as usize;\n\n        loop {\n            let meter = meter.clone();\n            meter.process();\n            meter.drain(samples_to_drain);\n\n            thread::sleep(Duration::from_secs_f32(tick_rate));\n        }\n    };\n\n    thread::Builder::new()\n        .name(\"audio-analysis\".to_string())\n        .spawn(run)\n        .unwrap();\n}\n"
  },
  {
    "path": "src/audio/mod.rs",
    "content": "mod analysis;\npub mod pulse;\nmod source;\nmod system;\n\nuse std::sync::Arc;\n\nuse parking_lot::Mutex;\nuse ringbuf::{HeapConsumer, HeapProducer};\npub use source::*;\npub use system::*;\n\npub type Sample = f32;\n\npub type AudioProducer = Arc<Mutex<HeapProducer<u8>>>;\npub type AudioConsumer = Arc<Mutex<HeapConsumer<u8>>>;\n\npub const SAMPLE_RATE: usize = 48000;\npub const SAMPLE_IN_BYTES: usize = 4;\n\npub const LATENCY_IN_SECONDS: f32 = 0.05;\npub const BUFFER_SIZE: usize =\n    (SAMPLE_IN_BYTES * 2) * (SAMPLE_RATE as f32 * LATENCY_IN_SECONDS) as usize;\n"
  },
  {
    "path": "src/audio/pulse.rs",
    "content": "// TODO: Remove this once the dead code is used\n#![allow(unused)]\n\nuse std::{\n    sync::{mpsc, Arc},\n    thread,\n    time::Duration,\n};\nuse thiserror::Error;\n\nuse crate::audio::SAMPLE_RATE;\nuse crossbeam::channel::{unbounded, Receiver, Sender};\nuse libpulse_binding::{\n    callbacks::ListResult,\n    context::{\n        introspect::Introspector,\n        subscribe::{Facility, InterestMaskSet, Operation},\n        Context, FlagSet as ContextFlagSet, State,\n    },\n    def::BufferAttr,\n    error::Code,\n    mainloop::standard::{IterateResult, Mainloop},\n    proplist::{properties, Proplist},\n    sample::{Format, Spec},\n    stream::{FlagSet as StreamFlagSet, PeekResult, State as StreamState, Stream},\n    volume::Volume,\n};\nuse parking_lot::{Mutex, RwLock};\n\nuse super::BUFFER_SIZE;\n\n/// Abstracts connections and interfacing with pulseaudio\npub struct PulseClient {\n    context: Arc<Mutex<Context>>,\n    introspector: Introspector,\n    props: Proplist,\n    spec: Spec,\n\n    pub(super) events: Receiver<PulseClientEvent>,\n    event_sender: Sender<PulseClientEvent>,\n}\n\nimpl PulseClient {\n    pub fn new() -> Result<Self, PulseClientError> {\n        let spec = Spec {\n            format: Format::F32le,\n            channels: 2,\n            rate: SAMPLE_RATE as u32,\n        };\n\n        let mut proplist = Proplist::new().ok_or(PulseClientError::Fatal(\n            \"Failed to create proplist\".to_string(),\n        ))?;\n\n        let props = proplist.clone();\n\n        proplist\n            .set_str(properties::APPLICATION_NAME, \"pulseshitter\")\n            .and_then(|_| {\n                proplist.set_str(properties::APPLICATION_VERSION, env!(\"CARGO_PKG_VERSION\"))\n            })\n            .map_err(|_| {\n                PulseClientError::Fatal(\"Failed to set proplist properties\".to_string())\n            })?;\n\n        let (context_sender, context_rec) = mpsc::channel();\n\n        thread::spawn(move || {\n            let (context, mut mainloop) = match Self::setup_mainloop(proplist) {\n                Ok(tuple) => tuple,\n                Err(e) => {\n                    context_sender.send(Err(e)).unwrap();\n                    return;\n                }\n            };\n\n            context_sender.send(Ok(context)).unwrap();\n            mainloop.run().unwrap();\n        });\n\n        let context = context_rec\n            .recv_timeout(Duration::from_millis(1000))\n            .map_err(|_| PulseClientError::Fatal(\"Did not receive context\".to_string()))??;\n\n        let introspector = context.introspect();\n        let (sender, receiver) = unbounded();\n\n        let client = Self {\n            event_sender: sender,\n            events: receiver,\n            context: Mutex::new(context).into(),\n            introspector,\n            props,\n            spec,\n        };\n\n        Ok(client)\n    }\n\n    fn setup_mainloop(proplist: Proplist) -> Result<(Context, Mainloop), PulseClientError> {\n        let mut mainloop = Mainloop::new().ok_or(PulseClientError::Fatal(\n            \"Failed to create mainloop\".to_string(),\n        ))?;\n\n        let mut context = Context::new_with_proplist(&mainloop, \"pulseshitter\", &proplist).ok_or(\n            PulseClientError::Fatal(\"Failed to create context\".to_string()),\n        )?;\n\n        context\n            .connect(None, ContextFlagSet::NOFLAGS, None)\n            .map_err(|_| PulseClientError::ConnectionFailed)?;\n\n        loop {\n            match mainloop.iterate(false) {\n                IterateResult::Quit(_) | IterateResult::Err(_) => {\n                    return Err(PulseClientError::Fatal(\n                        \"Failed mainloop iterate state\".to_string(),\n                    ));\n                }\n                IterateResult::Success(_) => {}\n            }\n            match context.get_state() {\n                State::Ready => {\n                    break;\n                }\n                State::Failed | State::Terminated => {\n                    return Err(PulseClientError::Fatal(\n                        \"Context state failed/terminated\".to_string(),\n                    ));\n                }\n                _ => {}\n            }\n        }\n\n        Ok((context, mainloop))\n    }\n\n    pub fn subscribe_to_events(&self) {\n        let mut context = self.context.lock();\n        let sender = self.event_sender.clone();\n\n        // Set up the callback that will handle events.\n        context.set_subscribe_callback(Some(Box::new(move |facility_opt, operation, index| {\n            if let Some(Facility::SinkInput) = facility_opt {\n                sender\n                    .send(PulseClientEvent::SinkInput {\n                        index,\n                        operation: operation.expect(\"SinkEvent always has an operation\"),\n                    })\n                    .expect(\"Send event\")\n            }\n        })));\n\n        // Subscribe to all relevant events.\n        context.subscribe(\n            InterestMaskSet::SINK_INPUT | InterestMaskSet::SOURCE,\n            |success| {\n                if !success {\n                    eprintln!(\"Failed to subscribe to sink and source events\");\n                }\n            },\n        );\n    }\n\n    pub fn sink_inputs(&self) -> Result<Vec<SinkInput>, PulseClientError> {\n        let (sender, receiver) = mpsc::channel();\n\n        self.introspector.get_sink_input_info_list({\n            move |list| match list {\n                ListResult::End => sender.send(ListResult::End).unwrap(),\n                ListResult::Error => sender.send(ListResult::Error).unwrap(),\n                ListResult::Item(item) => {\n                    let volume = item.volume.max().0 as f32 / Volume::NORMAL.0 as f32;\n\n                    let sink_input = SinkInput {\n                        index: item.index,\n                        props: item.proplist.clone(),\n                        sink: item.sink,\n                        name: item\n                            .name\n                            .clone()\n                            .map(|n| n.to_string())\n                            .unwrap_or(\"Unknown\".to_string()),\n                        volume,\n                    };\n\n                    sender.send(ListResult::Item(sink_input)).unwrap();\n                }\n            }\n        });\n\n        let mut result = vec![];\n\n        loop {\n            match receiver.recv().unwrap() {\n                ListResult::End => break,\n                ListResult::Item(x) => result.push(x),\n                ListResult::Error => return Err(PulseClientError::ListError),\n            }\n        }\n\n        Ok(result)\n    }\n\n    pub fn record(&self, sink_input: &SinkInput) -> Result<SinkInputStream, PulseClientError> {\n        let props = self.props.clone();\n\n        let stream = SinkInputStream::new(\n            self.context.clone(),\n            self.event_sender.clone(),\n            props,\n            &self.spec,\n        );\n        stream.connect_to_sink_input(sink_input)?;\n        stream.set_event_callbacks();\n\n        Ok(stream)\n    }\n}\n\nimpl Drop for PulseClient {\n    fn drop(&mut self) {\n        self.context.lock().disconnect();\n    }\n}\n\n#[derive(Error, Debug)]\npub enum PulseClientError {\n    #[error(\"cannot connect to a pulseaudio-compliant server\")]\n    ConnectionFailed,\n    #[error(\"list fetching failed\")]\n    ListError,\n    #[error(\"fatal pulseaudio error: {0}\")]\n    Fatal(String),\n}\n\npub enum PulseClientEvent {\n    SinkInput { index: u32, operation: Operation },\n    Audio(Vec<u8>),\n}\n\n#[derive(Debug, Clone)]\npub struct SinkInput {\n    pub(super) name: String,\n    pub(super) index: u32,\n    pub(super) sink: u32,\n    pub(super) volume: f32,\n    pub(super) props: Proplist,\n}\n\n/// Represents a stream of audio from a sink input\n#[derive(Clone)]\npub struct SinkInputStream {\n    context: Arc<Mutex<Context>>,\n    stream: Arc<Mutex<Stream>>,\n\n    status: Arc<RwLock<SinkInputStreamStatus>>,\n    event_sender: Sender<PulseClientEvent>,\n}\n\nimpl SinkInputStream {\n    fn new(\n        context: Arc<Mutex<Context>>,\n        event_sender: Sender<PulseClientEvent>,\n        mut props: Proplist,\n        spec: &Spec,\n    ) -> Self {\n        let stream = {\n            let mut context = context.lock();\n\n            let stream = Stream::new_with_proplist(\n                &mut context,\n                \"pulseshitter-stream\",\n                spec,\n                None,\n                &mut props,\n            )\n            .expect(\"Creates stream\");\n\n            Arc::new(Mutex::new(stream))\n        };\n\n        Self {\n            context,\n            stream,\n            event_sender,\n            status: Default::default(),\n        }\n    }\n\n    fn set_event_callbacks(&self) {\n        let context = self.context.clone();\n        let mut locked_stream = self.stream.lock();\n\n        locked_stream.set_state_callback(Some(Box::new({\n            let stream = self.stream.clone();\n            let status = self.status.clone();\n\n            move || {\n                let mut status = status.write();\n\n                match stream.lock().get_state() {\n                    StreamState::Ready => *status = SinkInputStreamStatus::Connected,\n                    StreamState::Unconnected | StreamState::Creating => {\n                        *status = SinkInputStreamStatus::Connecting\n                    }\n                    StreamState::Terminated => *status = SinkInputStreamStatus::Terminated,\n                    StreamState::Failed => {\n                        let err: Code = context.lock().errno().try_into().unwrap_or(Code::Unknown);\n\n                        match err {\n                            Code::Timeout => *status = SinkInputStreamStatus::TimedOut,\n                            x => {\n                                *status = SinkInputStreamStatus::Failed(\n                                    x.to_string().unwrap_or_else(|| \"Unknown\".to_string()),\n                                )\n                            }\n                        }\n                    }\n                }\n            }\n        })));\n\n        locked_stream.set_read_callback(Some(Box::new({\n            let stream = self.stream.clone();\n            let sender = self.event_sender.clone();\n\n            move |_| {\n                let mut stream = stream.lock();\n\n                match stream.peek() {\n                    Ok(result) => match result {\n                        PeekResult::Empty => {}\n                        PeekResult::Hole(_) => stream.discard().expect(\"Discards if hole\"),\n                        PeekResult::Data(data) => {\n                            sender\n                                .send(PulseClientEvent::Audio(data.to_vec()))\n                                .expect(\"Sends audio\");\n\n                            //producer.lock().push_slice(data);\n                            stream.discard().expect(\"Discards after data\");\n                        }\n                    },\n                    Err(_) => {\n                        unimplemented!()\n                    }\n                }\n            }\n        })));\n\n        locked_stream.set_suspended_callback(Some(Box::new({\n            let stream = self.stream.clone();\n            let status = self.status.clone();\n\n            move || {\n                let stream = stream.lock();\n                let mut status = status.write();\n\n                if stream.is_suspended().unwrap_or_default() {\n                    *status = SinkInputStreamStatus::Suspended\n                } else {\n                    *status = SinkInputStreamStatus::Connected\n                }\n            }\n        })));\n    }\n\n    fn connect_to_sink_input(&self, sink_input: &SinkInput) -> Result<(), PulseClientError> {\n        let mut stream = self.stream.lock();\n\n        stream\n            .set_monitor_stream(sink_input.index)\n            .expect(\"Sets monitor stream\");\n\n        *self.status.write() = SinkInputStreamStatus::Connecting;\n\n        stream\n            .connect_record(\n                Some(sink_input.sink.to_string().as_str()),\n                Some(&BufferAttr {\n                    maxlength: std::u32::MAX,\n                    tlength: 0,\n                    prebuf: 0,\n                    minreq: 0,\n                    fragsize: (BUFFER_SIZE / 2) as u32,\n                }),\n                StreamFlagSet::DONT_MOVE,\n            )\n            .expect(\"Connects stream for recording\");\n\n        Ok(())\n    }\n\n    pub fn status(&self) -> SinkInputStreamStatus {\n        self.status.read().clone()\n    }\n}\n\nimpl Drop for SinkInputStream {\n    fn drop(&mut self) {\n        let mut stream = self.stream.lock();\n\n        stream.set_suspended_callback(None);\n        stream.set_read_callback(None);\n        stream.set_event_callback(None);\n        stream.set_state_callback(None);\n\n        if let StreamState::Ready = stream.get_state() {\n            stream.disconnect().unwrap_or_else(|e| {\n                eprintln!(\"Failed to disconnect stream: {}\", e);\n            })\n        }\n    }\n}\n\n#[derive(Debug, Default, Clone)]\npub enum SinkInputStreamStatus {\n    #[default]\n    Idle,\n    TimedOut,\n    Connected,\n    Suspended,\n    Terminated,\n    Connecting,\n    Failed(String),\n}\n"
  },
  {
    "path": "src/audio/source.rs",
    "content": "// TODO: Remove this once the dead code is used\n#![allow(unused)]\n\nuse super::pulse::{PulseClient, SinkInput};\nuse crossbeam::atomic::AtomicCell;\nuse lazy_static::lazy_static;\nuse libpulse_binding::context::subscribe::Operation;\nuse parking_lot::{Mutex, RwLock};\nuse regex::Regex;\nuse std::{\n    fmt::Display,\n    sync::Arc,\n    time::{Duration, Instant},\n};\nuse strsim::jaro;\n\n/// Due to Discord having an agreement with Spotify, you cannot actually stream Spotify audio on Discord\n/// without it pausing your Spotify playback after a few seconds when it detects you may be doing this.\n///\n/// Because of this, pulseshitter is technically a workaround, as there is no way for Discord to detect that you may be streaming Spotify through it.\n/// In order to be on the safe side regarding TOS and legal matters, Spotify streaming is disabled by default.\n///\n/// If you don't care about this, you can compile pulseshitter with the environment variable below present to enable it anyway.\nconst ALLOW_SPOTIFY_STREAMING: Option<&'static str> = option_env!(\"ALLOW_SPOTIFY_STREAMING\");\nconst SPOTIFY_NAME: &str = \"Spotify\";\n\n// These are words commonly used in vague source names that is not useful to the user\nconst VAGUE_WORDS: [&str; 10] = [\n    \"play\", \"audio\", \"voice\", \"stream\", \"driver\", \"webrtc\", \"engine\", \"playback\", \"callback\",\n    \"alsa\",\n];\n\n/// Keeps track of active sources and diffing\npub struct SourceSelector {\n    client: Arc<PulseClient>,\n    current_source: Mutex<Option<Source>>,\n\n    /// The source the user selected.\n    /// Not to be confused with current source which is what is currently being streamed.\n    selected_source: Mutex<Option<Source>>,\n    stored_sources: Mutex<Vec<Source>>,\n}\n\nimpl SourceSelector {\n    pub fn new(client: Arc<PulseClient>) -> Self {\n        let sources: Vec<Source> = client\n            .sink_inputs()\n            .expect(\"Gets sink inputs\")\n            .into_iter()\n            .map(|f| f.into())\n            .collect();\n\n        Self {\n            client,\n            stored_sources: sources.into(),\n            current_source: Default::default(),\n            selected_source: Default::default(),\n        }\n    }\n\n    pub fn sources(&self) -> Vec<Source> {\n        self.stored_sources\n            .lock()\n            .clone()\n            .into_iter()\n            .filter(|s| {\n                ALLOW_SPOTIFY_STREAMING.is_some()\n                    || s.name().to_uppercase() != SPOTIFY_NAME.to_uppercase()\n            })\n            .collect()\n    }\n\n    pub fn current_source(&self) -> Option<Source> {\n        self.current_source.lock().clone().filter(|s| s.available())\n    }\n\n    pub fn selected_source(&self) -> Option<Source> {\n        self.selected_source.lock().clone()\n    }\n\n    pub(super) fn select(&self, source: Option<Source>) {\n        match source {\n            Some(x) => {\n                *self.current_source.lock() = Some(x.clone());\n                *self.selected_source.lock() = Some(x.clone());\n            }\n            None => {\n                *self.current_source.lock() = None;\n                *self.selected_source.lock() = None;\n            }\n        }\n    }\n\n    pub fn handle_sink_input_event(&self, index: u32, operation: Operation) {\n        let mut current_sources = self.stored_sources.lock();\n\n        let new_sources: Vec<Source> = self\n            .client\n            .sink_inputs()\n            .unwrap_or_default()\n            .into_iter()\n            .map(|f| f.into())\n            .collect();\n\n        let source = new_sources\n            .into_iter()\n            .find(|x| x.sink_input().index == index);\n\n        let existing_source = current_sources\n            .iter()\n            .find(|x| x.sink_input().index == index);\n\n        match operation {\n            Operation::New => {\n                let selected_source = self.selected_source();\n\n                if let Some(new_source) = source {\n                    let new_as_selected = selected_source\n                        .filter(|s| !s.available() && s.compare(&new_source).is_similar_enough());\n\n                    if let Some(selected) = new_as_selected {\n                        selected.update(new_source);\n                    } else {\n                        current_sources.push(new_source);\n                    }\n                }\n            }\n            Operation::Changed => {\n                source.and_then(|s| existing_source.map(|e| e.update(s)));\n            }\n            Operation::Removed => {\n                if let Some(e) = existing_source {\n                    e.remove()\n                }\n            }\n        }\n\n        current_sources.retain(|s| !s.is_dead());\n    }\n}\n\n/// A sink input simplified for ease of use\n#[derive(Debug, Clone)]\npub struct Source {\n    kind: SourceKind,\n    sink_input: Arc<Mutex<SinkInput>>,\n\n    /// The best fitting name for this source\n    name: Arc<RwLock<String>>,\n\n    /// The binary that spawned the associated sink input\n    application: String,\n\n    /// This will be false when listing applications from pulsectl does not include this source\n    available: Arc<AtomicCell<bool>>,\n    age: Arc<AtomicCell<Instant>>,\n\n    /// Volume of the sink input, used for normalization\n    volume: Arc<AtomicCell<f32>>,\n}\n\n#[derive(Debug)]\nenum SourceComparison {\n    Exact,\n    Partial(f64),\n    None,\n}\n\nimpl Source {\n    /// How long should a source persist for after it is unavailable\n    const MAX_LIFESPAN: Duration = Duration::from_secs(60);\n\n    fn update(&self, incoming: Source) {\n        self.age.store(Instant::now());\n\n        self.name.write().clone_from(&incoming.name.read());\n        *self.sink_input.lock() = incoming.sink_input.lock().clone();\n\n        self.volume.store(incoming.volume.load());\n        self.available.store(true);\n    }\n\n    /// Checks to see how similar this source is to an old one\n    fn compare(&self, rhs: &Source) -> SourceComparison {\n        // It is unlikely that there will ever be conflicts, so if the indices match, this is most likely the same source.\n        let is_same_index = self.index() == rhs.index();\n        let is_same_name = *self.name.read() == *rhs.name.read();\n\n        if is_same_index || is_same_name {\n            return SourceComparison::Exact;\n        }\n\n        if self.application != rhs.application {\n            return SourceComparison::None;\n        }\n\n        let score = jaro(&self.name.read(), &rhs.name.read());\n        SourceComparison::Partial(score)\n    }\n\n    fn remove(&self) {\n        self.available.store(false);\n    }\n\n    fn is_dead(&self) -> bool {\n        !self.available() && self.age.load().elapsed() >= Self::MAX_LIFESPAN\n    }\n\n    pub fn sink_input(&self) -> SinkInput {\n        self.sink_input.lock().clone()\n    }\n\n    pub fn index(&self) -> u32 {\n        self.sink_input.lock().index\n    }\n\n    pub fn available(&self) -> bool {\n        self.available.load()\n    }\n\n    pub fn volume(&self) -> f32 {\n        self.volume.load()\n    }\n\n    pub fn name(&self) -> String {\n        self.name.read().clone()\n    }\n}\n\nimpl SourceComparison {\n    fn is_similar_enough(&self) -> bool {\n        match self {\n            SourceComparison::Partial(score) => *score > 0.3,\n            SourceComparison::Exact => true,\n            SourceComparison::None => false,\n        }\n    }\n}\n\n/// When apps like browsers have multiple tabs, there is no way to differentiate the source from each one without covering these edge cases.\n/// That is the purpose of this enum.\n#[derive(Debug, Clone, Copy, PartialEq)]\npub enum SourceKind {\n    Standalone,\n    BrowserTab(BrowserKind),\n}\n\nimpl SourceKind {\n    fn parse<T: AsRef<str>>(candidates: &[T]) -> Self {\n        candidates\n            .iter()\n            .map(AsRef::as_ref)\n            .map(BrowserKind::parse)\n            .find_map(|k| k.map(Into::into))\n            .unwrap_or(Self::Standalone)\n    }\n\n    fn determine_name<T: AsRef<str>>(&self, candidates: &[T]) -> String {\n        match self {\n            SourceKind::BrowserTab(b) => b.determine_tab_name(candidates),\n            SourceKind::Standalone => candidates\n                .iter()\n                .map(AsRef::as_ref)\n                .map(ToOwned::to_owned)\n                .next()\n                .unwrap_or_else(|| \"Unidentifiable audio source\".to_string()),\n        }\n    }\n}\n\n/// Currently supported Browser edgecases\n#[derive(Debug, Clone, Copy, PartialEq)]\npub enum BrowserKind {\n    Firefox,\n    Chrome,\n}\n\nimpl BrowserKind {\n    const FIREFOX: &'static str = \"Firefox\";\n    const CHROME: &'static str = \"Chrome\";\n\n    fn parse<T: AsRef<str>>(name: T) -> Option<Self> {\n        match name.as_ref().to_uppercase() {\n            x if x == Self::FIREFOX.to_uppercase() => Self::Firefox.into(),\n            x if x == Self::CHROME.to_uppercase() => Self::Chrome.into(),\n            _ => None,\n        }\n    }\n\n    fn determine_tab_name<T: AsRef<str>>(&self, candidates: &[T]) -> String {\n        let browser_name = self.to_string();\n\n        candidates\n            .iter()\n            .map(AsRef::as_ref)\n            .map(ToOwned::to_owned)\n            .find(|c| c.to_uppercase() != browser_name.to_uppercase())\n            .unwrap_or_else(|| format!(\"Unidentifiable {} Tab\", browser_name))\n    }\n}\n\nimpl Display for BrowserKind {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        let name = match self {\n            Self::Firefox => Self::FIREFOX,\n            Self::Chrome => Self::CHROME,\n        };\n\n        write!(f, \"{}\", name)\n    }\n}\n\nimpl From<BrowserKind> for SourceKind {\n    fn from(value: BrowserKind) -> Self {\n        Self::BrowserTab(value)\n    }\n}\n\nimpl From<SinkInput> for Source {\n    fn from(raw: SinkInput) -> Self {\n        let mut name_candidates: Vec<_> = [\n            Some(raw.name.clone()),\n            raw.props.get_str(\"application.process.binary\"),\n            raw.props.get_str(\"application.name\"),\n            raw.props.get_str(\"media.name\"),\n            raw.props.get_str(\"node.name\"),\n        ]\n        .into_iter()\n        .flatten()\n        .filter_map(|s| {\n            let score = calculate_name_quality(&s);\n\n            if score > 1 {\n                Some((s, score))\n            } else {\n                None\n            }\n        })\n        .collect();\n\n        name_candidates.sort_by(|(_, a), (_, b)| b.cmp(a));\n        let name_candidates: Vec<_> = name_candidates.into_iter().map(|(s, _)| s).collect();\n\n        let kind = SourceKind::parse(&name_candidates);\n        let name = kind.determine_name(&name_candidates);\n\n        let application = raw\n            .props\n            .get_str(\"application.process.binary\")\n            .or_else(|| raw.props.get_str(\"application.name\"))\n            .unwrap_or_else(|| \"Unknown app\".to_string());\n\n        let volume = AtomicCell::new(raw.volume);\n\n        Self {\n            kind,\n            application,\n            volume: volume.into(),\n            name: RwLock::new(name).into(),\n            sink_input: Mutex::new(raw).into(),\n            available: AtomicCell::new(true).into(),\n            age: AtomicCell::new(Instant::now()).into(),\n        }\n    }\n}\n\nlazy_static! {\n    static ref WORD_SPLIT_REGEX: Regex =\n        Regex::new(r\"([^.,\\-_\\sA-Z]+)|([^.,\\-_\\sa-z][^.\\sA-Z]+)\").unwrap();\n}\n\nfn str_is_doublecase(str: &str) -> bool {\n    str.chars().filter(|c| c.is_lowercase()).count() < str.len()\n}\n\nfn calculate_name_quality(str: &str) -> i32 {\n    let mut score = 0;\n\n    score += str_is_doublecase(str) as i32;\n\n    let words: Vec<_> = WORD_SPLIT_REGEX\n        .find_iter(str)\n        .map(|m| m.as_str())\n        .collect();\n\n    score += words.into_iter().fold(0, |acc, w| {\n        let is_vague = VAGUE_WORDS\n            .iter()\n            .any(|word| w.to_uppercase() == word.to_uppercase());\n\n        if is_vague {\n            acc - 1\n        } else {\n            acc + 1\n        }\n    });\n\n    score\n}\n"
  },
  {
    "path": "src/audio/system.rs",
    "content": "use std::{\n    io::{Read, Seek},\n    sync::Arc,\n    thread,\n};\n\nuse parking_lot::Mutex;\nuse ringbuf::HeapRb;\nuse songbird::input::{reader::MediaSource, Codec, Container, Input, Reader};\n\nuse super::{\n    analysis::{raw_samples_from_bytes, spawn_analysis_thread, StereoMeter},\n    pulse::{PulseClient, PulseClientError, PulseClientEvent, SinkInputStream},\n    source::{Source, SourceSelector},\n    AudioConsumer, AudioProducer, BUFFER_SIZE, SAMPLE_IN_BYTES,\n};\n\n/// Manages all audio related stuff\npub struct AudioSystem {\n    client: Arc<PulseClient>,\n\n    selector: Arc<SourceSelector>,\n    stream: Arc<Mutex<Option<SinkInputStream>>>,\n\n    producer: AudioProducer,\n    consumer: AudioConsumer,\n\n    meter: Arc<StereoMeter>,\n}\n\nimpl AudioSystem {\n    pub fn new() -> Result<Arc<Self>, PulseClientError> {\n        let client = Arc::new(PulseClient::new()?);\n        client.subscribe_to_events();\n\n        let selector = Arc::new(SourceSelector::new(client.clone()));\n\n        let (audio_producer, audio_consumer) = HeapRb::new(BUFFER_SIZE).split();\n\n        let audio = Arc::new(Self {\n            client,\n            selector,\n            stream: Default::default(),\n            meter: StereoMeter::new().into(),\n            producer: Mutex::new(audio_producer).into(),\n            consumer: Mutex::new(audio_consumer).into(),\n        });\n\n        spawn_analysis_thread(audio.meter.clone());\n        spawn_event_thread(audio.clone());\n        Ok(audio)\n    }\n\n    pub fn select(&self, source: Option<Source>) {\n        self.selector.select(source);\n        self.refresh_stream();\n    }\n\n    pub fn stream(&self) -> AudioStream {\n        AudioStream(self.consumer.clone())\n    }\n\n    pub fn sources(&self) -> Vec<Source> {\n        self.selector.sources()\n    }\n\n    pub fn current_source(&self) -> Option<Source> {\n        self.selector.current_source()\n    }\n\n    pub fn selected_source(&self) -> Option<Source> {\n        self.selector.selected_source()\n    }\n\n    pub fn meter_value_ranged(&self) -> (f32, f32) {\n        self.meter.value_ranged()\n    }\n\n    fn refresh_stream(&self) {\n        let current_source = self.selector.current_source();\n\n        if let Some(source) = current_source {\n            let stream = self\n                .client\n                .record(&source.sink_input())\n                .expect(\"Creates recording stream\");\n\n            *self.stream.lock() = Some(stream);\n        } else {\n            *self.stream.lock() = None;\n        }\n    }\n}\n\nfn spawn_event_thread(audio: Arc<AudioSystem>) {\n    let run = move || {\n        let events = audio.client.events.clone();\n        let mut producer = audio.producer.lock();\n\n        loop {\n            match events.recv().unwrap() {\n                PulseClientEvent::SinkInput { index, operation } => {\n                    let old_id = audio\n                        .selector\n                        .current_source()\n                        .map(|s| s.index())\n                        .unwrap_or_default();\n\n                    audio.selector.handle_sink_input_event(index, operation);\n\n                    let new_id = audio\n                        .selector\n                        .current_source()\n                        .map(|s| s.index())\n                        .unwrap_or_default();\n\n                    if new_id != old_id {\n                        audio.refresh_stream();\n                    }\n                }\n                PulseClientEvent::Audio(data) => {\n                    let current_source_volume = audio\n                        .selector\n                        .current_source()\n                        .map(|s| s.volume())\n                        .unwrap_or(1.);\n\n                    let normalized_bytes = normalize_volume(&data, current_source_volume);\n\n                    producer.push_slice(&normalized_bytes);\n                    audio.meter.write(&normalized_bytes);\n                }\n            };\n        }\n    };\n\n    thread::Builder::new()\n        .name(\"audio-events\".to_string())\n        .spawn(run)\n        .unwrap();\n}\n\n#[derive(Clone)]\npub struct AudioStream(AudioConsumer);\n\nimpl AudioStream {\n    pub fn into_input(self) -> Input {\n        // Clear the stream to minimize latency\n        self.0.lock().clear();\n\n        Input::new(\n            true,\n            Reader::Extension(Box::new(self)),\n            Codec::FloatPcm,\n            Container::Raw,\n            None,\n        )\n    }\n}\n\nimpl Read for AudioStream {\n    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {\n        let mut consumer = self.0.lock();\n\n        let stereo = SAMPLE_IN_BYTES * 2;\n        let safe_length = buf.len() / stereo * stereo;\n\n        consumer\n            .read_exact(&mut buf[..safe_length])\n            .unwrap_or_default();\n\n        Ok(safe_length)\n    }\n}\n\nimpl Seek for AudioStream {\n    fn seek(&mut self, _: std::io::SeekFrom) -> std::io::Result<u64> {\n        unreachable!()\n    }\n}\n\nimpl MediaSource for AudioStream {\n    fn byte_len(&self) -> Option<u64> {\n        None\n    }\n\n    fn is_seekable(&self) -> bool {\n        false\n    }\n}\n\nfn normalize_volume(bytes: &[u8], incoming_volume: f32) -> Vec<u8> {\n    let reciprocal = 1. / incoming_volume;\n    let db_loudness = 10. * reciprocal.log(3.);\n    let signal_factor = 10f32.powf(db_loudness / 20.);\n\n    raw_samples_from_bytes(bytes)\n        .into_iter()\n        .map(|s| s * signal_factor)\n        .flat_map(|s| s.to_le_bytes())\n        .collect()\n}\n"
  },
  {
    "path": "src/dickcord/bot.rs",
    "content": "use super::TargetUser;\nuse crate::{audio::AudioStream, state::Config};\nuse crossbeam::channel::{unbounded, Receiver, Sender};\nuse serenity::{\n    async_trait,\n    client::{bridge::gateway::ShardManager, Context as SerenityContext, EventHandler},\n    futures::future::{join_all, try_join_all},\n    model::{\n        channel::{ChannelType, GuildChannel},\n        event::ResumedEvent,\n        gateway::{Activity, GatewayIntents, Ready},\n        guild::Member,\n        id::UserId,\n        user::CurrentUser,\n        voice::VoiceState,\n    },\n    Client,\n};\nuse songbird::{error::JoinError, Call, SerenityInit};\nuse std::sync::Arc;\nuse tokio::{runtime::Runtime, sync::Mutex};\n\ntype ConnectedToChannel = Arc<Mutex<Option<GuildChannel>>>;\n\n/// The bot handling logic\npub struct Bot {\n    event_sender: Sender<BotEvent>,\n    event_receiver: Receiver<BotEvent>,\n\n    /// The user the bot should follow\n    target_user: TargetUser,\n\n    shard_manager: Arc<Mutex<ShardManager>>,\n    context: Arc<Mutex<Option<SerenityContext>>>,\n\n    connected_to_channel: ConnectedToChannel,\n}\n\n/// The event handler for the Serenity client\npub struct BotHandler {\n    event_sender: Sender<BotEvent>,\n    context: Arc<Mutex<Option<SerenityContext>>>,\n\n    target_user: TargetUser,\n    connected_to_channel: ConnectedToChannel,\n}\n\n#[derive(Clone)]\npub enum BotEvent {\n    /// Bot has connected to Discord\n    Connected(CurrentUser),\n    /// Disconnected from Discord, either by an error or intentionally\n    Reconnected,\n    /// Joining a voice channel\n    Joining(GuildChannel),\n    /// Successfully joined a voice channel\n    Joined(GuildChannel),\n    /// Disconnected from voice channel\n    Left,\n    /// The user the bot is following connected or disconnected from a channel\n    TargetUserMoved(Option<GuildChannel>),\n    // The user the bot is following started or stopped a live stream\n    TargetUserStreamStateChanged(bool),\n    /// Something bad happened, duh.\n    ClientError(String),\n    /// An error occurred with the voice connection\n    VoiceError(String),\n}\n\nimpl Bot {\n    pub fn new(rt: Arc<Runtime>, config: &Config) -> Self {\n        let (event_sender, event_receiver) = unbounded();\n\n        let connected_to_channel = ConnectedToChannel::default();\n        let target_user = config.user_id;\n        let context = Arc::new(Mutex::new(None));\n\n        let event_handler = BotHandler {\n            context: context.clone(),\n            event_sender: event_sender.clone(),\n            connected_to_channel: connected_to_channel.clone(),\n            target_user,\n        };\n\n        let mut client = rt.block_on(async move {\n            Client::builder(&config.bot_token, intents())\n                .register_songbird()\n                .event_handler(event_handler)\n                .await\n                .expect(\"client is created\")\n        });\n\n        let shard_manager = client.shard_manager.clone();\n        let inner_event_sender = event_sender.clone();\n\n        rt.spawn(async move {\n            if let Err(e) = client.start().await {\n                inner_event_sender\n                    .send(BotEvent::ClientError(e.to_string()))\n                    .unwrap();\n            }\n        });\n\n        Self {\n            context,\n            target_user,\n            event_sender,\n            shard_manager,\n            event_receiver,\n            connected_to_channel,\n        }\n    }\n\n    pub async fn set_streaming_status(&self, name: Option<String>) {\n        let context = self.context().await;\n\n        if let Some(name) = name {\n            context\n                .set_activity(Activity::streaming(\n                    name,\n                    \"https://github.com/Enitoni/pulseshitter\",\n                ))\n                .await;\n        } else {\n            context.reset_presence().await\n        }\n    }\n\n    pub async fn attempt_join_and_stream(&self, audio: AudioStream) {\n        let channel = self.locate_target_user_channel().await;\n\n        let call = match channel {\n            Some(c) => self.connect_to_channel(&c).await,\n            None => None,\n        };\n\n        if let Some(call) = call {\n            self.stream_call_audio(call, audio).await;\n        }\n    }\n\n    pub fn poll(&self) -> BotEvent {\n        self.event_receiver.recv().unwrap()\n    }\n\n    pub async fn connect_to_channel(&self, channel: &GuildChannel) -> Option<Arc<Mutex<Call>>> {\n        let context = self.context().await;\n        let manager = songbird::get(&context)\n            .await\n            .expect(\"get songbird instance\");\n\n        self.event_sender\n            .send(BotEvent::Joining(channel.clone()))\n            .unwrap();\n\n        let (handler, result) = manager.join(channel.guild_id, channel.id).await;\n\n        match result {\n            Err(x) => {\n                self.event_sender\n                    .send(BotEvent::VoiceError(x.to_string()))\n                    .unwrap();\n\n                None\n            }\n            Ok(_) => {\n                let _ = self\n                    .connected_to_channel\n                    .lock()\n                    .await\n                    .insert(channel.clone());\n\n                self.event_sender\n                    .send(BotEvent::Joined(channel.clone()))\n                    .unwrap();\n\n                Some(handler)\n            }\n        }\n    }\n\n    pub async fn disconnect_from_channel(&self) -> Result<(), JoinError> {\n        let context = self.context().await;\n        let manager = songbird::get(&context).await.unwrap();\n\n        if let Some(channel) = self.connected_to_channel.lock().await.take() {\n            return manager.remove(channel.guild_id).await;\n        }\n\n        self.event_sender.send(BotEvent::Left).unwrap();\n\n        Ok(())\n    }\n\n    pub async fn stream_call_audio(&self, call: Arc<Mutex<Call>>, audio: AudioStream) {\n        call.lock().await.play_only_source(audio.into_input());\n    }\n\n    /// Finds the channel the target user is in, if any\n    pub async fn locate_target_user_channel(&self) -> Option<GuildChannel> {\n        let context = self.context().await;\n        let members_in_channels = self.all_members_in_channels(&context).await;\n\n        members_in_channels\n            .into_iter()\n            .find_map(|(members, guild_channel)| {\n                members\n                    .into_iter()\n                    .find(|m| m.user.id == self.target_user)\n                    .map(|_| guild_channel)\n            })\n    }\n\n    pub async fn is_target_user_streaming(&self) -> bool {\n        let context = self.context().await;\n        let channel = self.locate_target_user_channel().await;\n\n        let voice_states = channel\n            .map(|c| c.guild_id)\n            .and_then(|id| context.cache.guild(id))\n            .map(|guild| guild.voice_states);\n\n        if let Some(voice_states) = voice_states {\n            let user_id = UserId(self.target_user);\n\n            return voice_states\n                .get(&user_id)\n                .and_then(|v| v.self_stream)\n                .unwrap_or_default();\n        }\n\n        false\n    }\n\n    async fn all_members_in_channels(\n        &self,\n        context: &SerenityContext,\n    ) -> Vec<(Vec<Member>, GuildChannel)> {\n        let channels = self.all_channels(context).await;\n\n        let member_futures = channels\n            .into_iter()\n            .map(|c| async { (c.members(context).await, c) });\n\n        join_all(member_futures)\n            .await\n            .into_iter()\n            .flat_map(|(member, guild)| member.map(|m| (m, guild)))\n            .collect()\n    }\n\n    async fn all_channels(&self, context: &SerenityContext) -> Vec<GuildChannel> {\n        let guilds = context.cache.guilds();\n        let channel_futures = guilds.into_iter().map(|g| g.channels(context));\n\n        try_join_all(channel_futures)\n            .await\n            .unwrap_or_default()\n            .into_iter()\n            .flat_map(|h| h.into_values())\n            .filter(|c| matches!(c.kind, ChannelType::Voice))\n            .collect()\n    }\n\n    async fn context(&self) -> SerenityContext {\n        self.context\n            .lock()\n            .await\n            .clone()\n            .expect(\"context() is not called before initialization\")\n    }\n\n    pub async fn stop(&self) {\n        let mut manager = self.shard_manager.lock().await;\n        let context = self.context.lock().await.clone();\n\n        if let Some(context) = context {\n            let _ = self.disconnect_from_channel().await;\n            context.invisible().await\n        }\n\n        manager.shutdown_all().await\n    }\n}\n\n#[async_trait]\nimpl EventHandler for BotHandler {\n    async fn ready(&self, context: SerenityContext, ready: Ready) {\n        *self.context.lock().await = Some(context.clone());\n\n        self.event_sender\n            .send(BotEvent::Connected(ready.user.clone()))\n            .unwrap();\n    }\n\n    async fn resume(&self, _context: SerenityContext, _resumed: ResumedEvent) {\n        self.event_sender.send(BotEvent::Reconnected).unwrap()\n    }\n\n    async fn voice_state_update(\n        &self,\n        context: SerenityContext,\n        old: Option<VoiceState>,\n        new: VoiceState,\n    ) {\n        if new.user_id != self.target_user {\n            return;\n        }\n\n        let has_changed = old\n            .as_ref()\n            .map(|o| o.channel_id != new.channel_id)\n            .unwrap_or_default();\n\n        let old_stream_state = old.and_then(|o| o.self_stream).unwrap_or_default();\n        let new_stream_state = new.self_stream.unwrap_or_default();\n\n        if old_stream_state != new_stream_state {\n            self.event_sender\n                .send(BotEvent::TargetUserStreamStateChanged(new_stream_state))\n                .unwrap();\n        }\n\n        if !has_changed {\n            return;\n        }\n\n        let connected_to_channel = self.connected_to_channel.lock().await;\n\n        let new_channel = new\n            .channel_id\n            .filter(|x| Some(*x) != connected_to_channel.as_ref().map(|x| x.id));\n\n        if let Some(channel_id) = new_channel {\n            let channel = context.cache.guild_channel(channel_id);\n\n            self.event_sender\n                .send(BotEvent::TargetUserMoved(channel))\n                .unwrap();\n        } else {\n            self.event_sender\n                .send(BotEvent::TargetUserMoved(None))\n                .unwrap();\n        }\n    }\n}\n\nfn intents() -> GatewayIntents {\n    GatewayIntents::GUILDS\n        | GatewayIntents::GUILD_MEMBERS\n        | GatewayIntents::DIRECT_MESSAGES\n        | GatewayIntents::GUILD_VOICE_STATES\n}\n"
  },
  {
    "path": "src/dickcord/mod.rs",
    "content": "mod bot;\nmod system;\n\npub use bot::*;\npub use system::*;\n\ntype TargetUser = u64;\n"
  },
  {
    "path": "src/dickcord/system.rs",
    "content": "use crate::{\n    app::AppEvent,\n    audio::{AudioStream, Source},\n    state::{Config, ReadOnlyConfig},\n};\n\nuse super::{Bot, BotEvent};\nuse crossbeam::{atomic::AtomicCell, channel::Sender};\nuse parking_lot::Mutex;\nuse serenity::model::{channel::GuildChannel, user::CurrentUser};\nuse std::{sync::Arc, thread, time::Duration};\nuse tokio::runtime::Runtime;\n\n/// Manages all discord related things\npub struct DiscordSystem {\n    rt: Arc<Runtime>,\n    app_events: Sender<AppEvent>,\n\n    bot: Mutex<Option<Arc<Bot>>>,\n    state: Mutex<State>,\n    is_streaming: AtomicCell<bool>,\n\n    config: Mutex<Option<ReadOnlyConfig>>,\n    stream: AudioStream,\n}\n\n#[allow(clippy::large_enum_variant)]\n#[derive(Debug, Default, Clone)]\npub enum State {\n    #[default]\n    Idle,\n    Connecting,\n    Connected(CurrentUser, VoiceState),\n    Error(String),\n}\n\n#[derive(Debug, Default, Clone)]\npub enum VoiceState {\n    #[default]\n    Idle,\n    Joining(GuildChannel),\n    Active(GuildChannel),\n    Error(String),\n}\n\nimpl DiscordSystem {\n    pub fn new(rt: Arc<Runtime>, app_events: Sender<AppEvent>, stream: AudioStream) -> Arc<Self> {\n        let system = Arc::new(Self {\n            rt,\n            stream,\n            bot: Default::default(),\n            state: Default::default(),\n            is_streaming: Default::default(),\n            config: Default::default(),\n            app_events,\n        });\n\n        spawn_discord_event_thread(system.clone());\n        system\n    }\n\n    pub fn connect(&self, config: &Config) {\n        let bot = Bot::new(self.rt.clone(), config).into();\n\n        *self.bot.lock() = Some(bot);\n        *self.config.lock() = Some(config.read_only());\n\n        self.set_state(State::Connecting);\n    }\n\n    pub fn disconnect(&self) {\n        let bot = self.bot.lock().take();\n\n        if let Some(bot) = bot {\n            self.rt.block_on(async move { bot.stop().await });\n        }\n\n        self.set_state(State::Idle);\n    }\n\n    pub fn announce_source_streaming(&self, source: Option<Source>) {\n        let bot = self.bot_unwrapped();\n        let name = source.map(|s| s.name());\n\n        self.rt\n            .spawn(async move { bot.set_streaming_status(name).await });\n    }\n\n    pub fn state(&self) -> State {\n        self.state.lock().clone()\n    }\n\n    fn stream_on_demand(&self) {\n        let audio = self.stream.clone();\n        let config = self.config_unwrapped();\n        let state = self.state.lock().clone();\n        let bot = self.bot_unwrapped();\n\n        if config.screen_share_only {\n            let is_streaming = self.is_streaming.load();\n\n            if state.is_connected() && !is_streaming {\n                self.set_voice_state(VoiceState::Idle);\n                self.rt\n                    .spawn(async move { bot.disconnect_from_channel().await.ok() });\n\n                return;\n            }\n\n            if !is_streaming {\n                return;\n            }\n        }\n\n        self.rt\n            .spawn(async move { bot.attempt_join_and_stream(audio).await });\n    }\n\n    fn set_state(&self, new_state: State) {\n        *self.state.lock() = new_state.clone();\n\n        self.app_events\n            .send(AppEvent::DiscordStateUpdate(new_state))\n            .unwrap();\n    }\n\n    fn set_voice_state(&self, new_voice_state: VoiceState) {\n        self.state.lock().set_voice_state(new_voice_state)\n    }\n\n    fn handle_event(&self, event: BotEvent) {\n        match event {\n            BotEvent::Connected(user) => self.handle_connected(user),\n            BotEvent::Joined(channel) => self.handle_joined(channel),\n            BotEvent::Joining(channel) => self.handle_joining(channel),\n            BotEvent::Left => self.handle_left(),\n            BotEvent::ClientError(error) => self.handle_client_error(error),\n            BotEvent::VoiceError(error) => self.handle_voice_error(error),\n            BotEvent::TargetUserMoved(new_channel) => self.handle_target_user_moved(new_channel),\n            BotEvent::TargetUserStreamStateChanged(new_state) => {\n                self.handle_target_user_stream_state_changed(new_state)\n            }\n            BotEvent::Reconnected => {}\n        }\n    }\n\n    fn handle_connected(&self, user: CurrentUser) {\n        self.set_state(State::Connected(user, VoiceState::Idle));\n\n        let bot = self.bot_unwrapped();\n        let is_streaming = self\n            .rt\n            .block_on(async move { bot.is_target_user_streaming().await });\n\n        self.is_streaming.store(is_streaming);\n        self.stream_on_demand();\n    }\n\n    fn handle_client_error(&self, error: String) {\n        self.set_state(State::Error(error))\n    }\n\n    fn handle_joining(&self, channel: GuildChannel) {\n        self.set_voice_state(VoiceState::Joining(channel))\n    }\n\n    fn handle_joined(&self, channel: GuildChannel) {\n        self.set_voice_state(VoiceState::Active(channel))\n    }\n\n    fn handle_left(&self) {\n        self.set_voice_state(VoiceState::Idle)\n    }\n\n    fn handle_voice_error(&self, error: String) {\n        self.set_voice_state(VoiceState::Error(error))\n    }\n\n    fn handle_target_user_moved(&self, new_channel: Option<GuildChannel>) {\n        if let Some(new_channel) = new_channel {\n            self.set_voice_state(VoiceState::Active(new_channel));\n            self.stream_on_demand();\n        } else {\n            self.set_voice_state(VoiceState::Idle);\n            let bot = self.bot_unwrapped();\n            self.rt.spawn(async move {\n                bot.disconnect_from_channel().await.ok();\n            });\n        }\n    }\n\n    fn handle_target_user_stream_state_changed(&self, new_state: bool) {\n        self.is_streaming.store(new_state);\n        self.stream_on_demand();\n    }\n\n    fn bot_unwrapped(&self) -> Arc<Bot> {\n        self.bot\n            .lock()\n            .clone()\n            .expect(\"bot_unwrapped() is not called when there is not a bot\")\n    }\n\n    pub fn set_config(&self, config: ReadOnlyConfig) {\n        *self.config.lock() = Some(config);\n        self.stream_on_demand();\n    }\n\n    fn config_unwrapped(&self) -> ReadOnlyConfig {\n        self.config\n            .lock()\n            .clone()\n            .expect(\"config_unwrapped() is not called when there is not a config\")\n    }\n}\n\nimpl State {\n    fn set_voice_state(&mut self, new_state: VoiceState) {\n        match self {\n            Self::Connected(user, _) => *self = Self::Connected(user.clone(), new_state),\n            _ => {\n                eprintln!(\"set_voice_state() was called when not connected.\")\n            }\n        }\n    }\n\n    fn is_connected(&self) -> bool {\n        matches!(self, Self::Connected(_, _))\n    }\n}\n\nfn spawn_discord_event_thread(discord: Arc<DiscordSystem>) {\n    let run = move || loop {\n        let bot = discord.bot.lock().clone();\n        let event = bot.map(|b| b.poll());\n\n        if let Some(event) = event {\n            discord.handle_event(event)\n        } else {\n            thread::sleep(Duration::from_millis(1))\n        }\n    };\n\n    thread::Builder::new()\n        .name(\"discord-events\".to_string())\n        .spawn(run)\n        .unwrap();\n}\n"
  },
  {
    "path": "src/interface/components/mod.rs",
    "content": "mod text_field;\npub use text_field::*;\n"
  },
  {
    "path": "src/interface/components/text_field.rs",
    "content": "use crossterm::event::Event;\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Modifier, Style},\n    widgets::{Paragraph, Widget},\n};\nuse tui_textarea::TextArea;\n\nuse crate::interface::View;\n\npub struct TextField {\n    label: String,\n    area: TextArea<'static>,\n}\n\nimpl TextField {\n    pub fn new(label: &str) -> Self {\n        let label = label.to_string();\n        let area = TextArea::new(vec![\"\".to_string()]);\n\n        let mut result = Self { label, area };\n        result.blur();\n\n        result\n    }\n\n    pub fn focus(&mut self) {\n        self.area\n            .set_cursor_style(Style::default().add_modifier(Modifier::REVERSED));\n\n        self.area\n            .set_cursor_line_style(Style::default().add_modifier(Modifier::UNDERLINED));\n    }\n\n    pub fn blur(&mut self) {\n        self.area.set_cursor_style(Style::reset());\n        self.area.set_cursor_line_style(Style::reset());\n    }\n\n    pub fn value(&self) -> String {\n        self.area.lines()[0].to_string()\n    }\n}\n\nimpl View for TextField {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let text =\n            Paragraph::new(self.label.clone()).style(Style::default().add_modifier(Modifier::BOLD));\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([Constraint::Length(1), Constraint::Length(1)])\n            .split(area);\n\n        text.render(chunks[0], buf);\n        self.area.widget().render(chunks[1], buf);\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        if let Event::Key(key) = event {\n            self.area.input(key);\n        }\n    }\n}\n"
  },
  {
    "path": "src/interface/dashboard/discord_module.rs",
    "content": "use tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n    widgets::{Block, Borders, Paragraph, Widget, Wrap},\n};\n\nuse crate::{\n    app::AppContext,\n    dickcord::{State, VoiceState},\n    interface::View,\n};\n\npub struct DiscordModule {\n    context: AppContext,\n}\n\nimpl DiscordModule {\n    pub fn new(context: AppContext) -> Self {\n        Self { context }\n    }\n}\n\nimpl View for DiscordModule {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let block = Block::default()\n            .border_style(Style::default().fg(Color::DarkGray))\n            .title(\"─ Discord \")\n            .borders(Borders::all());\n\n        let block_inner = {\n            let area = block.inner(area);\n            tui::layout::Rect::new(\n                area.left() + 2,\n                area.top() + 1,\n                area.width - 2,\n                area.height - 1,\n            )\n        };\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([Constraint::Length(1), Constraint::Length(1)])\n            .split(block_inner);\n\n        block.render(area, buf);\n\n        let state = self.context.discord_state();\n\n        if let State::Error(err) = &state {\n            let paragraph = Paragraph::new(format!(\"⚠  An error occurred! {}\", err))\n                .style(Style::default().fg(Color::Red))\n                .wrap(Wrap { trim: false });\n\n            paragraph.render(block_inner, buf);\n        }\n\n        if let State::Connecting = &state {\n            let paragraph = Paragraph::new(\"Logging in, please wait...\")\n                .style(Style::default().fg(Color::Yellow));\n\n            paragraph.render(chunks[0], buf);\n        }\n\n        if let State::Connected(user, voice_state) = state {\n            let paragraph =\n                Paragraph::new(format!(\"● {}\", user.name)).style(Style::default().fg(Color::Green));\n\n            paragraph.render(chunks[0], buf);\n\n            if let VoiceState::Idle = &voice_state {\n                let paragraph =\n                    Paragraph::new(\"└ Inactive\").style(Style::default().fg(Color::DarkGray));\n\n                paragraph.render(chunks[1], buf);\n            }\n\n            if let VoiceState::Joining(channel) = &voice_state {\n                let paragraph = Paragraph::new(format!(\"└ Joining {}...\", channel.name()))\n                    .style(Style::default().fg(Color::Yellow));\n\n                paragraph.render(chunks[1], buf);\n            }\n\n            if let VoiceState::Active(channel) = &voice_state {\n                let paragraph = Paragraph::new(format!(\"└ 🔊\\u{FE0E} {}\", channel.name()))\n                    .style(Style::default().fg(Color::Green));\n\n                paragraph.render(chunks[1], buf);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/interface/dashboard/meter.rs",
    "content": "use tui::{\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n};\n\nuse crate::{app::AppContext, interface::View};\n\npub struct Meter {\n    context: AppContext,\n}\n\nimpl Meter {\n    pub fn new(context: AppContext) -> Self {\n        Self { context }\n    }\n\n    fn render_meter(&self, value: f32, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {\n        let value = value.min(1.);\n        let bar_width = area.width as f32 * value;\n\n        let amount_of_full_characters = bar_width.floor() as usize;\n\n        let partial = bar_width - amount_of_full_characters as f32;\n        let partial_index = (BAR_PARTIALS.len() - 1) as f32 * partial;\n        let partial_symbol = BAR_PARTIALS[partial_index as usize];\n\n        buf.set_string(\n            area.x + amount_of_full_characters as u16,\n            area.y,\n            partial_symbol,\n            Style::default(),\n        );\n\n        buf.set_string(\n            area.x,\n            area.y,\n            BAR_PARTIALS[8].repeat(amount_of_full_characters),\n            Style::default(),\n        );\n\n        let mut bar_area = Rect::new(area.x, area.y, area.width, 1);\n\n        buf.set_style(\n            bar_area,\n            Style::default()\n                .fg(Color::Rgb(82, 224, 45))\n                .bg(Color::Rgb(10, 17, 9)),\n        );\n\n        let yellow_size = (area.width as f32 * 0.4) as u16;\n\n        bar_area.width = yellow_size;\n        bar_area.x = area.width - yellow_size;\n        buf.set_style(\n            bar_area,\n            Style::default()\n                .fg(Color::Rgb(255, 240, 85))\n                .bg(Color::Rgb(17, 16, 9)),\n        );\n\n        let red_size = (area.width as f32 * 0.1) as u16;\n\n        bar_area.width = red_size;\n        bar_area.x = (area.width - red_size) + 2;\n\n        buf.set_style(\n            bar_area,\n            Style::default()\n                .bg(Color::Rgb(17, 10, 9))\n                .fg(Color::Rgb(199, 54, 28)),\n        );\n    }\n}\n\nimpl View for Meter {\n    fn render(&self, area: Rect, buf: &mut tui::buffer::Buffer) {\n        let (left, right) = self.context.meter_value_ranged();\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([Constraint::Length(2), Constraint::Length(1)])\n            .split(area);\n\n        self.render_meter(left, chunks[0], buf);\n        self.render_meter(right, chunks[1], buf);\n    }\n}\n\nconst BAR_PARTIALS: [&str; 9] = [\" \", \"▏\", \"▎\", \"▍\", \"▌\", \"▋\", \"▊\", \"▉\", \"█\"];\n"
  },
  {
    "path": "src/interface/dashboard/mod.rs",
    "content": "use crossterm::event::{Event, KeyCode};\nuse enum_iterator::{next_cycle, Sequence};\nuse tui::{\n    buffer::Buffer,\n    layout::{Alignment, Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n    widgets::{Paragraph, Widget, Wrap},\n};\n\nmod source_selector;\nuse source_selector::*;\n\nmod meter;\nuse meter::*;\n\nmod discord_module;\nuse discord_module::*;\n\nmod settings_module;\nuse settings_module::*;\n\nmod version;\nuse version::*;\n\nuse crate::app::AppContext;\n\nuse super::{View, LOGO};\n\npub struct Dashboard {\n    content: Content,\n    version: Version,\n}\n\npub struct Content {\n    context: AppContext,\n    selector_module: SourceSelector,\n    discord_module: DiscordModule,\n    settings_module: SettingsModule,\n    focused_module: FocusedModule,\n    meter: Meter,\n}\n\n#[derive(Debug, Default, PartialEq, Sequence)]\nenum FocusedModule {\n    #[default]\n    SourceSelector,\n    SettingsModule,\n}\n\nimpl Dashboard {\n    pub fn new(context: AppContext) -> Self {\n        let mut selector_module = SourceSelector::new(context.clone());\n        selector_module.focus();\n\n        Self {\n            version: Version::new(context.clone()),\n            content: Content {\n                selector_module,\n                discord_module: DiscordModule::new(context.clone()),\n                settings_module: SettingsModule::new(context.clone()),\n                focused_module: Default::default(),\n                meter: Meter::new(context.clone()),\n                context,\n            },\n        }\n    }\n}\n\nimpl View for Dashboard {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let is_big_enough = area.width >= 70 && area.height >= 29;\n\n        if !is_big_enough {\n            let text = \"Please resize your terminal window.\";\n\n            let centered_y = area.height / 2;\n            let centered_area = Rect::new(area.x, centered_y, area.width, area.height - centered_y);\n\n            let notice = Paragraph::new(text)\n                .alignment(Alignment::Center)\n                .wrap(Wrap { trim: false });\n\n            notice.render(centered_area, buf);\n            return;\n        }\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([\n                Constraint::Length(4),\n                Constraint::Length(area.height.saturating_sub(6)),\n                Constraint::Length(2),\n            ])\n            .horizontal_margin(1)\n            .split(area);\n\n        let logo = Paragraph::new(LOGO).alignment(Alignment::Center);\n\n        let footer_style = Style::default().fg(Color::DarkGray);\n        let copyright = Paragraph::new(\"© 2024 Enitoni, Some rights reserved.\")\n            .alignment(Alignment::Left)\n            .style(footer_style);\n\n        let footer_chunks = Layout::default()\n            .direction(Direction::Horizontal)\n            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])\n            .horizontal_margin(1)\n            .split(chunks[2]);\n\n        logo.render(chunks[0], buf);\n\n        self.content.render(chunks[1], buf);\n\n        copyright.render(footer_chunks[0], buf);\n        self.version.render(footer_chunks[1], buf);\n    }\n\n    fn handle_event(&mut self, event: crossterm::event::Event) {\n        self.content.handle_event(event)\n    }\n}\n\nimpl Content {\n    fn cycle_focus(&mut self) {\n        self.focused_module = next_cycle(&self.focused_module).expect(\"Implements sequence\");\n\n        self.selector_module.blur();\n        self.settings_module.blur();\n\n        match self.focused_module {\n            FocusedModule::SourceSelector => self.selector_module.focus(),\n            FocusedModule::SettingsModule => self.settings_module.focus(),\n        }\n    }\n}\n\nimpl View for Content {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let config = self.context.config();\n\n        let mut chunk_constraints = vec![Constraint::Length(area.height.saturating_sub(5))];\n\n        if config.show_meter {\n            chunk_constraints.push(Constraint::Length(4))\n        }\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints(chunk_constraints)\n            .split(area);\n\n        let main_chunks = Layout::default()\n            .direction(Direction::Horizontal)\n            .constraints([\n                Constraint::Length(area.width.saturating_sub(38)),\n                Constraint::Length(38),\n            ])\n            .split(chunks[0]);\n\n        let sidebar_area = main_chunks[1];\n        let sidebar_area = tui::layout::Rect::new(\n            sidebar_area.x + 1,\n            sidebar_area.y,\n            sidebar_area.width.saturating_sub(1),\n            sidebar_area.height,\n        );\n\n        let sidebar_chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([\n                Constraint::Length(6),\n                Constraint::Length(sidebar_area.height.saturating_sub(7)),\n            ])\n            .split(sidebar_area);\n\n        self.selector_module.render(main_chunks[0], buf);\n        self.settings_module.render(sidebar_chunks[1], buf);\n        self.discord_module.render(sidebar_chunks[0], buf);\n\n        if config.show_meter {\n            let mut meter_area = chunks[1];\n            meter_area.x += 1;\n            meter_area.y += 1;\n            meter_area.width -= 1;\n\n            self.meter.render(meter_area, buf);\n        }\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        if let Event::Key(key) = event {\n            if key.code == KeyCode::Tab || key.code == KeyCode::Right || key.code == KeyCode::Left {\n                self.cycle_focus();\n                return;\n            }\n        }\n\n        match self.focused_module {\n            FocusedModule::SourceSelector => self.selector_module.handle_event(event),\n            FocusedModule::SettingsModule => self.settings_module.handle_event(event),\n        }\n    }\n}\n"
  },
  {
    "path": "src/interface/dashboard/settings_module.rs",
    "content": "use crossterm::event::{Event, KeyCode};\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Style},\n    widgets::{Block, Borders, Paragraph, Widget},\n};\n\nuse crate::{\n    app::{AppAction, AppContext},\n    interface::View,\n};\n\nstruct Option {\n    context: AppContext,\n    action: AppAction,\n    paragraph: String,\n    kind: OptionKind,\n    focused: bool,\n}\n\nenum OptionKind {\n    Switch(bool),\n    Button,\n}\n\npub struct SettingsModule {\n    options: Vec<Option>,\n    selected_option: usize,\n    focused: bool,\n}\n\nimpl SettingsModule {\n    pub fn new(context: AppContext) -> Self {\n        let config = context.config();\n\n        Self {\n            options: vec![\n                Option::new(\n                    context.clone(),\n                    \"Show Meter\".to_owned(),\n                    OptionKind::Switch(config.show_meter),\n                    AppAction::ToggleMeter,\n                ),\n                Option::new(\n                    context.clone(),\n                    \"Screenshare Only\".to_owned(),\n                    OptionKind::Switch(config.screen_share_only),\n                    AppAction::ToggleScreenshareOnly,\n                ),\n                Option::new(\n                    context.clone(),\n                    \"Redo Setup\".to_owned(),\n                    OptionKind::Button,\n                    AppAction::RedoSetup,\n                ),\n            ],\n            focused: false,\n            selected_option: 0,\n        }\n    }\n\n    fn navigate(&mut self, amount: isize) {\n        let new_index =\n            ((self.selected_option) as isize + amount).rem_euclid(self.options.len() as isize);\n\n        self.selected_option = new_index as usize;\n        self.update_focus_states()\n    }\n\n    fn update_focus_states(&mut self) {\n        for option in self.options.iter_mut() {\n            option.blur();\n        }\n\n        if self.focused {\n            self.options[self.selected_option].focus();\n        }\n    }\n\n    pub fn focus(&mut self) {\n        self.focused = true;\n        self.update_focus_states();\n    }\n\n    pub fn blur(&mut self) {\n        self.focused = false;\n        self.update_focus_states();\n    }\n}\n\nimpl View for SettingsModule {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let block = Block::default()\n            .border_style(Style::default().fg(Color::DarkGray))\n            .title(\"─ Settings \")\n            .borders(Borders::all());\n\n        let block_inner = {\n            let area = block.inner(area);\n            Rect::new(\n                area.left() + 2,\n                area.top() + 1,\n                area.width - 3,\n                area.height - 1,\n            )\n        };\n\n        let calculated_constraints: Vec<_> =\n            self.options.iter().map(|_| Constraint::Length(1)).collect();\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints(calculated_constraints)\n            .split(block_inner);\n\n        block.render(area, buf);\n\n        for (index, option) in self.options.iter().enumerate() {\n            option.render(chunks[index], buf);\n        }\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        if let Event::Key(key) = event {\n            match key.code {\n                KeyCode::Up => self.navigate(-1),\n                KeyCode::Down => self.navigate(1),\n                _ => {}\n            };\n        }\n\n        self.options[self.selected_option].handle_event(event);\n    }\n}\n\nimpl Option {\n    fn new(context: AppContext, name: String, kind: OptionKind, action: AppAction) -> Self {\n        Self {\n            context,\n            paragraph: name,\n            focused: false,\n            action,\n            kind,\n        }\n    }\n\n    fn toggle_if_switch(&mut self) {\n        if let OptionKind::Switch(is_selected) = &self.kind {\n            self.kind = OptionKind::Switch(!is_selected);\n        }\n    }\n\n    fn focus(&mut self) {\n        self.focused = true;\n    }\n\n    fn blur(&mut self) {\n        self.focused = false;\n    }\n}\n\nimpl View for Option {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let chunks = Layout::default()\n            .direction(Direction::Horizontal)\n            .constraints([Constraint::Length(area.width - 3), Constraint::Length(3)])\n            .split(area);\n\n        let focus_symbol = if self.focused {\n            FOCUS_SYMBOL\n        } else {\n            IDLE_SYMBOL\n        };\n\n        let paragraph = Paragraph::new(format!(\"{} {}\", focus_symbol, self.paragraph));\n        paragraph.render(chunks[0], buf);\n\n        if let OptionKind::Switch(is_selected) = &self.kind {\n            let symbol = if *is_selected { \"ON\" } else { \"OFF\" };\n\n            let paragraph = Paragraph::new(symbol).style(if *is_selected {\n                Style::default().fg(Color::Green)\n            } else {\n                Style::default().fg(Color::DarkGray)\n            });\n\n            paragraph.render(chunks[1], buf);\n        }\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        if let Event::Key(key) = event {\n            if key.code == KeyCode::Enter {\n                self.toggle_if_switch();\n                self.context.dispatch_action(self.action.clone());\n            }\n        }\n    }\n}\n\nconst IDLE_SYMBOL: &str = \"○\";\nconst FOCUS_SYMBOL: &str = \"●\";\n"
  },
  {
    "path": "src/interface/dashboard/source_selector.rs",
    "content": "use crossterm::event::{Event, KeyCode};\nuse parking_lot::Mutex;\nuse tui::{\n    buffer::Buffer,\n    layout::Rect,\n    style::{Color, Style},\n    widgets::{Block, Borders, Paragraph, Widget},\n};\n\nuse crate::{\n    app::{AppAction, AppContext},\n    dickcord,\n    interface::View,\n};\n\npub struct SourceSelector {\n    context: AppContext,\n    selected_index: Mutex<usize>,\n    focused: bool,\n}\n\nimpl SourceSelector {\n    pub fn new(context: AppContext) -> Self {\n        Self {\n            context,\n            selected_index: Default::default(),\n            focused: false,\n        }\n    }\n\n    pub fn navigate(&mut self, amount: isize) {\n        let mut selected_index = self.selected_index.lock();\n        let app_length = self.context.sources().len() as isize;\n\n        let new_index = ((*selected_index) as isize + amount).rem_euclid(app_length);\n        *selected_index = new_index as usize;\n    }\n\n    pub fn select(&self) {\n        let selected_source = self.context.current_source();\n        let selected_index = self.selected_index.lock();\n        let sources = self.context.sources();\n\n        if let Some(source) = sources.get(*selected_index) {\n            let selected_app_index = selected_source\n                .as_ref()\n                .map(|a| a.index())\n                .unwrap_or_default();\n\n            // Stop the stream if pressing play on the same one\n            if source.index() == selected_app_index {\n                self.context.dispatch_action(AppAction::StopStream);\n            } else {\n                self.context\n                    .dispatch_action(AppAction::SetAudioSource(source.to_owned()));\n            }\n        }\n    }\n\n    pub fn focus(&mut self) {\n        self.focused = true;\n    }\n\n    pub fn blur(&mut self) {\n        self.focused = false;\n    }\n}\n\nimpl View for SourceSelector {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let block = Block::default()\n            .title(\"─ Sources \")\n            .border_style(Style::default().fg(Color::DarkGray))\n            .borders(Borders::all());\n\n        // Add margins\n        let block_inner = {\n            let area = block.inner(area);\n            tui::layout::Rect::new(area.left() + 2, area.top() + 1, area.width - 2, area.height)\n        };\n\n        block.render(area, buf);\n\n        let sources = self.context.sources();\n\n        let selected_index = self.selected_index.lock();\n\n        let selected_source = self.context.selected_source();\n        let current_source = self.context.current_source();\n\n        let discord_state = self.context.discord_state();\n        let is_discord_ready = matches!(discord_state, dickcord::State::Connected(_, _));\n\n        let top = block_inner.top();\n\n        for (index, source) in sources.iter().enumerate() {\n            let is_over = *selected_index == index;\n\n            let is_active = current_source\n                .as_ref()\n                .map(|f| f.index() == source.index())\n                .unwrap_or_default();\n\n            let is_selected = selected_source\n                .as_ref()\n                .map(|f| f.index() == source.index())\n                .unwrap_or_default();\n\n            let paragraph_area = tui::layout::Rect::new(\n                block_inner.left(),\n                top + index as u16,\n                block_inner.width,\n                1,\n            );\n\n            let symbol = if !is_discord_ready || !self.focused {\n                IDLE_SYMBOL\n            } else if is_over {\n                HOVER_SYMBOL\n            } else if is_selected {\n                ACTIVE_SYMBOL\n            } else {\n                IDLE_SYMBOL\n            };\n\n            let color = if !is_discord_ready {\n                DISABLE_COLOR\n            } else if is_active {\n                ACTIVE_COLOR\n            } else if source.available() {\n                IDLE_COLOR\n            } else {\n                UNAVAILABLE_COLOR\n            };\n\n            let paragraph = Paragraph::new(format!(\"{} {}\", symbol, source.name()))\n                .style(Style::default().fg(color));\n\n            paragraph.render(paragraph_area, buf);\n        }\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        {\n            let discord_state = self.context.discord_state();\n\n            // Prevent selecting app before discord connects\n            if !matches!(discord_state, dickcord::State::Connected(_, _)) {\n                return;\n            }\n        }\n\n        if let Event::Key(key) = event {\n            match key.code {\n                KeyCode::Up => self.navigate(-1),\n                KeyCode::Down => self.navigate(1),\n                KeyCode::Enter => self.select(),\n                _ => {}\n            }\n        }\n    }\n}\n\nconst IDLE_SYMBOL: &str = \"○\";\nconst HOVER_SYMBOL: &str = \"●\";\nconst ACTIVE_SYMBOL: &str = \"►\";\n\nconst ACTIVE_COLOR: Color = Color::Green;\nconst IDLE_COLOR: Color = Color::Reset;\nconst DISABLE_COLOR: Color = Color::DarkGray;\nconst UNAVAILABLE_COLOR: Color = Color::Yellow;\n"
  },
  {
    "path": "src/interface/dashboard/version.rs",
    "content": "use tui::{\n    buffer::Buffer,\n    layout::{Alignment, Rect},\n    style::{Color, Style},\n    widgets::{Paragraph, Widget},\n};\n\nuse crate::{\n    app::{AppContext, VERSION},\n    interface::View,\n};\n\npub struct Version {\n    context: AppContext,\n}\n\nimpl Version {\n    pub fn new(context: AppContext) -> Self {\n        Self { context }\n    }\n}\n\nimpl View for Version {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let new_update = self.context.update_available();\n\n        if let Some(new_update) = new_update {\n            Paragraph::new(format!(\"Update available! v{} > {}\", VERSION, new_update))\n                .alignment(Alignment::Right)\n                .style(Style::default().fg(Color::Green))\n                .render(area, buf);\n\n            return;\n        }\n\n        Paragraph::new(format!(\"v{}\", VERSION))\n            .alignment(Alignment::Right)\n            .style(Style::default().fg(Color::DarkGray))\n            .render(area, buf);\n    }\n}\n"
  },
  {
    "path": "src/interface/mod.rs",
    "content": "use std::{\n    io, thread,\n    time::{Duration, Instant},\n};\n\nmod components;\npub use components::*;\n\nmod view;\npub use view::*;\n\nmod splash;\npub use splash::*;\n\nmod dashboard;\npub use dashboard::*;\n\nmod setup;\npub use setup::*;\n\nuse crossbeam::{\n    atomic::AtomicCell,\n    channel::{unbounded, Receiver, Sender},\n};\nuse crossterm::{\n    event::{read, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},\n    execute,\n    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},\n};\nuse parking_lot::Mutex;\nuse tui::{backend::CrosstermBackend, Terminal};\n\nuse crate::app::{AppAction, AppEvent};\n\npub const TARGET_FPS: u32 = 144;\npub const MS_PER_FRAME: f32 = 1000. / TARGET_FPS as f32;\n\npub const LOGO: &str = \"\n█▀█ █░█ █░░ █▀ █▀▀ █▀ █░█ █ ▀█▀ ▀█▀ █▀▀ █▀█\n█▀▀ █▄█ █▄▄ ▄█ ██▄ ▄█ █▀█ █ ░█░ ░█░ ██▄ █▀▄\n\";\n\n/// Handles rendering logic\npub struct Interface {\n    view: Mutex<BoxedView>,\n    exiting: AtomicCell<bool>,\n    sender: Sender<AppEvent>,\n}\n\nimpl Interface {\n    pub fn new<V>(view: V, sender: Sender<AppEvent>) -> Self\n    where\n        V: View + Sync + Send + 'static,\n    {\n        Self {\n            view: Mutex::new(BoxedView::new(view)),\n            exiting: false.into(),\n            sender,\n        }\n    }\n\n    pub fn set_view<V>(&self, view: V)\n    where\n        V: View + Sync + Send + 'static,\n    {\n        *self.view.lock() = BoxedView::new(view)\n    }\n\n    /// Renders the TUI until exit\n    pub fn run(&self) -> Result<(), io::Error> {\n        enable_raw_mode()?;\n\n        let mut stdout = io::stdout();\n        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;\n\n        let backend = CrosstermBackend::new(stdout);\n        let events = spawn_event_loop();\n\n        let mut terminal = Terminal::new(backend)?;\n\n        'ui: loop {\n            let frame_now = Instant::now();\n            let mut view = self.view.lock();\n\n            let result = terminal.draw(|f| f.render_widget(&*view, f.size()));\n\n            if let Err(err) = result {\n                eprintln!(\"Failed to draw: {:?}\", err);\n                break;\n            };\n\n            if self.exiting.load() {\n                break 'ui;\n            }\n\n            while let Ok(event) = events.try_recv() {\n                if let Event::Key(key) = &event {\n                    if key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c') {\n                        self.sender.send(AppEvent::Action(AppAction::Exit)).unwrap();\n                        continue;\n                    }\n                }\n\n                view.handle_event(event);\n            }\n\n            let elapsed = frame_now.elapsed().as_secs_f32();\n            let remainder = (MS_PER_FRAME / 1000.) - elapsed;\n\n            let sleep_duration = Duration::from_secs_f32(remainder.max(0.));\n\n            drop(view);\n            thread::sleep(sleep_duration);\n        }\n\n        disable_raw_mode()?;\n        execute!(\n            terminal.backend_mut(),\n            LeaveAlternateScreen,\n            DisableMouseCapture\n        )?;\n        terminal.show_cursor()?;\n\n        Ok(())\n    }\n\n    pub fn stop(&self) {\n        self.exiting.store(true)\n    }\n}\n\nfn spawn_event_loop() -> Receiver<Event> {\n    let (sender, receiver) = unbounded();\n\n    let run = move || loop {\n        match read() {\n            Ok(event) => {\n                if matches!(event, Event::Key(_)) {\n                    sender.send(event).expect(\"Send\");\n                }\n            }\n            Err(err) => eprintln!(\"{:?}\", err),\n        };\n    };\n\n    thread::Builder::new()\n        .name(\"tui-events\".to_string())\n        .spawn(run)\n        .unwrap();\n\n    receiver\n}\n"
  },
  {
    "path": "src/interface/setup/form.rs",
    "content": "use crossterm::event::{Event, KeyCode};\nuse enum_iterator::{next_cycle, Sequence};\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n};\n\nuse crate::interface::{TextField, View};\n\n#[derive(Default, PartialEq, Sequence)]\npub enum SelectedField {\n    #[default]\n    BotToken,\n    UserId,\n}\n\npub struct Form {\n    selected_field: SelectedField,\n    bot_token: TextField,\n    user_id: TextField,\n}\n\nimpl Form {\n    pub fn new() -> Self {\n        let mut bot_token = TextField::new(\"Bot Token\");\n        let user_id = TextField::new(\"User ID\");\n\n        bot_token.focus();\n\n        Self {\n            selected_field: Default::default(),\n            bot_token,\n            user_id,\n        }\n    }\n\n    fn cycle_selection(&mut self) {\n        self.selected_field = next_cycle(&self.selected_field).expect(\"Implements sequence\");\n\n        let (focus, blur) = match self.selected_field {\n            SelectedField::BotToken => (&mut self.bot_token, &mut self.user_id),\n            SelectedField::UserId => (&mut self.user_id, &mut self.bot_token),\n        };\n\n        focus.focus();\n        blur.blur();\n    }\n\n    pub fn current_selection(&self) -> &SelectedField {\n        &self.selected_field\n    }\n\n    pub fn current_values(&self) -> (String, String) {\n        let bot_token = self.bot_token.value();\n        let user_id = self.user_id.value();\n\n        (bot_token, user_id)\n    }\n}\n\nimpl View for Form {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([Constraint::Length(3), Constraint::Length(4)])\n            .split(area);\n\n        self.bot_token.render(chunks[0], buf);\n        self.user_id.render(chunks[1], buf);\n    }\n\n    fn handle_event(&mut self, event: crossterm::event::Event) {\n        if let Event::Key(key) = event {\n            if key.code == KeyCode::Tab || key.code == KeyCode::Enter {\n                self.cycle_selection();\n                return;\n            }\n        }\n\n        match self.selected_field {\n            SelectedField::BotToken => self.bot_token.handle_event(event),\n            SelectedField::UserId => self.user_id.handle_event(event),\n        };\n    }\n}\n"
  },
  {
    "path": "src/interface/setup/mod.rs",
    "content": "use crossterm::event::{Event, KeyCode};\nuse form::{Form, SelectedField};\nuse tui::{\n    buffer::Buffer,\n    layout::{Constraint, Direction, Layout, Rect},\n    style::{Color, Modifier, Style},\n    text::{Span, Spans},\n    widgets::{Block, Borders, Paragraph, Widget, Wrap},\n};\n\nuse crate::{\n    app::{AppAction, AppContext},\n    dickcord::State as DiscordState,\n    state::Config,\n};\n\nuse super::View;\nmod form;\n\npub struct Setup {\n    context: AppContext,\n    form: Form,\n}\n\nimpl Setup {\n    pub fn new(context: AppContext) -> Self {\n        Self {\n            context,\n            form: Form::new(),\n        }\n    }\n\n    fn is_valid(&self) -> bool {\n        let (bot_token, user_id) = self.form.current_values();\n        !(bot_token.is_empty()) && !(user_id.is_empty())\n    }\n}\n\nimpl View for Setup {\n    fn render(&self, area: Rect, buf: &mut Buffer) {\n        let outer_margin = Layout::default()\n            .constraints([Constraint::Percentage(100)])\n            .margin(2)\n            .vertical_margin(1)\n            .split(area);\n\n        let block = Block::default()\n            .title(\"─ Setup \")\n            .borders(Borders::all())\n            .border_style(Style::default().fg(Color::DarkGray));\n\n        let chunks = Layout::default()\n            .direction(Direction::Vertical)\n            .constraints([\n                Constraint::Length(7),\n                Constraint::Length(3),\n                Constraint::Percentage(100),\n            ])\n            .margin(1)\n            .horizontal_margin(2)\n            .split(block.inner(outer_margin[0]));\n\n        let discord_state = self.context.discord_state();\n\n        let status_text = match &discord_state {\n            DiscordState::Idle => {\n                \"Press tab to switch between fields. Press enter to connect when you're done.\"\n                    .to_string()\n            }\n            DiscordState::Connecting => \"Connecting...\".to_string(),\n            DiscordState::Connected(_, _) => \"Connected!\".to_string(),\n            DiscordState::Error(error) => error.to_string(),\n        };\n\n        let status_color = match &discord_state {\n            DiscordState::Idle => Color::DarkGray,\n            DiscordState::Connecting => Color::Yellow,\n            DiscordState::Connected(_, _) => Color::Green,\n            DiscordState::Error(_) => Color::Red,\n        };\n\n        let status_text = Paragraph::new(status_text).style(Style::default().fg(status_color));\n\n        let help_text = match self.form.current_selection() {\n            SelectedField::BotToken => get_bot_token_help(),\n            SelectedField::UserId => get_user_id_help(),\n        };\n\n        self.form.render(chunks[0], buf);\n        status_text.render(chunks[1], buf);\n        help_text.render(chunks[2], buf);\n        block.render(outer_margin[0], buf);\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        let discord_state = self.context.discord_state();\n\n        // Don't allow the user to input while we're connecting\n        if !matches!(discord_state, DiscordState::Idle | DiscordState::Error(_)) {\n            return;\n        }\n\n        // Handle submission\n        if let Event::Key(key) = event {\n            if key.code == KeyCode::Enter && self.is_valid() {\n                let (bot_token, user_id) = self.form.current_values();\n                let safe_user_id = user_id.parse().unwrap_or_default();\n\n                let new_config = Config::new(bot_token, safe_user_id);\n                self.context\n                    .dispatch_action(AppAction::SetConfig(new_config));\n\n                return;\n            }\n        }\n\n        // Otherwise, handle the form events\n        self.form.handle_event(event);\n    }\n}\n\nfn get_bot_token_help() -> Paragraph<'static> {\n    let bold = Style::default().add_modifier(Modifier::BOLD);\n\n    let spans = vec![\n        Spans::from(vec![\n            Span::raw(\"Required to connect to Discord with a bot. \"),\n            Span::styled(\n                \"Make sure \\\"Server Members Intent\\\" is enabled in the Bot settings.\",\n                bold,\n            ),\n        ]),\n        Spans::default(),\n        Spans::from(vec![\n            Span::raw(\"If you don't have a bot token at hand, visit https://discord.com/developers/applications/ , Create a new bot by pressing \\\"New Application\\\" on the top right of the page, on the application settings page, on the left sidebar go to \\\"Bot\\\". Click \\\"Reset Token\\\", Discord will generate a bot token pulseshitter can use; copy it, keep it secured, don't lose it. Scroll down, \"),\n            Span::styled(\"enable \\\"Server Members Intent\\\"\", bold),\n            Span::raw(\", then Save Changes.\")\n        ]),\n        Spans::default(),\n        Spans::from(Span::raw(\"You will need a link to invite your bot into the servers you need to use. On the sidebar, head over to \\\"OAuth2 > URL Generator.\\\" Under \\\"Scopes\\\" select \\\"bot\\\", under \\\"Bot Permissions\\\" select \\\"Connect\\\" and \\\"Speak.\\\" At the bottom, copy the Generated URL and visit it in your browser to invite your bot to your server\"))\n    ];\n\n    Paragraph::new(spans).wrap(Wrap { trim: false })\n}\n\nfn get_user_id_help() -> Paragraph<'static> {\n    let spans = vec![\n        Spans::from(Span::raw(\"pulseshitter will automatically join all voice channels this user joins. This should be your own user ID. \")),\n        Spans::default(),\n        Spans::from(Span::raw(\"To get your user ID, right click yourself in any server's user list or in a message, then click \\\"Copy ID.\\\"\")),\n        Spans::default(),\n        Spans::from(Span::raw(\"If there's no \\\"Copy ID\\\" option, go to Settings > Advanced and enable \\\"Developer Mode\\\" and try again.\"))\n    ];\n\n    Paragraph::new(spans).wrap(Wrap { trim: false })\n}\n"
  },
  {
    "path": "src/interface/splash.rs",
    "content": "use tui::{\n    layout::Alignment,\n    widgets::{Paragraph, Widget},\n};\n\nuse super::{View, LOGO};\npub struct Splash;\n\nimpl View for Splash {\n    fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {\n        let logo = Paragraph::new(LOGO).alignment(Alignment::Center);\n        logo.render(area, buf);\n    }\n}\n"
  },
  {
    "path": "src/interface/view.rs",
    "content": "use crossterm::event::Event;\nuse tui::{buffer::Buffer, layout::Rect, widgets::Widget};\n\npub trait View {\n    fn handle_event(&mut self, _event: Event) {}\n\n    fn render(&self, area: Rect, buf: &mut Buffer);\n}\n\npub struct BoxedView {\n    view: Box<dyn View + Sync + Send>,\n}\n\nimpl BoxedView {\n    pub fn new<V>(view: V) -> Self\n    where\n        V: View + Sync + Send + 'static,\n    {\n        Self {\n            view: Box::new(view),\n        }\n    }\n}\n\nimpl Widget for &BoxedView {\n    fn render(self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {\n        self.view.render(area, buf)\n    }\n}\n\nimpl View for BoxedView {\n    fn render(&self, area: tui::layout::Rect, buf: &mut tui::buffer::Buffer) {\n        self.view.render(area, buf)\n    }\n\n    fn handle_event(&mut self, event: Event) {\n        self.view.handle_event(event)\n    }\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "use app::App;\n\nmod app;\nmod audio;\nmod dickcord;\nmod interface;\nmod state;\n\nfn main() {\n    let app = App::new();\n\n    match app {\n        Ok(app) => app.run_tui(),\n        Err(err) => {\n            eprintln!(\"pulseshitter failed to start. please verify that you have all the required components installed.\");\n            eprintln!(\"error: {}\", err);\n        }\n    }\n}\n"
  },
  {
    "path": "src/state.rs",
    "content": "use serde::{Deserialize, Serialize};\nuse std::env;\nuse std::io::Write;\nuse std::{fs::File, io::Read};\n\n#[derive(Debug, Deserialize, Serialize, Clone)]\npub struct Config {\n    pub bot_token: String,\n    pub user_id: u64,\n\n    pub show_meter: bool,\n    pub screen_share_only: bool,\n}\n\n#[derive(Debug, Clone)]\npub struct ReadOnlyConfig {\n    pub bot_token: String,\n    pub user_id: u64,\n    pub show_meter: bool,\n    pub screen_share_only: bool,\n}\n\nimpl Config {\n    fn path() -> String {\n        let config_dir = env::var(\"XDG_CONFIG_HOME\")\n            .or_else(|_| env::var(\"HOME\").map(|path| path + \"/.config\"))\n            .unwrap_or_else(|_| \".\".to_string());\n\n        format!(\"{}/pulseshitter-config.ron\", config_dir)\n    }\n\n    pub fn new(bot_token: String, user_id: u64) -> Self {\n        Self {\n            bot_token,\n            user_id,\n            show_meter: true,\n            screen_share_only: false,\n        }\n    }\n\n    pub fn restore() -> Option<Self> {\n        File::open(Self::path())\n            .ok()\n            .and_then(|mut file| {\n                let mut contents = String::new();\n                file.read_to_string(&mut contents).map(|_| contents).ok()\n            })\n            .and_then(|content| ron::from_str(&content).ok())\n    }\n\n    pub fn save(&self) {\n        match ron::to_string(self) {\n            Ok(result) => {\n                File::create(Self::path())\n                    .ok()\n                    .and_then(|mut f| write!(f, \"{}\", result).ok());\n            }\n            Err(err) => eprintln!(\"Config save failed: {:?}\", err),\n        }\n    }\n\n    pub fn read_only(&self) -> ReadOnlyConfig {\n        ReadOnlyConfig {\n            bot_token: self.bot_token.clone(),\n            user_id: self.user_id,\n            show_meter: self.show_meter,\n            screen_share_only: self.screen_share_only,\n        }\n    }\n}\n"
  }
]