Respect the date tolerance setting
[beifahrer] / src / adac-mitfahrclub.vala
1 /* This file is part of Beifahrer.
2  *
3  * Copyright (C) 2010 Philipp Zabel
4  *
5  * Beifahrer is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * Beifahrer is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with Beifahrer. If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 [Compact]
20 public class City {
21         public int number;
22         public string name;
23         public double latitude;
24         public double longitude;
25         public double north;
26         public double south;
27         public double east;
28         public double west;
29
30         public City (int _number, string _name) {
31                 number = _number;
32                 name = _name;
33                 latitude = 0.0;
34                 longitude = 0.0;
35         }
36
37         internal double bb_area () {
38                 return (north - south) * (east - west);
39         }
40 }
41
42 public enum LiftFlags {
43         SMOKER = 1,
44         NON_SMOKER = 2,
45         ADAC_MEMBER = 4,
46         WOMEN_ONLY = 8
47 }
48
49 public class Lift : Object {
50         public string city_from;
51         public string city_to;
52         public string date;
53         public string time;
54         public int places;
55         public string price;
56         public LiftFlags flags;
57
58         public string href;
59
60         public List<string> city_via;
61         public string name;
62         public string cell;
63         public string phone;
64         public string phone2;
65         public string email;
66         public string description;
67         public string modified;
68 }
69
70 public class AdacMitfahrclub {
71         const string BASE_URI = "http://mitfahrclub.adac.de";
72
73         string response;
74         int size;
75         List<City> city_list = null;
76
77         static size_t write_memory_cb (void* ptr, size_t size, size_t nmemb, void* data) {
78                 unowned AdacMitfahrclub self = (AdacMitfahrclub) data;
79
80                 self.response += ((string) ptr).ndup (size * nmemb);
81                 self.size += (int) (size * nmemb);
82
83                 return size * nmemb;
84         }
85
86         private Html.Doc* get_html_document (string url) {
87                 var handle = new Curl.EasyHandle ();
88
89                 handle.setopt (Curl.Option.URL, url);
90                 handle.setopt (Curl.Option.WRITEFUNCTION, write_memory_cb);
91                 handle.setopt (Curl.Option.WRITEDATA, (void*) this);
92
93                 this.response = "";
94                 this.size = 0;
95
96                 handle.perform ();
97
98                 return Html.Doc.read_memory ((char[]) this.response, this.size,
99                                              url, null, Html.ParserOption.NOERROR | Html.ParserOption.NOWARNING);
100         }
101
102         private void save_city_list () {
103                 FileStream list_file = FileStream.open ("/home/user/.cache/beifahrer/city_list", "w");
104                 if (list_file == null)
105                         return;
106
107                 foreach (unowned City city in city_list) {
108                         if (city.north != 0.0 || city.south != 0.0 || city.east != 0.0 || city.west != 0.0)
109                                 list_file.printf ("%d\t%s\t%f\t%f\t%f\t%f\t%f\t%f\n", city.number, city.name, city.latitude, city.longitude, city.north, city.south, city.east, city.west);
110                         else if (city.latitude != 0.0 || city.longitude != 0.0)
111                                 list_file.printf ("%d\t%s\t%f\t%f\n", city.number, city.name, city.latitude, city.longitude);
112                         else
113                                 list_file.printf ("%d\t%s\n", city.number, city.name);
114                 }
115         }
116
117         private bool load_city_list () {
118                 FileStream list_file = FileStream.open ("/home/user/.cache/beifahrer/city_list", "r");
119                 if (list_file == null)
120                         list_file = FileStream.open ("/usr/share/beifahrer/city_list", "r");
121                 if (list_file == null)
122                         return false;
123
124                 city_list = new List<City> ();
125                 string line = list_file.read_line ();
126                 while (line != null) {
127                         var split_line = line.split ("\t");
128                         if (split_line.length < 2)
129                                 continue;
130                         int number = split_line[0].to_int ();
131                         weak string name = split_line[1];
132
133                         var city = new City (number, name);
134                         if (split_line.length >= 4) {
135                                 city.latitude = split_line[2].to_double ();
136                                 city.longitude = split_line[3].to_double ();
137                         }
138                         if (split_line.length >= 8) {
139                                 city.north = split_line[4].to_double ();
140                                 city.south = split_line[5].to_double ();
141                                 city.east = split_line[6].to_double ();
142                                 city.west = split_line[7].to_double ();
143                         }
144                         city_list.append ((owned) city);
145
146                         line = list_file.read_line ();
147                 }
148
149                 return true;
150         }
151
152         public unowned List<City>? get_city_list () {
153                 if (city_list != null)
154                         return city_list;
155
156                 if (load_city_list ())
157                         return city_list;
158
159                 var doc = get_html_document (BASE_URI);
160                 if (doc == null) {
161                         print ("Error: parsing failed");
162                         print ("%s\n", this.response);
163                         return null;
164                 }
165
166                 var form = search_tag_by_id (doc->children, "form", "search_national_form");
167                 if (form == null) {
168                         print ("Error: does not contain search_national_form");
169                         print ("%s\n", this.response);
170                         return null;
171                 }
172
173                 var select = search_tag_by_name (form->children, "select", "city_from");
174                 if (select == null) {
175                         print ("Error: does not contain city_from");
176                         print ("%s\n", this.response);
177                         return null;
178                 }
179
180                 city_list = new List<City> ();
181                 for (var n = select->children; n != null; n = n->next) {
182                         if (n->name == "option" && n->children != null && n->children->name == "text") {
183                                 int number = n->get_prop ("value").to_int ();
184                                 // Skip 0 "Alle St.dte"
185                                 if (number == 0)
186                                         continue;
187                                 var city = new City(number,
188                                                     n->children->content);
189                                 city_list.append ((owned) city);
190                         }
191                 }
192
193                 // TODO: get coordinates
194
195                 save_city_list ();
196
197                 return city_list;
198         }
199
200         private int get_city_number (string name) {
201                 foreach (unowned City city in city_list) {
202                         if (city.name == name)
203                                 return city.number;
204                 }
205                 return 0;
206         }
207
208         public unowned City find_nearest_city (double latitude, double longitude) {
209                 unowned City result = null;
210                 double min_distance = 0.0;
211                 bool in_result = false;
212
213                 foreach (unowned City city in city_list) {
214                         double lat = latitude - city.latitude;
215                         double lng = longitude - city.longitude;
216                         double distance = lat * lat + lng * lng;
217                         bool in_city = ((city.south <= latitude <= city.north) &&
218                                         (city.west <= longitude <= city.east));
219
220                         if ((result == null) ||
221                             (in_city && !in_result) ||
222                             (in_city && in_result && distance / city.bb_area () < min_distance / result.bb_area ()) ||
223                             (!in_city && !in_result && distance < min_distance)) {
224                                 result = city;
225                                 min_distance = distance;
226                                 in_result = in_city;
227                         }
228                 }
229
230                 return result;
231         }
232
233         public List<Lift>? get_lift_list (string city_from, string city_to, Date date, int tolerance = 0) {
234                 if (city_list == null)
235                         get_city_list ();
236
237                 int num_from = get_city_number (city_from);
238                 if (num_from == 0) {
239                         stderr.printf ("Unknown city: %s\n", city_to);
240                         return null;
241                 }
242
243                 int num_to = get_city_number (city_to);
244                 if (num_to == 0) {
245                         stderr.printf ("Unknown city: %s\n", city_to);
246                         return null;
247                 }
248
249                 string url = BASE_URI + "/mitfahrclub/%s/%s/b.html".printf (
250                         city_from,
251                         city_to
252                 );
253
254                 url += "?type=b&city_from=%d&radius_from=0&city_to=%d&radius_to=0".printf (
255                         num_from,
256                         num_to
257                 );
258
259                 url += "&date=date&day=%d&month=%d&year=%d&tolerance=%d&smoking=&avg_speed=&".printf (
260                         date.get_day (),
261                         date.get_month (),
262                         date.get_year (),
263                         tolerance
264                 );
265
266                 var doc = get_html_document (url);
267                 if (doc == null) {
268                         print ("Error: parsing failed");
269                         print ("%s\n", this.response);
270                         return null;
271                 }
272
273                 var table = search_tag_by_class (doc->children, "table", "list p_15");
274                 if (table == null) {
275                         print ("Error: does not contain list p_15 table");
276                         print ("%s\n", this.response);
277                         return null;
278                 }
279
280                 var list = new List<Lift> ();
281                 for (var n = table->children; n != null; n = n->next) {
282                         if (n->name == "tr") {
283                                 var lift = parse_lift_row (n->children);
284                                 if (lift.city_from != null) // Skip the title row
285                                         list.append ((owned) lift);
286                         }
287                 }
288
289                 // Error message?
290                 var div = table->next;
291                 if (div != null && div->get_prop ("class") == "error-message") {
292                         if (div->children == null || div->children->content == null ||
293                             !div->children->content.has_prefix ("Es sind leider noch keine Einträge vorhanden.")) {
294                                 stderr.printf ("Got an unknown error message!\n");
295                                 if (div->children != null && div->children->content != null)
296                                         stderr.printf ("\"%s\"\n", div->children->content);
297                         }
298                 }
299
300                 return list;
301         }
302
303         Lift parse_lift_row (Xml.Node* node) {
304                 var lift = new Lift ();
305                 int i = 0;
306                 for (var n = node; n != null; n = n->next) {
307                         if (n->name == "td") {
308                                 var n2 = n->children;
309                                 if (n2 != null) {
310                                         if (n2->name == "a") {
311                                                 var href = n2->get_prop ("href");
312                                                 if (href != null && lift.href == null)
313                                                         lift.href = href;
314                                                 var n3 = n2->children;
315                                                 while (n3 != null) {
316                                                         if (n3->name == "text")
317                                                                 switch (i) {
318                                                                 case 0:
319                                                                         lift.city_from = n3->content;
320                                                                         break;
321                                                                 case 1:
322                                                                         lift.city_to = n3->content;
323                                                                         break;
324                                                                 case 2:
325                                                                         lift.date = n3->content;
326                                                                         break;
327                                                                 case 3:
328                                                                         lift.time = n3->content;
329                                                                         break;
330                                                                 case 4:
331                                                                         lift.places = n3->content.to_int ();
332                                                                         break;
333                                                                 case 5:
334                                                                         lift.price = n3->content;
335                                                                         break;
336                                                                 default:
337                                                                         print ("TEXT:%s\n", n3->content);
338                                                                         break;
339                                                                 }
340                                                         if (n3->name == "span") {
341                                                                 string class = n3->get_prop ("class");
342                                                                 if (class == "icon_smoker")
343                                                                         lift.flags |= LiftFlags.SMOKER;
344                                                                 else if (class == "icon_non_smoker")
345                                                                         lift.flags |= LiftFlags.NON_SMOKER;
346                                                                 else if (class == "icon_adac")
347                                                                         lift.flags |= LiftFlags.ADAC_MEMBER;
348                                                                 else if (class == "icon_women")
349                                                                         lift.flags |= LiftFlags.WOMEN_ONLY;
350                                                                 else if (class != null)
351                                                                         print ("SPAN %s\n", class);
352                                                         }
353                                                         n3 = n3->next;
354                                                 }
355                                         }
356                                 }
357                                 i++;
358                         }
359                 }
360
361                 return lift;
362         }
363
364         public Lift? get_lift_details (string lift_url) {
365                 var lift = new Lift ();
366                 lift.href = lift_url;
367                 if (update_lift_details (lift))
368                         return lift;
369                 else
370                         return null;
371         }
372
373         public bool update_lift_details (Lift lift) {
374                 string url = BASE_URI + lift.href;
375
376                 var doc = get_html_document (url);
377                 if (doc == null) {
378                         print ("Error: parsing failed");
379                         print ("%s\n", this.response);
380                         return false;
381                 }
382
383                 var table = search_tag_by_class (doc->children, "table", "lift");
384                 if (table == null) {
385                         print ("Error: does not contain lift table");
386                         print ("%s\n", this.response);
387                         return false;
388                 }
389
390                 for (var n = table->children; n != null; n = n->next) {
391                         if (n->name == "tr") {
392                                 var n2 = n->children;
393                                 if (n2 == null || n2->name != "td" ||
394                                     n2->children == null || n2->children->name != "text")
395                                         continue;
396
397                                 string text = n2->children->content;
398
399                                 if (text != "Strecke & Infos" && text != "&nbsp;" && !text.has_prefix ("\xc2\xa0") &&
400                                     text != "Datum" &&
401                                     text != "Freie Pl\xc3\xa4tze" &&
402                                     text != "Name" &&
403                                     text != "Handy" &&
404                                     text != "Telefon" &&
405                                     text != "Telefon 2" &&
406                                     text != "E-Mail 1" &&
407                                     text != "Details" &&
408                                     text != "Beschreibung")
409                                         continue;
410
411                                 n2 = n2->next;
412                                 if (n2 == null)
413                                         continue;
414
415                                 // Skip text between td nodes
416                                 if (n2->name == "text")
417                                         n2 = n2->next;
418
419                                 if (n2 == null || n2->name != "td" || n2->children == null)
420                                         continue;
421
422                                 if (n2->children->name == "img") {
423                                         // FIXME: email image
424                                         // n2->children->get_prop ("src"))
425                                         continue;
426                                 }
427
428                                 if (n2->children->name == "div" && text == "Beschreibung") {
429                                         var n3 = n2->children->children;
430                                         lift.description = "";
431                                         while (n3 != null) {
432                                                 if (n3->name == "text")
433                                                         lift.description += n3->content.strip () + "\n";
434                                                 n3 = n3->next;
435                                         }
436                                         continue;
437                                 } else if (n2->children->name != "text") {
438                                         continue;
439                                 }
440
441                                 var text1 = n2->children->content.strip ();
442
443                                 if (text == "Datum")
444                                         lift.date = text1;
445                                 else if (text == "Freie Pl\xc3\xa4tze")
446                                         lift.places = text1.to_int ();
447                                 else if (text == "Name")
448                                         lift.name = text1;
449                                 else if (text == "Handy")
450                                         lift.cell = text1;
451                                 else if (text == "Telefon")
452                                         lift.phone = text1;
453                                 else if (text == "Telefon 2")
454                                         lift.phone2 = text1;
455                                 else if (text == "E-Mail 1")
456                                         lift.email = text1;
457                                 else if (text != "Strecke & Infos" && text != "&nbsp;" &&
458                                     !text.has_prefix ("\xc2\xa0") && text != "Datum" &&
459                                     text != "Details")
460                                         continue;
461
462                                 n2 = n2->next;
463                                 if (n2 == null)
464                                         continue;
465
466                                 // Skip text between td nodes
467                                 if (n2->name == "text")
468                                         n2 = n2->next;
469
470                                 if (n2 == null || n2->name != "td" ||
471                                     n2->children == null)
472                                         continue;
473
474                                 if (n2->children->name == "span" &&
475                                     n2->children->get_prop ("class") == "icon_non_smoker") {
476                                         lift.flags |= LiftFlags.NON_SMOKER;
477                                         continue;
478                                 } else if (n2->children->name == "span" &&
479                                     n2->children->get_prop ("class") == "icon_smoker") {
480                                         lift.flags |= LiftFlags.SMOKER;
481                                         continue;
482                                 } else if (n2->children->name != "text")
483                                         continue;
484
485                                 var text2 = n2->children->content.strip ();
486
487                                 if (text1 == "von")
488                                         lift.city_from = text2;
489                                 else if (text1.has_prefix ("\xc3\xbc"))
490                                         lift.city_via.append (text2);
491                                 else if (text1 == "nach")
492                                         lift.city_to = text2;
493                                 else if (text1 == "Datum")
494                                         lift.date = text2;
495                                 else if (text1 == "Uhrzeit")
496                                         lift.time = text2;
497                                 else if (text1 == "Raucher")
498                                         print ("Raucher: %s\n", text2);
499                                 else if (text1 == "Fahrpreis")
500                                         lift.price = text2;
501                                 else if (text1 == "ADAC-Mitglied" && text2 != "nein")
502                                         lift.flags |= LiftFlags.ADAC_MEMBER;
503                         }
504                 }
505
506                 // The paragraph after the table contains the date of last modification
507                 var p = table->next;
508                 for (var n = p->children; n != null; n = n->next) {
509                         if (n->name != "text")
510                                 continue;
511
512                         var s = n->content.strip ();
513                         if (s.has_prefix ("Letztmalig aktualisiert am "))
514                                 lift.modified = s.offset (27).dup (); // "Do 15.04.2010 20:32"
515                 }
516
517                 return true;
518         }
519
520         Xml.Node* search_tag_by_property (Xml.Node* node, string tag, string prop, string val) requires (node != null) {
521                 for (var n = node; n != null; n = n->next) {
522                         if (n->name == tag && n->get_prop (prop) == val)
523                                 return n;
524                         if (n->children != null) {
525                                 var found = search_tag_by_property (n->children, tag, prop, val);
526                                 if (found != null)
527                                         return found;
528                         }
529                 }
530                 return null;
531         }
532
533         Xml.Node* search_tag_by_id (Xml.Node* node, string tag, string id) requires (node != null) {
534                 return search_tag_by_property (node, tag, "id", id);
535         }
536
537         Xml.Node* search_tag_by_name (Xml.Node* node, string tag, string name) requires (node != null) {
538                 return search_tag_by_property (node, tag, "name", name);
539         }
540
541         Xml.Node* search_tag_by_class (Xml.Node* node, string tag, string @class) requires (node != null) {
542                 return search_tag_by_property (node, tag, "class", @class);
543         }
544 }