]> Untitled Git - lemmy.git/blob - src/scheduled_tasks.rs
Update translations
[lemmy.git] / src / scheduled_tasks.rs
1 use clokwerk::{Scheduler, TimeUnits as CTimeUnits};
2 use diesel::{
3   dsl::{now, IntervalDsl},
4   Connection,
5   ExpressionMethods,
6   QueryDsl,
7 };
8 // Import week days and WeekDay
9 use diesel::{sql_query, PgConnection, RunQueryDsl};
10 use lemmy_db_schema::{
11   schema::{
12     activity,
13     comment_aggregates,
14     community_aggregates,
15     community_person_ban,
16     instance,
17     person,
18     post_aggregates,
19   },
20   source::instance::{Instance, InstanceForm},
21   utils::{functions::hot_rank, naive_now},
22 };
23 use lemmy_routes::nodeinfo::NodeInfo;
24 use lemmy_utils::{error::LemmyError, REQWEST_TIMEOUT};
25 use reqwest::blocking::Client;
26 use std::{thread, time::Duration};
27 use tracing::{error, info};
28
29 /// Schedules various cleanup tasks for lemmy in a background thread
30 pub fn setup(db_url: String, user_agent: String) -> Result<(), LemmyError> {
31   // Setup the connections
32   let mut scheduler = Scheduler::new();
33
34   let mut conn_1 = PgConnection::establish(&db_url).expect("could not establish connection");
35   let mut conn_2 = PgConnection::establish(&db_url).expect("could not establish connection");
36   let mut conn_3 = PgConnection::establish(&db_url).expect("could not establish connection");
37   let mut conn_4 = PgConnection::establish(&db_url).expect("could not establish connection");
38
39   // Run on startup
40   active_counts(&mut conn_1);
41   update_hot_ranks(&mut conn_1, false);
42   update_banned_when_expired(&mut conn_1);
43   clear_old_activities(&mut conn_1);
44
45   // Update active counts every hour
46   scheduler.every(CTimeUnits::hour(1)).run(move || {
47     active_counts(&mut conn_1);
48     update_banned_when_expired(&mut conn_1);
49   });
50
51   // Update hot ranks every 5 minutes
52   scheduler.every(CTimeUnits::minutes(5)).run(move || {
53     update_hot_ranks(&mut conn_2, true);
54   });
55
56   // Clear old activities every week
57   scheduler.every(CTimeUnits::weeks(1)).run(move || {
58     clear_old_activities(&mut conn_3);
59   });
60
61   scheduler.every(CTimeUnits::days(1)).run(move || {
62     update_instance_software(&mut conn_4, &user_agent);
63   });
64
65   // Manually run the scheduler in an event loop
66   loop {
67     scheduler.run_pending();
68     thread::sleep(Duration::from_millis(1000));
69   }
70 }
71
72 /// Update the hot_rank columns for the aggregates tables
73 fn update_hot_ranks(conn: &mut PgConnection, last_week_only: bool) {
74   let mut post_update = diesel::update(post_aggregates::table).into_boxed();
75   let mut comment_update = diesel::update(comment_aggregates::table).into_boxed();
76   let mut community_update = diesel::update(community_aggregates::table).into_boxed();
77
78   // Only update for the last week of content
79   if last_week_only {
80     info!("Updating hot ranks for last week...");
81     let last_week = now - diesel::dsl::IntervalDsl::weeks(1);
82
83     post_update = post_update.filter(post_aggregates::published.gt(last_week));
84     comment_update = comment_update.filter(comment_aggregates::published.gt(last_week));
85     community_update = community_update.filter(community_aggregates::published.gt(last_week));
86   } else {
87     info!("Updating hot ranks for all history...");
88   }
89
90   match post_update
91     .set((
92       post_aggregates::hot_rank.eq(hot_rank(post_aggregates::score, post_aggregates::published)),
93       post_aggregates::hot_rank_active.eq(hot_rank(
94         post_aggregates::score,
95         post_aggregates::newest_comment_time_necro,
96       )),
97     ))
98     .execute(conn)
99   {
100     Ok(_) => {}
101     Err(e) => {
102       error!("Failed to update post_aggregates hot_ranks: {}", e)
103     }
104   }
105
106   match comment_update
107     .set(comment_aggregates::hot_rank.eq(hot_rank(
108       comment_aggregates::score,
109       comment_aggregates::published,
110     )))
111     .execute(conn)
112   {
113     Ok(_) => {}
114     Err(e) => {
115       error!("Failed to update comment_aggregates hot_ranks: {}", e)
116     }
117   }
118
119   match community_update
120     .set(community_aggregates::hot_rank.eq(hot_rank(
121       community_aggregates::subscribers,
122       community_aggregates::published,
123     )))
124     .execute(conn)
125   {
126     Ok(_) => {
127       info!("Done.");
128     }
129     Err(e) => {
130       error!("Failed to update community_aggregates hot_ranks: {}", e)
131     }
132   }
133 }
134
135 /// Clear old activities (this table gets very large)
136 fn clear_old_activities(conn: &mut PgConnection) {
137   info!("Clearing old activities...");
138   match diesel::delete(activity::table.filter(activity::published.lt(now - 6.months())))
139     .execute(conn)
140   {
141     Ok(_) => {
142       info!("Done.");
143     }
144     Err(e) => {
145       error!("Failed to clear old activities: {}", e)
146     }
147   }
148 }
149
150 /// Re-calculate the site and community active counts every 12 hours
151 fn active_counts(conn: &mut PgConnection) {
152   info!("Updating active site and community aggregates ...");
153
154   let intervals = vec![
155     ("1 day", "day"),
156     ("1 week", "week"),
157     ("1 month", "month"),
158     ("6 months", "half_year"),
159   ];
160
161   for i in &intervals {
162     let update_site_stmt = format!(
163       "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
164       i.1, i.0
165     );
166     match sql_query(update_site_stmt).execute(conn) {
167       Ok(_) => {}
168       Err(e) => {
169         error!("Failed to update site stats: {}", e)
170       }
171     }
172
173     let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", i.1, i.0);
174     match sql_query(update_community_stmt).execute(conn) {
175       Ok(_) => {}
176       Err(e) => {
177         error!("Failed to update community stats: {}", e)
178       }
179     }
180   }
181
182   info!("Done.");
183 }
184
185 /// Set banned to false after ban expires
186 fn update_banned_when_expired(conn: &mut PgConnection) {
187   info!("Updating banned column if it expires ...");
188
189   match diesel::update(
190     person::table
191       .filter(person::banned.eq(true))
192       .filter(person::ban_expires.lt(now)),
193   )
194   .set(person::banned.eq(false))
195   .execute(conn)
196   {
197     Ok(_) => {}
198     Err(e) => {
199       error!("Failed to update person.banned when expires: {}", e)
200     }
201   }
202   match diesel::delete(community_person_ban::table.filter(community_person_ban::expires.lt(now)))
203     .execute(conn)
204   {
205     Ok(_) => {}
206     Err(e) => {
207       error!("Failed to remove community_ban expired rows: {}", e)
208     }
209   }
210 }
211
212 /// Updates the instance software and version
213 fn update_instance_software(conn: &mut PgConnection, user_agent: &str) {
214   info!("Updating instances software and versions...");
215
216   let client = match Client::builder()
217     .user_agent(user_agent)
218     .timeout(REQWEST_TIMEOUT)
219     .build()
220   {
221     Ok(client) => client,
222     Err(e) => {
223       error!("Failed to build reqwest client: {}", e);
224       return;
225     }
226   };
227
228   let instances = match instance::table.get_results::<Instance>(conn) {
229     Ok(instances) => instances,
230     Err(e) => {
231       error!("Failed to get instances: {}", e);
232       return;
233     }
234   };
235
236   for instance in instances {
237     let node_info_url = format!("https://{}/nodeinfo/2.0.json", instance.domain);
238
239     // Skip it if it can't connect
240     let res = client
241       .get(&node_info_url)
242       .send()
243       .ok()
244       .and_then(|t| t.json::<NodeInfo>().ok());
245
246     if let Some(node_info) = res {
247       let software = node_info.software.as_ref();
248       let form = InstanceForm::builder()
249         .domain(instance.domain)
250         .software(software.and_then(|s| s.name.clone()))
251         .version(software.and_then(|s| s.version.clone()))
252         .updated(Some(naive_now()))
253         .build();
254
255       match diesel::update(instance::table.find(instance.id))
256         .set(form)
257         .execute(conn)
258       {
259         Ok(_) => {
260           info!("Done.");
261         }
262         Err(e) => {
263           error!("Failed to update site instance software: {}", e);
264           return;
265         }
266       }
267     }
268   }
269 }
270
271 #[cfg(test)]
272 mod tests {
273   use lemmy_routes::nodeinfo::NodeInfo;
274   use reqwest::Client;
275
276   #[tokio::test]
277   #[ignore]
278   async fn test_nodeinfo() {
279     let client = Client::builder().build().unwrap();
280     let lemmy_ml_nodeinfo = client
281       .get("https://lemmy.ml/nodeinfo/2.0.json")
282       .send()
283       .await
284       .unwrap()
285       .json::<NodeInfo>()
286       .await
287       .unwrap();
288
289     assert_eq!(lemmy_ml_nodeinfo.software.unwrap().name.unwrap(), "lemmy");
290   }
291 }