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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (C) 2017 Kisio Digital and/or its affiliates.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by the
// Free Software Foundation, version 3.

// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
// details.

// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>
//! This exposes common information between GTFS and NTFS
//! Mainly 2 common things are grouped here:
//! - Accessibility of some equipments
//! - calendar.txt and calendar_dates.txt format are identical between the GTFS
//!   and NTFS

use crate::model::Collections;
use crate::objects::{self, Date, ExceptionType};
use crate::read_utils::FileHandler;
use crate::utils::*;
use crate::utils::{de_from_date_string, ser_from_naive_date};
use crate::vptranslator::translate;
use crate::Result;
use chrono::{self, Datelike, Weekday};
use failure::{bail, format_err, ResultExt};
use log::{info, Level as LogLevel};
use serde::{Deserialize, Serialize};
use skip_error::skip_error_and_log;
use std::collections::BTreeSet;
use std::path;
use typed_index_collection::*;

/// Structure to serialize/deserialize the file calendar_dates.txt
#[derive(Serialize, Deserialize, Debug)]
pub struct CalendarDate {
    /// Identifiers of the Service
    pub service_id: String,
    #[serde(
        deserialize_with = "de_from_date_string",
        serialize_with = "ser_from_naive_date"
    )]
    /// Date at which the CalendarDate applies
    pub date: Date,
    /// Is the CalendarDate included or excluded
    pub exception_type: ExceptionType,
}

/// Structure to serialize/deserialize the file calendar.txt
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Calendar {
    /// Identifiers of the Service
    #[serde(rename = "service_id")]
    id: String,
    /// True if the Service is active on Mondays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    monday: bool,
    /// True if the Service is active on Tuesdays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    tuesday: bool,
    /// True if the Service is active on Wednesdays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    wednesday: bool,
    /// True if the Service is active on Thursdays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    thursday: bool,
    /// True if the Service is active on Fridays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    friday: bool,
    /// True if the Service is active on Saturdays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    saturday: bool,
    /// True if the Service is active on Sundays
    #[serde(deserialize_with = "de_from_u8", serialize_with = "ser_from_bool")]
    sunday: bool,
    /// The Service is active starting from this date
    #[serde(
        deserialize_with = "de_from_date_string",
        serialize_with = "ser_from_naive_date"
    )]
    start_date: Date,
    /// The Service is active until this date
    #[serde(
        deserialize_with = "de_from_date_string",
        serialize_with = "ser_from_naive_date"
    )]
    end_date: Date,
}

impl Calendar {
    fn get_valid_days(&self) -> Vec<Weekday> {
        let mut valid_days: Vec<Weekday> = vec![];
        if self.monday {
            valid_days.push(Weekday::Mon);
        }
        if self.tuesday {
            valid_days.push(Weekday::Tue);
        }
        if self.wednesday {
            valid_days.push(Weekday::Wed);
        }
        if self.thursday {
            valid_days.push(Weekday::Thu);
        }
        if self.friday {
            valid_days.push(Weekday::Fri);
        }
        if self.saturday {
            valid_days.push(Weekday::Sat);
        }
        if self.sunday {
            valid_days.push(Weekday::Sun);
        }

        valid_days
    }

    fn get_valid_dates(&self) -> BTreeSet<Date> {
        let valid_days = self.get_valid_days();
        let duration = self.end_date - self.start_date;
        (0..=duration.num_days())
            .map(|i| self.start_date + chrono::Duration::days(i))
            .filter(|d| valid_days.contains(&d.weekday()))
            .collect()
    }
}

fn manage_calendar_dates<H>(
    calendars: &mut CollectionWithId<objects::Calendar>,
    file_handler: &mut H,
    calendar_exists: bool,
) -> Result<()>
where
    for<'a> &'a mut H: FileHandler,
{
    let file = "calendar_dates.txt";
    let (reader, path) = file_handler.get_file_if_exists(file)?;
    match reader {
        None => {
            if !calendar_exists {
                bail!("calendar_dates.txt or calendar.txt not found");
            }
            info!("Skipping {}", file);
        }
        Some(reader) => {
            info!("Reading {}", file);

            let mut rdr = csv::Reader::from_reader(reader);
            for calendar_date in rdr.deserialize() {
                let calendar_date: CalendarDate =
                    calendar_date.with_context(|_| format!("Error reading {:?}", path))?;

                let is_inserted =
                    calendars
                        .get_mut(&calendar_date.service_id)
                        .map(|mut calendar| match calendar_date.exception_type {
                            ExceptionType::Add => {
                                calendar.dates.insert(calendar_date.date);
                            }
                            ExceptionType::Remove => {
                                calendar.dates.remove(&calendar_date.date);
                            }
                        });
                is_inserted.unwrap_or_else(|| {
                    if calendar_date.exception_type == ExceptionType::Add {
                        let mut dates = BTreeSet::new();
                        dates.insert(calendar_date.date);
                        calendars
                            .push(objects::Calendar {
                                id: calendar_date.service_id,
                                dates,
                            })
                            .unwrap();
                    }
                });
            }
        }
    }
    Ok(())
}

