libobs-bootstrapper 0.4.0

Downloads OBS binaries at runtime and bootstraps libobs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
// awaits and streams use unsafe internally, so I'm gonna check for unsafe blocks manually here.
#![allow(unknown_lints, require_safety_comments_on_unsafe)]

use std::{env, path::PathBuf, process};

use async_stream::stream;
use download::DownloadStatus;
use extract::ExtractStatus;
use futures_core::Stream;
use futures_util::{StreamExt, pin_mut};
use lazy_static::lazy_static;
use libobs::{LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER};
use tokio::{fs::File, io::AsyncWriteExt, process::Command};

#[cfg_attr(coverage_nightly, coverage(off))]
mod download;
mod error;
#[cfg_attr(coverage_nightly, coverage(off))]
mod extract;
#[cfg_attr(coverage_nightly, coverage(off))]
mod github_types;
mod options;
pub mod status_handler;
mod version;

#[cfg(test)]
mod download_tests;
#[cfg(test)]
mod options_tests;
#[cfg(test)]
mod version_tests;

pub use error::ObsBootstrapError;

pub use options::{ObsBootstrapperOptions, UpdateTargetMode};

use crate::status_handler::{ObsBootstrapConsoleHandler, ObsBootstrapStatusHandler};

pub enum BootstrapStatus {
    /// Downloading status (first is progress from 0.0 to 1.0 and second is message)
    Downloading(f32, String),

    /// Extracting status (first is progress from 0.0 to 1.0 and second is message)
    Extracting(f32, String),
    Error(ObsBootstrapError),
    /// The application must be restarted to use the new version of OBS.
    /// This is because the obs.dll file is in use by the application and can not be replaced while running.
    /// Therefore, the "updater" is spawned to watch for the application to exit and rename the "obs_new.dll" file to "obs.dll".
    /// The updater will start the application again with the same arguments as the original application.
    RestartRequired,
}

/// A struct for bootstrapping OBS Studio.
///
/// This struct provides functionality to download, extract, and set up OBS Studio
/// for use with libobs-rs. It also handles updates to OBS when necessary.
///
/// If you want to use this bootstrapper to also install required OBS binaries at runtime,
/// do the following:
/// - Add a `obs.dll` file to your executable directory. This file will be replaced by the obs installer.
///   Recommended to use is the dll dummy (found [here](https://github.com/sshcrack/libobs-builds/releases), make sure you use the correct OBS version)
///   and rename it to `obs.dll`.
/// - Call `ObsBootstrapper::bootstrap()` at the start of your application. Options must be configured. For more documentation look at the [tauri example app](https://github.com/libobs-rs/libobs-rs/tree/main/examples/tauri-app). This will download the latest version of OBS and extract it in the executable directory.
/// - If BootstrapStatus::RestartRequired is returned, you'll need to restart your application. A updater process has been spawned to watch for the application to exit and rename the `obs_new.dll` file to `obs.dll`.
/// - Exit the application. The updater process will wait for the application to exit and rename the `obs_new.dll` file to `obs.dll` and restart your application with the same arguments as before.
///
/// [Example project](https://github.com/libobs-rs/libobs-rs/tree/main/examples/download-at-runtime)
pub struct ObsBootstrapper {}

lazy_static! {
    pub(crate) static ref LIBRARY_OBS_VERSION: String = format!(
        "{}.{}.{}",
        LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER
    );
}

pub const UPDATER_SCRIPT: &str = include_str!("./updater.ps1");

fn get_obs_dll_path() -> Result<PathBuf, ObsBootstrapError> {
    let executable =
        env::current_exe().map_err(|e| ObsBootstrapError::IoError("Getting current exe", e))?;
    let obs_dll = executable
        .parent()
        .ok_or_else(|| {
            ObsBootstrapError::IoError(
                "Failed to get parent directory",
                std::io::Error::from(std::io::ErrorKind::InvalidInput),
            )
        })?
        .join("obs.dll");

    Ok(obs_dll)
}

