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