acter/platform/
native.rs

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
use anyhow::{bail, Result};
use chrono::Local;
use lazy_static::lazy_static;
use log::{log_enabled, Level, LevelFilter, Log, Metadata, Record};
use matrix_sdk::{Client, ClientBuilder, SqliteEventCacheStore};
use matrix_sdk_base::{event_cache::store::EventCacheStoreError, store::StoreConfig};
use matrix_sdk_sqlite::{OpenStoreError, SqliteCryptoStore, SqliteStateStore};
use parse_env_filter::eager::{filters, Filter};
use std::{
    fmt::{Display, Error},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use crate::RUNTIME;

pub async fn destroy_local_data(
    base_path: String,
    home_dir: String,
    media_cache_base_path: Option<String>,
) -> Result<bool> {
    if let Some(media_base) = media_cache_base_path {
        let data_path = sanitize(&media_base, &home_dir);
        if Path::new(&data_path).try_exists()? {
            std::fs::remove_dir_all(&data_path)?;
        }
    }

    let data_path = sanitize(&base_path, &home_dir);
    if Path::new(&data_path).try_exists()? {
        std::fs::remove_dir_all(&data_path)?;
        return Ok(true);
    }
    Ok(false)
}
fn make_data_path(
    base_path: &str,
    sub_dir: &str,
    should_reset_if_existing: bool,
) -> Result<PathBuf> {
    let data_path = sanitize(base_path, sub_dir);

    if should_reset_if_existing && Path::new(&data_path).try_exists()? {
        let backup_path = sanitize(
            base_path,
            &format!("{sub_dir}_backup_{}", Local::now().to_rfc3339()),
        );
        tracing::warn!("{data_path:?} already existing. Moving to backup at {backup_path:?}.");
        std::fs::rename(&data_path, backup_path)?;
    }
    std::fs::create_dir_all(&data_path)?;
    anyhow::Ok(data_path)
}

pub async fn new_client_config(
    db_base_path: String,
    home_dir: String,
    media_cache_base_path: String,
    db_passphrase: Option<String>,
    reset_if_existing: bool,
) -> Result<ClientBuilder> {
    let media_cached_path = make_data_path(&media_cache_base_path, &home_dir, false)?;
    RUNTIME
        .spawn(async move {
            let data_path = make_data_path(&db_base_path, &home_dir, reset_if_existing)?;

            let config = match make_store_config(
                &data_path,
                media_cached_path.clone(),
                db_passphrase.as_deref(),
            )
            .await
            {
                Err(MakeStoreConfigError::OpenStoreError(OpenStoreError::InitCipher(e))) => {
                    tracing::warn!("Failed to initialize cipher: {e}");
                    let data_path = make_data_path(&db_base_path, &home_dir, true)?; // try resetting the path and do it again.
                    make_store_config(&data_path, media_cached_path, db_passphrase.as_deref())
                        .await?
                }
                Err(e) => {
                    tracing::warn!("Failed to open database: {e}");
                    return Err(e.into());
                }
                Ok(config) => config,
            };
            let builder = Client::builder()
                .store_config(config)
                .user_agent(format!("acter-testing/{:}", env!("CARGO_PKG_VERSION")));
            Ok(builder)
        })
        .await?
}

lazy_static! {
    static ref FILE_LOGGER: Mutex<Option<Arc<fern::ImplDispatch>>> = Mutex::new(None);
}

#[cfg(feature = "tracing")]
pub fn init_logging(
    log_dir: String,
    filter: String,
    console_logger: Option<Box<dyn Log>>,
) -> Result<()> {
    use tracing_subscriber::layer::SubscriberExt;

    let file_appender = tracing_appender::rolling::minutely(log_dir, "acter-tracing.log");
    let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);

    let subscriber = tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(filter))
        .with(tracing_subscriber::fmt::Layer::new().with_writer(non_blocking))
        .with(tracing_subscriber::fmt::Layer::new().with_writer(std::io::stdout));

    tracing_log::LogTracer::init()?;
    #[cfg(feature = "tracing-console")]
    {
        let console_layer = console_subscriber::spawn();
        tracing::subscriber::set_global_default(subscriber.with(console_layer))?;
    }
    #[cfg(not(feature = "tracing-console"))]
    tracing::subscriber::set_global_default(subscriber)?;

    Ok(())
}