pub(crate) fn bootstrap(
    options: &ObsBootstrapperOptions,
) -> Result<Option<impl Stream<Item = BootstrapStatus>>, ObsBootstrapError> {
    let repo = options.repository.to_string();

    log::trace!("Checking for update...");
    let installed = version::get_installed_version(&get_obs_dll_path()?)?;

    let update = if options.update {
        if let Some(installed_version) = &installed {
            if !version::is_compatible_major(installed_version)? {
                log::warn!(
                    "Installed OBS major version ({}) does not match required major ({}); skipping automatic update.",
                    installed_version,
                    LIBOBS_API_MAJOR_VER
                );
                false
            } else {
                true
            }
        } else {
            true
        }
    } else {
        installed.is_none()
    };

    if !update {
        log::debug!("No update needed.");
        return Ok(None);
    }

    let options = options.clone();
    Ok(Some(stream! {
        let resolved_release = download::resolve_latest_compatible_release(&repo, options.update_target_mode).await;
        if let Err(err) = resolved_release {
            yield BootstrapStatus::Error(err);
            return;
        }

        let resolved_release = resolved_release.unwrap();

        if let Some(installed_version) = installed.as_deref() {
            let should_update = version::should_update(installed_version, &resolved_release.version);
            if let Err(err) = should_update {
                yield BootstrapStatus::Error(err);
                return;
            }

            if !should_update.unwrap() {
                log::debug!(
                    "No update needed; installed OBS version {} is up-to-date for compatible target {}.",
                    installed_version,
                    resolved_release.version
                );
                return;
            }
        }

        log::debug!("Downloading OBS from {}", repo);
        let download_stream = download::download_obs(&resolved_release).await;
        if let Err(err) = download_stream {
            yield BootstrapStatus::Error(err);
            return;
        }

        let download_stream = download_stream.unwrap();
        pin_mut!(download_stream);

        let mut file = None;
        while let Some(item) = download_stream.next().await {
            match item {
                DownloadStatus::Error(err) => {
                    yield BootstrapStatus::Error(err);
                    return;
                }
                DownloadStatus::Progress(progress, message) => {
                    yield BootstrapStatus::Downloading(progress, message);
                }
                DownloadStatus::Done(path) => {
                    file = Some(path)
                }
            }
        }

        let archive_file = file.ok_or(ObsBootstrapError::InvalidState);
        if let Err(err) = archive_file {
            yield BootstrapStatus::Error(err);
            return;
        }

        log::debug!("Extracting OBS to {:?}", archive_file);
        let archive_file = archive_file.unwrap();
        let extract_stream = extract::extract_obs(&archive_file).await;
        if let Err(err) = extract_stream {
            yield BootstrapStatus::Error(err);
            return;
        }

        let extract_stream = extract_stream.unwrap();
        pin_mut!(extract_stream);

        while let Some(item) = extract_stream.next().await {
            match item {
                ExtractStatus::Error(err) => {
                    yield BootstrapStatus::Error(err);
                    return;
                }
                ExtractStatus::Progress(progress, message) => {
                    yield BootstrapStatus::Extracting(progress, message);
                }
            }
        }

        let r = spawn_updater(options).await;
        if let Err(err) = r {
            yield BootstrapStatus::Error(err);
            return;
        }

        yield BootstrapStatus::RestartRequired;
    }))
}

