remove unneeded comment
[enigma2.git] / lib / dvb / db.cpp
1 #include <errno.h>
2 #include <lib/dvb/db.h>
3 #include <lib/dvb/frontend.h>
4 #include <lib/base/eerror.h>
5 #include <lib/base/estring.h>
6 #include <dvbsi++/service_description_section.h>
7 #include <dvbsi++/descriptor_tag.h>
8 #include <dvbsi++/service_descriptor.h>
9 #include <dvbsi++/satellite_delivery_system_descriptor.h>
10
11 DEFINE_REF(eDVBService);
12
13 eDVBService::eDVBService()
14 {
15 }
16
17 eDVBService::~eDVBService()
18 {
19 }
20
21 eDVBService &eDVBService::operator=(const eDVBService &s)
22 {
23         m_service_name = s.m_service_name;
24         m_service_name_sort = s.m_service_name_sort;
25         m_provider_name = s.m_provider_name;
26         m_flags = s.m_flags;
27         m_ca = s.m_ca;
28         m_cache = s.m_cache;
29         return *this;
30 }
31
32 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
33 {
34         if ( ref.name.length() )
35                 name = ref.name;
36         else
37                 name = m_service_name;
38         return 0;
39 }
40
41 int eDVBService::getLength(const eServiceReference &ref)
42 {
43         return -1;
44 }
45
46 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
47 {
48         int res = 0;
49         switch (query.m_type)
50         {
51         case eDVBChannelQuery::tName:
52                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
53                 break;
54         case eDVBChannelQuery::tProvider:
55                 res = m_provider_name.find(query.m_string) != std::string::npos;
56                 break;
57         case eDVBChannelQuery::tType:
58                 res = ref.getServiceType() == query.m_int;
59                 break;
60         case eDVBChannelQuery::tBouquet:
61                 res = 0;
62                 break;
63         case eDVBChannelQuery::tSatellitePosition:
64                 res = (ref.getDVBNamespace().get() >> 16) == query.m_int;
65                 break;
66         case eDVBChannelQuery::tChannelID:
67         {
68                 eDVBChannelID chid;
69                 ref.getChannelID(chid);
70                 res = chid == query.m_channelid;
71                 break;
72         }
73         case eDVBChannelQuery::tAND:
74                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
75                 break;
76         case eDVBChannelQuery::tOR:
77                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
78                 break;
79         }
80
81         if (query.m_inverse)
82                 return !res;
83         else
84                 return res;
85 }
86
87 int eDVBService::getCachePID(cacheID id)
88 {
89         std::map<int, int>::iterator it = m_cache.find(id);
90         if ( it != m_cache.end() )
91                 return it->second;
92         return -1;
93 }
94
95 void eDVBService::setCachePID(cacheID id, int pid)
96 {
97         m_cache[id] = pid;
98 }
99
100 DEFINE_REF(eDVBDB);
101
102         /* THIS CODE IS BAD. it should be replaced by somethine better. */
103 void eDVBDB::load()
104 {
105         eDebug("---- opening lame channel db");
106         FILE *f=fopen("lamedb", "rt");
107         if (!f)
108                 return;
109         char line[256];
110         if ((!fgets(line, 256, f)) || strncmp(line, "eDVB services", 13))
111         {
112                 eDebug("not a servicefile");
113                 fclose(f);
114                 return;
115         }
116         eDebug("reading services");
117         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
118         {
119                 eDebug("services invalid, no transponders");
120                 fclose(f);
121                 return;
122         }
123
124         // clear all transponders
125
126         while (!feof(f))
127         {
128                 if (!fgets(line, 256, f))
129                         break;
130                 if (!strcmp(line, "end\n"))
131                         break;
132                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
133                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
134                 if (original_network_id == -1)
135                         continue;
136                 eDVBChannelID channelid = eDVBChannelID(
137                         eDVBNamespace(dvb_namespace),
138                         eTransportStreamID(transport_stream_id),
139                         eOriginalNetworkID(original_network_id));
140
141                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
142                 while (!feof(f))
143                 {
144                         fgets(line, 256, f);
145                         if (!strcmp(line, "/\n"))
146                                 break;
147                         if (line[1]=='s')
148                         {
149                                 eDVBFrontendParametersSatellite sat;
150                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion;
151                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion);
152                                 sat.frequency = frequency;
153                                 sat.symbol_rate = symbol_rate;
154                                 sat.polarisation = polarisation;
155                                 sat.fec = fec;
156                                 sat.orbital_position = orbital_position;
157                                 sat.inversion = inversion;
158                                 // ...
159 //                              t.setSatellite(frequency, symbol_rate, polarisation, fec, sat, inversion);
160                                 feparm->setDVBS(sat);
161                         } else if (line[1]=='t')
162                         {
163                                 eDVBFrontendParametersTerrestrial ter;
164                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion;
165                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion);
166                                 ter.frequency = frequency;
167                                 ter.bandwidth = bandwidth;
168                                 ter.code_rate_HP = code_rate_HP;
169                                 ter.code_rate_LP = code_rate_LP;
170                                 ter.modulation = modulation;
171                                 ter.transmission_mode = transmission_mode;
172                                 ter.guard_interval = guard_interval;
173                                 ter.hierarchy = hierarchy;
174                                 ter.inversion = inversion;
175                                 
176                                 feparm->setDVBT(ter);
177                         } else if (line[1]=='c')
178                         {
179                                 int frequency, symbol_rate, inversion=0, modulation=3;
180                                 sscanf(line+2, "%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation);
181 //                              t.setCable(frequency, symbol_rate, inversion, modulation);
182                         }
183                 }
184                 addChannelToList(channelid, feparm);
185         }
186
187         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
188         {
189                 eDebug("services invalid, no services");
190                 return;
191         }
192
193         // clear all services
194
195         int count=0;
196
197         while (!feof(f))
198         {
199                 if (!fgets(line, 256, f))
200                         break;
201                 if (!strcmp(line, "end\n"))
202                         break;
203
204                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
205                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
206                 if (service_number == -1)
207                         continue;
208                 ePtr<eDVBService> s = new eDVBService;
209                 eServiceReferenceDVB ref =
210                                                 eServiceReferenceDVB(
211                                                 eDVBNamespace(dvb_namespace),
212                                                 eTransportStreamID(transport_stream_id),
213                                                 eOriginalNetworkID(original_network_id),
214                                                 eServiceID(service_id),
215                                                 service_type);
216                 count++;
217                 fgets(line, 256, f);
218                 if (strlen(line))
219                         line[strlen(line)-1]=0;
220
221                 s->m_service_name = line;
222                 s->m_service_name_sort = removeDVBChars(line);
223                 makeUpper(s->m_service_name_sort);
224
225                 fgets(line, 256, f);
226                 if (strlen(line))
227                         line[strlen(line)-1]=0;
228
229                 std::string str=line;
230
231                 if (str[1]!=':')        // old ... (only service_provider)
232                 {
233                         s->m_provider_name=line;
234                 } else
235                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
236                         {
237                                 unsigned int c=str.find(',');
238                                 char p=str[0];
239                                 std::string v;
240                                 if (c == std::string::npos)
241                                 {
242                                         v=str.substr(2);
243                                         str="";
244                                 } else
245                                 {
246                                         v=str.substr(2, c-2);
247                                         str=str.substr(c+1);
248                                 }
249 //                              eDebug("%c ... %s", p, v.c_str());
250                                 if (p == 'p')
251                                         s->m_provider_name=v;
252                                 else if (p == 'f')
253                                 {
254                                         sscanf(v.c_str(), "%x", &s->m_flags);
255                                 } else if (p == 'c')
256                                 {
257                                         int cid, val;
258                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
259                                         s->m_cache[cid]=val;
260                                 } else if (p == 'C')
261                                 {
262                                         int val;
263                                         sscanf(v.c_str(), "%04x", &val);
264                                         s->m_ca.insert(val);
265                                 }
266                         }
267                 addService(ref, s);
268         }
269
270         eDebug("loaded %d services", count);
271
272         fclose(f);
273 }
274
275 void eDVBDB::save()
276 {
277         eDebug("---- saving lame channel db");
278         FILE *f=fopen("lamedb", "wt");
279         int channels=0, services=0;
280         if (!f)
281                 eFatal("couldn't save lame channel db!");
282         fprintf(f, "eDVB services /3/\n");
283         fprintf(f, "transponders\n");
284         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
285                         i != m_channels.end(); ++i)
286         {
287                 const eDVBChannelID &chid = i->first;
288                 const channel &ch = i->second;
289
290                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
291                                 chid.transport_stream_id.get(), chid.original_network_id.get());
292                 eDVBFrontendParametersSatellite sat;
293                 eDVBFrontendParametersTerrestrial ter;
294                 if (!ch.m_frontendParameters->getDVBS(sat))
295                 {
296                         fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
297                                 sat.frequency, sat.symbol_rate,
298                                 sat.polarisation, sat.fec, sat.orbital_position,
299                                 sat.inversion);
300                 }
301                 if (!ch.m_frontendParameters->getDVBT(ter))
302                 {
303                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
304                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
305                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
306                                 ter.guard_interval, ter.hierarchy, ter.inversion);
307                 }
308                 fprintf(f, "/\n");
309                 channels++;
310         }
311         fprintf(f, "end\nservices\n");
312
313         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
314                 i != m_services.end(); ++i)
315         {
316                 const eServiceReferenceDVB &s = i->first;
317                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
318                                 s.getServiceID().get(), s.getDVBNamespace().get(),
319                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
320                                 s.getServiceType(),
321                                 0);
322
323                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
324                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
325
326                 // write cached pids
327                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
328                         ca != i->second->m_cache.end(); ++ca)
329                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
330
331                 // write cached ca pids
332                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
333                         ca != i->second->m_ca.end(); ++ca)
334                         fprintf(f, ",C:%04x", *ca);
335
336                 fprintf(f, "\n");
337                 services++;
338         }
339         fprintf(f, "end\nHave a lot of bugs!\n");
340         eDebug("saved %d channels and %d services!", channels, services);
341         fclose(f);
342 }
343
344 void eDVBDB::loadBouquet(const char *path)
345 {
346         std::string bouquet_name = path;
347         if (!bouquet_name.length())
348         {
349                 eDebug("Bouquet load failed.. no path given..");
350                 return;
351         }
352         unsigned int pos = bouquet_name.rfind('/');
353         if ( pos != std::string::npos )
354                 bouquet_name.erase(0, pos+1);
355         if (bouquet_name.empty())
356         {
357                 eDebug("Bouquet load failed.. no filename given..");
358                 return;
359         }
360         eBouquet &bouquet = m_bouquets[bouquet_name];
361         bouquet.m_path = path;
362         std::list<eServiceReference> &list = bouquet.m_services;
363         list.clear();
364
365         eDebug("loading bouquet... %s", path);
366         FILE *fp=fopen(path, "rt");
367         int entries=0;
368         if (!fp)
369         {
370                 eDebug("failed to open.");
371                 return;
372         }
373         char line[256];
374         bool read_descr=false;
375         eServiceReference *e = NULL;
376         while (1)
377         {
378                 if (!fgets(line, 256, fp))
379                         break;
380                 line[strlen(line)-1]=0;
381                 if (strlen(line) && line[strlen(line)-1]=='\r')
382                         line[strlen(line)-1]=0;
383                 if (!line[0])
384                         break;
385                 if (line[0]=='#')
386                 {
387                         if (!strncmp(line, "#SERVICE ", 9) || !strncmp(line, "#SERVICE: ", 10))
388                         {
389                                 int offs = line[8] == ':' ? 10 : 9;
390                                 eServiceReference tmp(line+offs);
391                                 if (tmp.type != eServiceReference::idDVB)
392                                 {
393                                         eDebug("only DVB Bouquets supported");
394                                         continue;
395                                 }
396                                 if ( (tmp.flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
397                                 {
398                                         std::string str = tmp.path;
399                                         unsigned int pos = str.rfind('/');
400                                         if ( pos != std::string::npos )
401                                                 str.erase(0, pos+1);
402                                         if (str.empty())
403                                         {
404                                                 eDebug("Bouquet load failed.. no filename given..");
405                                                 continue;
406                                         }
407                                         loadBouquet(tmp.path.c_str());
408                                         char buf[256];
409                                         snprintf(buf, 256, "(type == %d) FROM BOUQUET \"%s\" ORDER BY bouquet", tmp.data[0], str.c_str());
410                                         tmp.path = buf;
411                                         eDebug("read bouquet %s", tmp.toString().c_str());
412                                 }
413                                 list.push_back(tmp);
414                                 e = &list.back();
415                                 read_descr=true;
416                                 ++entries;
417                         }
418                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
419                         {
420                                 e->name = line+13;
421                                 read_descr=false;
422                         }
423                         else if (!strncmp(line, "#NAME ", 6))
424                                 bouquet.m_bouquet_name=line+6;
425                         continue;
426                 }
427         }
428         fclose(fp);
429         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
430 }
431
432 void eDVBDB::saveBouquet(const char *path)
433 {
434
435 }
436
437 void eDVBDB::loadBouquets()
438 {
439         loadBouquet("bouquets.tv");
440         loadBouquet("bouquets.radio");
441 }
442
443 void eDVBDB::saveBouquets()
444 {
445
446 }
447
448 eDVBDB::eDVBDB()
449 {
450         load();
451         loadBouquets();
452 }
453
454 eDVBDB::~eDVBDB()
455 {
456 //      save();
457 }
458
459 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
460 {
461         channel ch;
462         assert(feparm);
463         ch.m_frontendParameters = feparm;
464         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
465         return 0;
466 }
467
468 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
469 {
470         m_channels.erase(id);
471         return 0;
472 }
473
474 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
475 {
476         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
477         if (i == m_channels.end())
478         {
479                 parm = 0;
480                 return -ENOENT;
481         }
482         parm = i->second.m_frontendParameters;
483         return 0;
484 }
485
486 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
487 {
488         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
489         return 0;
490 }
491
492 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
493 {
494         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
495         i = m_services.find(reference);
496         if (i == m_services.end())
497         {
498                 service = 0;
499                 return -ENOENT;
500         }
501         service = i->second;
502         return 0;
503 }
504
505 RESULT eDVBDB::getBouquet(const eServiceReference &ref, const eBouquet* &bouquet)
506 {
507         std::string str = ref.path;
508         if (str.empty())
509         {
510                 eDebug("getBouquet failed.. no path given!");
511                 return -1;
512         }
513         unsigned int pos = str.find("FROM BOUQUET \"");
514         if ( pos != std::string::npos )
515         {
516                 str.erase(0, pos+14);
517                 eDebug("str now %s", str.c_str());
518                 pos = str.find('"');
519                 if ( pos != std::string::npos )
520                         str.erase(pos);
521                 else
522                         str.clear();
523                 eDebug("str now %s", str.c_str());
524         }
525         if (str.empty())
526         {
527                 eDebug("getBouquet failed.. couldn't parse bouquet name");
528                 return -1;
529         }
530         std::map<std::string, eBouquet>::iterator i =
531                 m_bouquets.find(str);
532         if (i == m_bouquets.end())
533         {
534                 bouquet = 0;
535                 return -ENOENT;
536         }
537         bouquet = &i->second;
538         return 0;
539 }
540
541 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
542 {
543         if ( q && q->m_bouquet_name.length() )
544                 query = new eDVBDBBouquetQuery(this, source, q);
545         else
546                 query = new eDVBDBQuery(this, source, q);
547         return 0;
548 }
549
550 DEFINE_REF(eDVBDBQueryBase);
551
552 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
553         :m_db(db), m_query(query), m_source(source)
554 {
555 }
556
557 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
558 {
559         ePtr<eDVBService> a_service, b_service;
560         
561         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
562         
563         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
564         {
565                 if (m_db->getService(a, a_service))
566                         return 1;
567                 if (m_db->getService(b, b_service))
568                         return 1;
569         }
570         
571         switch (sortmode)
572         {
573         case eDVBChannelQuery::tName:
574                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
575         case eDVBChannelQuery::tProvider:
576                 return a_service->m_provider_name < b_service->m_provider_name;
577         case eDVBChannelQuery::tType:
578                 return a.getServiceType() < b.getServiceType();
579         case eDVBChannelQuery::tBouquet:
580                 return 0;
581         case eDVBChannelQuery::tSatellitePosition:
582                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
583         default:
584                 return 1;
585         }
586         return 0;
587 }
588
589 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
590         :eDVBDBQueryBase(db, source, query)
591 {
592         m_cursor = m_db->m_services.begin();
593 }
594
595 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
596 {
597         while (m_cursor != m_db->m_services.end())
598         {
599                 ref = m_cursor->first;
600
601                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
602
603                 ++m_cursor;
604
605                 if (res)
606                         return 0;
607         }
608
609         ref = eServiceReferenceDVB();
610         return 1;
611 }
612
613 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
614         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
615 {
616 }
617
618 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
619 {
620         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
621         std::list<eServiceReference> &list = bouquet.m_services;
622         while (m_cursor != list.end())
623         {
624                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
625
626                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
627                         m_db->m_services.find(ref);
628
629                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
630
631                 ++m_cursor;
632
633                 if (res)
634                         return 0;
635         }
636
637         ref = eServiceReferenceDVB();
638
639         return 1;
640 }
641
642 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
643
644 static int decodeType(const std::string &type)
645 {
646         if (type == "name")
647                 return eDVBChannelQuery::tName;
648         else if (type == "provider")
649                 return eDVBChannelQuery::tProvider;
650         else if (type == "type")
651                 return eDVBChannelQuery::tType;
652         else if (type == "bouquet")
653                 return eDVBChannelQuery::tBouquet;
654         else if (type == "satellitePosition")
655                 return eDVBChannelQuery::tSatellitePosition;
656         else if (type == "channelID")
657                 return eDVBChannelQuery::tChannelID;
658         else
659                 return -1;
660 }
661
662         /* never, NEVER write a parser in C++! */
663 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
664 {
665         std::list<std::string>::const_iterator end_of_exp;
666         if (*begin == "(")
667         {
668                 end_of_exp = begin;
669                 while (end_of_exp != end)
670                         if (*end_of_exp == ")")
671                                 break;
672                         else
673                                 ++end_of_exp;
674         
675                 if (end_of_exp == end)
676                 {
677                         eDebug("expression parse: end of expression while searching for closing brace");
678                         return -1;
679                 }
680                 
681                 ++begin;
682                 // begin..end_of_exp
683                 int r = parseExpression(res, begin, end_of_exp);
684                 if (r)
685                         return r;
686                 ++end_of_exp;
687                 
688                         /* we had only one sub expression */
689                 if (end_of_exp == end)
690                 {
691                         eDebug("only one sub expression");
692                         return 0;
693                 }
694                 
695                         /* otherwise we have an operator here.. */
696                 
697                 ePtr<eDVBChannelQuery> r2 = res;
698                 res = new eDVBChannelQuery();
699                 res->m_sort = 0;
700                 res->m_p1 = r2;
701                 res->m_inverse = 0;
702                 r2 = 0;
703                 
704                 if (*end_of_exp == "||")
705                         res->m_type = eDVBChannelQuery::tOR;
706                 else if (*end_of_exp == "&&")
707                         res->m_type = eDVBChannelQuery::tAND;
708                 else
709                 {
710                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
711                         res = 0;
712                         return 1;
713                 }
714                 
715                 ++end_of_exp;
716                 
717                 return parseExpression(res->m_p2, end_of_exp, end);
718         }
719         
720         // "begin" <op> "end"
721         std::string type, op, val;
722         
723         res = new eDVBChannelQuery();
724         res->m_sort = 0;
725         
726         int cnt = 0;
727         while (begin != end)
728         {
729                 switch (cnt)
730                 {
731                 case 0:
732                         type = *begin;
733                         break;
734                 case 1:
735                         op = *begin;
736                         break;
737                 case 2:
738                         val = *begin;
739                         break;
740                 case 3:
741                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
742                         return 1;
743                 }
744                 ++begin;
745                 ++cnt;
746         }
747         
748         if (cnt != 3)
749         {
750                 eDebug("malformed query: missing stuff");
751                 res = 0;
752                 return 1;
753         }
754         
755         res->m_type = decodeType(type);
756         
757         if (res->m_type == -1)
758         {
759                 eDebug("malformed query: invalid type %s", type.c_str());
760                 res = 0;
761                 return 1;
762         }
763         
764         if (op == "==")
765                 res->m_inverse = 0;
766         else if (op == "!=")
767                 res->m_inverse = 1;
768         else
769         {
770                 eDebug("invalid operator %s", op.c_str());
771                 res = 0;
772                 return 1;
773         }
774         
775         res->m_string = val;
776         res->m_int = atoi(val.c_str());
777 //      res->m_channelid = eDVBChannelID(val);
778         
779         return 0;
780 }
781
782 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
783 {
784         std::list<std::string> tokens;
785         
786         std::string current_token;
787         std::string bouquet_name;
788
789         eDebug("splitting %s....", query.c_str());
790         unsigned int i = 0;
791         const char *splitchars="()";
792         int quotemode = 0, lastsplit = 0, lastalnum = 0;
793         while (i <= query.size())
794         {
795                 int c = (i < query.size()) ? query[i] : ' ';
796                 ++i;
797                 
798                 int issplit = !!strchr(splitchars, c);
799                 int isaln = isalnum(c);
800                 int iswhite = c == ' ';
801                 int isquot = c == '\"';
802                 
803                 if (quotemode)
804                 {
805                         iswhite = issplit = 0;
806                         isaln = lastalnum;
807                 }
808                 
809                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
810                 {
811                         if (current_token.size())
812                                 tokens.push_back(current_token);
813                         current_token.clear();
814                 }
815                 
816                 if (!(iswhite || isquot))
817                         current_token += c;
818                 
819                 if (isquot)
820                         quotemode = !quotemode;
821                 lastsplit = issplit;
822                 lastalnum = isaln;
823         }
824         
825 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
826 //      {
827 //              printf("%s\n", a->c_str());
828 //      }
829
830         int sort = eDVBChannelQuery::tName;
831                 /* check for "ORDER BY ..." */
832
833         while (tokens.size() > 2)
834         {
835                 std::list<std::string>::iterator it = tokens.end();
836                 --it; --it; --it;
837                 if (*it == "ORDER")
838                 {
839                         ++it;
840                         if (*it == "BY")
841                         {
842                                 ++it;
843                                 sort = decodeType(*it);
844                                 tokens.pop_back(); // ...
845                                 tokens.pop_back(); // BY
846                                 tokens.pop_back(); // ORDER
847                         } else
848                                 sort = -1;
849                 }
850                 else if (*it == "FROM")
851                 {
852                         ++it;
853                         if (*it == "BOUQUET")
854                         {
855                                 ++it;
856                                 bouquet_name = *it;
857                                 tokens.pop_back(); // ...
858                                 tokens.pop_back(); // FROM
859                                 tokens.pop_back(); // BOUQUET
860                         }
861                 }
862                 else
863                         break;
864         }
865
866         if (sort == -1)
867         {
868                 eWarning("ORDER BY .. string invalid.");
869                 res = 0;
870                 return -1;
871         }
872         
873         eDebug("sort by %d", sort);
874         
875                 /* now we recursivly parse that. */
876         int r = parseExpression(res, tokens.begin(), tokens.end());
877         
878         if (res)
879         {
880                 res->m_sort = sort;
881                 res->m_bouquet_name = bouquet_name;
882         }
883
884         eDebug("return: %d", r);
885         return r;
886 }
887
888 DEFINE_REF(eDVBChannelQuery);