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