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