#[cfg(not(feature = "tracing"))]
pub fn init_logging(
    log_dir: String,
    filter: String,
    console_logger: Option<Box<dyn Log>>,
) -> Result<()> {
    std::env::set_var("RUST_BACKTRACE", "1");
    log_panics::init();

    let mut builder = fern::Dispatch::new().format(|out, message, record| {
        out.finish(format_args!(
            "{}[{}][{}] {}",
            Local::now().format("[%Y-%m-%d][%H:%M:%S%.6f]"),
            record.target(),
            record.level(),
            message
        ))
    });

    let Ok(items) = filters(&filter) else {
        bail!("Parsing log filters failed");
    };
    for Filter {
        target,
        span,
        level,
    } in items
    {
        match level {
            Some(level) => {
                if let Some(level) = get_log_filter(level) {
                    // Add level filter per module
                    builder = builder.level_for(target.to_owned(), level);
                }
            }
            None => {
                if let Some(level) = get_log_filter(target) {
                    // Add blanket level filter
                    builder = builder.level(level);
                }
            }
        }
    }

    // Output to console
    if let Some(console_logger) = console_logger {
        builder = builder.chain(console_logger);
    } else {
        builder = builder.chain(std::io::stdout());
    }

    let mut path = PathBuf::from(&log_dir);
    path.push("app_");

    let (level, dispatch) = builder
        // Output to file
        .chain(fern::Manual::new(path, "%Y-%m-%d_%H-%M-%S%.f.log"))
        .into_dispatch_with_arc();

    if level == LevelFilter::Off {
        log::set_boxed_logger(Box::new(NopLogger))?;
    } else {
        log::set_boxed_logger(Box::new(dispatch.clone()))?;
    }
    log::set_max_level(level);

    *FILE_LOGGER.lock().unwrap() = Some(dispatch);

    Ok(())
}

pub fn rotate_log_file() -> Result<String> {
    match &*FILE_LOGGER.lock().unwrap() {
        Some(dispatch) => {
            for output in dispatch.rotate().iter() {
                let Some((old_path, new_path)) = output else {
                    continue;
                };
                return Ok(old_path.to_string_lossy().to_string());
            }
        }
        None => {
            bail!("You didn’t set up file logger.");
        }
    }
    Ok("".to_string())
}

fn parse_log_level(level: &str) -> Level {
    match level {
        "debug" => Level::Debug,
        "error" => Level::Error,
        "info" => Level::Info,
        "warn" => Level::Warn,
        _ => Level::Trace,
    }
}

pub fn would_log(target: String, level: String) -> bool {
    log_enabled!(target: &target, parse_log_level(&level))
}

pub fn write_log(
    target: String,
    level: String,
    message: String,
    file: Option<String>,
    line: Option<u32>,
    module_path: Option<String>,
) {
    log::logger().log(
        &Record::builder()
            .args(format_args!("{message}"))
            .level(parse_log_level(&level))
            .target(&target)
            .file(file.as_deref())
            .line(line)
            .module_path(module_path.as_deref())
            .build(),
    );
}

pub fn sanitize(base_path: &str, home: &str) -> PathBuf {
    PathBuf::from(base_path).join(sanitize_filename_reader_friendly::sanitize(home))
}

struct NopLogger;

impl Log for NopLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        false
    }

    fn log(&self, record: &Record) {}

    fn flush(&self) {}
}

fn get_log_filter(level: &str) -> Option<LevelFilter> {
    match level {
        "debug" => Some(LevelFilter::Debug),
        "error" => Some(LevelFilter::Error),
        "info" => Some(LevelFilter::Info),
        "warn" => Some(LevelFilter::Warn),
        "trace" => Some(LevelFilter::Trace),
        _ => None,
    }
}

#[derive(Debug)]
enum MakeStoreConfigError {
    OpenStoreError(OpenStoreError),
    EventCacheStoreError(EventCacheStoreError),
}

impl Display for MakeStoreConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MakeStoreConfigError::OpenStoreError(i) => {
                write!(f, "MakeStoreConfigError::OpenStoreError {}", i)
            }
            MakeStoreConfigError::EventCacheStoreError(i) => {
                write!(f, "MakeStoreConfigError::EventCacheStoreError {}", i)
            }
        }
    }
}

impl std::error::Error for MakeStoreConfigError {}

impl From<OpenStoreError> for MakeStoreConfigError {
    fn from(value: OpenStoreError) -> Self {
        MakeStoreConfigError::OpenStoreError(value)
    }
}

impl From<EventCacheStoreError> for MakeStoreConfigError {
    fn from(value: EventCacheStoreError) -> Self {
        MakeStoreConfigError::EventCacheStoreError(value)
    }
}

async fn make_store_config(
    path: &Path,
    media_cache_path: PathBuf,
    passphrase: Option<&str>,
) -> Result<StoreConfig, MakeStoreConfigError> {
    // FIXME: this stock holder name probably needs to be decided upon
    //        by the outer part to inform us whether this is the main
    //        process or the background job
    let config = StoreConfig::new("acter".to_owned())
        .crypto_store(SqliteCryptoStore::open(path, passphrase).await?);

    let sql_state_store = SqliteStateStore::open(path, passphrase).await?;
    let event_cache_store = SqliteEventCacheStore::open(path, passphrase).await?;
    let Some(passphrase) = passphrase else {
        return Ok(config
            .state_store(sql_state_store)
            .event_cache_store(event_cache_store));
    };

    let event_cache_store = matrix_sdk_store_file_event_cache::wrap_with_file_cache_and_limits(
        &sql_state_store,
        event_cache_store,
        media_cache_path,
        passphrase,
        #[cfg(target_os = "ios")]
        50,
        #[cfg(not(target_os = "ios"))]
        200,
    )
    .await?;
    Ok(config
        .state_store(sql_state_store)
        .event_cache_store(event_cache_store))
}