deltachat/
location.rs

1//! Location handling.
2//!
3//! Delta Chat handles two kind of locations.
4//!
5//! There are two kinds of locations:
6//! - Independent locations, also known as Points of Interest (POI).
7//! - Path locations.
8//!
9//! Locations are sent as KML attachments.
10//! Independent locations are sent in `message.kml` attachments
11//! and path locations are sent in `location.kml` attachments.
12
13use std::time::Duration;
14
15use anyhow::{Context as _, Result, ensure};
16use async_channel::Receiver;
17use quick_xml::events::{BytesEnd, BytesStart, BytesText};
18use tokio::time::timeout;
19
20use crate::chat::{self, ChatId};
21use crate::constants::DC_CHAT_ID_TRASH;
22use crate::contact::ContactId;
23use crate::context::Context;
24use crate::events::EventType;
25use crate::log::warn;
26use crate::message::{Message, MsgId, Viewtype};
27use crate::mimeparser::SystemMessage;
28use crate::tools::{duration_to_str, time};
29use crate::{chatlist_events, stock_str};
30
31/// Location record.
32#[derive(Debug, Clone, Default)]
33pub struct Location {
34    /// Row ID of the location.
35    pub location_id: u32,
36
37    /// Location latitude.
38    pub latitude: f64,
39
40    /// Location longitude.
41    pub longitude: f64,
42
43    /// Nonstandard `accuracy` attribute of the `coordinates` tag.
44    pub accuracy: f64,
45
46    /// Location timestamp in seconds.
47    pub timestamp: i64,
48
49    /// Contact ID.
50    pub contact_id: ContactId,
51
52    /// Message ID.
53    pub msg_id: u32,
54
55    /// Chat ID.
56    pub chat_id: ChatId,
57
58    /// A marker string, such as an emoji, to be displayed on top of the location.
59    pub marker: Option<String>,
60
61    /// Whether location is independent, i.e. not part of the path.
62    pub independent: u32,
63}
64
65impl Location {
66    /// Creates a new empty location.
67    pub fn new() -> Self {
68        Default::default()
69    }
70}
71
72/// KML document.
73///
74/// See <https://www.ogc.org/standards/kml/> for the standard and
75/// <https://developers.google.com/kml> for documentation.
76#[derive(Debug, Clone, Default)]
77pub struct Kml {
78    /// Nonstandard `addr` attribute of the `Document` tag storing the user email address.
79    pub addr: Option<String>,
80
81    /// Placemarks.
82    pub locations: Vec<Location>,
83
84    /// Currently parsed XML tag.
85    tag: KmlTag,
86
87    /// Currently parsed placemark.
88    pub curr: Location,
89}
90
91#[derive(Default, Debug, Clone, PartialEq, Eq)]
92enum KmlTag {
93    #[default]
94    Undefined,
95    Placemark,
96    PlacemarkTimestamp,
97    PlacemarkTimestampWhen,
98    PlacemarkPoint,
99    PlacemarkPointCoordinates,
100}
101
102impl Kml {
103    /// Creates a new empty KML document.
104    pub fn new() -> Self {
105        Default::default()
106    }
107
108    /// Parses a KML document.
109    pub fn parse(to_parse: &[u8]) -> Result<Self> {
110        ensure!(to_parse.len() <= 1024 * 1024, "kml-file is too large");
111
112        let mut reader = quick_xml::Reader::from_reader(to_parse);
113        reader.config_mut().trim_text(true);
114
115        let mut kml = Kml::new();
116        kml.locations = Vec::with_capacity(100);
117
118        let mut buf = Vec::new();
119
120        loop {
121            match reader.read_event_into(&mut buf).with_context(|| {
122                format!(
123                    "location parsing error at position {}",
124                    reader.buffer_position()
125                )
126            })? {
127                quick_xml::events::Event::Start(ref e) => kml.starttag_cb(e, &reader),
128                quick_xml::events::Event::End(ref e) => kml.endtag_cb(e),
129                quick_xml::events::Event::Text(ref e) => kml.text_cb(e),
130                quick_xml::events::Event::Eof => break,
131                _ => (),
132            }
133            buf.clear();
134        }
135
136        Ok(kml)
137    }
138
139    fn text_cb(&mut self, event: &BytesText) {
140        if self.tag == KmlTag::PlacemarkTimestampWhen
141            || self.tag == KmlTag::PlacemarkPointCoordinates
142        {
143            let val = event.xml_content().unwrap_or_default();
144
145            let val = val.replace(['\n', '\r', '\t', ' '], "");
146
147            if self.tag == KmlTag::PlacemarkTimestampWhen && val.len() >= 19 {
148                // YYYY-MM-DDTHH:MM:SSZ
149                // 0   4  7  10 13 16 19
150                match chrono::NaiveDateTime::parse_from_str(&val, "%Y-%m-%dT%H:%M:%SZ") {
151                    Ok(res) => {
152                        self.curr.timestamp = res.and_utc().timestamp();
153                        let now = time();
154                        if self.curr.timestamp > now {
155                            self.curr.timestamp = now;
156                        }
157                    }
158                    Err(_err) => {
159                        self.curr.timestamp = time();
160                    }
161                }
162            } else if self.tag == KmlTag::PlacemarkPointCoordinates {
163                let parts = val.splitn(2, ',').collect::<Vec<_>>();
164                if let [longitude, latitude] = &parts[..] {
165                    self.curr.longitude = longitude.parse().unwrap_or_default();
166                    self.curr.latitude = latitude.parse().unwrap_or_default();
167                }
168            }
169        }
170    }
171
172    fn endtag_cb(&mut self, event: &BytesEnd) {
173        let tag = String::from_utf8_lossy(event.name().as_ref())
174            .trim()
175            .to_lowercase();
176
177        match self.tag {
178            KmlTag::PlacemarkTimestampWhen => {
179                if tag == "when" {
180                    self.tag = KmlTag::PlacemarkTimestamp
181                }
182            }
183            KmlTag::PlacemarkTimestamp => {
184                if tag == "timestamp" {
185                    self.tag = KmlTag::Placemark
186                }
187            }
188            KmlTag::PlacemarkPointCoordinates => {
189                if tag == "coordinates" {
190                    self.tag = KmlTag::PlacemarkPoint
191                }
192            }
193            KmlTag::PlacemarkPoint => {
194                if tag == "point" {
195                    self.tag = KmlTag::Placemark
196                }
197            }
198            KmlTag::Placemark => {
199                if tag == "placemark" {
200                    if 0 != self.curr.timestamp
201                        && 0. != self.curr.latitude
202                        && 0. != self.curr.longitude
203                    {
204                        self.locations
205                            .push(std::mem::replace(&mut self.curr, Location::new()));
206                    }
207                    self.tag = KmlTag::Undefined;
208                }
209            }
210            KmlTag::Undefined => {}
211        }
212    }
213
214    fn starttag_cb<B: std::io::BufRead>(
215        &mut self,
216        event: &BytesStart,
217        reader: &quick_xml::Reader<B>,
218    ) {
219        let tag = String::from_utf8_lossy(event.name().as_ref())
220            .trim()
221            .to_lowercase();
222        if tag == "document" {
223            if let Some(addr) = event.attributes().filter_map(|a| a.ok()).find(|attr| {
224                String::from_utf8_lossy(attr.key.as_ref())
225                    .trim()
226                    .to_lowercase()
227                    == "addr"
228            }) {
229                self.addr = addr
230                    .decode_and_unescape_value(reader.decoder())
231                    .ok()
232                    .map(|a| a.into_owned());
233            }
234        } else if tag == "placemark" {
235            self.tag = KmlTag::Placemark;
236            self.curr.timestamp = 0;
237            self.curr.latitude = 0.0;
238            self.curr.longitude = 0.0;
239            self.curr.accuracy = 0.0
240        } else if tag == "timestamp" && self.tag == KmlTag::Placemark {
241            self.tag = KmlTag::PlacemarkTimestamp;
242        } else if tag == "when" && self.tag == KmlTag::PlacemarkTimestamp {
243            self.tag = KmlTag::PlacemarkTimestampWhen;
244        } else if tag == "point" && self.tag == KmlTag::Placemark {
245            self.tag = KmlTag::PlacemarkPoint;
246        } else if tag == "coordinates" && self.tag == KmlTag::PlacemarkPoint {
247            self.tag = KmlTag::PlacemarkPointCoordinates;
248            if let Some(acc) = event.attributes().find_map(|attr| {
249                attr.ok().filter(|a| {
250                    String::from_utf8_lossy(a.key.as_ref())
251                        .trim()
252                        .eq_ignore_ascii_case("accuracy")
253                })
254            }) {
255                let v = acc
256                    .decode_and_unescape_value(reader.decoder())
257                    .unwrap_or_default();
258
259                self.curr.accuracy = v.trim().parse().unwrap_or_default();
260            }
261        }
262    }
263}
264
265/// Enables location streaming in chat identified by `chat_id` for `seconds` seconds.
266#[expect(clippy::arithmetic_side_effects)]
267pub async fn send_locations_to_chat(
268    context: &Context,
269    chat_id: ChatId,
270    seconds: i64,
271) -> Result<()> {
272    ensure!(seconds >= 0);
273    ensure!(!chat_id.is_special());
274    let now = time();
275    let is_sending_locations_before = is_sending_locations_to_chat(context, Some(chat_id)).await?;
276    context
277        .sql
278        .execute(
279            "UPDATE chats    \
280         SET locations_send_begin=?,        \
281         locations_send_until=?  \
282         WHERE id=?",
283            (
284                if 0 != seconds { now } else { 0 },
285                if 0 != seconds { now + seconds } else { 0 },
286                chat_id,
287            ),
288        )
289        .await?;
290    if 0 != seconds && !is_sending_locations_before {
291        let mut msg = Message::new_text(stock_str::msg_location_enabled(context).await);
292        msg.param.set_cmd(SystemMessage::LocationStreamingEnabled);
293        chat::send_msg(context, chat_id, &mut msg)
294            .await
295            .unwrap_or_default();
296    } else if 0 == seconds && is_sending_locations_before {
297        let stock_str = stock_str::msg_location_disabled(context).await;
298        chat::add_info_msg(context, chat_id, &stock_str).await?;
299    }
300    context.emit_event(EventType::ChatModified(chat_id));
301    chatlist_events::emit_chatlist_item_changed(context, chat_id);
302    if 0 != seconds {
303        context.scheduler.interrupt_location().await;
304    }
305    Ok(())
306}
307
308/// Returns whether `chat_id` or any chat is sending locations.
309///
310/// If `chat_id` is `Some` only that chat is checked, otherwise returns `true` if any chat
311/// is sending locations.
312pub async fn is_sending_locations_to_chat(
313    context: &Context,
314    chat_id: Option<ChatId>,
315) -> Result<bool> {
316    let exists = match chat_id {
317        Some(chat_id) => {
318            context
319                .sql
320                .exists(
321                    "SELECT COUNT(id) FROM chats  WHERE id=?  AND locations_send_until>?;",
322                    (chat_id, time()),
323                )
324                .await?
325        }
326        None => {
327            context
328                .sql
329                .exists(
330                    "SELECT COUNT(id) FROM chats  WHERE locations_send_until>?;",
331                    (time(),),
332                )
333                .await?
334        }
335    };
336    Ok(exists)
337}
338
339/// Sets current location of the user device.
340pub async fn set(context: &Context, latitude: f64, longitude: f64, accuracy: f64) -> Result<bool> {
341    if latitude == 0.0 && longitude == 0.0 {
342        return Ok(true);
343    }
344    let mut continue_streaming = false;
345    let now = time();
346
347    let chats = context
348        .sql
349        .query_map_vec(
350            "SELECT id FROM chats WHERE locations_send_until>?;",
351            (now,),
352            |row| {
353                let id: i32 = row.get(0)?;
354                Ok(id)
355            },
356        )
357        .await?;
358
359    let mut stored_location = false;
360    for chat_id in chats {
361        context.sql.execute(
362                "INSERT INTO locations  \
363                 (latitude, longitude, accuracy, timestamp, chat_id, from_id) VALUES (?,?,?,?,?,?);",
364                 (
365                    latitude,
366                    longitude,
367                    accuracy,
368                    now,
369                    chat_id,
370                    ContactId::SELF,
371                )).await.context("Failed to store location")?;
372        stored_location = true;
373
374        info!(context, "Stored location for chat {chat_id}.");
375        continue_streaming = true;
376    }
377    if continue_streaming {
378        context.emit_location_changed(Some(ContactId::SELF)).await?;
379    };
380    if stored_location {
381        // Interrupt location loop so it may send a location-only message.
382        context.scheduler.interrupt_location().await;
383    }
384
385    Ok(continue_streaming)
386}
387
388/// Searches for locations in the given time range, optionally filtering by chat and contact IDs.
389#[expect(clippy::arithmetic_side_effects)]
390pub async fn get_range(
391    context: &Context,
392    chat_id: Option<ChatId>,
393    contact_id: Option<u32>,
394    timestamp_from: i64,
395    mut timestamp_to: i64,
396) -> Result<Vec<Location>> {
397    if timestamp_to == 0 {
398        timestamp_to = time() + 10;
399    }
400
401    let (disable_chat_id, chat_id) = match chat_id {
402        Some(chat_id) => (0, chat_id),
403        None => (1, ChatId::new(0)), // this ChatId is unused
404    };
405    let (disable_contact_id, contact_id) = match contact_id {
406        Some(contact_id) => (0, contact_id),
407        None => (1, 0), // this contact_id is unused
408    };
409    let list = context
410        .sql
411        .query_map_vec(
412            "SELECT l.id, l.latitude, l.longitude, l.accuracy, l.timestamp, l.independent, \
413             COALESCE(m.id, 0) AS msg_id, l.from_id, l.chat_id, COALESCE(m.txt, '') AS txt \
414             FROM locations l  LEFT JOIN msgs m ON l.id=m.location_id  WHERE (? OR l.chat_id=?) \
415             AND (? OR l.from_id=?) \
416             AND (l.independent=1 OR (l.timestamp>=? AND l.timestamp<=?)) \
417             ORDER BY l.timestamp DESC, l.id DESC, msg_id DESC;",
418            (
419                disable_chat_id,
420                chat_id,
421                disable_contact_id,
422                contact_id as i32,
423                timestamp_from,
424                timestamp_to,
425            ),
426            |row| {
427                let msg_id = row.get(6)?;
428                let txt: String = row.get(9)?;
429                let marker = if msg_id != 0 && is_marker(&txt) {
430                    Some(txt)
431                } else {
432                    None
433                };
434                let loc = Location {
435                    location_id: row.get(0)?,
436                    latitude: row.get(1)?,
437                    longitude: row.get(2)?,
438                    accuracy: row.get(3)?,
439                    timestamp: row.get(4)?,
440                    independent: row.get(5)?,
441                    msg_id,
442                    contact_id: row.get(7)?,
443                    chat_id: row.get(8)?,
444                    marker,
445                };
446                Ok(loc)
447            },
448        )
449        .await?;
450    Ok(list)
451}
452
453fn is_marker(txt: &str) -> bool {
454    let mut chars = txt.chars();
455    if let Some(c) = chars.next() {
456        !c.is_whitespace() && chars.next().is_none()
457    } else {
458        false
459    }
460}
461
462/// Deletes all locations from the database.
463pub async fn delete_all(context: &Context) -> Result<()> {
464    context.sql.execute("DELETE FROM locations;", ()).await?;
465    context.emit_location_changed(None).await?;
466    Ok(())
467}
468
469/// Deletes expired locations.
470///
471/// Only path locations are deleted.
472/// POIs should be deleted when corresponding message is deleted.
473pub(crate) async fn delete_expired(context: &Context, now: i64) -> Result<()> {
474    let Some(delete_device_after) = context.get_config_delete_device_after().await? else {
475        return Ok(());
476    };
477
478    let threshold_timestamp = now.saturating_sub(delete_device_after);
479    let deleted = context
480        .sql
481        .execute(
482            "DELETE FROM locations WHERE independent=0 AND timestamp < ?",
483            (threshold_timestamp,),
484        )
485        .await?
486        > 0;
487    if deleted {
488        info!(context, "Deleted {deleted} expired locations.");
489        context.emit_location_changed(None).await?;
490    }
491    Ok(())
492}
493
494/// Deletes location if it is an independent location.
495///
496/// This function is used when a message is deleted
497/// that has a corresponding `location_id`.
498pub(crate) async fn delete_poi_location(context: &Context, location_id: u32) -> Result<()> {
499    context
500        .sql
501        .execute(
502            "DELETE FROM locations WHERE independent = 1 AND id=?",
503            (location_id as i32,),
504        )
505        .await?;
506    Ok(())
507}
508
509/// Deletes POI locations that don't have corresponding message anymore.
510pub(crate) async fn delete_orphaned_poi_locations(context: &Context) -> Result<()> {
511    context.sql.execute("
512    DELETE FROM locations
513    WHERE independent=1 AND id NOT IN
514    (SELECT location_id from MSGS LEFT JOIN locations
515     ON locations.id=location_id
516     WHERE location_id>0 -- This check makes the query faster by not looking for locations with ID 0 that don't exist.
517     AND msgs.chat_id != ?)", (DC_CHAT_ID_TRASH,)).await?;
518    Ok(())
519}
520
521/// Returns `location.kml` contents.
522#[expect(clippy::arithmetic_side_effects)]
523pub async fn get_kml(context: &Context, chat_id: ChatId) -> Result<Option<(String, u32)>> {
524    let mut last_added_location_id = 0;
525
526    let self_addr = context.get_primary_self_addr().await?;
527
528    let (locations_send_begin, locations_send_until, locations_last_sent) = context.sql.query_row(
529        "SELECT locations_send_begin, locations_send_until, locations_last_sent  FROM chats  WHERE id=?;",
530        (chat_id,), |row| {
531            let send_begin: i64 = row.get(0)?;
532            let send_until: i64 = row.get(1)?;
533            let last_sent: i64 = row.get(2)?;
534
535            Ok((send_begin, send_until, last_sent))
536        })
537        .await?;
538
539    let now = time();
540    let mut location_count = 0;
541    let mut ret = String::new();
542    if locations_send_begin != 0 && now <= locations_send_until {
543        ret += &format!(
544            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
545            <kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"{self_addr}\">\n",
546        );
547
548        context
549            .sql
550            .query_map(
551                "SELECT id, latitude, longitude, accuracy, timestamp \
552             FROM locations  WHERE from_id=? \
553             AND timestamp>=? \
554             AND (timestamp>=? OR \
555                  timestamp=(SELECT MAX(timestamp) FROM locations WHERE from_id=?)) \
556             AND independent=0 \
557             GROUP BY timestamp \
558             ORDER BY timestamp;",
559             (
560                    ContactId::SELF,
561                    locations_send_begin,
562                    locations_last_sent,
563                    ContactId::SELF
564                ),
565                |row| {
566                    let location_id: i32 = row.get(0)?;
567                    let latitude: f64 = row.get(1)?;
568                    let longitude: f64 = row.get(2)?;
569                    let accuracy: f64 = row.get(3)?;
570                    let timestamp = get_kml_timestamp(row.get(4)?);
571
572                    Ok((location_id, latitude, longitude, accuracy, timestamp))
573                },
574                |rows| {
575                    for row in rows {
576                        let (location_id, latitude, longitude, accuracy, timestamp) = row?;
577                        ret += &format!(
578                            "<Placemark>\
579                <Timestamp><when>{timestamp}</when></Timestamp>\
580                <Point><coordinates accuracy=\"{accuracy}\">{longitude},{latitude}</coordinates></Point>\
581                </Placemark>\n"
582                        );
583                        location_count += 1;
584                        last_added_location_id = location_id as u32;
585                    }
586                    Ok(())
587                },
588            )
589            .await?;
590        ret += "</Document>\n</kml>";
591    }
592
593    if location_count > 0 {
594        Ok(Some((ret, last_added_location_id)))
595    } else {
596        Ok(None)
597    }
598}
599
600fn get_kml_timestamp(utc: i64) -> String {
601    // Returns a string formatted as YYYY-MM-DDTHH:MM:SSZ. The trailing `Z` indicates UTC.
602    chrono::DateTime::<chrono::Utc>::from_timestamp(utc, 0)
603        .unwrap()
604        .format("%Y-%m-%dT%H:%M:%SZ")
605        .to_string()
606}
607
608/// Returns a KML document containing a single location with the given timestamp and coordinates.
609pub fn get_message_kml(timestamp: i64, latitude: f64, longitude: f64) -> String {
610    format!(
611        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
612         <kml xmlns=\"http://www.opengis.net/kml/2.2\">\n\
613         <Document>\n\
614         <Placemark>\
615         <Timestamp><when>{}</when></Timestamp>\
616         <Point><coordinates>{},{}</coordinates></Point>\
617         </Placemark>\n\
618         </Document>\n\
619         </kml>",
620        get_kml_timestamp(timestamp),
621        longitude,
622        latitude,
623    )
624}
625
626/// Sets the timestamp of the last time location was sent in the chat.
627pub async fn set_kml_sent_timestamp(
628    context: &Context,
629    chat_id: ChatId,
630    timestamp: i64,
631) -> Result<()> {
632    context
633        .sql
634        .execute(
635            "UPDATE chats SET locations_last_sent=? WHERE id=?;",
636            (timestamp, chat_id),
637        )
638        .await?;
639    Ok(())
640}
641
642/// Sets the location of the message.
643pub async fn set_msg_location_id(context: &Context, msg_id: MsgId, location_id: u32) -> Result<()> {
644    context
645        .sql
646        .execute(
647            "UPDATE msgs SET location_id=? WHERE id=?;",
648            (location_id, msg_id),
649        )
650        .await?;
651
652    Ok(())
653}
654
655/// Saves given locations to the database.
656///
657/// Returns the database row ID of the location with the highest timestamp.
658pub(crate) async fn save(
659    context: &Context,
660    chat_id: ChatId,
661    contact_id: ContactId,
662    locations: &[Location],
663    independent: bool,
664) -> Result<Option<u32>> {
665    ensure!(!chat_id.is_special(), "Invalid chat id");
666
667    let mut newest_timestamp = 0;
668    let mut newest_location_id = None;
669
670    let stmt_insert = "INSERT INTO locations\
671             (timestamp, from_id, chat_id, latitude, longitude, accuracy, independent) \
672             VALUES (?,?,?,?,?,?,?);";
673
674    for location in locations {
675        let &Location {
676            timestamp,
677            latitude,
678            longitude,
679            accuracy,
680            ..
681        } = location;
682
683        context
684            .sql
685            .call_write(|conn| {
686                let mut stmt_test = conn
687                    .prepare_cached("SELECT id FROM locations WHERE timestamp=? AND from_id=?")?;
688                let mut stmt_insert = conn.prepare_cached(stmt_insert)?;
689
690                let exists = stmt_test.exists((timestamp, contact_id))?;
691
692                if independent || !exists {
693                    stmt_insert.execute((
694                        timestamp,
695                        contact_id,
696                        chat_id,
697                        latitude,
698                        longitude,
699                        accuracy,
700                        independent,
701                    ))?;
702
703                    if timestamp > newest_timestamp {
704                        newest_timestamp = timestamp;
705                        newest_location_id = Some(u32::try_from(conn.last_insert_rowid())?);
706                    }
707                }
708
709                Ok(())
710            })
711            .await?;
712    }
713
714    Ok(newest_location_id)
715}
716
717pub(crate) async fn location_loop(context: &Context, interrupt_receiver: Receiver<()>) {
718    loop {
719        let next_event = match maybe_send_locations(context).await {
720            Err(err) => {
721                warn!(context, "maybe_send_locations failed: {:#}", err);
722                Some(60) // Retry one minute later.
723            }
724            Ok(next_event) => next_event,
725        };
726
727        let duration = if let Some(next_event) = next_event {
728            Duration::from_secs(next_event)
729        } else {
730            Duration::from_secs(86400)
731        };
732
733        info!(
734            context,
735            "Location loop is waiting for {} or interrupt",
736            duration_to_str(duration)
737        );
738        match timeout(duration, interrupt_receiver.recv()).await {
739            Err(_err) => {
740                info!(context, "Location loop timeout.");
741            }
742            Ok(Err(err)) => {
743                warn!(
744                    context,
745                    "Interrupt channel closed, location loop exits now: {err:#}."
746                );
747                return;
748            }
749            Ok(Ok(())) => {
750                info!(context, "Location loop received interrupt.");
751            }
752        }
753    }
754}
755
756/// Returns number of seconds until the next time location streaming for some chat ends
757/// automatically.
758#[expect(clippy::arithmetic_side_effects)]
759async fn maybe_send_locations(context: &Context) -> Result<Option<u64>> {
760    let mut next_event: Option<u64> = None;
761
762    let now = time();
763    let rows = context
764        .sql
765        .query_map_vec(
766            "SELECT id, locations_send_begin, locations_send_until, locations_last_sent
767             FROM chats
768             WHERE locations_send_until>0",
769            [],
770            |row| {
771                let chat_id: ChatId = row.get(0)?;
772                let locations_send_begin: i64 = row.get(1)?;
773                let locations_send_until: i64 = row.get(2)?;
774                let locations_last_sent: i64 = row.get(3)?;
775                Ok((
776                    chat_id,
777                    locations_send_begin,
778                    locations_send_until,
779                    locations_last_sent,
780                ))
781            },
782        )
783        .await
784        .context("failed to query location streaming chats")?;
785
786    for (chat_id, locations_send_begin, locations_send_until, locations_last_sent) in rows {
787        if locations_send_begin > 0 && locations_send_until > now {
788            let can_send = now > locations_last_sent + 60;
789            let has_locations = context
790                .sql
791                .exists(
792                    "SELECT COUNT(id) \
793     FROM locations \
794     WHERE from_id=? \
795     AND timestamp>=? \
796     AND timestamp>? \
797     AND independent=0",
798                    (ContactId::SELF, locations_send_begin, locations_last_sent),
799                )
800                .await?;
801
802            next_event = next_event
803                .into_iter()
804                .chain(u64::try_from(locations_send_until - now))
805                .min();
806
807            if has_locations {
808                if can_send {
809                    // Send location-only message.
810                    // Pending locations are attached automatically to every message,
811                    // so also to this empty text message.
812                    info!(
813                        context,
814                        "Chat {} has pending locations, sending them.", chat_id
815                    );
816                    let mut msg = Message::new(Viewtype::Text);
817                    msg.hidden = true;
818                    msg.param.set_cmd(SystemMessage::LocationOnly);
819                    chat::send_msg(context, chat_id, &mut msg).await?;
820                } else {
821                    // Wait until pending locations can be sent.
822                    info!(
823                        context,
824                        "Chat {} has pending locations, but they can't be sent yet.", chat_id
825                    );
826                    next_event = next_event
827                        .into_iter()
828                        .chain(u64::try_from(locations_last_sent + 61 - now))
829                        .min();
830                }
831            } else {
832                info!(
833                    context,
834                    "Chat {} has location streaming enabled, but no pending locations.", chat_id
835                );
836            }
837        } else {
838            // Location streaming was either explicitly disabled (locations_send_begin = 0) or
839            // locations_send_until is in the past.
840            info!(
841                context,
842                "Disabling location streaming for chat {}.", chat_id
843            );
844            context
845                .sql
846                .execute(
847                    "UPDATE chats \
848                         SET locations_send_begin=0, locations_send_until=0 \
849                         WHERE id=?",
850                    (chat_id,),
851                )
852                .await
853                .context("failed to disable location streaming")?;
854
855            let stock_str = stock_str::msg_location_disabled(context).await;
856            chat::add_info_msg(context, chat_id, &stock_str).await?;
857            context.emit_event(EventType::ChatModified(chat_id));
858            chatlist_events::emit_chatlist_item_changed(context, chat_id);
859        }
860    }
861
862    Ok(next_event)
863}
864
865#[cfg(test)]
866mod tests {
867    use super::*;
868    use crate::config::Config;
869    use crate::message::MessageState;
870    use crate::receive_imf::receive_imf;
871    use crate::test_utils::{TestContext, TestContextManager};
872    use crate::tools::SystemTime;
873
874    #[test]
875    fn test_kml_parse() {
876        let xml =
877            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document addr=\"user@example.org\">\n<Placemark><Timestamp><when>2019-03-06T21:09:57Z</when></Timestamp><Point><coordinates accuracy=\"32.000000\">9.423110,53.790302</coordinates></Point></Placemark>\n<PlaceMARK>\n<Timestamp><WHEN > \n\t2018-12-13T22:11:12Z\t</WHEN></Timestamp><Point><coordinates aCCuracy=\"2.500000\"> 19.423110 \t , \n 63.790302\n </coordinates></Point></PlaceMARK>\n</Document>\n</kml>";
878
879        let kml = Kml::parse(xml).expect("parsing failed");
880
881        assert!(kml.addr.is_some());
882        assert_eq!(kml.addr.as_ref().unwrap(), "user@example.org",);
883
884        let locations_ref = &kml.locations;
885        assert_eq!(locations_ref.len(), 2);
886
887        assert!(locations_ref[0].latitude > 53.6f64);
888        assert!(locations_ref[0].latitude < 53.8f64);
889        assert!(locations_ref[0].longitude > 9.3f64);
890        assert!(locations_ref[0].longitude < 9.5f64);
891        assert!(locations_ref[0].accuracy > 31.9f64);
892        assert!(locations_ref[0].accuracy < 32.1f64);
893        assert_eq!(locations_ref[0].timestamp, 1551906597);
894
895        assert!(locations_ref[1].latitude > 63.6f64);
896        assert!(locations_ref[1].latitude < 63.8f64);
897        assert!(locations_ref[1].longitude > 19.3f64);
898        assert!(locations_ref[1].longitude < 19.5f64);
899        assert!(locations_ref[1].accuracy > 2.4f64);
900        assert!(locations_ref[1].accuracy < 2.6f64);
901        assert_eq!(locations_ref[1].timestamp, 1544739072);
902    }
903
904    #[test]
905    fn test_kml_parse_error() {
906        let xml = b"<?><xmlversi\"\"\">?</document>";
907        assert!(Kml::parse(xml).is_err());
908    }
909
910    #[test]
911    fn test_get_message_kml() {
912        let timestamp = 1598490000;
913
914        let xml = get_message_kml(timestamp, 51.423723f64, 8.552556f64);
915        let kml = Kml::parse(xml.as_bytes()).expect("parsing failed");
916        let locations_ref = &kml.locations;
917        assert_eq!(locations_ref.len(), 1);
918
919        assert!(locations_ref[0].latitude >= 51.423723f64);
920        assert!(locations_ref[0].latitude < 51.423724f64);
921        assert!(locations_ref[0].longitude >= 8.552556f64);
922        assert!(locations_ref[0].longitude < 8.552557f64);
923        assert!(locations_ref[0].accuracy.abs() < f64::EPSILON);
924        assert_eq!(locations_ref[0].timestamp, timestamp);
925    }
926
927    #[test]
928    fn test_is_marker() {
929        assert!(is_marker("f"));
930        assert!(!is_marker("foo"));
931        assert!(is_marker("🏠"));
932        assert!(!is_marker(" "));
933        assert!(!is_marker("\t"));
934    }
935
936    /// Tests that location.kml is hidden.
937    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
938    async fn receive_location_kml() -> Result<()> {
939        let alice = TestContext::new_alice().await;
940
941        receive_imf(
942            &alice,
943            br#"Subject: Hello
944Message-ID: hello@example.net
945To: Alice <alice@example.org>
946From: Bob <bob@example.net>
947Date: Mon, 20 Dec 2021 00:00:00 +0000
948Chat-Version: 1.0
949Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
950
951Text message."#,
952            false,
953        )
954        .await?;
955        let received_msg = alice.get_last_msg().await;
956        assert_eq!(received_msg.text, "Text message.");
957
958        receive_imf(
959            &alice,
960            br#"Subject: locations
961MIME-Version: 1.0
962To: <alice@example.org>
963From: <bob@example.net>
964Date: Tue, 21 Dec 2021 00:00:00 +0000
965Chat-Version: 1.0
966Message-ID: <foobar@example.net>
967Content-Type: multipart/mixed; boundary="U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF"
968
969
970--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF
971Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
972
973
974
975--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF
976Content-Type: application/vnd.google-earth.kml+xml
977Content-Disposition: attachment; filename="location.kml"
978
979<?xml version="1.0" encoding="UTF-8"?>
980<kml xmlns="http://www.opengis.net/kml/2.2">
981<Document addr="bob@example.net">
982<Placemark><Timestamp><when>2021-11-21T00:00:00Z</when></Timestamp><Point><coordinates accuracy="1.0000000000000000">10.00000000000000,20.00000000000000</coordinates></Point></Placemark>
983</Document>
984</kml>
985
986--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF--"#,
987            false,
988        )
989        .await?;
990
991        // Received location message is not visible, last message stays the same.
992        let received_msg2 = alice.get_last_msg().await;
993        assert_eq!(received_msg2.id, received_msg.id);
994
995        let locations = get_range(&alice, None, None, 0, 0).await?;
996        assert_eq!(locations.len(), 1);
997        Ok(())
998    }
999
1000    /// Tests that `location.kml` is not hidden and not seen if it contains a message.
1001    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1002    async fn receive_visible_location_kml() -> Result<()> {
1003        let alice = TestContext::new_alice().await;
1004
1005        receive_imf(
1006            &alice,
1007            br#"Subject: locations
1008MIME-Version: 1.0
1009To: <alice@example.org>
1010From: <bob@example.net>
1011Date: Tue, 21 Dec 2021 00:00:00 +0000
1012Chat-Version: 1.0
1013Message-ID: <foobar@localhost>
1014Content-Type: multipart/mixed; boundary="U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF"
1015
1016
1017--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF
1018Content-Type: text/plain; charset=utf-8; format=flowed; delsp=no
1019
1020Text message.
1021
1022
1023--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF
1024Content-Type: application/vnd.google-earth.kml+xml
1025Content-Disposition: attachment; filename="location.kml"
1026
1027<?xml version="1.0" encoding="UTF-8"?>
1028<kml xmlns="http://www.opengis.net/kml/2.2">
1029<Document addr="bob@example.net">
1030<Placemark><Timestamp><when>2021-11-21T00:00:00Z</when></Timestamp><Point><coordinates accuracy="1.0000000000000000">10.00000000000000,20.00000000000000</coordinates></Point></Placemark>
1031</Document>
1032</kml>
1033
1034--U8BOG8qNXfB0GgLiQ3PKUjlvdIuLRF--"#,
1035            false,
1036        )
1037        .await?;
1038
1039        let received_msg = alice.get_last_msg().await;
1040        assert_eq!(received_msg.text, "Text message.");
1041        assert_eq!(received_msg.state, MessageState::InFresh);
1042
1043        let locations = get_range(&alice, None, None, 0, 0).await?;
1044        assert_eq!(locations.len(), 1);
1045        Ok(())
1046    }
1047
1048    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1049    async fn test_send_locations_to_chat() -> Result<()> {
1050        let alice = TestContext::new_alice().await;
1051        let bob = TestContext::new_bob().await;
1052
1053        let alice_chat = alice.create_chat(&bob).await;
1054        send_locations_to_chat(&alice, alice_chat.id, 1000).await?;
1055        let sent = alice.pop_sent_msg().await;
1056        let msg = bob.recv_msg(&sent).await;
1057        assert_eq!(msg.text, "Location streaming enabled by alice@example.org.");
1058        let bob_chat_id = msg.chat_id;
1059
1060        assert_eq!(set(&alice, 10.0, 20.0, 1.0).await?, true);
1061
1062        // Send image without text.
1063        let file_name = "image.png";
1064        let bytes = include_bytes!("../test-data/image/logo.png");
1065        let file = alice.get_blobdir().join(file_name);
1066        tokio::fs::write(&file, bytes).await?;
1067        let mut msg = Message::new(Viewtype::Image);
1068        msg.set_file_and_deduplicate(&alice, &file, Some("logo.png"), None)?;
1069        let sent = alice.send_msg(alice_chat.id, &mut msg).await;
1070        let alice_msg = Message::load_from_db(&alice, sent.sender_msg_id).await?;
1071        assert_eq!(alice_msg.has_location(), false);
1072
1073        let msg = bob.recv_msg_opt(&sent).await.unwrap();
1074        assert!(msg.chat_id == bob_chat_id);
1075        assert_eq!(msg.msg_ids.len(), 1);
1076
1077        let bob_msg = Message::load_from_db(&bob, *msg.msg_ids.first().unwrap()).await?;
1078        assert_eq!(bob_msg.chat_id, bob_chat_id);
1079        assert_eq!(bob_msg.viewtype, Viewtype::Image);
1080        assert_eq!(bob_msg.has_location(), false);
1081
1082        let bob_locations = get_range(&bob, None, None, 0, 0).await?;
1083        assert_eq!(bob_locations.len(), 1);
1084
1085        Ok(())
1086    }
1087
1088    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1089    async fn test_delete_expired_locations() -> Result<()> {
1090        let mut tcm = TestContextManager::new();
1091        let alice = &tcm.alice().await;
1092        let bob = &tcm.bob().await;
1093
1094        // Alice enables deletion of messages from device after 1 week.
1095        alice
1096            .set_config(Config::DeleteDeviceAfter, Some("604800"))
1097            .await?;
1098        // Bob enables deletion of messages from device after 1 day.
1099        bob.set_config(Config::DeleteDeviceAfter, Some("86400"))
1100            .await?;
1101
1102        let alice_chat = alice.create_chat(bob).await;
1103
1104        // Alice enables location streaming.
1105        // Bob receives a message saying that Alice enabled location streaming.
1106        send_locations_to_chat(alice, alice_chat.id, 60).await?;
1107        bob.recv_msg(&alice.pop_sent_msg().await).await;
1108
1109        // Alice gets new location from GPS.
1110        assert_eq!(set(alice, 10.0, 20.0, 1.0).await?, true);
1111        assert_eq!(get_range(alice, None, None, 0, 0).await?.len(), 1);
1112
1113        // 10 seconds later location sending stream manages to send location.
1114        SystemTime::shift(Duration::from_secs(10));
1115        delete_expired(alice, time()).await?;
1116        maybe_send_locations(alice).await?;
1117        bob.recv_msg_opt(&alice.pop_sent_msg().await).await;
1118        assert_eq!(get_range(alice, None, None, 0, 0).await?.len(), 1);
1119        assert_eq!(get_range(bob, None, None, 0, 0).await?.len(), 1);
1120
1121        // Location-only messages are "auto-generated", but they mustn't make the contact a bot.
1122        let contact = bob.add_or_lookup_contact(alice).await;
1123        assert!(!contact.is_bot());
1124
1125        // Day later Bob removes location.
1126        SystemTime::shift(Duration::from_secs(86400));
1127        delete_expired(alice, time()).await?;
1128        delete_expired(bob, time()).await?;
1129        assert_eq!(get_range(alice, None, None, 0, 0).await?.len(), 1);
1130        assert_eq!(get_range(bob, None, None, 0, 0).await?.len(), 0);
1131
1132        // Week late Alice removes location.
1133        SystemTime::shift(Duration::from_secs(604800));
1134        delete_expired(alice, time()).await?;
1135        delete_expired(bob, time()).await?;
1136        assert_eq!(get_range(alice, None, None, 0, 0).await?.len(), 0);
1137        assert_eq!(get_range(bob, None, None, 0, 0).await?.len(), 0);
1138
1139        Ok(())
1140    }
1141}