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