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