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