bugfix: no more remove any sat transponder when cable or terrestrial is
[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::canDescent )
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 int 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 0;
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%x", &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::canDescent )
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 ( 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         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1019         
1020         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1021         {
1022                 if (a.name.empty() && m_db->getService(a, a_service))
1023                         return 1;
1024                 if (b.name.empty() && m_db->getService(b, b_service))
1025                         return 1;
1026         }
1027         
1028         switch (sortmode)
1029         {
1030         case eDVBChannelQuery::tName:
1031                 if (a_service)
1032                 {
1033                         if (b_service)
1034                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1035                         else
1036                         {
1037                                 std::string str = b.name;
1038                                 makeUpper(str);
1039                                 return a_service->m_service_name_sort < str;
1040                         }
1041                 }
1042                 else if (b_service)
1043                 {
1044                         std::string str = a.name;
1045                         makeUpper(str);
1046                         return str < b_service->m_service_name_sort;
1047                 }
1048                 else
1049                 {
1050                         std::string aa = a.name, bb = b.name;
1051                         makeUpper(aa);
1052                         makeUpper(bb);
1053                         return aa < bb;
1054                 }
1055         case eDVBChannelQuery::tProvider:
1056                 return a_service->m_provider_name < b_service->m_provider_name;
1057         case eDVBChannelQuery::tType:
1058                 return a.getServiceType() < b.getServiceType();
1059         case eDVBChannelQuery::tBouquet:
1060                 return 0;
1061         case eDVBChannelQuery::tSatellitePosition:
1062                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1063         default:
1064                 return 1;
1065         }
1066         return 0;
1067 }
1068
1069 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1070         :eDVBDBQueryBase(db, source, query)
1071 {
1072         m_cursor = m_db->m_services.begin();
1073 }
1074
1075 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1076 {
1077         while (m_cursor != m_db->m_services.end())
1078         {
1079                 ref = m_cursor->first;
1080
1081                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
1082
1083                 ++m_cursor;
1084
1085                 if (res)
1086                         return 0;
1087         }
1088
1089         ref.type = eServiceReference::idInvalid;
1090
1091         return 1;
1092 }
1093
1094 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1095         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1096 {
1097 }
1098
1099 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1100 {
1101         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1102         std::list<eServiceReference> &list = bouquet.m_services;
1103         while (m_cursor != list.end())
1104         {
1105                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1106
1107                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1108                         m_db->m_services.find(ref);
1109
1110                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
1111
1112                 ++m_cursor;
1113
1114                 if (res)
1115                         return 0;
1116         }
1117
1118         ref.type = eServiceReference::idInvalid;
1119
1120         return 1;
1121 }
1122
1123 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1124         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1125 {
1126 }
1127
1128 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1129 {
1130         if (m_cursor != m_list.end())
1131         {
1132                 ref = *m_cursor++;
1133                 return 0;
1134         }
1135         ref.type = eServiceReference::idInvalid;
1136         return 1;
1137 }
1138
1139 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1140 {
1141         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1142         {
1143                 int x = (a.getDVBNamespace().get() >> 16);
1144                 int y = (b.getDVBNamespace().get() >> 16);
1145                 if ( x > 1800 )
1146                         x -= 3600;
1147                 if ( y > 1800 )
1148                         y -= 3600;
1149                 return x < y;
1150         }
1151         std::string aa = a.name, bb = b.name;
1152         makeUpper(aa);
1153         makeUpper(bb);
1154         return aa < bb;
1155 }
1156
1157 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1158         :eDVBDBListQuery(db, source, query)
1159 {
1160         std::set<unsigned int> found;
1161         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1162                 it != m_db->m_services.end(); ++it)
1163         {
1164                 int res = it->second->checkFilter(it->first, *query);
1165                 if (res)
1166                 {
1167                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1168                         if (found.find(dvbnamespace) == found.end())
1169                         {
1170                                 found.insert(dvbnamespace);
1171                                 eServiceReferenceDVB ref;
1172                                 ref.setDVBNamespace(dvbnamespace);
1173                                 ref.flags=eServiceReference::flagDirectory;
1174                                 char buf[128];
1175                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1176
1177                                 ref.path=buf+source.path;
1178                                 unsigned int pos=ref.path.find("FROM");
1179                                 ref.path.erase(pos);
1180                                 ref.path+="ORDER BY name";
1181 //                              eDebug("ref.path now %s", ref.path.c_str());
1182                                 m_list.push_back(ref);
1183
1184                                 ref.path=buf+source.path;
1185                                 pos=ref.path.find("FROM");
1186                                 ref.path.erase(pos+5);
1187                                 ref.path+="PROVIDERS ORDER BY name";
1188 //                              eDebug("ref.path now %s", ref.path.c_str());
1189                                 m_list.push_back(ref);
1190
1191                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1192                                 ref.path=buf+source.path;
1193                                 pos=ref.path.find("FROM");
1194                                 ref.path.erase(pos);
1195                                 ref.path+="ORDER BY name";
1196 //                              eDebug("ref.path now %s", ref.path.c_str());
1197                                 m_list.push_back(ref);
1198                         }
1199                 }
1200         }
1201         m_cursor=m_list.begin();
1202 }
1203
1204 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1205         :eDVBDBListQuery(db, source, query)
1206 {
1207         std::set<std::string> found;
1208         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1209                 it != m_db->m_services.end(); ++it)
1210         {
1211                 int res = it->second->checkFilter(it->first, *query);
1212                 if (res)
1213                 {
1214                         const char *provider_name = it->second->m_provider_name.length() ?
1215                                 it->second->m_provider_name.c_str() :
1216                                 "Unknown";
1217                         if (found.find(std::string(provider_name)) == found.end())
1218                         {
1219                                 found.insert(std::string(provider_name));
1220                                 eServiceReferenceDVB ref;
1221                                 char buf[64];
1222                                 ref.name=provider_name;
1223                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1224                                 ref.path=buf+source.path;
1225                                 unsigned int pos = ref.path.find("FROM");
1226                                 ref.flags=eServiceReference::flagDirectory;
1227                                 ref.path.erase(pos);
1228                                 ref.path+="ORDER BY name";
1229 //                              eDebug("ref.path now %s", ref.path.c_str());
1230                                 m_list.push_back(ref);
1231                         }
1232                 }
1233         }
1234         m_cursor=m_list.begin();
1235 }
1236
1237 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1238
1239 static int decodeType(const std::string &type)
1240 {
1241         if (type == "name")
1242                 return eDVBChannelQuery::tName;
1243         else if (type == "provider")
1244                 return eDVBChannelQuery::tProvider;
1245         else if (type == "type")
1246                 return eDVBChannelQuery::tType;
1247         else if (type == "bouquet")
1248                 return eDVBChannelQuery::tBouquet;
1249         else if (type == "satellitePosition")
1250                 return eDVBChannelQuery::tSatellitePosition;
1251         else if (type == "channelID")
1252                 return eDVBChannelQuery::tChannelID;
1253         else if (type == "flags")
1254                 return eDVBChannelQuery::tFlags;
1255         else
1256                 return -1;
1257 }
1258
1259         /* never, NEVER write a parser in C++! */
1260 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1261 {
1262         std::list<std::string>::const_iterator end_of_exp;
1263         
1264         if (begin == end)
1265         {
1266                 eDebug("empty expression!");
1267                 return 0;
1268         }
1269         
1270         if (*begin == "(")
1271         {
1272                 end_of_exp = begin;
1273                 while (end_of_exp != end)
1274                         if (*end_of_exp == ")")
1275                                 break;
1276                         else
1277                                 ++end_of_exp;
1278         
1279                 if (end_of_exp == end)
1280                 {
1281                         eDebug("expression parse: end of expression while searching for closing brace");
1282                         return -1;
1283                 }
1284                 
1285                 ++begin;
1286                 // begin..end_of_exp
1287                 int r = parseExpression(res, begin, end_of_exp);
1288                 if (r)
1289                         return r;
1290                 ++end_of_exp;
1291                 
1292                         /* we had only one sub expression */
1293                 if (end_of_exp == end)
1294                 {
1295 //                      eDebug("only one sub expression");
1296                         return 0;
1297                 }
1298                 
1299                         /* otherwise we have an operator here.. */
1300                 
1301                 ePtr<eDVBChannelQuery> r2 = res;
1302                 res = new eDVBChannelQuery();
1303                 res->m_sort = 0;
1304                 res->m_p1 = r2;
1305                 res->m_inverse = 0;
1306                 r2 = 0;
1307                 
1308                 if (*end_of_exp == "||")
1309                         res->m_type = eDVBChannelQuery::tOR;
1310                 else if (*end_of_exp == "&&")
1311                         res->m_type = eDVBChannelQuery::tAND;
1312                 else
1313                 {
1314                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1315                         res = 0;
1316                         return 1;
1317                 }
1318                 
1319                 ++end_of_exp;
1320                 
1321                 return parseExpression(res->m_p2, end_of_exp, end);
1322         }
1323         
1324         // "begin" <op> "end"
1325         std::string type, op, val;
1326         
1327         res = new eDVBChannelQuery();
1328         res->m_sort = 0;
1329         
1330         int cnt = 0;
1331         while (begin != end)
1332         {
1333                 switch (cnt)
1334                 {
1335                 case 0:
1336                         type = *begin;
1337                         break;
1338                 case 1:
1339                         op = *begin;
1340                         break;
1341                 case 2:
1342                         val = *begin;
1343                         break;
1344                 case 3:
1345                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1346                         return 1;
1347                 }
1348                 ++begin;
1349                 ++cnt;
1350         }
1351         
1352         if (cnt != 3)
1353         {
1354                 eDebug("malformed query: missing stuff");
1355                 res = 0;
1356                 return 1;
1357         }
1358         
1359         res->m_type = decodeType(type);
1360         
1361         if (res->m_type == -1)
1362         {
1363                 eDebug("malformed query: invalid type %s", type.c_str());
1364                 res = 0;
1365                 return 1;
1366         }
1367         
1368         if (op == "==")
1369                 res->m_inverse = 0;
1370         else if (op == "!=")
1371                 res->m_inverse = 1;
1372         else
1373         {
1374                 eDebug("invalid operator %s", op.c_str());
1375                 res = 0;
1376                 return 1;
1377         }
1378         
1379         res->m_string = val;
1380         res->m_int = atoi(val.c_str());
1381 //      res->m_channelid = eDVBChannelID(val);
1382         
1383         return 0;
1384 }
1385
1386 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1387 {
1388         std::list<std::string> tokens;
1389         
1390         std::string current_token;
1391         std::string bouquet_name;
1392
1393 //      eDebug("splitting %s....", query.c_str());
1394         unsigned int i = 0;
1395         const char *splitchars="()";
1396         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1397         while (i <= query.size())
1398         {
1399                 int c = (i < query.size()) ? query[i] : ' ';
1400                 ++i;
1401                 
1402                 int issplit = !!strchr(splitchars, c);
1403                 int isaln = isalnum(c);
1404                 int iswhite = c == ' ';
1405                 int isquot = c == '\"';
1406                 
1407                 if (quotemode)
1408                 {
1409                         iswhite = issplit = 0;
1410                         isaln = lastalnum;
1411                 }
1412                 
1413                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1414                 {
1415                         if (current_token.size())
1416                                 tokens.push_back(current_token);
1417                         current_token.clear();
1418                 }
1419                 
1420                 if (!(iswhite || isquot))
1421                         current_token += c;
1422                 
1423                 if (isquot)
1424                         quotemode = !quotemode;
1425                 lastsplit = issplit;
1426                 lastalnum = isaln;
1427         }
1428         
1429 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1430 //      {
1431 //              printf("%s\n", a->c_str());
1432 //      }
1433
1434         int sort = eDVBChannelQuery::tName;
1435                 /* check for "ORDER BY ..." */
1436
1437         std::list<std::string>::iterator it = tokens.begin();
1438         while (it != tokens.end())
1439         {
1440                 if (*it == "ORDER")
1441                 {
1442                         tokens.erase(it++);
1443                         if (it != tokens.end() && *it == "BY")
1444                         {
1445                                 tokens.erase(it++);
1446                                 sort = decodeType(*it);
1447                                 tokens.erase(it++);
1448                         } else
1449                                 sort = -1;
1450                 }
1451                 else if (*it == "FROM")
1452                 {
1453                         tokens.erase(it++);
1454                         if (it != tokens.end() && *it == "BOUQUET")
1455                         {
1456                                 tokens.erase(it++);
1457                                 bouquet_name = *it;
1458                                 tokens.erase(it++);
1459                         }
1460                         else if (it != tokens.end() && *it == "SATELLITES")
1461                                 tokens.erase(it++);
1462                         else if (it != tokens.end() && *it == "PROVIDERS")
1463                                 tokens.erase(it++);
1464                         else
1465                         {
1466                                 eDebug("FROM unknown %s", (*it).c_str());
1467                                 tokens.erase(it++);
1468                         }
1469                 }
1470                 else
1471                         ++it;
1472         }
1473
1474         if (sort == -1)
1475         {
1476                 eWarning("ORDER BY .. string invalid.");
1477                 res = 0;
1478                 return -1;
1479         }
1480         
1481 //      eDebug("sort by %d", sort);
1482         
1483                 /* now we recursivly parse that. */
1484         int r = parseExpression(res, tokens.begin(), tokens.end());
1485         
1486                 /* we have an empty (but valid!) expression */
1487         if (!r && !res)
1488         {
1489                 res = new eDVBChannelQuery();
1490                 res->m_inverse = 0;
1491                 res->m_type = eDVBChannelQuery::tAny;
1492         }
1493         
1494         if (res)
1495         {
1496                 res->m_sort = sort;
1497                 res->m_bouquet_name = bouquet_name;
1498         }
1499
1500 //      eDebug("return: %d", r);
1501         return r;
1502 }
1503
1504 DEFINE_REF(eDVBChannelQuery);