~anteater/vgmms

c370de16ae9f996055767b06ac0e1da9d1d1fcbd — anteater 3 months ago 343e7a9
state.rs: rustfmt (mostly)
1 files changed, 70 insertions(+), 67 deletions(-)

M src/state.rs
M src/state.rs => src/state.rs +70 -67
@@ 23,9 23,7 @@ pub struct StateHandle {

impl Default for StateHandle {
	fn default() -> Self {
		StateHandle {
			state: Arc::clone(&GLOBAL_STATE),
		}
		StateHandle { state: Arc::clone(&GLOBAL_STATE) }
	}
}



@@ 77,7 75,7 @@ fn parse_date(date: &str) -> chrono::format::ParseResult<u64> {
	match chrono::DateTime::parse_from_rfc3339(&date) {
		Err(e) if e.to_string().contains("invalid") => {
			let mut date = date.to_owned();
			date.insert(date.len()-2, ':');
			date.insert(date.len() - 2, ':');
			chrono::DateTime::parse_from_rfc3339(&date)
		},
		Err(e) if e.to_string().contains("premature end") => {


@@ 86,7 84,8 @@ fn parse_date(date: &str) -> chrono::format::ParseResult<u64> {
			chrono::DateTime::parse_from_rfc3339(&date)
		},
		x => x,
	}.map(|x| x.timestamp() as u64)
	}
	.map(|x| x.timestamp() as u64)
}

#[test]


@@ 126,28 125,29 @@ impl VgmmsState {
	pub fn summarize_all(&self) -> Vec<(Chat, String, bool)> {
		let mut sorted = self.chats.iter().collect::<Vec<_>>();
		/* sort chats by highest timestamp, treating any as greater than none */
		sorted.sort_by(|(_c1, cs1), (_c2, cs2)| {
			match (&cs1.last_message, &cs2.last_message) {
				(Some((t1, _id1)), Some((t2, _id2))) => t2.cmp(t1),
				(Some(_), None) => std::cmp::Ordering::Less,
				(None, Some(_)) => std::cmp::Ordering::Greater,
				(None, None) => std::cmp::Ordering::Equal,
			}
		sorted.sort_by(|(_c1, cs1), (_c2, cs2)| match (&cs1.last_message, &cs2.last_message) {
			(Some((t1, _id1)), Some((t2, _id2))) => t2.cmp(t1),
			(Some(_), None) => std::cmp::Ordering::Less,
			(None, Some(_)) => std::cmp::Ordering::Greater,
			(None, None) => std::cmp::Ordering::Equal,
		});
		let atts = &self.attachments.read().unwrap();
		/* summarize each chat */
		sorted.into_iter().map(|(c, cs)| {
			let chat = c.clone();
			let (desc, unread) = match &cs.last_message {
				Some((ts, msg_id)) => {
					let summary = self.message_info.get(msg_id).map(|msg| msg.summarize_with_time(atts)).unwrap_or("".into());
					let unread = *ts > cs.last_read_timestamp.unwrap_or(0);
					(summary, unread)
				},
				_ => ("".into(), false),
			};
			(chat, desc, unread)
		}).collect()
		sorted
			.into_iter()
			.map(|(c, cs)| {
				let chat = c.clone();
				let (desc, unread) = match &cs.last_message {
					Some((ts, msg_id)) => {
						let summary = self.message_info.get(msg_id).map(|msg| msg.summarize_with_time(atts)).unwrap_or("".into());
						let unread = *ts > cs.last_read_timestamp.unwrap_or(0);
						(summary, unread)
					},
					_ => ("".into(), false),
				};
				(chat, desc, unread)
			})
			.collect()
	}

	pub fn add_message(&mut self, id: MessageId, message: MessageInfo) -> &mut MessageInfo {


@@ 201,13 201,13 @@ impl VgmmsState {
		self.db_conn.lock().unwrap()
	}

	pub fn chat_messages<'a>(&'a self, chat: &'a Chat) -> Option<impl
		DoubleEndedIterator<Item=(&MessageId, &MessageInfo)> +
		ExactSizeIterator<Item=(&MessageId, &MessageInfo)> +
		Clone + 'a> {
		self.chat_message_ids.get(chat).map(|mids| {
			mids.iter().map(move |&MessageTime(_t, ref id)| (id, self.message_info.get(id).unwrap()))
		})
	pub fn chat_messages<'a>(
		&'a self,
		chat: &'a Chat,
	) -> Option<impl DoubleEndedIterator<Item = (&MessageId, &MessageInfo)> + ExactSizeIterator<Item = (&MessageId, &MessageInfo)> + Clone + 'a> {
		self.chat_message_ids
			.get(chat)
			.map(|mids| mids.iter().map(move |&MessageTime(_t, ref id)| (id, self.message_info.get(id).unwrap())))
	}

	/** mark a chat as having been last read now. returns whether the unread state of the chat changed */


@@ 255,9 255,10 @@ impl VgmmsState {
			return None
		}
		let items = {
			draft_items.into_iter().map(|item| match item {
				DraftItem::Attachment(att) =>
					MessageItem::Attachment({
			draft_items
				.into_iter()
				.map(|item| match item {
					DraftItem::Attachment(att) => MessageItem::Attachment({
						let id = self.next_attachment_id();
						if let Err(e) = db::insert_attachment(&mut self.db_conn.lock().unwrap(), &id, &att) {
							eprintln!("error saving attachment: {}", e);


@@ 265,9 266,9 @@ impl VgmmsState {
						self.attachments.write().unwrap().insert(id, att);
						id
					}),
				DraftItem::Text(t) => MessageItem::Text(t),
					DraftItem::Text(t) => MessageItem::Text(t),
				})
			.collect()
				.collect()
		};

		let num = self.my_number;


@@ 342,9 343,7 @@ impl VgmmsState {
		/* handle the event */
		use self::dbus::ModemEvent::*;
		match notif.event {
			MessageStatusUpdate {
				id, status, attachment_update, text_update,
			} => {
			MessageStatusUpdate { id, status, attachment_update, text_update } => {
				if let Some(msg) = self.message_info.get_mut(&id) {
					/* update message status */
					println!("updating message {} status to {:?}", hex::encode(&id[..]), status);


@@ 378,10 377,15 @@ impl VgmmsState {
							a.name == b.name && a.len == b.len
						}

						let att_ids = msg.contents.iter().filter_map(|item| match item {
							MessageItem::Attachment(att_id) => Some(att_id),
							_ => None,
						}).copied().collect::<Vec<AttachmentId>>();
						let att_ids = msg
							.contents
							.iter()
							.filter_map(|item| match item {
								MessageItem::Attachment(att_id) => Some(att_id),
								_ => None,
							})
							.copied()
							.collect::<Vec<AttachmentId>>();

						for att_id in &att_ids {
							if let Some(old) = self.get_attachment(att_id) {


@@ 411,8 415,12 @@ impl VgmmsState {
				None
			},
			MmsReceived {
				id, date, subject: _, sender,
				recipients, attachments,
				id,
				date,
				subject: _,
				sender,
				recipients,
				attachments,
				smil: _,
			} => {
				let sender = match sender {


@@ 454,8 462,7 @@ impl VgmmsState {
				}
				contents.insert(0, MessageItem::Text(text));

				let mut chat: Vec<_> = recipients.iter()
					.filter_map(|r| Number::normalize(&*r, self.my_country)).collect();
				let mut chat: Vec<_> = recipients.iter().filter_map(|r| Number::normalize(&*r, self.my_country)).collect();
				chat.push(sender);
				chat.sort();
				let message = MessageInfo {


@@ 468,9 475,7 @@ impl VgmmsState {
				println!("inserting mms {}: {:?}", hex::encode(&id[..]), message);
				Some(self.add_message(id, message))
			},
			SmsReceived {
				id, text, date, sender, status,
			} => {
			SmsReceived { id, text, date, sender, status } => {
				let time = match parse_date(&date) {
					Ok(d) => d,
					Err(e) => {


@@ 546,29 551,27 @@ impl VgmmsState {
			},
		};

		let my_number_from_modem = modem_path.and_then(|modem_path| {
			match dbus::get_my_number(&modem_path) {
				Ok(Some(n)) => {
					Some(n)
				},
				Ok(None) => {
					eprintln!("subscriber has no number");
					None
				},
				Err(e) => {
					eprintln!("could not determine subscriber phone number from modem: {}", e);
					None
				},
			}
		let my_number_from_modem = modem_path.and_then(|modem_path| match dbus::get_my_number(&modem_path) {
			Ok(Some(n)) => Some(n),
			Ok(None) => {
				eprintln!("subscriber has no number");
				None
			},
			Err(e) => {
				eprintln!("could not determine subscriber phone number from modem: {}", e);
				None
			},
		});

		let mut number_cache_path = fs::data_dir();
		std::fs::create_dir_all(&number_cache_path)
			.expect(&format!("could not create data dir {}", number_cache_path.display()));
		std::fs::create_dir_all(&number_cache_path).expect(&format!("could not create data dir {}", number_cache_path.display()));
		number_cache_path.push("last-number");
		let cached_number = match std::fs::read_to_string(&number_cache_path) {
			Ok(n) => Some(n),
			Err(e) => { eprintln!("could not load cached number: {}", e); None },
			Err(e) => {
				eprintln!("could not load cached number: {}", e);
				None
			},
		};

		let my_number = if let Some(n) = my_number_from_modem {