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