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
//! # DJILog Parser Module
//!
//! This module provides functionality for parsing DJI log files.
//!
//! ## Encryption in Version 13 and Later
//! Starting with version 13, log records are AES encrypted and require a specific keychain
//! for decryption. This keychain must be obtained from DJI using their API. An apiKey is
//! necessary to access the DJI API.
//!
//! Once keychains are retrieved, they can be stored along with the original log for further
//! offline use.
//!
//! ### Obtaining an ApiKey
//! To acquire an apiKey, follow these steps:
//! 1. Visit [DJI Developer Technologies](https://developer.dji.com/user) and log in.
//! 2. Click `CREATE APP`, choose `Open API` as the App Type, and provide the necessary
//!    details like `App Name`, `Category`, and `Description`.
//! 3. After creating the app, activate it through the link sent to your email.
//! 4. On your developer user page, find your app's details to retrieve the ApiKey
//!    (labeled as the SDK key).
//!
//! ## Usage
//!
//! ### Initialization
//! Initialize a `DJILog` instance from a byte slice to access version information and metadata:
//! ```
//! let parser = DJILog::from_bytes(bytes).unwrap();
//! ```
//!
//! ### Access general data
//!
//! General data are not encrypted and can be accessed from the parser for all log versions:
//!
//! ```
//! // Print the log version
//! println!("Version: {:?}", parser.version);
//!
//! // Print the log details section
//! println!("Details: {}", parser.details);
//! ```
//!
//! ### Retrieve keychains
//!
//! For logs version 13 and later, keychains must be retrieved from the DJI API to decode the records:
//!
//! ```
//! // Replace `__DJI_API_KEY__` with your actual apiKey
//! let keychains = parser.fetch_keychains("__DJI_API_KEY__").unwrap();
//! ```
//!
//! Keychains can be retrieved once, serialized, and stored along with the log file for future offline use.
//!
//! ### Accessing Frames
//!
//! Decrypt frames based on the log file version.
//!
//! A `Frame` is a standardized representation of log data, normalized across different log versions.
//! It provides a consistent and easy-to-use format for analyzing and processing DJI log information.
//!
//! For versions prior to 13:
//!
//! ```
//! let frames = parser.frames(None);
//! ```
//!
//! For version 13 and later:
//!
//! ```
//! let frames = parser.frames(Some(keychains));
//! ```
//!
//! ### Accessing raw Records
//!
//! Decrypt raw records based on the log file version.
//! For versions prior to 13:
//!
//! ```
//! let records = parser.records(None);
//! ```
//!
//! For version 13 and later:
//!
//! ```
//! let records = parser.records(Some(keychains));
//! ```
//!
//!
//! ## Binary structure of log files:
//!
//! v1 -> v6
//! ```text
//! ┌─────────────────┐
//! │     Prefix      │ detail_offset ─┐
//! ├─────────────────┤                │
//! │     Records     │                │
//! ├─────────────────┤<───────────────┘
//! │     Details     │ detail_length
//! └─────────────────┘
//! ```
//!
//! v7 -> v11
//! ```text
//! ┌─────────────────┐
//! │     Prefix      │ detail_offset ─┐
//! ├─────────────────┤                │
//! │     Records     │                │
//! │   (Encrypted)   │                |
//! ├─────────────────┤<───────────────┘
//! │     Details     │ detail_length
//! └─────────────────┘
//!```
//!
//! v12
//! ```text
//! ┌─────────────────┐
//! │     Prefix      │ detail_offset ─┐
//! ├─────────────────┤                │
//! │      Details    │ detail_length  │
//! ├─────────────────┤                │
//! │     Records     │                │
//! │   (Encrypted)   │                │
//! └─────────────────┘<───────────────┘
//!```
//!
//! v13 -> v14
//! ```text
//! ┌─────────────────┐
//! │     Prefix      │ detail_offset ─┐
//! ├─────────────────┤                │
//! │ Auxiliary Info  |                |
//! │ (Encrypted      │ detail_length  │
//! │      Details)   |                |
//! ├─────────────────┤                │
//! │    Auxiliary    |                |
//! │     Version     |                │
//! ├─────────────────┤<───────────────┘
//! │     Records     │
//! │(Encrypted + AES)|
//! └─────────────────┘
//! ```
use base64::engine::general_purpose::STANDARD as Base64Standard;
use base64::Engine as _;
use binrw::io::Cursor;
use binrw::BinRead;
use std::cell::RefCell;
use std::collections::VecDeque;

