04c03b94c850ea14c734fbf0bbb75e0655297767
[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                                 }
412                                 list.push_back(tmp);
413                                 e = &list.back();
414                                 read_descr=true;
415                                 ++entries;
416                         }
417                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
418                         {
419                                 e->name = line+13;
420                                 read_descr=false;
421                         }
422                         else if (!strncmp(line, "#NAME ", 6))
423                                 bouquet.m_bouquet_name=line+6;
424                         continue;
425                 }
426         }
427         fclose(fp);
428         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
429 }
430
431 void eDVBDB::saveBouquet(const char *path)
432 {
433
434 }
435
436 void eDVBDB::loadBouquets()
437 {
438         loadBouquet("bouquets.tv");
439         loadBouquet("bouquets.radio");
440 }
441
442 void eDVBDB::saveBouquets()
443 {
444
445 }
446
447 eDVBDB::eDVBDB()
448 {
449         load();
450         loadBouquets();
451 }
452
453 eDVBDB::~eDVBDB()
454 {
455 //      save();
456 }
457
458 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
459 {
460         channel ch;
461         assert(feparm);
462         ch.m_frontendParameters = feparm;
463         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
464         return 0;
465 }
466
467 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
468 {
469         m_channels.erase(id);
470         return 0;
471 }
472
473 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
474 {
475         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
476         if (i == m_channels.end())
477         {
478                 parm = 0;
479                 return -ENOENT;
480         }
481         parm = i->second.m_frontendParameters;
482         return 0;
483 }
484
485 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
486 {
487         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
488         return 0;
489 }
490
491 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
492 {
493         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
494         i = m_services.find(reference);
495         if (i == m_services.end())
496         {
497                 service = 0;
498                 return -ENOENT;
499         }
500         service = i->second;
501         return 0;
502 }
503
504 RESULT eDVBDB::getBouquet(const eServiceReference &ref, const eBouquet* &bouquet)
505 {
506         std::string str = ref.path;
507         if (str.empty())
508         {
509                 eDebug("getBouquet failed.. no path given!");
510                 return -1;
511         }
512         unsigned int pos = str.find("FROM BOUQUET \"");
513         if ( pos != std::string::npos )
514         {
515                 str.erase(0, pos+14);
516                 pos = str.find('"');
517                 if ( pos != std::string::npos )
518                         str.erase(pos);
519                 else
520                         str.clear();
521         }
522         if (str.empty())
523         {
524                 eDebug("getBouquet failed.. couldn't parse bouquet name");
525                 return -1;
526         }
527         std::map<std::string, eBouquet>::iterator i =
528                 m_bouquets.find(str);
529         if (i == m_bouquets.end())
530         {
531                 bouquet = 0;
532                 return -ENOENT;
533         }
534         bouquet = &i->second;
535         return 0;
536 }
537
538 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
539 {
540         if ( q && q->m_bouquet_name.length() )
541                 query = new eDVBDBBouquetQuery(this, source, q);
542         else
543                 query = new eDVBDBQuery(this, source, q);
544         return 0;
545 }
546
547 DEFINE_REF(eDVBDBQueryBase);
548
549 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
550         :m_db(db), m_query(query), m_source(source)
551 {
552 }
553
554 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
555 {
556         ePtr<eDVBService> a_service, b_service;
557         
558         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
559         
560         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
561         {
562                 if (m_db->getService(a, a_service))
563                         return 1;
564                 if (m_db->getService(b, b_service))
565                         return 1;
566         }
567         
568         switch (sortmode)
569         {
570         case eDVBChannelQuery::tName:
571                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
572         case eDVBChannelQuery::tProvider:
573                 return a_service->m_provider_name < b_service->m_provider_name;
574         case eDVBChannelQuery::tType:
575                 return a.getServiceType() < b.getServiceType();
576         case eDVBChannelQuery::tBouquet:
577                 return 0;
578         case eDVBChannelQuery::tSatellitePosition:
579                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
580         default:
581                 return 1;
582         }
583         return 0;
584 }
585
586 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
587         :eDVBDBQueryBase(db, source, query)
588 {
589         m_cursor = m_db->m_services.begin();
590 }
591
592 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
593 {
594         while (m_cursor != m_db->m_services.end())
595         {
596                 ref = m_cursor->first;
597
598                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
599
600                 ++m_cursor;
601
602                 if (res)
603                         return 0;
604         }
605
606         ref = eServiceReferenceDVB();
607         return 1;
608 }
609
610 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
611         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
612 {
613 }
614
615 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
616 {
617         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
618         std::list<eServiceReference> &list = bouquet.m_services;
619         while (m_cursor != list.end())
620         {
621                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
622
623                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
624                         m_db->m_services.find(ref);
625
626                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
627
628                 ++m_cursor;
629
630                 if (res)
631                         return 0;
632         }
633
634         ref = eServiceReferenceDVB();
635
636         return 1;
637 }
638
639 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
640
641 static int decodeType(const std::string &type)
642 {
643         if (type == "name")
644                 return eDVBChannelQuery::tName;
645         else if (type == "provider")
646                 return eDVBChannelQuery::tProvider;
647         else if (type == "type")
648                 return eDVBChannelQuery::tType;
649         else if (type == "bouquet")
650                 return eDVBChannelQuery::tBouquet;
651         else if (type == "satellitePosition")
652                 return eDVBChannelQuery::tSatellitePosition;
653         else if (type == "channelID")
654                 return eDVBChannelQuery::tChannelID;
655         else
656                 return -1;
657 }
658
659         /* never, NEVER write a parser in C++! */
660 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
661 {
662         std::list<std::string>::const_iterator end_of_exp;
663         if (*begin == "(")
664         {
665                 end_of_exp = begin;
666                 while (end_of_exp != end)
667                         if (*end_of_exp == ")")
668                                 break;
669                         else
670                                 ++end_of_exp;
671         
672                 if (end_of_exp == end)
673                 {
674                         eDebug("expression parse: end of expression while searching for closing brace");
675                         return -1;
676                 }
677                 
678                 ++begin;
679                 // begin..end_of_exp
680                 int r = parseExpression(res, begin, end_of_exp);
681                 if (r)
682                         return r;
683                 ++end_of_exp;
684                 
685                         /* we had only one sub expression */
686                 if (end_of_exp == end)
687                 {
688                         eDebug("only one sub expression");
689                         return 0;
690                 }
691                 
692                         /* otherwise we have an operator here.. */
693                 
694                 ePtr<eDVBChannelQuery> r2 = res;
695                 res = new eDVBChannelQuery();
696                 res->m_sort = 0;
697                 res->m_p1 = r2;
698                 res->m_inverse = 0;
699                 r2 = 0;
700                 
701                 if (*end_of_exp == "||")
702                         res->m_type = eDVBChannelQuery::tOR;
703                 else if (*end_of_exp == "&&")
704                         res->m_type = eDVBChannelQuery::tAND;
705                 else
706                 {
707                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
708                         res = 0;
709                         return 1;
710                 }
711                 
712                 ++end_of_exp;
713                 
714                 return parseExpression(res->m_p2, end_of_exp, end);
715         }
716         
717         // "begin" <op> "end"
718         std::string type, op, val;
719         
720         res = new eDVBChannelQuery();
721         res->m_sort = 0;
722         
723         int cnt = 0;
724         while (begin != end)
725         {
726                 switch (cnt)
727                 {
728                 case 0:
729                         type = *begin;
730                         break;
731                 case 1:
732                         op = *begin;
733                         break;
734                 case 2:
735                         val = *begin;
736                         break;
737                 case 3:
738                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
739                         return 1;
740                 }
741                 ++begin;
742                 ++cnt;
743         }
744         
745         if (cnt != 3)
746         {
747                 eDebug("malformed query: missing stuff");
748                 res = 0;
749                 return 1;
750         }
751         
752         res->m_type = decodeType(type);
753         
754         if (res->m_type == -1)
755         {
756                 eDebug("malformed query: invalid type %s", type.c_str());
757                 res = 0;
758                 return 1;
759         }
760         
761         if (op == "==")
762                 res->m_inverse = 0;
763         else if (op == "!=")
764                 res->m_inverse = 1;
765         else
766         {
767                 eDebug("invalid operator %s", op.c_str());
768                 res = 0;
769                 return 1;
770         }
771         
772         res->m_string = val;
773         res->m_int = atoi(val.c_str());
774 //      res->m_channelid = eDVBChannelID(val);
775         
776         return 0;
777 }
778
779 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
780 {
781         std::list<std::string> tokens;
782         
783         std::string current_token;
784         std::string bouquet_name;
785
786         eDebug("splitting %s....", query.c_str());
787         unsigned int i = 0;
788         const char *splitchars="()";
789         int quotemode = 0, lastsplit = 0, lastalnum = 0;
790         while (i <= query.size())
791         {
792                 int c = (i < query.size()) ? query[i] : ' ';
793                 ++i;
794                 
795                 int issplit = !!strchr(splitchars, c);
796                 int isaln = isalnum(c);
797                 int iswhite = c == ' ';
798                 int isquot = c == '\"';
799                 
800                 if (quotemode)
801                 {
802                         iswhite = issplit = 0;
803                         isaln = lastalnum;
804                 }
805                 
806                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
807                 {
808                         if (current_token.size())
809                                 tokens.push_back(current_token);
810                         current_token.clear();
811                 }
812                 
813                 if (!(iswhite || isquot))
814                         current_token += c;
815                 
816                 if (isquot)
817                         quotemode = !quotemode;
818                 lastsplit = issplit;
819                 lastalnum = isaln;
820         }
821         
822 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
823 //      {
824 //              printf("%s\n", a->c_str());
825 //      }
826
827         int sort = eDVBChannelQuery::tName;
828                 /* check for "ORDER BY ..." */
829
830         while (tokens.size() > 2)
831         {
832                 std::list<std::string>::iterator it = tokens.end();
833                 --it; --it; --it;
834                 if (*it == "ORDER")
835                 {
836                         ++it;
837                         if (*it == "BY")
838                         {
839                                 ++it;
840                                 sort = decodeType(*it);
841                                 tokens.pop_back(); // ...
842                                 tokens.pop_back(); // BY
843                                 tokens.pop_back(); // ORDER
844                         } else
845                                 sort = -1;
846                 }
847                 else if (*it == "FROM")
848                 {
849                         ++it;
850                         if (*it == "BOUQUET")
851                         {
852                                 ++it;
853                                 bouquet_name = *it;
854                                 tokens.pop_back(); // ...
855                                 tokens.pop_back(); // FROM
856                                 tokens.pop_back(); // BOUQUET
857                         }
858                 }
859                 else
860                         break;
861         }
862
863         if (sort == -1)
864         {
865                 eWarning("ORDER BY .. string invalid.");
866                 res = 0;
867                 return -1;
868         }
869         
870         eDebug("sort by %d", sort);
871         
872                 /* now we recursivly parse that. */
873         int r = parseExpression(res, tokens.begin(), tokens.end());
874         
875         if (res)
876         {
877                 res->m_sort = sort;
878                 res->m_bouquet_name = bouquet_name;
879         }
880
881         eDebug("return: %d", r);
882         return r;
883 }
884
885 DEFINE_REF(eDVBChannelQuery);