fix linked tuners (i hope)
[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 ( q && q->m_bouquet_name.length() )
688                 query = new eDVBDBBouquetQuery(this, source, q);
689         else
690                 query = new eDVBDBQuery(this, source, q);
691         return 0;
692 }
693
694 DEFINE_REF(eDVBDBQueryBase);
695
696 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
697         :m_db(db), m_query(query), m_source(source)
698 {
699 }
700
701 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
702 {
703         ePtr<eDVBService> a_service, b_service;
704         
705         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
706         
707         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
708         {
709                 if (m_db->getService(a, a_service))
710                         return 1;
711                 if (m_db->getService(b, b_service))
712                         return 1;
713         }
714         
715         switch (sortmode)
716         {
717         case eDVBChannelQuery::tName:
718                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
719         case eDVBChannelQuery::tProvider:
720                 return a_service->m_provider_name < b_service->m_provider_name;
721         case eDVBChannelQuery::tType:
722                 return a.getServiceType() < b.getServiceType();
723         case eDVBChannelQuery::tBouquet:
724                 return 0;
725         case eDVBChannelQuery::tSatellitePosition:
726                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
727         default:
728                 return 1;
729         }
730         return 0;
731 }
732
733 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
734         :eDVBDBQueryBase(db, source, query)
735 {
736         m_cursor = m_db->m_services.begin();
737 }
738
739 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
740 {
741         while (m_cursor != m_db->m_services.end())
742         {
743                 ref = m_cursor->first;
744
745                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
746
747                 ++m_cursor;
748
749                 if (res)
750                         return 0;
751         }
752
753         ref.type = eServiceReference::idInvalid;
754
755         return 1;
756 }
757
758 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
759         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
760 {
761 }
762
763 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
764 {
765         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
766         std::list<eServiceReference> &list = bouquet.m_services;
767         while (m_cursor != list.end())
768         {
769                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
770
771                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
772                         m_db->m_services.find(ref);
773
774                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
775
776                 ++m_cursor;
777
778                 if (res)
779                         return 0;
780         }
781
782         ref.type = eServiceReference::idInvalid;
783
784         return 1;
785 }
786
787 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
788
789 static int decodeType(const std::string &type)
790 {
791         if (type == "name")
792                 return eDVBChannelQuery::tName;
793         else if (type == "provider")
794                 return eDVBChannelQuery::tProvider;
795         else if (type == "type")
796                 return eDVBChannelQuery::tType;
797         else if (type == "bouquet")
798                 return eDVBChannelQuery::tBouquet;
799         else if (type == "satellitePosition")
800                 return eDVBChannelQuery::tSatellitePosition;
801         else if (type == "channelID")
802                 return eDVBChannelQuery::tChannelID;
803         else
804                 return -1;
805 }
806
807         /* never, NEVER write a parser in C++! */
808 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
809 {
810         std::list<std::string>::const_iterator end_of_exp;
811         if (*begin == "(")
812         {
813                 end_of_exp = begin;
814                 while (end_of_exp != end)
815                         if (*end_of_exp == ")")
816                                 break;
817                         else
818                                 ++end_of_exp;
819         
820                 if (end_of_exp == end)
821                 {
822                         eDebug("expression parse: end of expression while searching for closing brace");
823                         return -1;
824                 }
825                 
826                 ++begin;
827                 // begin..end_of_exp
828                 int r = parseExpression(res, begin, end_of_exp);
829                 if (r)
830                         return r;
831                 ++end_of_exp;
832                 
833                         /* we had only one sub expression */
834                 if (end_of_exp == end)
835                 {
836 //                      eDebug("only one sub expression");
837                         return 0;
838                 }
839                 
840                         /* otherwise we have an operator here.. */
841                 
842                 ePtr<eDVBChannelQuery> r2 = res;
843                 res = new eDVBChannelQuery();
844                 res->m_sort = 0;
845                 res->m_p1 = r2;
846                 res->m_inverse = 0;
847                 r2 = 0;
848                 
849                 if (*end_of_exp == "||")
850                         res->m_type = eDVBChannelQuery::tOR;
851                 else if (*end_of_exp == "&&")
852                         res->m_type = eDVBChannelQuery::tAND;
853                 else
854                 {
855                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
856                         res = 0;
857                         return 1;
858                 }
859                 
860                 ++end_of_exp;
861                 
862                 return parseExpression(res->m_p2, end_of_exp, end);
863         }
864         
865         // "begin" <op> "end"
866         std::string type, op, val;
867         
868         res = new eDVBChannelQuery();
869         res->m_sort = 0;
870         
871         int cnt = 0;
872         while (begin != end)
873         {
874                 switch (cnt)
875                 {
876                 case 0:
877                         type = *begin;
878                         break;
879                 case 1:
880                         op = *begin;
881                         break;
882                 case 2:
883                         val = *begin;
884                         break;
885                 case 3:
886                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
887                         return 1;
888                 }
889                 ++begin;
890                 ++cnt;
891         }
892         
893         if (cnt != 3)
894         {
895                 eDebug("malformed query: missing stuff");
896                 res = 0;
897                 return 1;
898         }
899         
900         res->m_type = decodeType(type);
901         
902         if (res->m_type == -1)
903         {
904                 eDebug("malformed query: invalid type %s", type.c_str());
905                 res = 0;
906                 return 1;
907         }
908         
909         if (op == "==")
910                 res->m_inverse = 0;
911         else if (op == "!=")
912                 res->m_inverse = 1;
913         else
914         {
915                 eDebug("invalid operator %s", op.c_str());
916                 res = 0;
917                 return 1;
918         }
919         
920         res->m_string = val;
921         res->m_int = atoi(val.c_str());
922 //      res->m_channelid = eDVBChannelID(val);
923         
924         return 0;
925 }
926
927 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
928 {
929         std::list<std::string> tokens;
930         
931         std::string current_token;
932         std::string bouquet_name;
933
934 //      eDebug("splitting %s....", query.c_str());
935         unsigned int i = 0;
936         const char *splitchars="()";
937         int quotemode = 0, lastsplit = 0, lastalnum = 0;
938         while (i <= query.size())
939         {
940                 int c = (i < query.size()) ? query[i] : ' ';
941                 ++i;
942                 
943                 int issplit = !!strchr(splitchars, c);
944                 int isaln = isalnum(c);
945                 int iswhite = c == ' ';
946                 int isquot = c == '\"';
947                 
948                 if (quotemode)
949                 {
950                         iswhite = issplit = 0;
951                         isaln = lastalnum;
952                 }
953                 
954                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
955                 {
956                         if (current_token.size())
957                                 tokens.push_back(current_token);
958                         current_token.clear();
959                 }
960                 
961                 if (!(iswhite || isquot))
962                         current_token += c;
963                 
964                 if (isquot)
965                         quotemode = !quotemode;
966                 lastsplit = issplit;
967                 lastalnum = isaln;
968         }
969         
970 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
971 //      {
972 //              printf("%s\n", a->c_str());
973 //      }
974
975         int sort = eDVBChannelQuery::tName;
976                 /* check for "ORDER BY ..." */
977
978         while (tokens.size() > 2)
979         {
980                 std::list<std::string>::iterator it = tokens.end();
981                 --it; --it; --it;
982                 if (*it == "ORDER")
983                 {
984                         ++it;
985                         if (*it == "BY")
986                         {
987                                 ++it;
988                                 sort = decodeType(*it);
989                                 tokens.pop_back(); // ...
990                                 tokens.pop_back(); // BY
991                                 tokens.pop_back(); // ORDER
992                         } else
993                                 sort = -1;
994                 }
995                 else if (*it == "FROM")
996                 {
997                         ++it;
998                         if (*it == "BOUQUET")
999                         {
1000                                 ++it;
1001                                 bouquet_name = *it;
1002                                 tokens.pop_back(); // ...
1003                                 tokens.pop_back(); // FROM
1004                                 tokens.pop_back(); // BOUQUET
1005                         }
1006                 }
1007                 else
1008                         break;
1009         }
1010
1011         if (sort == -1)
1012         {
1013                 eWarning("ORDER BY .. string invalid.");
1014                 res = 0;
1015                 return -1;
1016         }
1017         
1018 //      eDebug("sort by %d", sort);
1019         
1020                 /* now we recursivly parse that. */
1021         int r = parseExpression(res, tokens.begin(), tokens.end());
1022         
1023         if (res)
1024         {
1025                 res->m_sort = sort;
1026                 res->m_bouquet_name = bouquet_name;
1027         }
1028
1029 //      eDebug("return: %d", r);
1030         return r;
1031 }
1032
1033 DEFINE_REF(eDVBChannelQuery);