notifications/
synchronize.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
use hdk::prelude::*;
use notifications_integrity::UnitEntryTypes;
use notifications_types::{
	Notification, NotificationsEncryptedMessage, NotificationsStatusChanges,
};

use crate::{
	encrypted_message::{commit_my_pending_encrypted_messages, create_encrypted_message},
	linked_devices::query_my_linked_devices,
	notification::{query_notifications, query_notifications_status_changes},
};

#[hdk_extern(infallible)]
fn scheduled_synchronize_with_linked_devices(_: Option<Schedule>) -> Option<Schedule> {
	if let Err(err) = commit_my_pending_encrypted_messages() {
		error!("Failed to commit my encrypted messages: {err:?}");
	}
	if let Err(err) = synchronize_with_linked_devices() {
		error!("Failed to synchronize with other agents: {err:?}");
	}

	Some(Schedule::Persisted("*/30 * * * * * *".into())) // Every 30 seconds
}

pub fn synchronize_with_linked_devices() -> ExternResult<()> {
	let my_pub_key = agent_info()?.agent_initial_pubkey;

	let agents = query_my_linked_devices()?;
	let other_agents = agents.into_iter().filter(|a| a.ne(&my_pub_key));

	let notifications = query_notifications()?;

	let notifications_status_changes = query_notifications_status_changes()?;

	let notifications_filter = ChainQueryFilter::new()
		.entry_type(UnitEntryTypes::Notification.try_into()?)
		.include_entries(false)
		.action_type(ActionType::Create);

	let notifications_status_changes_filter = ChainQueryFilter::new()
		.entry_type(UnitEntryTypes::NotificationsStatusChanges.try_into()?)
		.include_entries(false)
		.action_type(ActionType::Create);

	for agent in other_agents {
		let notifications_agent_activity = get_agent_activity(
			agent.clone(),
			notifications_filter.clone(),
			ActivityRequest::Full,
		)?;

		let actions_get_inputs = notifications_agent_activity
			.valid_activity
			.into_iter()
			.map(|(_, action_hash)| GetInput::new(action_hash.into(), GetOptions::network()))
			.collect();

		let records = HDK.with(|hdk| hdk.borrow().get(actions_get_inputs))?;
		let existing_notifications_hashes: HashSet<EntryHash> = records
			.into_iter()
			.filter_map(|r| r)
			.filter_map(|r| r.action().entry_hash().cloned())
			.collect();

		let missing_notifications: Vec<(EntryHash, Notification)> = notifications
			.clone()
			.into_iter()
			.filter(|(entry_hash, _)| !existing_notifications_hashes.contains(entry_hash))
			.collect();

		let mut offline = false;

		for (_, notification) in missing_notifications {
			if !offline {
				let response = call_remote(
					agent.clone(),
					zome_info()?.name,
					"receive_notification".into(),
					None,
					notification.clone(),
				)?;

				match response {
					ZomeCallResponse::Ok(_) => continue,
					_ => offline = true,
				}
			}
			create_encrypted_message(
				agent.clone(),
				NotificationsEncryptedMessage::Notification(notification.clone()),
			)?;
		}

		let notifications_status_changes_agent_activity = get_agent_activity(
			agent.clone(),
			notifications_status_changes_filter.clone(),
			ActivityRequest::Full,
		)?;

		let actions_get_inputs = notifications_status_changes_agent_activity
			.valid_activity
			.into_iter()
			.map(|(_, action_hash)| GetInput::new(action_hash.into(), GetOptions::network()))
			.collect();

		let records = HDK.with(|hdk| hdk.borrow().get(actions_get_inputs))?;
		let existing_notifications_status_changes_hashes: HashSet<EntryHash> = records
			.into_iter()
			.filter_map(|r| r)
			.filter_map(|r| r.action().entry_hash().cloned())
			.collect();

		let missing_notifications_status_changes: Vec<(EntryHash, NotificationsStatusChanges)> =
			notifications_status_changes
				.clone()
				.into_iter()
				.filter(|(entry_hash, _)| {
					!existing_notifications_status_changes_hashes.contains(entry_hash)
				})
				.collect();

		for (_, notifications_status_changes) in missing_notifications_status_changes {
			if !offline {
				let response = call_remote(
					agent.clone(),
					zome_info()?.name,
					"receive_change_notifications_status".into(),
					None,
					notifications_status_changes.clone(),
				)?;

				match response {
					ZomeCallResponse::Ok(_) => continue,
					_ => offline = true,
				}
			}

			create_encrypted_message(
				agent.clone(),
				NotificationsEncryptedMessage::NotificationsStatusChanges(
					notifications_status_changes.clone(),
				),
			)?;
		}
	}

	Ok(())
}