mod decoder;
mod error;
pub mod frame;
pub mod keychain;
pub mod layout;
pub mod record;
mod utils;

pub use error::{Error, Result};
use frame::{records_to_frames, Frame};
use keychain::{EncodedKeychainFeaturePoint, Keychain, KeychainFeaturePoint, KeychainsRequest};
use layout::auxiliary::Auxiliary;
use layout::details::Details;
use layout::prefix::Prefix;
use record::Record;

use crate::utils::pad_with_zeros;

#[derive(Debug)]
pub struct DJILog {
    inner: Vec<u8>,
    prefix: Prefix,
    /// Log format version
    pub version: u8,
    /// Log Details. Contains record summary and general informations
    pub details: Details,
}

impl DJILog {
    /// Constructs a `DJILog` from an array of bytes.
    ///
    /// This function parses the Prefix and Info blocks of the log file,
    /// and handles different versions of the log format.
    ///
    /// # Arguments
    ///
    /// * `bytes` - An array of bytes representing the DJI log file.
    ///
    /// # Returns
    ///
    /// This function returns `Result<DJILog>`.
    /// On success, it returns the `DJILog` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use djilog_parser::DJILog;
    ///
    /// let log_bytes = include_bytes!("path/to/log/file");
    /// let log = DJILog::from_bytes(log_bytes).unwrap();
    /// ```
    ///
    pub fn from_bytes(bytes: Vec<u8>) -> Result<DJILog> {
        // Decode Prefix
        let mut prefix = Prefix::read(&mut Cursor::new(&bytes))?;

        let version = prefix.version;

        // Decode Detail
        let detail_offset = prefix.detail_offset() as usize;
        let mut cursor = Cursor::new(pad_with_zeros(&bytes[detail_offset..], 400));

        let details = if version < 13 {
            Details::read_args(&mut cursor, (version,))?
        } else {
            // Get details from first auxiliary block
            if let Auxiliary::Info(data) = Auxiliary::read(&mut cursor)? {
                Details::read_args(&mut Cursor::new(&data.info_data), (version,))?
            } else {
                return Err(Error::MissingAuxilliaryData("Info".into()));
            }
        };

        // Try to recover detail offset
        if prefix.records_offset() == 0 && version >= 13 {
            // Skip second auxiliary block
            let _ = Auxiliary::read(&mut cursor)?;
            prefix.recover_detail_offset(cursor.position() + detail_offset as u64);
        }

        Ok(DJILog {
            inner: bytes,
            prefix,
            version,
            details,
        })
    }

    /// Creates a `KeychainsRequest` object by parsing `KeyStorage` records.
    ///
    /// This function is used to build a request body for manually retrieving the keychain from the DJI API.
    /// Keychains are required to decode records for logs with a version greater than or equal to 13.
    /// For earlier versions, this function returns a default `KeychainsRequest`.
    ///
    /// # Returns
    ///
    /// Returns a `Result<KeychainsRequest>`. On success, it provides a `KeychainsRequest`
    /// instance, which contains the necessary information to fetch keychains from the DJI API.
    ///
    pub fn keychains_request(&self) -> Result<KeychainsRequest> {
        let mut keychain_request = KeychainsRequest::default();

        // No keychain
        if self.version < 13 {
            return Ok(keychain_request);
        }

        let mut cursor = Cursor::new(&self.inner);
        cursor.set_position(self.prefix.detail_offset());

        // Skip first auxiliary block
        let _ = Auxiliary::read(&mut cursor)?;

        // Get version from second auxilliary block
        if let Auxiliary::Version(data) = Auxiliary::read(&mut cursor)? {
            keychain_request.version = data.version;
            keychain_request.department = data.department.into();
        } else {
            return Err(Error::MissingAuxilliaryData("Version".into()));
        }

        // Extract keychains from KeyStorage Records
        cursor.set_position(self.prefix.records_offset());

        let mut keychain: Vec<EncodedKeychainFeaturePoint> = Vec::new();

        while cursor.position() < self.prefix.records_end_offset(self.inner.len() as u64) {
            let empty_keychain = &RefCell::new(Keychain::empty());
            let record = match Record::read_args(
                &mut cursor,
                binrw::args! {
                    version: self.version,
                    keychain: empty_keychain
                },
            ) {
                Ok(record) => record,
                Err(_) => break,
            };

            match record {
                Record::KeyStorage(data) => {
                    // add EncodedKeychainFeaturePoint to current keychain
                    keychain.push(EncodedKeychainFeaturePoint {
                        feature_point: data.feature_point,
                        aes_ciphertext: Base64Standard.encode(&data.data),
                    });
                }
                Record::KeyStorageRecover(_) => {
                    // start a new keychain
                    keychain_request.keychains.push(keychain);
                    keychain = Vec::new();
                }
                _ => {}
            }
        }

        keychain_request.keychains.push(keychain);

        Ok(keychain_request)
    }