pub(crate) fn manage_calendars<H>(file_handler: &mut H, collections: &mut Collections) -> Result<()>
where
    for<'a> &'a mut H: FileHandler,
{
    let mut calendars: Vec<objects::Calendar> = vec![];
    let calendar_exists = {
        let file = "calendar.txt";
        let (calendar_reader, path) = file_handler.get_file_if_exists(file)?;
        match calendar_reader {
            None => {
                info!("Skipping {}", file);
                false
            }
            Some(calendar_reader) => {
                info!("Reading {}", file);
                let mut rdr = csv::Reader::from_reader(calendar_reader);
                for calendar in rdr.deserialize() {
                    let calendar: Calendar =
                        calendar.with_context(|_| format!("Error reading {:?}", path))?;
                    let dates = calendar.get_valid_dates();
                    if !dates.is_empty() {
                        calendars.push(objects::Calendar {
                            id: calendar.id.clone(),
                            dates,
                        });
                    }
                }
                collections.calendars = CollectionWithId::new(calendars)?;
                true
            }
        }
    };

    manage_calendar_dates(&mut collections.calendars, file_handler, calendar_exists)?;

    Ok(())
}

/// Write the calendar_dates.txt file into a Path from a list of Calendar
pub fn write_calendar_dates(
    path: &path::Path,
    calendars: &CollectionWithId<objects::Calendar>,
) -> Result<()> {
    info!("Writing calendar_dates.txt");
    let calendar_dates_path = path.join("calendar_dates.txt");
    let mut translations: Vec<Calendar> = vec![];
    let mut exceptions: Vec<CalendarDate> = vec![];
    for c in calendars.values() {
        let translation = translate(&c.dates);
        if !translation.operating_days.is_empty() {
            let validity_period = skip_error_and_log!(
                translation.validity_period.ok_or_else(|| format_err!(
                    "Validity period not found for service id {}",
                    c.id.clone()
                )),
                LogLevel::Warn
            );
            translations.push(Calendar {
                id: c.id.clone(),
                monday: translation.operating_days.contains(&Weekday::Mon),
                tuesday: translation.operating_days.contains(&Weekday::Tue),
                wednesday: translation.operating_days.contains(&Weekday::Wed),
                thursday: translation.operating_days.contains(&Weekday::Thu),
                friday: translation.operating_days.contains(&Weekday::Fri),
                saturday: translation.operating_days.contains(&Weekday::Sat),
                sunday: translation.operating_days.contains(&Weekday::Sun),
                start_date: validity_period.start_date,
                end_date: validity_period.end_date,
            });
        };
        for e in translation.exceptions {
            exceptions.push(CalendarDate {
                service_id: c.id.clone(),
                date: e.date,
                exception_type: e.exception_type,
            });
        }
    }
    if !exceptions.is_empty() {
        let mut wtr = csv::Writer::from_path(&calendar_dates_path)
            .with_context(|_| format!("Error reading {:?}", calendar_dates_path))?;
        for e in exceptions {
            wtr.serialize(&e)
                .with_context(|_| format!("Error reading {:?}", calendar_dates_path))?;
        }
        wtr.flush()
            .with_context(|_| format!("Error reading {:?}", calendar_dates_path))?;
    }
    write_calendar(path, &translations)
}

/// Write the calendar.txt file into a Path from a list of Calendar
pub fn write_calendar(path: &path::Path, calendars: &[Calendar]) -> Result<()> {
    info!("Writing calendar.txt");
    if calendars.is_empty() {
        return Ok(());
    }

    let calendar_path = path.join("calendar.txt");
    let mut wtr = csv::Writer::from_path(&calendar_path)
        .with_context(|_| format!("Error reading {:?}", calendar_path))?;
    for calendar in calendars {
        wtr.serialize(calendar)
            .with_context(|_| format!("Error reading {:?}", calendar_path))?;
    }
    wtr.flush()
        .with_context(|_| format!("Error reading {:?}", calendar_path))?;
    Ok(())
}