data_backup_restore.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. //! Example for restoring a data backup.
  2. #![expect(unused_crate_dependencies, reason = "Example triggered false positive")]
  3. mod utils;
  4. use std::{
  5. collections::{HashMap, HashSet},
  6. fs,
  7. io::{self, Read as _, Seek as _},
  8. path,
  9. sync::{Arc, Mutex},
  10. };
  11. use clap::Parser;
  12. use libthreema::{
  13. common::{ConversationId, DistributionListId, GroupIdentity, MessageId, ThreemaId},
  14. data_backup::task::{
  15. DataBackupProviders,
  16. restore::{
  17. DataBackupRestoreLocalReadInstruction, DataBackupRestoreLoop, DataBackupRestoreReadInstruction,
  18. DataBackupRestoreReadResponse, DataBackupRestoreResponse, DataBackupRestoreTask,
  19. },
  20. },
  21. model::{poll::PollId, settings::Settings},
  22. protobuf,
  23. utils::logging::init_stderr_logging,
  24. };
  25. use tracing::{Level, debug, info};
  26. use crate::{
  27. provider::{
  28. RestoreContactProvider, RestoreConversationProvider, RestoreDistributionListProvider,
  29. RestoreGroupProvider, RestoreNonceProvider, RestorePollProvider, RestoreSettingsProvider,
  30. RestoreUserProfileProvider,
  31. },
  32. utils::sync::MutexPoisonPanic as _,
  33. };
  34. mod provider {
  35. //! Provider implementations for the backup restore example.
  36. //!
  37. //! _Note: We are only interested in ensuring that the backup was correct, the actual data (profile
  38. //! pictures, messages, etc.) don't matter. We therefore keep only the minimal required information to
  39. //! do all checks required in the steps._
  40. #![expect(clippy::unimplemented, reason = "Unused methods for backup restore")]
  41. use std::{
  42. collections::{HashMap, HashSet},
  43. sync::{Arc, Mutex},
  44. };
  45. use libthreema::{
  46. common::{
  47. ConversationId, ConversationType, DistributionListId, GroupIdentity, HashedNonce, MessageId,
  48. ThreemaId,
  49. },
  50. model::{
  51. contact::{Contact, ContactProvider, ContactWithProfilePictures},
  52. conversation::ConversationProvider,
  53. distribution_list::{DistributionList, DistributionListProvider},
  54. group::{GroupMembershipFilter, GroupProvider, GroupWithProfilePicture},
  55. message::{MessageState, MessageStateMetadata, MessageStateUpdate},
  56. poll::{Poll, PollId, PollProvider, PollVotes},
  57. profile::ProfilePicture,
  58. settings::{Settings, SettingsProvider, SettingsUpdate},
  59. user_profile::{UserProfile, UserProfileProvider},
  60. },
  61. protobuf,
  62. provider::{NonceProvider, ProviderError},
  63. };
  64. use tracing::debug;
  65. use crate::utils::sync::MutexPoisonPanic as _;
  66. pub(super) struct RestoreContactProvider {
  67. pub(super) contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  68. pub(super) user_identity: ThreemaId,
  69. }
  70. impl ContactProvider for RestoreContactProvider {
  71. fn add(&mut self, _contacts: Vec<Contact>) -> Result<(), ProviderError> {
  72. unimplemented!("Not needed for backup restore");
  73. }
  74. fn add_with_profile_pictures(
  75. &mut self,
  76. contacts: Vec<ContactWithProfilePictures>,
  77. ) -> Result<(), ProviderError> {
  78. debug!("Adding {} contacts", contacts.len());
  79. let mut contact_storage = self.contacts.lock_unwrap();
  80. for contact in &contacts {
  81. // Bail if the contact's identity is the user's identity.
  82. if contact.contact.identity == self.user_identity {
  83. return Err(ProviderError::ContractViolation(
  84. "Unexpected encounter of user's identity in contact provider".to_owned(),
  85. ));
  86. }
  87. // Bail if the contact already exists.
  88. if contact_storage.contains_key(&contact.contact.identity) {
  89. return Err(ProviderError::ContractViolation(format!(
  90. "Contact {} to be added already exists",
  91. contact.contact.identity
  92. )));
  93. }
  94. }
  95. // Add all contacts.
  96. contact_storage.extend(
  97. contacts
  98. .into_iter()
  99. .map(|contact| (contact.contact.identity, contact.contact.acquaintance_level)),
  100. );
  101. Ok(())
  102. }
  103. fn set_contact_defined_profile_picture(
  104. &self,
  105. _identity: ThreemaId,
  106. _profile_picture: Option<ProfilePicture>,
  107. ) -> Result<(), ProviderError> {
  108. unimplemented!("Not needed for backup restore");
  109. }
  110. fn set_user_defined_profile_picture(
  111. &self,
  112. _identity: ThreemaId,
  113. _profile_picture: Option<ProfilePicture>,
  114. ) -> Result<(), ProviderError> {
  115. unimplemented!("Not needed for backup restore");
  116. }
  117. fn update(
  118. &mut self,
  119. _updates: Vec<libthreema::model::contact::ContactUpdate>,
  120. ) -> Result<(), ProviderError> {
  121. unimplemented!("Not needed for backup restore");
  122. }
  123. fn count_existing(&self, _identities: &[ThreemaId]) -> Result<usize, ProviderError> {
  124. unimplemented!("Not needed for backup restore");
  125. }
  126. fn get(&self, _identity: ThreemaId) -> Result<Option<Contact>, ProviderError> {
  127. unimplemented!("Not needed for backup restore");
  128. }
  129. fn get_identities(&self) -> Result<HashSet<ThreemaId>, ProviderError> {
  130. Ok(self.contacts.lock_unwrap().keys().copied().collect())
  131. }
  132. fn get_with_profile_pictures(
  133. &self,
  134. _identity: ThreemaId,
  135. ) -> Result<Option<ContactWithProfilePictures>, ProviderError> {
  136. unimplemented!("Not needed for backup restore");
  137. }
  138. fn is_explicitly_blocked(&self, _identity: ThreemaId) -> Result<bool, ProviderError> {
  139. unimplemented!("Not needed for backup restore");
  140. }
  141. fn has(&self, _identity: ThreemaId) -> Result<bool, ProviderError> {
  142. unimplemented!("Not needed for backup restore");
  143. }
  144. }
  145. pub(super) struct RestoreGroupProvider {
  146. pub(super) groups: Arc<Mutex<HashMap<GroupIdentity, HashSet<ThreemaId>>>>,
  147. pub(super) user_identity: ThreemaId,
  148. pub(super) contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  149. }
  150. impl GroupProvider for RestoreGroupProvider {
  151. fn add_with_profile_picture(
  152. &mut self,
  153. mut groups: Vec<GroupWithProfilePicture>,
  154. ) -> Result<(), ProviderError> {
  155. let mut group_storage = self.groups.lock_unwrap();
  156. let contacts = self.contacts.lock_unwrap();
  157. for group in &mut groups {
  158. let group_id = group.group.identity;
  159. // Bail if the group already exists.
  160. if group_storage.contains_key(&group_id) {
  161. return Err(ProviderError::ContractViolation(format!(
  162. "Group {group_id} already exists"
  163. )));
  164. }
  165. // Bail if creator is neither the user nor a known contact.
  166. if !(group_id.creator_identity == self.user_identity
  167. || contacts.contains_key(&group_id.creator_identity))
  168. {
  169. return Err(ProviderError::ContractViolation(format!(
  170. "Creator of group {group_id} is not known"
  171. )));
  172. }
  173. // Bail if a member's identity is the user's identity or refers to an unknown contact.
  174. for member in &group.group.members {
  175. if *member == self.user_identity {
  176. return Err(ProviderError::ContractViolation(format!(
  177. "Unexpected encounter of user's identity in members of group {group_id}"
  178. )));
  179. }
  180. if !contacts.contains_key(member) {
  181. return Err(ProviderError::ContractViolation(format!(
  182. "Member of group {group_id} is not known"
  183. )));
  184. }
  185. }
  186. }
  187. // Add all groups.
  188. group_storage.extend(
  189. groups
  190. .into_iter()
  191. .map(|group| (group.group.identity, group.group.members)),
  192. );
  193. Ok(())
  194. }
  195. fn set_profile_picture(
  196. &mut self,
  197. _identity: GroupIdentity,
  198. _profile_picture: Option<ProfilePicture>,
  199. ) -> Result<(), ProviderError> {
  200. unimplemented!("Not needed for backup restore");
  201. }
  202. fn update(
  203. &mut self,
  204. _updates: Vec<libthreema::model::group::GroupUpdate>,
  205. ) -> Result<(), ProviderError> {
  206. unimplemented!("Not needed for backup restore");
  207. }
  208. fn get(
  209. &self,
  210. _identity: GroupIdentity,
  211. ) -> Result<Option<libthreema::model::group::Group>, ProviderError> {
  212. unimplemented!("Not needed for backup restore");
  213. }
  214. fn get_identities(&self) -> Result<HashSet<GroupIdentity>, ProviderError> {
  215. unimplemented!("Not needed for backup restore");
  216. }
  217. fn get_with_profile_picture(
  218. &self,
  219. _identity: GroupIdentity,
  220. ) -> Result<Option<GroupWithProfilePicture>, ProviderError> {
  221. unimplemented!("Not needed for backup restore");
  222. }
  223. fn has(&self, _identity: GroupIdentity) -> Result<bool, ProviderError> {
  224. unimplemented!("Not needed for backup restore");
  225. }
  226. fn is_part_of_any_group(
  227. &self,
  228. _identity: ThreemaId,
  229. _filter: GroupMembershipFilter,
  230. ) -> Result<bool, ProviderError> {
  231. unimplemented!("Not needed for backup restore");
  232. }
  233. }
  234. pub(super) struct RestoreDistributionListProvider {
  235. pub(super) distribution_lists: Arc<Mutex<HashMap<DistributionListId, HashSet<ThreemaId>>>>,
  236. pub(super) user_identity: ThreemaId,
  237. pub(super) contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  238. }
  239. impl DistributionListProvider for RestoreDistributionListProvider {
  240. fn add(&mut self, distribution_lists: Vec<DistributionList>) -> Result<(), ProviderError> {
  241. debug!("Adding {} distribution lists", distribution_lists.len());
  242. let mut distribution_list_storage = self.distribution_lists.lock_unwrap();
  243. let contacts = self.contacts.lock_unwrap();
  244. for distribution_list in &distribution_lists {
  245. let distribution_list_id = distribution_list.identity;
  246. // Bail if distribution list already exists.
  247. if distribution_list_storage.contains_key(&distribution_list_id) {
  248. return Err(ProviderError::ContractViolation(format!(
  249. "Distribution list {distribution_list_id} already exists"
  250. )));
  251. }
  252. // Bail if a member's identity is the user's identity or refers to an unknown contact.
  253. for member in &distribution_list.members {
  254. if *member == self.user_identity {
  255. return Err(ProviderError::ContractViolation(format!(
  256. "Distribution list {distribution_list_id} references user in members",
  257. )));
  258. }
  259. if !contacts.contains_key(member) {
  260. return Err(ProviderError::ContractViolation(format!(
  261. "Distribution list {distribution_list_id} references unknown member {member}"
  262. )));
  263. }
  264. }
  265. }
  266. // Add all distribution lists.
  267. distribution_list_storage.extend(
  268. distribution_lists
  269. .into_iter()
  270. .map(|distribution_list| (distribution_list.identity, distribution_list.members)),
  271. );
  272. Ok(())
  273. }
  274. fn get(&self, _identity: DistributionListId) -> Result<Option<DistributionList>, ProviderError> {
  275. unimplemented!("Not needed for backup restore");
  276. }
  277. fn get_ids(&self) -> Result<HashSet<DistributionListId>, ProviderError> {
  278. unimplemented!("Not needed for backup restore");
  279. }
  280. }
  281. pub(super) struct RestoreSettingsProvider {
  282. pub(super) settings: Arc<Mutex<Settings>>,
  283. }
  284. impl SettingsProvider for RestoreSettingsProvider {
  285. fn set(&mut self, settings: Settings) -> Result<(), ProviderError> {
  286. debug!(?settings, "Settings restored");
  287. *self.settings.lock_unwrap() = settings;
  288. Ok(())
  289. }
  290. fn update(&mut self, _update: SettingsUpdate) -> Result<(), ProviderError> {
  291. unimplemented!("Not needed for backup restore");
  292. }
  293. fn get(&self) -> Result<Settings, ProviderError> {
  294. unimplemented!("Not needed for backup restore");
  295. }
  296. }
  297. pub(super) struct RestoreUserProfileProvider;
  298. impl UserProfileProvider for RestoreUserProfileProvider {
  299. fn get(&self) -> Result<UserProfile, ProviderError> {
  300. unimplemented!("Not needed for backup restore");
  301. }
  302. fn set(&mut self, user_profile: UserProfile) -> Result<(), ProviderError> {
  303. debug!(?user_profile, "Set user profile");
  304. Ok(())
  305. }
  306. }
  307. pub(super) struct RestoreConversationProvider {
  308. pub(super) contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  309. pub(super) groups: Arc<Mutex<HashMap<GroupIdentity, HashSet<ThreemaId>>>>,
  310. pub(super) messages: Arc<Mutex<HashSet<(ConversationId, MessageId)>>>,
  311. pub(super) distribution_lists: Arc<Mutex<HashMap<DistributionListId, HashSet<ThreemaId>>>>,
  312. }
  313. impl ConversationProvider for RestoreConversationProvider {
  314. fn add_messages(&mut self, messages: Vec<MessageState>) -> Result<(), ProviderError> {
  315. debug!("Adding {} message states", messages.len());
  316. let contacts = self.contacts.lock_unwrap();
  317. let groups = self.groups.lock_unwrap();
  318. let distribution_lists = self.distribution_lists.lock_unwrap();
  319. let mut registered_messages = self.messages.lock_unwrap();
  320. for message in &messages {
  321. // Check whether the referred contact/distribution list/group exists and is in the expected
  322. // state.
  323. match &message.conversation_id {
  324. ConversationId::Contact(identity) => {
  325. let Some(contact) = contacts.get(identity) else {
  326. return Err(ProviderError::ContractViolation(format!(
  327. "Contact {identity} does not exist",
  328. )));
  329. };
  330. if !matches!(*contact, protobuf::d2d_sync::contact::AcquaintanceLevel::Direct) {
  331. return Err(ProviderError::ContractViolation(format!(
  332. "Contact {identity} does not have acquaintance level direct",
  333. )));
  334. }
  335. },
  336. ConversationId::DistributionList(distribution_list_id) => {
  337. if !distribution_lists.contains_key(distribution_list_id) {
  338. return Err(ProviderError::ContractViolation(format!(
  339. "Distribution list {distribution_list_id} does not exist"
  340. )));
  341. }
  342. },
  343. ConversationId::Group(group_identity) => {
  344. if !groups.contains_key(group_identity) {
  345. return Err(ProviderError::ContractViolation(format!(
  346. "Group {group_identity} does not exist",
  347. )));
  348. }
  349. },
  350. }
  351. // Check if the message was already added to the conversation.
  352. if registered_messages.contains(&(message.conversation_id, message.message_id)) {
  353. return Err(ProviderError::ContractViolation(format!(
  354. "Message {} already exists in conversation {}",
  355. message.message_id, message.conversation_id,
  356. )));
  357. }
  358. }
  359. // Add all message states to the corresponding conversation.
  360. for message in messages {
  361. let _ = registered_messages.insert((message.conversation_id, message.message_id));
  362. }
  363. Ok(())
  364. }
  365. fn set_typing_indicator(
  366. &mut self,
  367. _sender_identity: ThreemaId,
  368. _is_typing: bool,
  369. ) -> Result<(), ProviderError> {
  370. unimplemented!("Not needed for backup restore");
  371. }
  372. fn update_messages(&mut self, _updates: Vec<MessageStateUpdate>) -> Result<(), ProviderError> {
  373. unimplemented!("Not needed for backup restore");
  374. }
  375. fn get_many_messages(
  376. &self,
  377. _conversation_type: ConversationType,
  378. _batch_index: usize,
  379. ) -> Result<Vec<MessageState>, ProviderError> {
  380. unimplemented!("Not needed for backup restore");
  381. }
  382. fn get_messages_metadata(
  383. &self,
  384. _conversation_id: ConversationId,
  385. _message_ids: &[MessageId],
  386. ) -> Result<Vec<MessageStateMetadata>, ProviderError> {
  387. unimplemented!("Not needed for backup restore");
  388. }
  389. fn is_message_marked_used(
  390. &self,
  391. _sender_identity: ThreemaId,
  392. _message_id: MessageId,
  393. ) -> Result<bool, ProviderError> {
  394. unimplemented!("Not needed for backup restore");
  395. }
  396. }
  397. pub(super) struct RestorePollProvider {
  398. pub(super) user_identity: ThreemaId,
  399. pub(super) contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  400. pub(super) groups: Arc<Mutex<HashMap<GroupIdentity, HashSet<ThreemaId>>>>,
  401. pub(super) polls: Arc<Mutex<HashSet<(ConversationId, PollId)>>>,
  402. }
  403. impl PollProvider for RestorePollProvider {
  404. fn get_many(&self, _batch_index: usize) -> Result<Vec<Poll>, ProviderError> {
  405. unimplemented!("Not needed for backup restore");
  406. }
  407. fn add(&mut self, polls: Vec<Poll>) -> Result<(), ProviderError> {
  408. debug!("Adding {} polls", polls.len());
  409. let contacts = self.contacts.lock_unwrap();
  410. let groups = self.groups.lock_unwrap();
  411. let mut polls_storage = self.polls.lock_unwrap();
  412. for poll in &polls {
  413. let poll_id = poll.id;
  414. // Bail if referred conversation does not exist or if it is a distribution list.
  415. match poll.conversation {
  416. ConversationId::Contact(contact) => {
  417. if !contacts.contains_key(&contact) {
  418. return Err(ProviderError::ContractViolation(format!(
  419. "Poll {poll_id} references an unknown contact conversation {contact}",
  420. )));
  421. }
  422. },
  423. ConversationId::DistributionList(_) => {
  424. return Err(ProviderError::ContractViolation(format!(
  425. "Poll {poll_id} references a distribution list which is not supported",
  426. )));
  427. },
  428. ConversationId::Group(group_identity) => {
  429. if !groups.contains_key(&group_identity) {
  430. return Err(ProviderError::ContractViolation(format!(
  431. "Poll {poll_id} references an unknown group {group_identity}",
  432. )));
  433. }
  434. },
  435. }
  436. // Bail if creator is neither the user nor a known contact.
  437. if poll.creator_identity != self.user_identity
  438. && !contacts.contains_key(&poll.creator_identity)
  439. {
  440. return Err(ProviderError::ContractViolation(format!(
  441. "Poll creator {} is unknown",
  442. poll.creator_identity,
  443. )));
  444. }
  445. // Bail if poll already exists.
  446. if polls_storage.contains(&(poll.conversation, poll_id)) {
  447. return Err(ProviderError::ContractViolation(format!(
  448. "Poll {poll_id} already exists",
  449. )));
  450. }
  451. // Bail if a voter refers to an unknown contact.
  452. if let PollVotes::Votes(voters) = &poll.votes {
  453. for voter in voters.keys() {
  454. if *voter != self.user_identity && !contacts.contains_key(voter) {
  455. return Err(ProviderError::ContractViolation(format!(
  456. "Poll {poll_id} contains voter {voter} that is not a known contact",
  457. )));
  458. }
  459. }
  460. }
  461. }
  462. // Add all polls.
  463. polls_storage.extend(polls.into_iter().map(|poll| (poll.conversation, poll.id)));
  464. Ok(())
  465. }
  466. }
  467. pub(super) struct RestoreNonceProvider {
  468. pub(super) nonce_counter: Arc<Mutex<usize>>,
  469. }
  470. impl NonceProvider for RestoreNonceProvider {
  471. fn has(&self, _hashed_nonce: &HashedNonce) -> Result<bool, ProviderError> {
  472. unimplemented!("Not needed for backup restore");
  473. }
  474. fn add_many(&mut self, hashed_nonces: Vec<HashedNonce>) -> Result<(), ProviderError> {
  475. let mut nonce_counter = self.nonce_counter.lock_unwrap();
  476. *nonce_counter = nonce_counter.saturating_add(hashed_nonces.len());
  477. Ok(())
  478. }
  479. fn get_many(&self, _batch_index: usize) -> Result<Vec<HashedNonce>, ProviderError> {
  480. unimplemented!("Not needed for backup restore");
  481. }
  482. }
  483. }
  484. struct FileReader {
  485. file: fs::File,
  486. }
  487. impl FileReader {
  488. fn new(path: &path::Path) -> anyhow::Result<Self> {
  489. Ok(Self {
  490. file: fs::OpenOptions::new().read(true).open(path)?,
  491. })
  492. }
  493. fn read_at(&mut self, offset: u64, length: usize) -> anyhow::Result<Vec<u8>> {
  494. let mut buffer = vec![0_u8; length];
  495. let _ = self.file.seek(io::SeekFrom::Start(offset))?;
  496. self.file.read_exact(&mut buffer)?;
  497. Ok(buffer)
  498. }
  499. fn handle(
  500. &mut self,
  501. read_instruction: &DataBackupRestoreLocalReadInstruction,
  502. ) -> anyhow::Result<DataBackupRestoreReadResponse> {
  503. Ok(DataBackupRestoreReadResponse {
  504. offset: read_instruction.offset,
  505. chunk: self.read_at(read_instruction.offset.0, read_instruction.length.try_into()?)?,
  506. })
  507. }
  508. }
  509. struct ExampleBackupRestorer {
  510. file_reader: FileReader,
  511. task: DataBackupRestoreTask,
  512. contacts: Arc<Mutex<HashMap<ThreemaId, protobuf::d2d_sync::contact::AcquaintanceLevel>>>,
  513. groups: Arc<Mutex<HashMap<GroupIdentity, HashSet<ThreemaId>>>>,
  514. distribution_lists: Arc<Mutex<HashMap<DistributionListId, HashSet<ThreemaId>>>>,
  515. messages: Arc<Mutex<HashSet<(ConversationId, MessageId)>>>,
  516. csp_nonces: Arc<Mutex<usize>>,
  517. polls: Arc<Mutex<HashSet<(ConversationId, PollId)>>>,
  518. }
  519. impl ExampleBackupRestorer {
  520. fn new(path: &path::Path, password: String) -> anyhow::Result<Self> {
  521. Ok(Self {
  522. file_reader: FileReader::new(path)?,
  523. task: DataBackupRestoreTask::new(password),
  524. contacts: Arc::new(Mutex::new(HashMap::new())),
  525. groups: Arc::new(Mutex::new(HashMap::new())),
  526. distribution_lists: Arc::new(Mutex::new(HashMap::new())),
  527. messages: Arc::new(Mutex::new(HashSet::new())),
  528. csp_nonces: Arc::new(Mutex::new(0)),
  529. polls: Arc::new(Mutex::new(HashSet::new())),
  530. })
  531. }
  532. fn create_providers(&self, user_identity: ThreemaId) -> DataBackupProviders {
  533. DataBackupProviders {
  534. user_profile: Arc::new(Mutex::new(RestoreUserProfileProvider {})),
  535. contacts: Arc::new(Mutex::new(RestoreContactProvider {
  536. contacts: Arc::clone(&self.contacts),
  537. user_identity,
  538. })),
  539. groups: Arc::new(Mutex::new(RestoreGroupProvider {
  540. groups: Arc::clone(&self.groups),
  541. user_identity,
  542. contacts: Arc::clone(&self.contacts),
  543. })),
  544. distribution_lists: Arc::new(Mutex::new(RestoreDistributionListProvider {
  545. distribution_lists: Arc::clone(&self.distribution_lists),
  546. user_identity,
  547. contacts: Arc::clone(&self.contacts),
  548. })),
  549. csp_nonces: Arc::new(Mutex::new(RestoreNonceProvider {
  550. nonce_counter: Arc::clone(&self.csp_nonces),
  551. })),
  552. polls: Arc::new(Mutex::new(RestorePollProvider {
  553. user_identity,
  554. polls: Arc::clone(&self.polls),
  555. contacts: Arc::clone(&self.contacts),
  556. groups: Arc::clone(&self.groups),
  557. })),
  558. settings: Arc::new(Mutex::new(RestoreSettingsProvider {
  559. settings: Arc::new(Mutex::new(Settings::default())),
  560. })),
  561. conversations: Arc::new(Mutex::new(RestoreConversationProvider {
  562. messages: Arc::clone(&self.messages),
  563. contacts: Arc::clone(&self.contacts),
  564. groups: Arc::clone(&self.groups),
  565. distribution_lists: Arc::clone(&self.distribution_lists),
  566. })),
  567. }
  568. }
  569. fn run(mut self) -> anyhow::Result<()> {
  570. info!("Restoring backup");
  571. loop {
  572. match self.task.poll()? {
  573. DataBackupRestoreLoop::Instruction(instruction) => {
  574. // Handle any identity data.
  575. let providers = instruction.identity_data.map(|identity_data| {
  576. debug!(?identity_data, "Restored identity data");
  577. self.create_providers(identity_data.user_identity)
  578. });
  579. // Handle any state update.
  580. if let Some(state_update) = instruction.state_update {
  581. debug!(?state_update, "Changed state");
  582. }
  583. // Handle any read instruction.
  584. let read_response = match instruction.read_instruction {
  585. Some(DataBackupRestoreReadInstruction::Local(read_instruction)) => {
  586. Some(self.file_reader.handle(&read_instruction)?)
  587. },
  588. None => None,
  589. };
  590. // Provide response.
  591. self.task.response(DataBackupRestoreResponse {
  592. providers,
  593. read_response,
  594. })?;
  595. },
  596. DataBackupRestoreLoop::Done(()) => {
  597. info!(
  598. "Successfully restored {} contacts, {} groups, {} distribution lists, {} messages, \
  599. {} polls, {} csp nonces",
  600. self.contacts.lock_unwrap().len(),
  601. self.groups.lock_unwrap().len(),
  602. self.distribution_lists.lock_unwrap().len(),
  603. self.messages.lock_unwrap().len(),
  604. self.polls.lock_unwrap().len(),
  605. self.csp_nonces.lock_unwrap(),
  606. );
  607. return Ok(());
  608. },
  609. }
  610. }
  611. }
  612. }
  613. #[derive(Parser)]
  614. #[command()]
  615. struct DataBackupCommand {
  616. /// Path to the backup file.
  617. #[arg(short, long)]
  618. path: path::PathBuf,
  619. /// Password used for the backup to be restored.
  620. #[arg(long)]
  621. password: String,
  622. /// Turn on debugging information.
  623. /// Use -v -vv to control log level.
  624. #[arg(short, action = clap::ArgAction::Count)]
  625. verbose: u8,
  626. }
  627. fn main() -> anyhow::Result<()> {
  628. let arguments = DataBackupCommand::parse();
  629. let log_level = match arguments.verbose {
  630. 1 => Level::DEBUG,
  631. 2 => Level::TRACE,
  632. _ => Level::INFO,
  633. };
  634. init_stderr_logging(log_level);
  635. ExampleBackupRestorer::new(&arguments.path, arguments.password)?.run()?;
  636. Ok(())
  637. }
  638. #[cfg(test)]
  639. mod tests {
  640. use crate::DataBackupCommand;
  641. #[test]
  642. fn verify_cli() {
  643. use clap::CommandFactory;
  644. DataBackupCommand::command().debug_assert();
  645. }
  646. }