    /// Fetches keychains using the provided API key.
    ///
    /// This function first creates a `KeychainRequest` using the `keychain_request()` method,
    /// then uses that request to fetch the actual keychains from the DJI API.
    /// Keychains are required to decode records for logs with a version greater than or equal to 13.
    ///
    /// # Arguments
    ///
    /// * `api_key` - A string slice that holds the API key for authentication with the DJI API.
    ///
    /// # Returns
    ///
    /// Returns a `Result<Vec<Vec<KeychainFeaturePoint>>>`. On success, it provides a vector of vectors,
    /// where each inner vector represents a keychain.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn fetch_keychains(&self, api_key: &str) -> Result<Vec<Vec<KeychainFeaturePoint>>> {
        if self.version >= 13 {
            self.keychains_request()?.fetch(api_key)
        } else {
            Ok(Vec::new())
        }
    }

    /// Retrieves the parsed raw records from the DJI log.
    ///
    /// This function decodes the raw records from the log file
    ///
    /// # Arguments
    ///
    /// * `keychains` - An optional vector of vectors containing `KeychainFeaturePoint` instances. This parameter
    ///   is used for decryption when working with encrypted logs (versions >= 13). If `None` is provided,
    ///   the function will attempt to process the log without decryption.
    ///
    ///
    /// # Returns
    ///
    /// Returns a `Result<Vec<Record>>`. On success, it provides a vector of `Record`
    /// instances representing the parsed log records.
    ///
    pub fn records(
        &self,
        keychains: Option<Vec<Vec<KeychainFeaturePoint>>>,
    ) -> Result<Vec<Record>> {
        if self.version >= 13 && keychains.is_none() {
            return Err(Error::KeychainRequired);
        }

        let mut keychains = VecDeque::from(match keychains {
            Some(keychains) => keychains
                .iter()
                .map(Keychain::from_feature_points)
                .collect(),
            None => Vec::new(),
        });

        let mut cursor = Cursor::new(&self.inner);
        cursor.set_position(self.prefix.records_offset());

        let mut keychain = RefCell::new(keychains.pop_front().unwrap_or(Keychain::empty()));

        let mut records = Vec::new();

        while cursor.position() < self.prefix.records_end_offset(self.inner.len() as u64) {
            // decode record
            let record = match Record::read_args(
                &mut cursor,
                binrw::args! {
                    version: self.version,
                    keychain: &keychain
                },
            ) {
                Ok(record) => record,
                Err(_) => break,
            };

            if let Record::KeyStorageRecover(_) = record {
                keychain = RefCell::new(keychains.pop_front().unwrap_or(Keychain::empty()));
            }

            records.push(record);
        }

        Ok(records)
    }

    /// Retrieves the normalized frames from the DJI log.
    ///
    /// This function processes the raw records from the log file and converts them into standardized
    /// frames. Frames are a more user-friendly representation of the log data, normalized across all
    /// log versions for easier use and analysis.
    ///
    /// The function first decodes the raw records based on the specified decryption method, then
    /// converts these records into frames. This normalization process makes it easier to work with
    /// log data from different DJI log versions.
    ///
    /// # Arguments
    ///
    /// * `keychains` - An optional vector of vectors containing `KeychainFeaturePoint` instances. This parameter
    ///   is used for decryption when working with encrypted logs (versions >= 13). If `None` is provided,
    ///   the function will attempt to process the log without decryption.
    ///
    ///
    /// # Returns
    ///
    /// Returns a `Result<Vec<Frame>>`. On success, it provides a vector of `Frame`
    /// instances representing the normalized log data.
    ///
    /// # Note
    ///
    /// This method consumes and processes the raw records to create frames. It's generally preferred
    /// over using raw records directly, as frames provide a consistent format across different log
    /// versions, simplifying data analysis and interpretation.
    ///
    pub fn frames(&self, keychains: Option<Vec<Vec<KeychainFeaturePoint>>>) -> Result<Vec<Frame>> {
        let records = self.records(keychains)?;
        Ok(records_to_frames(records, self.details.clone()))
    }
}