Don't keep a reused Soup.Message around just for error reporting
[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, string city_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=0&city_to=%d&radius_to=0".printf (
261                         num_from,
262                         num_to
263                 );
264
265                 url += "&date=date&day=%d&month=%d&year=%d&tolerance=%d&smoking=&avg_speed=&".printf (
266                         date.get_day (),
267                         date.get_month (),
268                         date.get_year (),
269                         tolerance
270                 );
271
272                 var doc = yield get_html_document (url);
273                 if (doc == null) {
274                         stderr.printf ("Error: parsing failed\n");
275                         return null;
276                 }
277
278                 var table = search_tag_by_class (doc->children, "table", "list p_15");
279                 if (table == null) {
280                         stderr.printf ("Error: does not contain list p_15 table\n");
281                         return null;
282                 }
283
284                 var list = new List<Lift> ();
285                 for (var n = table->children; n != null; n = n->next) {
286                         if (n->name == "tr") {
287                                 var lift = parse_lift_row (n->children);
288                                 if (lift.city_from != null) // Skip the title row
289                                         list.append ((owned) lift);
290                         }
291                 }
292
293                 // Error message?
294                 var div = table->next;
295                 if (div != null && div->get_prop ("class") == "error-message") {
296                         if (div->children == null || div->children->content == null ||
297                             !div->children->content.has_prefix ("Es sind leider noch keine Einträge vorhanden.")) {
298                                 stderr.printf ("Got an unknown error message!\n");
299                                 if (div->children != null && div->children->content != null)
300                                         stderr.printf ("\"%s\"\n", div->children->content);
301                         }
302                 }
303
304                 return list;
305         }
306
307         Lift parse_lift_row (Xml.Node* node) {
308                 var lift = new Lift ();
309                 int i = 0;
310                 for (var n = node; n != null; n = n->next) {
311                         if (n->name == "td") {
312                                 var n2 = n->children;
313                                 if (n2 != null) {
314                                         if (n2->name == "a") {
315                                                 var href = n2->get_prop ("href");
316                                                 if (href != null && lift.href == null)
317                                                         lift.href = href;
318                                                 var n3 = n2->children;
319                                                 while (n3 != null) {
320                                                         if (n3->name == "text")
321                                                                 switch (i) {
322                                                                 case 0:
323                                                                         lift.city_from = n3->content;
324                                                                         break;
325                                                                 case 1:
326                                                                         lift.city_to = n3->content;
327                                                                         break;
328                                                                 case 2:
329                                                                         parse_date (n3->content, out lift.time);
330                                                                         break;
331                                                                 case 3:
332                                                                         parse_time (n3->content.strip (), out lift.time);
333                                                                         break;
334                                                                 case 4:
335                                                                         lift.places = n3->content.to_int ();
336                                                                         break;
337                                                                 case 5:
338                                                                         lift.price = n3->content;
339                                                                         break;
340                                                                 default:
341                                                                         print ("TEXT:%s\n", n3->content);
342                                                                         break;
343                                                                 }
344                                                         if (n3->name == "span") {
345                                                                 string class = n3->get_prop ("class");
346                                                                 if (class == "icon_smoker")
347                                                                         lift.flags |= LiftFlags.SMOKER;
348                                                                 else if (class == "icon_non_smoker")
349                                                                         lift.flags |= LiftFlags.NON_SMOKER;
350                                                                 else if (class == "icon_adac")
351                                                                         lift.flags |= LiftFlags.ADAC_MEMBER;
352                                                                 else if (class == "icon_women")
353                                                                         lift.flags |= LiftFlags.WOMEN_ONLY;
354                                                                 else if (class != null)
355                                                                         print ("SPAN %s\n", class);
356                                                         }
357                                                         n3 = n3->next;
358                                                 }
359                                         }
360                                 }
361                                 i++;
362                         }
363                 }
364
365                 return lift;
366         }
367
368         public async bool update_lift_details (Lift lift) {
369                 string url = BASE_URI + lift.href;
370
371                 var doc = yield get_html_document (url);
372                 if (doc == null) {
373                         stderr.printf ("Error: parsing failed\n");
374                         return false;
375                 }
376
377                 var table = search_tag_by_class (doc->children, "table", "lift");
378                 if (table == null) {
379                         stderr.printf ("Error: does not contain lift table\n");
380                         return false;
381                 }
382
383                 Xml.Node* n;
384                 for (n = table->children; n != null; n = n->next) {
385                         if (n->name == "tr") {
386                                 var n2 = n->children;
387                                 if (n2 == null || n2->name != "td" ||
388                                     n2->children == null || n2->children->name != "text")
389                                         continue;
390
391                                 string text = n2->children->content;
392
393                                 if (text != "Strecke & Infos" && text != "&nbsp;" && !text.has_prefix ("\xc2\xa0") &&
394                                     text != "Datum" &&
395                                     text != "Freie Pl\xc3\xa4tze" &&
396                                     text != "Name" &&
397                                     text != "Handy" &&
398                                     text != "Telefon" &&
399                                     text != "Telefon 2" &&
400                                     text != "E-Mail 1" &&
401                                     text != "Details" &&
402                                     text != "Beschreibung")
403                                         continue;
404
405                                 n2 = n2->next;
406                                 if (n2 == null)
407                                         continue;
408
409                                 // Skip text between td nodes
410                                 if (n2->name == "text")
411                                         n2 = n2->next;
412
413                                 if (n2 == null || n2->name != "td" || n2->children == null)
414                                         continue;
415
416                                 if (n2->children->name == "img") {
417                                         // FIXME: email image
418                                         // n2->children->get_prop ("src"))
419                                         continue;
420                                 }
421
422                                 if (n2->children->name == "div" && text == "Beschreibung") {
423                                         var n3 = n2->children->children;
424                                         lift.description = "";
425                                         while (n3 != null) {
426                                                 if (n3->name == "text")
427                                                         lift.description += n3->content.strip () + "\n";
428                                                 n3 = n3->next;
429                                         }
430                                         continue;
431                                 } else if (n2->children->name != "text") {
432                                         continue;
433                                 }
434
435                                 var text1 = n2->children->content.strip ();
436
437                                 if (text == "Freie Pl\xc3\xa4tze")
438                                         lift.places = text1.to_int ();
439                                 else if (text == "Name")
440                                         lift.name = text1;
441                                 else if (text == "Handy")
442                                         lift.cell = text1;
443                                 else if (text == "Telefon")
444                                         lift.phone = text1;
445                                 else if (text == "Telefon 2")
446                                         lift.phone2 = text1;
447                                 else if (text == "E-Mail 1")
448                                         lift.email = text1;
449                                 else if (text != "Strecke & Infos" && text != "&nbsp;" &&
450                                     !text.has_prefix ("\xc2\xa0") && text != "Datum" &&
451                                     text != "Details")
452                                         continue;
453
454                                 n2 = n2->next;
455                                 if (n2 == null)
456                                         continue;
457
458                                 // Skip text between td nodes
459                                 if (n2->name == "text")
460                                         n2 = n2->next;
461
462                                 if (n2 == null || n2->name != "td" ||
463                                     n2->children == null)
464                                         continue;
465
466                                 if (n2->children->name == "span" &&
467                                     n2->children->get_prop ("class") == "icon_non_smoker") {
468                                         lift.flags |= LiftFlags.NON_SMOKER;
469                                         continue;
470                                 } else if (n2->children->name == "span" &&
471                                     n2->children->get_prop ("class") == "icon_smoker") {
472                                         lift.flags |= LiftFlags.SMOKER;
473                                         continue;
474                                 } else if (n2->children->name != "text")
475                                         continue;
476
477                                 var text2 = n2->children->content.strip ();
478
479                                 if (text1 == "von")
480                                         lift.city_from = text2;
481                                 else if (text1.has_prefix ("\xc3\xbc"))
482                                         lift.city_via.append (text2);
483                                 else if (text1 == "nach")
484                                         lift.city_to = text2;
485                                 else if (text1 == "Datum")
486                                         parse_date (text2, out lift.time);
487                                 else if (text1 == "Uhrzeit")
488                                         parse_time (text2, out lift.time);
489                                 else if (text1 == "Raucher")
490                                         print ("Raucher: %s\n", text2);
491                                 else if (text1 == "Fahrpreis")
492                                         lift.price = text2;
493                                 else if (text1 == "ADAC-Mitglied" && text2 != "nein")
494                                         lift.flags |= LiftFlags.ADAC_MEMBER;
495                         }
496                 }
497
498                 // The paragraph after the table contains the date of last modification
499                 var p = table->next;
500                 for (n = p->children; n != null; n = n->next) {
501                         if (n->name != "text")
502                                 continue;
503
504                         var s = n->content.strip ();
505                         if (s.has_prefix ("Letztmalig aktualisiert am "))
506                                 lift.modified = s.offset (27).dup (); // "Do 15.04.2010 20:32"
507                 }
508
509                 return true;
510         }
511
512         Xml.Node* search_tag_by_property (Xml.Node* node, string tag, string prop, string val) requires (node != null) {
513                 for (var n = node; n != null; n = n->next) {
514                         if (n->name == tag && n->get_prop (prop) == val)
515                                 return n;
516                         if (n->children != null) {
517                                 var found = search_tag_by_property (n->children, tag, prop, val);
518                                 if (found != null)
519                                         return found;
520                         }
521                 }
522                 return null;
523         }
524
525         Xml.Node* search_tag_by_id (Xml.Node* node, string tag, string id) requires (node != null) {
526                 return search_tag_by_property (node, tag, "id", id);
527         }
528
529         Xml.Node* search_tag_by_name (Xml.Node* node, string tag, string name) requires (node != null) {
530                 return search_tag_by_property (node, tag, "name", name);
531         }
532
533         Xml.Node* search_tag_by_class (Xml.Node* node, string tag, string @class) requires (node != null) {
534                 return search_tag_by_property (node, tag, "class", @class);
535         }
536
537         void parse_date (string date, out Time time) {
538                 int year;
539                 if (date.length == 11)
540                         date = date.offset (3);
541                 if (date.length != 8)
542                         return;
543                 var res = date.scanf ("%02d.%02d.%02d", out time.day, out time.month, out year);
544                 time.year = year + 2000;
545         }
546
547         void parse_time (string time, out Time result) {
548                 var res = time.scanf ("%d.%02d Uhr", out result.hour, out result.minute);
549         }
550 }