pub(crate) async fn spawn_updater(
    options: ObsBootstrapperOptions,
) -> Result<(), ObsBootstrapError> {
    let pid = process::id();
    let args = env::args().collect::<Vec<_>>();
    // Skip the first argument which is the executable path
    let args = args.into_iter().skip(1).collect::<Vec<_>>();

    let updater_path = env::temp_dir().join("libobs_updater.ps1");
    let mut updater_file = File::create(&updater_path)
        .await
        .map_err(|e| ObsBootstrapError::IoError("Creating updater script", e))?;

    updater_file
        .write_all(UPDATER_SCRIPT.as_bytes())
        .await
        .map_err(|e| ObsBootstrapError::IoError("Writing updater script", e))?;

    let mut command = Command::new("powershell");
    command
        .arg("-ExecutionPolicy")
        .arg("Bypass")
        .arg("-NoProfile")
        .arg("-WindowStyle")
        .arg("Hidden")
        .arg("-File")
        .arg(updater_path)
        .arg("-processPid")
        .arg(pid.to_string())
        .arg("-binary")
        .arg(
            env::current_exe()
                .map_err(|e| ObsBootstrapError::IoError("Getting current exe", e))?
                .to_string_lossy()
                .to_string(),
        );

    if options.restart_after_update {
        command.arg("-restart");
    }

    // Encode arguments as hex string (UTF-8, null-separated)
    if !args.is_empty() {
        let joined = args.join("\0");
        let bytes = joined.as_bytes();
        let hex_str = hex::encode(bytes);
        command.arg("-argumentHex");
        command.arg(hex_str);
    }

    command
        .spawn()
        .map_err(|e| ObsBootstrapError::IoError("Spawning updater process", e))?;

    Ok(())
}

pub enum ObsBootstrapperResult {
    /// No action was needed, OBS is already installed and up to date.
    None,
    /// The application must be restarted to complete the installation or update of OBS.
    Restart,
}

/// A convenience type that exposes high-level helpers to detect, update and
/// bootstrap an OBS installation.
///
/// The bootstrapper coordinates version checks and the streaming bootstrap
/// process. It does not itself perform low-level network or extraction work;
/// instead it delegates to internal modules (version checking and the
/// bootstrap stream) and surfaces a simple API for callers.
impl ObsBootstrapper {
    /// Returns true if a valid OBS installation (as determined by locating the
    /// OBS DLL and querying the installed version) is present on the system.
    ///
    /// # Returns
    ///
    /// - `Ok(true)` if an installed OBS version could be detected.
    /// - `Ok(false)` if no installed OBS version was found.
    ///
    /// # Errors
    ///
    /// Returns an `Err(ObsBootstrapError)` if there was an error locating the OBS DLL or
    /// reading the installed version information.
    pub fn is_valid_installation() -> Result<bool, ObsBootstrapError> {
        let installed = version::get_installed_version(&get_obs_dll_path()?)?;
        if installed.is_none() {
            log::trace!("No valid OBS installation found");
            return Ok(false);
        }

        Ok(true)
    }

    /// Returns true when an update to OBS should be performed.
    ///
    /// The function first checks whether OBS is installed. If no installation
    /// is found it treats that as an available update (returns `Ok(true)`).
    /// Otherwise it consults the internal version logic to determine whether
    /// the installed version should be updated.
    ///
    /// # Returns
    ///
    /// - `Ok(true)` when an update is recommended or when OBS is not installed.
    /// - `Ok(false)` when the installed version is up-to-date.
    ///
    /// # Errors
    ///
    /// Returns an `Err(ObsBootstrapError)` if there was an error locating the OBS DLL or
    /// determining the currently installed version or update necessity.
    pub fn is_update_available() -> Result<bool, ObsBootstrapError> {
        let installed = version::get_installed_version(&get_obs_dll_path()?)?;
        if installed.is_none() {
            log::trace!("No OBS installation found, treating as update available");
            return Ok(true);
        }

        let installed = installed.unwrap();
        if !version::is_compatible_major(&installed)? {
            log::warn!(
                "Installed OBS major version ({}) does not match required major ({}); not counting as update.",
                installed,
                LIBOBS_API_MAJOR_VER
            );
            return Ok(false);
        }

        Ok(true)
    }

