add needed functions
[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                                 int tpos = dvbnamespace>>16;
861                                 if (tpos > 1800) // west
862                                         snprintf(buf, 64, "Services (%3.1fW)", (0 - (tpos - 3600)) / 10.0);
863                                 else
864                                         snprintf(buf, 64, "Services (%3.1fE)", tpos / 10.0);
865                                 ref.name=buf;
866                                 snprintf(buf, 64, "(satellitePosition == %d) && ", dvbnamespace>>16);
867                                 ref.path=buf+source.path;
868                                 unsigned int pos=ref.path.find("FROM");
869                                 ref.flags=eServiceReference::flagDirectory;
870                                 ref.path.erase(pos);
871                                 ref.path+="ORDER BY name";
872 //                              eDebug("ref.path now %s", ref.path.c_str());
873                                 m_list.push_back(ref);
874
875                                 ref.path=buf+source.path;
876                                 pos=ref.path.find("FROM");
877                                 ref.path.erase(pos+5);
878                                 ref.path+="PROVIDERS ORDER BY name";
879 //                              eDebug("ref.path now %s", ref.path.c_str());
880                                 if (tpos > 1800) // west
881                                         snprintf(buf, 64, "Providers (%3.1fW)", (0 - (tpos - 3600)) / 10.0);
882                                 else
883                                         snprintf(buf, 64, "Providers (%3.1fE)", tpos / 10.0);
884                                 ref.name=buf;
885                                 m_list.push_back(ref);
886                         }
887                 }
888         }
889         m_cursor=m_list.begin();
890 }
891
892 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
893         :eDVBDBListQuery(db, source, query)
894 {
895         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
896                 it != m_db->m_services.end(); ++it)
897         {
898                 int res = it->second->checkFilter(it->first, *query);
899                 if (res)
900                 {
901                         bool found=0;
902
903                         const char *provider_name = it->second->m_provider_name.length() ?
904                                 it->second->m_provider_name.c_str() :
905                                 "Unknown";
906
907                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
908                                 if (i->name == provider_name)
909                                 {
910                                         found=true;
911                                         break;
912                                 }
913                         if (!found)
914                         {
915                                 eServiceReferenceDVB ref;
916                                 char buf[64];
917                                 ref.name=provider_name;
918                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
919                                 ref.path=buf+source.path;
920                                 unsigned int pos = ref.path.find("FROM");
921                                 ref.flags=eServiceReference::flagDirectory;
922                                 ref.path.erase(pos);
923                                 ref.path+="ORDER BY name";
924 //                              eDebug("ref.path now %s", ref.path.c_str());
925                                 m_list.push_back(ref);
926                         }
927                 }
928         }
929         m_cursor=m_list.begin();
930 }
931
932 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
933
934 static int decodeType(const std::string &type)
935 {
936         if (type == "name")
937                 return eDVBChannelQuery::tName;
938         else if (type == "provider")
939                 return eDVBChannelQuery::tProvider;
940         else if (type == "type")
941                 return eDVBChannelQuery::tType;
942         else if (type == "bouquet")
943                 return eDVBChannelQuery::tBouquet;
944         else if (type == "satellitePosition")
945                 return eDVBChannelQuery::tSatellitePosition;
946         else if (type == "channelID")
947                 return eDVBChannelQuery::tChannelID;
948         else
949                 return -1;
950 }
951
952         /* never, NEVER write a parser in C++! */
953 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
954 {
955         std::list<std::string>::const_iterator end_of_exp;
956         if (*begin == "(")
957         {
958                 end_of_exp = begin;
959                 while (end_of_exp != end)
960                         if (*end_of_exp == ")")
961                                 break;
962                         else
963                                 ++end_of_exp;
964         
965                 if (end_of_exp == end)
966                 {
967                         eDebug("expression parse: end of expression while searching for closing brace");
968                         return -1;
969                 }
970                 
971                 ++begin;
972                 // begin..end_of_exp
973                 int r = parseExpression(res, begin, end_of_exp);
974                 if (r)
975                         return r;
976                 ++end_of_exp;
977                 
978                         /* we had only one sub expression */
979                 if (end_of_exp == end)
980                 {
981 //                      eDebug("only one sub expression");
982                         return 0;
983                 }
984                 
985                         /* otherwise we have an operator here.. */
986                 
987                 ePtr<eDVBChannelQuery> r2 = res;
988                 res = new eDVBChannelQuery();
989                 res->m_sort = 0;
990                 res->m_p1 = r2;
991                 res->m_inverse = 0;
992                 r2 = 0;
993                 
994                 if (*end_of_exp == "||")
995                         res->m_type = eDVBChannelQuery::tOR;
996                 else if (*end_of_exp == "&&")
997                         res->m_type = eDVBChannelQuery::tAND;
998                 else
999                 {
1000                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1001                         res = 0;
1002                         return 1;
1003                 }
1004                 
1005                 ++end_of_exp;
1006                 
1007                 return parseExpression(res->m_p2, end_of_exp, end);
1008         }
1009         
1010         // "begin" <op> "end"
1011         std::string type, op, val;
1012         
1013         res = new eDVBChannelQuery();
1014         res->m_sort = 0;
1015         
1016         int cnt = 0;
1017         while (begin != end)
1018         {
1019                 switch (cnt)
1020                 {
1021                 case 0:
1022                         type = *begin;
1023                         break;
1024                 case 1:
1025                         op = *begin;
1026                         break;
1027                 case 2:
1028                         val = *begin;
1029                         break;
1030                 case 3:
1031                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1032                         return 1;
1033                 }
1034                 ++begin;
1035                 ++cnt;
1036         }
1037         
1038         if (cnt != 3)
1039         {
1040                 eDebug("malformed query: missing stuff");
1041                 res = 0;
1042                 return 1;
1043         }
1044         
1045         res->m_type = decodeType(type);
1046         
1047         if (res->m_type == -1)
1048         {
1049                 eDebug("malformed query: invalid type %s", type.c_str());
1050                 res = 0;
1051                 return 1;
1052         }
1053         
1054         if (op == "==")
1055                 res->m_inverse = 0;
1056         else if (op == "!=")
1057                 res->m_inverse = 1;
1058         else
1059         {
1060                 eDebug("invalid operator %s", op.c_str());
1061                 res = 0;
1062                 return 1;
1063         }
1064         
1065         res->m_string = val;
1066         res->m_int = atoi(val.c_str());
1067 //      res->m_channelid = eDVBChannelID(val);
1068         
1069         return 0;
1070 }
1071
1072 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1073 {
1074         std::list<std::string> tokens;
1075         
1076         std::string current_token;
1077         std::string bouquet_name;
1078
1079 //      eDebug("splitting %s....", query.c_str());
1080         unsigned int i = 0;
1081         const char *splitchars="()";
1082         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1083         while (i <= query.size())
1084         {
1085                 int c = (i < query.size()) ? query[i] : ' ';
1086                 ++i;
1087                 
1088                 int issplit = !!strchr(splitchars, c);
1089                 int isaln = isalnum(c);
1090                 int iswhite = c == ' ';
1091                 int isquot = c == '\"';
1092                 
1093                 if (quotemode)
1094                 {
1095                         iswhite = issplit = 0;
1096                         isaln = lastalnum;
1097                 }
1098                 
1099                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1100                 {
1101                         if (current_token.size())
1102                                 tokens.push_back(current_token);
1103                         current_token.clear();
1104                 }
1105                 
1106                 if (!(iswhite || isquot))
1107                         current_token += c;
1108                 
1109                 if (isquot)
1110                         quotemode = !quotemode;
1111                 lastsplit = issplit;
1112                 lastalnum = isaln;
1113         }
1114         
1115 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1116 //      {
1117 //              printf("%s\n", a->c_str());
1118 //      }
1119
1120         int sort = eDVBChannelQuery::tName;
1121                 /* check for "ORDER BY ..." */
1122
1123         std::list<std::string>::iterator it = tokens.begin();
1124         while (it != tokens.end())
1125         {
1126                 if (*it == "ORDER")
1127                 {
1128                         tokens.erase(it++);
1129                         if (it != tokens.end() && *it == "BY")
1130                         {
1131                                 tokens.erase(it++);
1132                                 sort = decodeType(*it);
1133                                 tokens.erase(it++);
1134                         } else
1135                                 sort = -1;
1136                 }
1137                 else if (*it == "FROM")
1138                 {
1139                         tokens.erase(it++);
1140                         if (it != tokens.end() && *it == "BOUQUET")
1141                         {
1142                                 tokens.erase(it++);
1143                                 bouquet_name = *it;
1144                                 tokens.erase(it++);
1145                         }
1146                         else if (it != tokens.end() && *it == "SATELLITES")
1147                                 tokens.erase(it++);
1148                         else if (it != tokens.end() && *it == "PROVIDERS")
1149                                 tokens.erase(it++);
1150                         else
1151                         {
1152                                 eDebug("FROM unknown %s", (*it).c_str());
1153                                 tokens.erase(it++);
1154                         }
1155                 }
1156                 else
1157                         ++it;
1158         }
1159
1160         if (sort == -1)
1161         {
1162                 eWarning("ORDER BY .. string invalid.");
1163                 res = 0;
1164                 return -1;
1165         }
1166         
1167 //      eDebug("sort by %d", sort);
1168         
1169                 /* now we recursivly parse that. */
1170         int r = parseExpression(res, tokens.begin(), tokens.end());
1171         
1172         if (res)
1173         {
1174                 res->m_sort = sort;
1175                 res->m_bouquet_name = bouquet_name;
1176         }
1177
1178 //      eDebug("return: %d", r);
1179         return r;
1180 }
1181
1182 DEFINE_REF(eDVBChannelQuery);