make enigma2 ready for dvb-s2
[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 RESULT eBouquet::setListName(const std::string &name)
111 {
112         m_bouquet_name = name;
113         return 0;
114 }
115
116 eDVBService::eDVBService()
117         :m_flags(0)
118 {
119 }
120
121 eDVBService::~eDVBService()
122 {
123 }
124
125 eDVBService &eDVBService::operator=(const eDVBService &s)
126 {
127         m_service_name = s.m_service_name;
128         m_service_name_sort = s.m_service_name_sort;
129         m_provider_name = s.m_provider_name;
130         m_flags = s.m_flags;
131         m_ca = s.m_ca;
132         m_cache = s.m_cache;
133         return *this;
134 }
135
136 void eDVBService::genSortName()
137 {
138         m_service_name_sort = removeDVBChars(m_service_name);
139         makeUpper(m_service_name_sort);
140         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
141                 m_service_name_sort.erase(0, 1);
142
143                 /* put unnamed services at the end, not at the beginning. */
144         if (m_service_name_sort.empty())
145                 m_service_name_sort = "\xFF";
146 }
147
148 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
149 {
150         if (!ref.name.empty())
151                 name = ref.name; // use renamed service name..
152         else if (!m_service_name.empty())
153                 name = m_service_name;
154         else
155                 name = "(...)";
156         return 0;
157 }
158
159 RESULT eDVBService::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &ptr, time_t start_time)
160 {
161         return eEPGCache::getInstance()->lookupEventTime(ref, start_time, ptr);
162 }
163
164 bool eDVBService::isPlayable(const eServiceReference &ref, const eServiceReference &ignore)
165 {
166         ePtr<eDVBResourceManager> res_mgr;
167         if ( eDVBResourceManager::getInstance( res_mgr ) )
168                 eDebug("isPlayble... no res manager!!");
169         else
170         {
171                 eDVBChannelID chid, chid_ignore;
172                 ((const eServiceReferenceDVB&)ref).getChannelID(chid);
173                 ((const eServiceReferenceDVB&)ignore).getChannelID(chid_ignore);
174                 return res_mgr->canAllocateChannel(chid, chid_ignore);
175         }
176         return false;
177 }
178
179 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
180 {
181         int res = 0;
182         switch (query.m_type)
183         {
184         case eDVBChannelQuery::tName:
185                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
186                 break;
187         case eDVBChannelQuery::tProvider:
188                 res = m_provider_name.find(query.m_string) != std::string::npos;
189                 break;
190         case eDVBChannelQuery::tType:
191                 res = ref.getServiceType() == query.m_int;
192                 break;
193         case eDVBChannelQuery::tBouquet:
194                 res = 0;
195                 break;
196         case eDVBChannelQuery::tSatellitePosition:
197                 res = ((unsigned int)ref.getDVBNamespace().get())>>16 == (unsigned int)query.m_int;
198                 break;
199         case eDVBChannelQuery::tFlags:
200                 res = (m_flags & query.m_int) == query.m_int;
201                 break;
202         case eDVBChannelQuery::tChannelID:
203         {
204                 eDVBChannelID chid;
205                 ref.getChannelID(chid);
206                 res = chid == query.m_channelid;
207                 break;
208         }
209         case eDVBChannelQuery::tAND:
210                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
211                 break;
212         case eDVBChannelQuery::tOR:
213                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
214                 break;
215         case eDVBChannelQuery::tAny:
216                 res = 1;
217                 break;
218         }
219
220         if (query.m_inverse)
221                 return !res;
222         else
223                 return res;
224 }
225
226 int eDVBService::getCachePID(cacheID id)
227 {
228         std::map<int, int>::iterator it = m_cache.find(id);
229         if ( it != m_cache.end() )
230                 return it->second;
231         return -1;
232 }
233
234 void eDVBService::setCachePID(cacheID id, int pid)
235 {
236         if (pid == -1)
237                 m_cache.erase(id);
238         else
239                 m_cache[id] = pid;
240 }
241
242 DEFINE_REF(eDVBDB);
243
244         /* THIS CODE IS BAD. it should be replaced by somethine better. */
245 void eDVBDB::reloadServicelist()
246 {
247         eDebug("---- opening lame channel db");
248         FILE *f=fopen(CONFIGDIR"/enigma2/lamedb", "rt");
249         if (!f)
250         {
251                 struct stat s;
252                 if ( !stat("lamedb", &s) )
253                 {
254                         if ( !stat(CONFIGDIR"/enigma2", &s) )
255                         {
256                                 rename("lamedb", CONFIGDIR"/enigma2/lamedb" );
257                                 reloadServicelist();
258                         }
259                 }
260                 return;
261         }
262         char line[256];
263         if ((!fgets(line, 256, f)) || strncmp(line, "eDVB services", 13))
264         {
265                 eDebug("not a servicefile");
266                 fclose(f);
267                 return;
268         }
269         eDebug("reading services");
270         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
271         {
272                 eDebug("services invalid, no transponders");
273                 fclose(f);
274                 return;
275         }
276
277         // clear all transponders
278
279         while (!feof(f))
280         {
281                 if (!fgets(line, 256, f))
282                         break;
283                 if (!strcmp(line, "end\n"))
284                         break;
285                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
286                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
287                 if (original_network_id == -1)
288                         continue;
289                 eDVBChannelID channelid = eDVBChannelID(
290                         eDVBNamespace(dvb_namespace),
291                         eTransportStreamID(transport_stream_id),
292                         eOriginalNetworkID(original_network_id));
293
294                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
295                 while (!feof(f))
296                 {
297                         fgets(line, 256, f);
298                         if (!strcmp(line, "/\n"))
299                                 break;
300                         if (line[1]=='s')
301                         {
302                                 eDVBFrontendParametersSatellite sat;
303                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion,
304                                         system=eDVBFrontendParametersSatellite::System::DVB_S,
305                                         modulation=eDVBFrontendParametersSatellite::Modulation::QPSK,
306                                         rolloff=eDVBFrontendParametersSatellite::RollOff::alpha_auto;
307                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &system, &modulation, &rolloff);
308                                 sat.frequency = frequency;
309                                 sat.symbol_rate = symbol_rate;
310                                 sat.polarisation = polarisation;
311                                 sat.fec = fec;
312                                 sat.orbital_position =
313                                         orbital_position < 0 ? orbital_position + 3600 : orbital_position;
314                                 sat.inversion = inversion;
315                                 sat.system = system;
316                                 sat.modulation = modulation;
317                                 sat.roll_off = rolloff;
318                                 feparm->setDVBS(sat);
319                         } else if (line[1]=='t')
320                         {
321                                 eDVBFrontendParametersTerrestrial ter;
322                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion;
323                                 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);
324                                 ter.frequency = frequency;
325                                 ter.bandwidth = bandwidth;
326                                 ter.code_rate_HP = code_rate_HP;
327                                 ter.code_rate_LP = code_rate_LP;
328                                 ter.modulation = modulation;
329                                 ter.transmission_mode = transmission_mode;
330                                 ter.guard_interval = guard_interval;
331                                 ter.hierarchy = hierarchy;
332                                 ter.inversion = inversion;
333                                 feparm->setDVBT(ter);
334                         } else if (line[1]=='c')
335                         {
336                                 eDVBFrontendParametersCable cab;
337                                 int frequency, symbol_rate,
338                                         inversion=eDVBFrontendParametersCable::Inversion::Unknown,
339                                         modulation=eDVBFrontendParametersCable::Modulation::Auto,
340                                         fec_inner=eDVBFrontendParametersCable::FEC::fAuto;
341                                 sscanf(line+2, "%d:%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation, &fec_inner);
342                                 cab.frequency = frequency;
343                                 cab.fec_inner = fec_inner;
344                                 cab.inversion = inversion;
345                                 cab.symbol_rate = symbol_rate;
346                                 cab.modulation = modulation;
347                                 feparm->setDVBC(cab);
348                         }
349                 }
350                 addChannelToList(channelid, feparm);
351         }
352
353         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
354         {
355                 eDebug("services invalid, no services");
356                 return;
357         }
358
359         // clear all services
360
361         int count=0;
362
363         while (!feof(f))
364         {
365                 if (!fgets(line, 256, f))
366                         break;
367                 if (!strcmp(line, "end\n"))
368                         break;
369
370                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
371                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
372                 if (service_number == -1)
373                         continue;
374                 ePtr<eDVBService> s = new eDVBService;
375                 eServiceReferenceDVB ref =
376                                                 eServiceReferenceDVB(
377                                                 eDVBNamespace(dvb_namespace),
378                                                 eTransportStreamID(transport_stream_id),
379                                                 eOriginalNetworkID(original_network_id),
380                                                 eServiceID(service_id),
381                                                 service_type);
382                 count++;
383                 fgets(line, 256, f);
384                 if (strlen(line))
385                         line[strlen(line)-1]=0;
386
387                 s->m_service_name = line;
388                 s->genSortName();
389
390                 fgets(line, 256, f);
391                 if (strlen(line))
392                         line[strlen(line)-1]=0;
393                 std::string str=line;
394
395                 if (str[1]!=':')        // old ... (only service_provider)
396                 {
397                         s->m_provider_name=line;
398                 } else
399                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
400                         {
401                                 unsigned int c=str.find(',');
402                                 char p=str[0];
403                                 std::string v;
404                                 if (c == std::string::npos)
405                                 {
406                                         v=str.substr(2);
407                                         str="";
408                                 } else
409                                 {
410                                         v=str.substr(2, c-2);
411                                         str=str.substr(c+1);
412                                 }
413 //                              eDebug("%c ... %s", p, v.c_str());
414                                 if (p == 'p')
415                                         s->m_provider_name=v;
416                                 else if (p == 'f')
417                                 {
418                                         sscanf(v.c_str(), "%x", &s->m_flags);
419                                 } else if (p == 'c')
420                                 {
421                                         int cid, val;
422                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
423                                         s->m_cache[cid]=val;
424                                 } else if (p == 'C')
425                                 {
426                                         int val;
427                                         sscanf(v.c_str(), "%04x", &val);
428                                         s->m_ca.insert(val);
429                                 }
430                         }
431                 addService(ref, s);
432         }
433
434         eDebug("loaded %d services", count);
435
436         fclose(f);
437 }
438
439 void eDVBDB::saveServicelist()
440 {
441         eDebug("---- saving lame channel db");
442         FILE *f=fopen(CONFIGDIR"/enigma2/lamedb", "w");
443         int channels=0, services=0;
444         if (!f)
445                 eFatal("couldn't save lame channel db!");
446         fprintf(f, "eDVB services /3/\n");
447         fprintf(f, "transponders\n");
448         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
449                         i != m_channels.end(); ++i)
450         {
451                 const eDVBChannelID &chid = i->first;
452                 const channel &ch = i->second;
453
454                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
455                                 chid.transport_stream_id.get(), chid.original_network_id.get());
456                 eDVBFrontendParametersSatellite sat;
457                 eDVBFrontendParametersTerrestrial ter;
458                 eDVBFrontendParametersCable cab;
459                 if (!ch.m_frontendParameters->getDVBS(sat))
460                 {
461                         if (sat.system == eDVBFrontendParametersSatellite::System::DVB_S2)
462                         {
463                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
464                                         sat.frequency, sat.symbol_rate,
465                                         sat.polarisation, sat.fec,
466                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
467                                         sat.inversion,
468                                         sat.system,
469                                         sat.modulation,
470                                         sat.roll_off);
471                         }
472                         else
473                         {
474                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
475                                         sat.frequency, sat.symbol_rate,
476                                         sat.polarisation, sat.fec,
477                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
478                                         sat.inversion);
479                         }
480                 }
481                 if (!ch.m_frontendParameters->getDVBT(ter))
482                 {
483                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
484                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
485                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
486                                 ter.guard_interval, ter.hierarchy, ter.inversion);
487                 }
488                 if (!ch.m_frontendParameters->getDVBC(cab))
489                 {
490                         fprintf(f, "\tc %d:%d:%d:%d:%d\n",
491                                 cab.frequency, cab.symbol_rate, cab.inversion, cab.modulation, cab.fec_inner);
492                 }
493                 fprintf(f, "/\n");
494                 channels++;
495         }
496         fprintf(f, "end\nservices\n");
497
498         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
499                 i != m_services.end(); ++i)
500         {
501                 const eServiceReferenceDVB &s = i->first;
502                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
503                                 s.getServiceID().get(), s.getDVBNamespace().get(),
504                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
505                                 s.getServiceType(),
506                                 0);
507
508                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
509
510                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
511
512                 // write cached pids
513                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
514                         ca != i->second->m_cache.end(); ++ca)
515                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
516
517                 // write cached ca pids
518                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
519                         ca != i->second->m_ca.end(); ++ca)
520                         fprintf(f, ",C:%04x", *ca);
521
522                 if (i->second->m_flags)
523                         fprintf(f, ",f:%x", i->second->m_flags);
524
525                 fprintf(f, "\n");
526                 services++;
527         }
528         fprintf(f, "end\nHave a lot of bugs!\n");
529         eDebug("saved %d channels and %d services!", channels, services);
530         fclose(f);
531 }
532
533 void eDVBDB::loadBouquet(const char *path)
534 {
535         std::string bouquet_name = path;
536         if (!bouquet_name.length())
537         {
538                 eDebug("Bouquet load failed.. no path given..");
539                 return;
540         }
541         unsigned int pos = bouquet_name.rfind('/');
542         if ( pos != std::string::npos )
543                 bouquet_name.erase(0, pos+1);
544         if (bouquet_name.empty())
545         {
546                 eDebug("Bouquet load failed.. no filename given..");
547                 return;
548         }
549         eBouquet &bouquet = m_bouquets[bouquet_name];
550         bouquet.m_filename = bouquet_name;
551         std::list<eServiceReference> &list = bouquet.m_services;
552         list.clear();
553
554         std::string p = CONFIGDIR"/enigma2/";
555         p+=path;
556         eDebug("loading bouquet... %s", p.c_str());
557         FILE *fp=fopen(p.c_str(), "rt");
558         int entries=0;
559         if (!fp)
560         {
561                 struct stat s;
562                 if ( !stat(path, &s) )
563                 {
564                         rename(path, p.c_str() );
565                         loadBouquet(path);
566                         return;
567                 }
568                 eDebug("failed to open.");
569                 if ( strstr(path, "bouquets.tv") )
570                 {
571                         eDebug("recreate bouquets.tv");
572                         bouquet.m_bouquet_name="Bouquets (TV)";
573                         bouquet.flushChanges();
574                 }
575                 else if ( strstr(path, "bouquets.radio") )
576                 {
577                         eDebug("recreate bouquets.radio");
578                         bouquet.m_bouquet_name="Bouquets (Radio)";
579                         bouquet.flushChanges();
580                 }
581                 return;
582         }
583         char line[256];
584         bool read_descr=false;
585         eServiceReference *e = NULL;
586         while (1)
587         {
588                 if (!fgets(line, 256, fp))
589                         break;
590                 line[strlen(line)-1]=0;
591                 if (strlen(line) && line[strlen(line)-1]=='\r')
592                         line[strlen(line)-1]=0;
593                 if (!line[0])
594                         break;
595                 if (line[0]=='#')
596                 {
597                         if (!strncmp(line, "#SERVICE ", 9) || !strncmp(line, "#SERVICE: ", 10))
598                         {
599                                 int offs = line[8] == ':' ? 10 : 9;
600                                 eServiceReference tmp(line+offs);
601                                 if (tmp.type != eServiceReference::idDVB)
602                                 {
603                                         eDebug("only DVB Bouquets supported");
604                                         continue;
605                                 }
606                                 if ( (tmp.flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
607                                 {
608                                         unsigned int pos = tmp.path.rfind('/');
609                                         if ( pos != std::string::npos )
610                                                 tmp.path.erase(0, pos+1);
611                                         if (tmp.path.empty())
612                                         {
613                                                 eDebug("Bouquet load failed.. no filename given..");
614                                                 continue;
615                                         }
616                                         loadBouquet(tmp.path.c_str());
617                                         char buf[256];
618                                         snprintf(buf, 256, "(type == %d) FROM BOUQUET \"%s\" ORDER BY bouquet", tmp.data[0], tmp.path.c_str());
619                                         tmp.path = buf;
620                                 }
621                                 list.push_back(tmp);
622                                 e = &list.back();
623                                 read_descr=true;
624                                 ++entries;
625                         }
626                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
627                         {
628                                 e->name = line+13;
629                                 read_descr=false;
630                         }
631                         else if (!strncmp(line, "#NAME ", 6))
632                                 bouquet.m_bouquet_name=line+6;
633                         continue;
634                 }
635         }
636         fclose(fp);
637         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
638 }
639
640 void eDVBDB::reloadBouquets()
641 {
642         m_bouquets.clear();
643         loadBouquet("bouquets.tv");
644         loadBouquet("bouquets.radio");
645 // create default bouquets when missing
646         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
647         {
648                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
649                 b.m_filename = "userbouquet.favourites.tv";
650                 b.m_bouquet_name = "Favourites (TV)";
651                 b.flushChanges();
652                 eServiceReference ref;
653                 memset(ref.data, 0, sizeof(ref.data));
654                 ref.type=1;
655                 ref.flags=7;
656                 ref.data[0]=1;
657                 ref.path="(type == 1) FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
658                 eBouquet &parent = m_bouquets["bouquets.tv"];
659                 parent.m_services.push_back(ref);
660                 parent.flushChanges();
661         }
662         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
663         {
664                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
665                 b.m_filename = "userbouquet.favourites.radio";
666                 b.m_bouquet_name = "Favourites (Radio)";
667                 b.flushChanges();
668                 eServiceReference ref;
669                 memset(ref.data, 0, sizeof(ref.data));
670                 ref.type=1;
671                 ref.flags=7;
672                 ref.data[0]=2;
673                 ref.path="(type == 2) FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
674                 eBouquet &parent = m_bouquets["bouquets.radio"];
675                 parent.m_services.push_back(ref);
676                 parent.flushChanges();
677         }
678 }
679
680 eDVBDB *eDVBDB::instance;
681
682 eDVBDB::eDVBDB()
683 {
684         instance = this;
685         reloadServicelist();
686 }
687
688 eDVBDB::~eDVBDB()
689 {
690         instance=NULL;
691 }
692
693 RESULT eDVBDB::removeService(const eServiceReference &ref)
694 {
695         if (ref.type == eServiceReference::idDVB)
696         {
697                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
698                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
699                 if (it != m_services.end())
700                 {
701                         m_services.erase(it);
702                         return 0;
703                 }
704         }
705         return -1;
706 }
707
708 RESULT eDVBDB::removeServices(int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
709 {
710         return removeServices(eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
711 }
712
713 RESULT eDVBDB::removeServices(eDVBChannelID chid, unsigned int orbpos)
714 {
715         RESULT ret=-1;
716         eDVBNamespace eNs;
717         eTransportStreamID eTsid;
718         eOriginalNetworkID eOnid;
719         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
720         std::set<eDVBChannelID> removed_chids;
721         while (it != m_channels.end())
722         {
723                 const eDVBChannelID &ch = it->first;
724                 bool remove=true;
725                 int system;
726                 it->second.m_frontendParameters->getSystem(system);
727                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
728                 {
729                         eDVBFrontendParametersSatellite sat;
730                         it->second.m_frontendParameters->getDVBS(sat);
731                         if ((unsigned int)sat.orbital_position != orbpos)
732                                 remove=false;
733                 }
734                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
735                         remove=false;
736                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
737                         remove=false;
738                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
739                         remove=false;
740                 if ( remove )
741                 {
742                         eDebug("remove %08x %04x %04x",
743                                 ch.dvbnamespace.get(),
744                                 ch.original_network_id.get(),
745                                 ch.transport_stream_id.get());
746                         removed_chids.insert(it->first);
747                         m_channels.erase(it++);
748                 }
749                 else
750                         ++it;
751         }
752         if (!removed_chids.empty())
753         {
754                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
755                 while(service != m_services.end())
756                 {
757                         eDVBChannelID chid;
758                         service->first.getChannelID(chid);
759                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
760                         if (it != removed_chids.end())
761                                 m_services.erase(service++);
762                         else
763                                 ++service;
764                         ret=0;
765                 }
766         }
767         return ret;
768 }
769
770 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
771 {
772         if (ref.type == eServiceReference::idDVB)
773         {
774                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
775                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
776                 if (it != m_services.end())
777                         it->second->m_flags |= ~flagmask;
778                 return 0;
779         }
780         return -1;
781 }
782
783 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
784 {
785         if (ref.type == eServiceReference::idDVB)
786         {
787                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
788                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
789                 if (it != m_services.end())
790                         it->second->m_flags &= ~flagmask;
791                 return 0;
792         }
793         return -1;
794 }
795
796 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
797 {
798         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
799 }
800
801 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
802 {
803         eDVBNamespace eNs;
804         eTransportStreamID eTsid;
805         eOriginalNetworkID eOnid;
806         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
807         std::set<eDVBChannelID> removed_chids;
808         while (it != m_channels.end())
809         {
810                 const eDVBChannelID &ch = it->first;
811                 bool remove=true;
812                 int system;
813                 it->second.m_frontendParameters->getSystem(system);
814                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
815                 {
816                         eDVBFrontendParametersSatellite sat;
817                         it->second.m_frontendParameters->getDVBS(sat);
818                         if ((unsigned int)sat.orbital_position != orbpos)
819                                 remove=false;
820                 }
821                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
822                         remove=false;
823                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
824                         remove=false;
825                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
826                         remove=false;
827                 if ( remove )
828                         removed_chids.insert(it->first);
829                 ++it;
830         }
831         if (!removed_chids.empty())
832         {
833                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
834                 while(service != m_services.end())
835                 {
836                         eDVBChannelID chid;
837                         service->first.getChannelID(chid);
838                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
839                         if (it != removed_chids.end())
840                                 service->second->m_flags &= ~flagmask;
841                         ++service;
842                 }
843         }
844         return 0;
845 }
846
847 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
848 {
849         channel ch;
850         assert(feparm);
851         ch.m_frontendParameters = feparm;
852         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
853         return 0;
854 }
855
856 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
857 {
858         m_channels.erase(id);
859         return 0;
860 }
861
862 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
863 {
864         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
865         if (i == m_channels.end())
866         {
867                 parm = 0;
868                 return -ENOENT;
869         }
870         parm = i->second.m_frontendParameters;
871         return 0;
872 }
873
874 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
875 {
876         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
877         if (it == m_services.end())
878                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
879         return 0;
880 }
881
882 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
883 {
884         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
885         i = m_services.find(reference);
886         if (i == m_services.end())
887         {
888                 service = 0;
889                 return -ENOENT;
890         }
891         service = i->second;
892         return 0;
893 }
894
895 RESULT eDVBDB::flush()
896 {
897         saveServicelist();
898         return 0;
899 }
900
901 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
902 {
903         std::string str = ref.path;
904         if (str.empty())
905         {
906                 eDebug("getBouquet failed.. no path given!");
907                 return -1;
908         }
909         unsigned int pos = str.find("FROM BOUQUET \"");
910         if ( pos != std::string::npos )
911         {
912                 str.erase(0, pos+14);
913                 pos = str.find('"');
914                 if ( pos != std::string::npos )
915                         str.erase(pos);
916                 else
917                         str.clear();
918         }
919         if (str.empty())
920         {
921                 eDebug("getBouquet failed.. couldn't parse bouquet name");
922                 return -1;
923         }
924         std::map<std::string, eBouquet>::iterator i =
925                 m_bouquets.find(str);
926         if (i == m_bouquets.end())
927         {
928                 bouquet = 0;
929                 return -ENOENT;
930         }
931         bouquet = &i->second;
932         return 0;
933 }
934
935 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
936 {
937         if ( source.path.find("FROM") != std::string::npos )
938         {
939                 if ( source.path.find("BOUQUET") != std::string::npos )
940                         query = new eDVBDBBouquetQuery(this, source, q);
941                 else if ( source.path.find("SATELLITES") != std::string::npos )
942                         query = new eDVBDBSatellitesQuery(this, source, q);
943                 else if ( source.path.find("PROVIDERS") != std::string::npos )
944                         query = new eDVBDBProvidersQuery(this, source, q);
945                 else
946                         eFatal("invalid query %s", source.toString().c_str());
947         }
948         else
949                 query = new eDVBDBQuery(this, source, q);
950         return 0;
951 }
952
953 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
954 {
955         eServiceID Sid(sid);
956         eTransportStreamID Tsid(tsid);
957         eOriginalNetworkID Onid(onid);
958         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
959                 sit != m_services.end(); ++sit)
960         {
961                 if (sit->first.getTransportStreamID() == Tsid &&
962                         sit->first.getOriginalNetworkID() == Onid &&
963                         sit->first.getServiceID() == Sid)
964                         return sit->first;
965         }
966         return eServiceReference();
967 }
968
969 DEFINE_REF(eDVBDBQueryBase);
970
971 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
972         :m_db(db), m_query(query), m_source(source)
973 {
974 }
975
976 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
977 {
978         ePtr<eDVBService> a_service, b_service;
979         
980         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
981         
982         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
983         {
984                 if (m_db->getService(a, a_service))
985                         return 1;
986                 if (m_db->getService(b, b_service))
987                         return 1;
988         }
989         
990         switch (sortmode)
991         {
992         case eDVBChannelQuery::tName:
993                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
994         case eDVBChannelQuery::tProvider:
995                 return a_service->m_provider_name < b_service->m_provider_name;
996         case eDVBChannelQuery::tType:
997                 return a.getServiceType() < b.getServiceType();
998         case eDVBChannelQuery::tBouquet:
999                 return 0;
1000         case eDVBChannelQuery::tSatellitePosition:
1001                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1002         default:
1003                 return 1;
1004         }
1005         return 0;
1006 }
1007
1008 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1009         :eDVBDBQueryBase(db, source, query)
1010 {
1011         m_cursor = m_db->m_services.begin();
1012 }
1013
1014 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1015 {
1016         while (m_cursor != m_db->m_services.end())
1017         {
1018                 ref = m_cursor->first;
1019
1020                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
1021
1022                 ++m_cursor;
1023
1024                 if (res)
1025                         return 0;
1026         }
1027
1028         ref.type = eServiceReference::idInvalid;
1029
1030         return 1;
1031 }
1032
1033 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1034         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1035 {
1036 }
1037
1038 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1039 {
1040         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1041         std::list<eServiceReference> &list = bouquet.m_services;
1042         while (m_cursor != list.end())
1043         {
1044                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1045
1046                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1047                         m_db->m_services.find(ref);
1048
1049                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
1050
1051                 ++m_cursor;
1052
1053                 if (res)
1054                         return 0;
1055         }
1056
1057         ref.type = eServiceReference::idInvalid;
1058
1059         return 1;
1060 }
1061
1062 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1063         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1064 {
1065 }
1066
1067 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1068 {
1069         if (m_cursor != m_list.end())
1070         {
1071                 ref = *m_cursor++;
1072                 return 0;
1073         }
1074         ref.type = eServiceReference::idInvalid;
1075         return 1;
1076 }
1077
1078 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1079 {
1080         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1081         {
1082                 int x = (a.getDVBNamespace().get() >> 16);
1083                 int y = (b.getDVBNamespace().get() >> 16);
1084                 if ( x > 1800 )
1085                         x -= 3600;
1086                 if ( y > 1800 )
1087                         y -= 3600;
1088                 return x < y;
1089         }
1090         return a.name < b.name;
1091 }
1092
1093 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1094         :eDVBDBListQuery(db, source, query)
1095 {
1096         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1097                 it != m_db->m_services.end(); ++it)
1098         {
1099                 int res = it->second->checkFilter(it->first, *query);
1100                 if (res)
1101                 {
1102                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1103                         bool found=0;
1104                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
1105                                 if ( (i->getDVBNamespace().get()&0xFFFF0000) == dvbnamespace )
1106                                 {
1107                                         found=true;
1108                                         break;
1109                                 }
1110                         if (!found)
1111                         {
1112                                 eServiceReferenceDVB ref;
1113                                 ref.setDVBNamespace(dvbnamespace);
1114                                 ref.flags=eServiceReference::flagDirectory;
1115                                 char buf[128];
1116                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1117
1118                                 ref.path=buf+source.path;
1119                                 unsigned int pos=ref.path.find("FROM");
1120                                 ref.path.erase(pos);
1121                                 ref.path+="ORDER BY name";
1122 //                              eDebug("ref.path now %s", ref.path.c_str());
1123                                 m_list.push_back(ref);
1124
1125                                 ref.path=buf+source.path;
1126                                 pos=ref.path.find("FROM");
1127                                 ref.path.erase(pos+5);
1128                                 ref.path+="PROVIDERS ORDER BY name";
1129 //                              eDebug("ref.path now %s", ref.path.c_str());
1130                                 m_list.push_back(ref);
1131
1132                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1133                                 ref.path=buf+source.path;
1134                                 pos=ref.path.find("FROM");
1135                                 ref.path.erase(pos);
1136                                 ref.path+="ORDER BY name";
1137 //                              eDebug("ref.path now %s", ref.path.c_str());
1138                                 m_list.push_back(ref);
1139                         }
1140                 }
1141         }
1142         m_cursor=m_list.begin();
1143 }
1144
1145 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1146         :eDVBDBListQuery(db, source, query)
1147 {
1148         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1149                 it != m_db->m_services.end(); ++it)
1150         {
1151                 int res = it->second->checkFilter(it->first, *query);
1152                 if (res)
1153                 {
1154                         bool found=0;
1155
1156                         const char *provider_name = it->second->m_provider_name.length() ?
1157                                 it->second->m_provider_name.c_str() :
1158                                 "Unknown";
1159
1160                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
1161                                 if (i->name == provider_name)
1162                                 {
1163                                         found=true;
1164                                         break;
1165                                 }
1166                         if (!found)
1167                         {
1168                                 eServiceReferenceDVB ref;
1169                                 char buf[64];
1170                                 ref.name=provider_name;
1171                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1172                                 ref.path=buf+source.path;
1173                                 unsigned int pos = ref.path.find("FROM");
1174                                 ref.flags=eServiceReference::flagDirectory;
1175                                 ref.path.erase(pos);
1176                                 ref.path+="ORDER BY name";
1177 //                              eDebug("ref.path now %s", ref.path.c_str());
1178                                 m_list.push_back(ref);
1179                         }
1180                 }
1181         }
1182         m_cursor=m_list.begin();
1183 }
1184
1185 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1186
1187 static int decodeType(const std::string &type)
1188 {
1189         if (type == "name")
1190                 return eDVBChannelQuery::tName;
1191         else if (type == "provider")
1192                 return eDVBChannelQuery::tProvider;
1193         else if (type == "type")
1194                 return eDVBChannelQuery::tType;
1195         else if (type == "bouquet")
1196                 return eDVBChannelQuery::tBouquet;
1197         else if (type == "satellitePosition")
1198                 return eDVBChannelQuery::tSatellitePosition;
1199         else if (type == "channelID")
1200                 return eDVBChannelQuery::tChannelID;
1201         else if (type == "flags")
1202                 return eDVBChannelQuery::tFlags;
1203         else
1204                 return -1;
1205 }
1206
1207         /* never, NEVER write a parser in C++! */
1208 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1209 {
1210         std::list<std::string>::const_iterator end_of_exp;
1211         
1212         if (begin == end)
1213         {
1214                 eDebug("empty expression!");
1215                 return 0;
1216         }
1217         
1218         if (*begin == "(")
1219         {
1220                 end_of_exp = begin;
1221                 while (end_of_exp != end)
1222                         if (*end_of_exp == ")")
1223                                 break;
1224                         else
1225                                 ++end_of_exp;
1226         
1227                 if (end_of_exp == end)
1228                 {
1229                         eDebug("expression parse: end of expression while searching for closing brace");
1230                         return -1;
1231                 }
1232                 
1233                 ++begin;
1234                 // begin..end_of_exp
1235                 int r = parseExpression(res, begin, end_of_exp);
1236                 if (r)
1237                         return r;
1238                 ++end_of_exp;
1239                 
1240                         /* we had only one sub expression */
1241                 if (end_of_exp == end)
1242                 {
1243 //                      eDebug("only one sub expression");
1244                         return 0;
1245                 }
1246                 
1247                         /* otherwise we have an operator here.. */
1248                 
1249                 ePtr<eDVBChannelQuery> r2 = res;
1250                 res = new eDVBChannelQuery();
1251                 res->m_sort = 0;
1252                 res->m_p1 = r2;
1253                 res->m_inverse = 0;
1254                 r2 = 0;
1255                 
1256                 if (*end_of_exp == "||")
1257                         res->m_type = eDVBChannelQuery::tOR;
1258                 else if (*end_of_exp == "&&")
1259                         res->m_type = eDVBChannelQuery::tAND;
1260                 else
1261                 {
1262                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1263                         res = 0;
1264                         return 1;
1265                 }
1266                 
1267                 ++end_of_exp;
1268                 
1269                 return parseExpression(res->m_p2, end_of_exp, end);
1270         }
1271         
1272         // "begin" <op> "end"
1273         std::string type, op, val;
1274         
1275         res = new eDVBChannelQuery();
1276         res->m_sort = 0;
1277         
1278         int cnt = 0;
1279         while (begin != end)
1280         {
1281                 switch (cnt)
1282                 {
1283                 case 0:
1284                         type = *begin;
1285                         break;
1286                 case 1:
1287                         op = *begin;
1288                         break;
1289                 case 2:
1290                         val = *begin;
1291                         break;
1292                 case 3:
1293                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1294                         return 1;
1295                 }
1296                 ++begin;
1297                 ++cnt;
1298         }
1299         
1300         if (cnt != 3)
1301         {
1302                 eDebug("malformed query: missing stuff");
1303                 res = 0;
1304                 return 1;
1305         }
1306         
1307         res->m_type = decodeType(type);
1308         
1309         if (res->m_type == -1)
1310         {
1311                 eDebug("malformed query: invalid type %s", type.c_str());
1312                 res = 0;
1313                 return 1;
1314         }
1315         
1316         if (op == "==")
1317                 res->m_inverse = 0;
1318         else if (op == "!=")
1319                 res->m_inverse = 1;
1320         else
1321         {
1322                 eDebug("invalid operator %s", op.c_str());
1323                 res = 0;
1324                 return 1;
1325         }
1326         
1327         res->m_string = val;
1328         res->m_int = atoi(val.c_str());
1329 //      res->m_channelid = eDVBChannelID(val);
1330         
1331         return 0;
1332 }
1333
1334 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1335 {
1336         std::list<std::string> tokens;
1337         
1338         std::string current_token;
1339         std::string bouquet_name;
1340
1341 //      eDebug("splitting %s....", query.c_str());
1342         unsigned int i = 0;
1343         const char *splitchars="()";
1344         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1345         while (i <= query.size())
1346         {
1347                 int c = (i < query.size()) ? query[i] : ' ';
1348                 ++i;
1349                 
1350                 int issplit = !!strchr(splitchars, c);
1351                 int isaln = isalnum(c);
1352                 int iswhite = c == ' ';
1353                 int isquot = c == '\"';
1354                 
1355                 if (quotemode)
1356                 {
1357                         iswhite = issplit = 0;
1358                         isaln = lastalnum;
1359                 }
1360                 
1361                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1362                 {
1363                         if (current_token.size())
1364                                 tokens.push_back(current_token);
1365                         current_token.clear();
1366                 }
1367                 
1368                 if (!(iswhite || isquot))
1369                         current_token += c;
1370                 
1371                 if (isquot)
1372                         quotemode = !quotemode;
1373                 lastsplit = issplit;
1374                 lastalnum = isaln;
1375         }
1376         
1377 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1378 //      {
1379 //              printf("%s\n", a->c_str());
1380 //      }
1381
1382         int sort = eDVBChannelQuery::tName;
1383                 /* check for "ORDER BY ..." */
1384
1385         std::list<std::string>::iterator it = tokens.begin();
1386         while (it != tokens.end())
1387         {
1388                 if (*it == "ORDER")
1389                 {
1390                         tokens.erase(it++);
1391                         if (it != tokens.end() && *it == "BY")
1392                         {
1393                                 tokens.erase(it++);
1394                                 sort = decodeType(*it);
1395                                 tokens.erase(it++);
1396                         } else
1397                                 sort = -1;
1398                 }
1399                 else if (*it == "FROM")
1400                 {
1401                         tokens.erase(it++);
1402                         if (it != tokens.end() && *it == "BOUQUET")
1403                         {
1404                                 tokens.erase(it++);
1405                                 bouquet_name = *it;
1406                                 tokens.erase(it++);
1407                         }
1408                         else if (it != tokens.end() && *it == "SATELLITES")
1409                                 tokens.erase(it++);
1410                         else if (it != tokens.end() && *it == "PROVIDERS")
1411                                 tokens.erase(it++);
1412                         else
1413                         {
1414                                 eDebug("FROM unknown %s", (*it).c_str());
1415                                 tokens.erase(it++);
1416                         }
1417                 }
1418                 else
1419                         ++it;
1420         }
1421
1422         if (sort == -1)
1423         {
1424                 eWarning("ORDER BY .. string invalid.");
1425                 res = 0;
1426                 return -1;
1427         }
1428         
1429 //      eDebug("sort by %d", sort);
1430         
1431                 /* now we recursivly parse that. */
1432         int r = parseExpression(res, tokens.begin(), tokens.end());
1433         
1434                 /* we have an empty (but valid!) expression */
1435         if (!r && !res)
1436         {
1437                 res = new eDVBChannelQuery();
1438                 res->m_inverse = 0;
1439                 res->m_type = eDVBChannelQuery::tAny;
1440         }
1441         
1442         if (res)
1443         {
1444                 res->m_sort = sort;
1445                 res->m_bouquet_name = bouquet_name;
1446         }
1447
1448 //      eDebug("return: %d", r);
1449         return r;
1450 }
1451
1452 DEFINE_REF(eDVBChannelQuery);