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