    /// Bootstraps OBS using the provided options and a default console status
    /// handler.
    ///
    /// This is a convenience wrapper around `bootstrap_with_handler` that
    /// supplies an `ObsBootstrapConsoleHandler` as the status consumer.
    ///
    /// # Returns
    ///
    /// - `Ok(ObsBootstrapperResult::None)` if no action was necessary.
    /// - `Ok(ObsBootstrapperResult::Restart)` if the bootstrap completed and a
    ///   restart is required.
    ///
    /// # Errors
    ///
    /// Returns `Err(ObsBootstrapError)` for any failure that prevents the
    /// bootstrap from completing (download failures, extraction failures,
    /// general errors).
    pub async fn bootstrap(
        options: &options::ObsBootstrapperOptions,
    ) -> Result<ObsBootstrapperResult, ObsBootstrapError> {
        ObsBootstrapper::bootstrap_with_handler(
            options,
            Box::new(ObsBootstrapConsoleHandler::default()),
        )
        .await
    }

    /// Bootstraps OBS using the provided options and a custom status handler.
    ///
    /// The handler will receive progress updates as the bootstrap stream emits
    /// statuses. The method drives the bootstrap stream to completion and maps
    /// stream statuses into handler calls or final results:
    ///
    /// - `BootstrapStatus::Downloading(progress, message)` → calls
    ///   `handler.handle_downloading(progress, message)`. Handler errors are
    ///   mapped to `ObsBootstrapError::DownloadError`.
    /// - `BootstrapStatus::Extracting(progress, message)` → calls
    ///   `handler.handle_extraction(progress, message)`. Handler errors are
    ///   mapped to `ObsBootstrapError::ExtractError`.
    /// - `BootstrapStatus::Error(err)` → returns `Err(ObsBootstrapError::GeneralError(_))`.
    /// - `BootstrapStatus::RestartRequired` → returns `Ok(ObsBootstrapperResult::Restart)`.
    ///
    /// If the underlying `bootstrap(options)` call returns `None` there is
    /// nothing to do and the function returns `Ok(ObsBootstrapperResult::None)`.
    ///
    /// # Parameters
    ///
    /// - `options`: configuration that controls download/extraction behavior.
    /// - `handler`: user-provided boxed trait object that receives progress
    ///   notifications; it is called on each progress update and can fail.
    ///
    /// # Returns
    ///
    /// - `Ok(ObsBootstrapperResult::None)` when no work was required or the
    ///   stream completed without requiring a restart.
    /// - `Ok(ObsBootstrapperResult::Restart)` when the bootstrap succeeded and
    ///   a restart is required.
    ///
    /// # Errors
    ///
    /// Returns `Err(ObsBootstrapError)` when:
    /// - the bootstrap pipeline could not be started,
    /// - the handler returns an error while handling a download or extraction
    ///   update (mapped respectively to `DownloadError` / `ExtractError`),
    /// - or when the bootstrap stream yields a general error.
    pub async fn bootstrap_with_handler<E: Send + Sync + 'static + std::error::Error>(
        options: &options::ObsBootstrapperOptions,
        mut handler: Box<dyn ObsBootstrapStatusHandler<Error = E>>,
    ) -> Result<ObsBootstrapperResult, ObsBootstrapError> {
        let stream = bootstrap(options)?;

        if let Some(stream) = stream {
            pin_mut!(stream);

            log::trace!("Waiting for bootstrapper to finish");
            while let Some(item) = stream.next().await {
                match item {
                    BootstrapStatus::Downloading(progress, message) => {
                        handler
                            .handle_downloading(progress, message)
                            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
                    }
                    BootstrapStatus::Extracting(progress, message) => {
                        handler
                            .handle_extraction(progress, message)
                            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
                    }
                    BootstrapStatus::Error(err) => {
                        return Err(err);
                    }
                    BootstrapStatus::RestartRequired => {
                        return Ok(ObsBootstrapperResult::Restart);
                    }
                }
            }
        }

        Ok(ObsBootstrapperResult::None)
    }
}