no more remove cable or terrestrial transponder when "Clear before scan" 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 ( 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                 else if (orbpos != 0xFFFFFFFF) // do not remove -C or -T transponders when a orbital position is given..
775                         remove=false;
776                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
777                         remove=false;
778                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
779                         remove=false;
780                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
781                         remove=false;
782                 if ( remove )
783                 {
784                         eDebug("remove %08x %04x %04x",
785                                 ch.dvbnamespace.get(),
786                                 ch.original_network_id.get(),
787                                 ch.transport_stream_id.get());
788                         removed_chids.insert(it->first);
789                         m_channels.erase(it++);
790                 }
791                 else
792                         ++it;
793         }
794         if (!removed_chids.empty())
795         {
796                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
797                 while(service != m_services.end())
798                 {
799                         eDVBChannelID chid;
800                         service->first.getChannelID(chid);
801                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
802                         if (it != removed_chids.end())
803                                 m_services.erase(service++);
804                         else
805                                 ++service;
806                         ret=0;
807                 }
808         }
809         return ret;
810 }
811
812 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
813 {
814         if (ref.type == eServiceReference::idDVB)
815         {
816                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
817                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
818                 if (it != m_services.end())
819                         it->second->m_flags |= ~flagmask;
820                 return 0;
821         }
822         return -1;
823 }
824
825 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
826 {
827         if (ref.type == eServiceReference::idDVB)
828         {
829                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
830                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
831                 if (it != m_services.end())
832                         it->second->m_flags &= ~flagmask;
833                 return 0;
834         }
835         return -1;
836 }
837
838 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
839 {
840         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
841 }
842
843 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
844 {
845         eDVBNamespace eNs;
846         eTransportStreamID eTsid;
847         eOriginalNetworkID eOnid;
848         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
849         std::set<eDVBChannelID> removed_chids;
850         while (it != m_channels.end())
851         {
852                 const eDVBChannelID &ch = it->first;
853                 bool remove=true;
854                 int system;
855                 it->second.m_frontendParameters->getSystem(system);
856                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
857                 {
858                         eDVBFrontendParametersSatellite sat;
859                         it->second.m_frontendParameters->getDVBS(sat);
860                         if ((unsigned int)sat.orbital_position != orbpos)
861                                 remove=false;
862                 }
863                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
864                         remove=false;
865                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
866                         remove=false;
867                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
868                         remove=false;
869                 if ( remove )
870                         removed_chids.insert(it->first);
871                 ++it;
872         }
873         if (!removed_chids.empty())
874         {
875                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
876                 while(service != m_services.end())
877                 {
878                         eDVBChannelID chid;
879                         service->first.getChannelID(chid);
880                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
881                         if (it != removed_chids.end())
882                                 service->second->m_flags &= ~flagmask;
883                         ++service;
884                 }
885         }
886         return 0;
887 }
888
889 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
890 {
891         channel ch;
892         assert(feparm);
893         ch.m_frontendParameters = feparm;
894         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
895         return 0;
896 }
897
898 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
899 {
900         m_channels.erase(id);
901         return 0;
902 }
903
904 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
905 {
906         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
907         if (i == m_channels.end())
908         {
909                 parm = 0;
910                 return -ENOENT;
911         }
912         parm = i->second.m_frontendParameters;
913         return 0;
914 }
915
916 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
917 {
918         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
919         if (it == m_services.end())
920                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
921         return 0;
922 }
923
924 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
925 {
926         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
927         i = m_services.find(reference);
928         if (i == m_services.end())
929         {
930                 service = 0;
931                 return -ENOENT;
932         }
933         service = i->second;
934         return 0;
935 }
936
937 RESULT eDVBDB::flush()
938 {
939         saveServicelist();
940         return 0;
941 }
942
943 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
944 {
945         std::string str = ref.path;
946         if (str.empty())
947         {
948                 eDebug("getBouquet failed.. no path given!");
949                 return -1;
950         }
951         unsigned int pos = str.find("FROM BOUQUET \"");
952         if ( pos != std::string::npos )
953         {
954                 str.erase(0, pos+14);
955                 pos = str.find('"');
956                 if ( pos != std::string::npos )
957                         str.erase(pos);
958                 else
959                         str.clear();
960         }
961         if (str.empty())
962         {
963                 eDebug("getBouquet failed.. couldn't parse bouquet name");
964                 return -1;
965         }
966         std::map<std::string, eBouquet>::iterator i =
967                 m_bouquets.find(str);
968         if (i == m_bouquets.end())
969         {
970                 bouquet = 0;
971                 return -ENOENT;
972         }
973         bouquet = &i->second;
974         return 0;
975 }
976
977 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
978 {
979         if ( source.path.find("FROM") != std::string::npos )
980         {
981                 if ( source.path.find("BOUQUET") != std::string::npos )
982                         query = new eDVBDBBouquetQuery(this, source, q);
983                 else if ( source.path.find("SATELLITES") != std::string::npos )
984                         query = new eDVBDBSatellitesQuery(this, source, q);
985                 else if ( source.path.find("PROVIDERS") != std::string::npos )
986                         query = new eDVBDBProvidersQuery(this, source, q);
987                 else
988                         eFatal("invalid query %s", source.toString().c_str());
989         }
990         else
991                 query = new eDVBDBQuery(this, source, q);
992         return 0;
993 }
994
995 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
996 {
997         eServiceID Sid(sid);
998         eTransportStreamID Tsid(tsid);
999         eOriginalNetworkID Onid(onid);
1000         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
1001                 sit != m_services.end(); ++sit)
1002         {
1003                 if (sit->first.getTransportStreamID() == Tsid &&
1004                         sit->first.getOriginalNetworkID() == Onid &&
1005                         sit->first.getServiceID() == Sid)
1006                         return sit->first;
1007         }
1008         return eServiceReference();
1009 }
1010
1011 DEFINE_REF(eDVBDBQueryBase);
1012
1013 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1014         :m_db(db), m_query(query), m_source(source)
1015 {
1016 }
1017
1018 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1019 {
1020         ePtr<eDVBService> a_service, b_service;
1021         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1022         
1023         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1024         {
1025                 if (a.name.empty() && m_db->getService(a, a_service))
1026                         return 1;
1027                 if (b.name.empty() && m_db->getService(b, b_service))
1028                         return 1;
1029         }
1030         
1031         switch (sortmode)
1032         {
1033         case eDVBChannelQuery::tName:
1034                 if (a_service)
1035                 {
1036                         if (b_service)
1037                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1038                         else
1039                         {
1040                                 std::string str = b.name;
1041                                 makeUpper(str);
1042                                 return a_service->m_service_name_sort < str;
1043                         }
1044                 }
1045                 else if (b_service)
1046                 {
1047                         std::string str = a.name;
1048                         makeUpper(str);
1049                         return str < b_service->m_service_name_sort;
1050                 }
1051                 else
1052                 {
1053                         std::string aa = a.name, bb = b.name;
1054                         makeUpper(aa);
1055                         makeUpper(bb);
1056                         return aa < bb;
1057                 }
1058         case eDVBChannelQuery::tProvider:
1059                 return a_service->m_provider_name < b_service->m_provider_name;
1060         case eDVBChannelQuery::tType:
1061                 return a.getServiceType() < b.getServiceType();
1062         case eDVBChannelQuery::tBouquet:
1063                 return 0;
1064         case eDVBChannelQuery::tSatellitePosition:
1065                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1066         default:
1067                 return 1;
1068         }
1069         return 0;
1070 }
1071
1072 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1073         :eDVBDBQueryBase(db, source, query)
1074 {
1075         m_cursor = m_db->m_services.begin();
1076 }
1077
1078 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1079 {
1080         while (m_cursor != m_db->m_services.end())
1081         {
1082                 ref = m_cursor->first;
1083
1084                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
1085
1086                 ++m_cursor;
1087
1088                 if (res)
1089                         return 0;
1090         }
1091
1092         ref.type = eServiceReference::idInvalid;
1093
1094         return 1;
1095 }
1096
1097 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1098         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1099 {
1100 }
1101
1102 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1103 {
1104         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1105         std::list<eServiceReference> &list = bouquet.m_services;
1106         while (m_cursor != list.end())
1107         {
1108                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1109
1110                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1111                         m_db->m_services.find(ref);
1112
1113                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
1114
1115                 ++m_cursor;
1116
1117                 if (res)
1118                         return 0;
1119         }
1120
1121         ref.type = eServiceReference::idInvalid;
1122
1123         return 1;
1124 }
1125
1126 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1127         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1128 {
1129 }
1130
1131 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1132 {
1133         if (m_cursor != m_list.end())
1134         {
1135                 ref = *m_cursor++;
1136                 return 0;
1137         }
1138         ref.type = eServiceReference::idInvalid;
1139         return 1;
1140 }
1141
1142 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1143 {
1144         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1145         {
1146                 int x = (a.getDVBNamespace().get() >> 16);
1147                 int y = (b.getDVBNamespace().get() >> 16);
1148                 if ( x > 1800 )
1149                         x -= 3600;
1150                 if ( y > 1800 )
1151                         y -= 3600;
1152                 return x < y;
1153         }
1154         std::string aa = a.name, bb = b.name;
1155         makeUpper(aa);
1156         makeUpper(bb);
1157         return aa < bb;
1158 }
1159
1160 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1161         :eDVBDBListQuery(db, source, query)
1162 {
1163         std::set<unsigned int> found;
1164         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1165                 it != m_db->m_services.end(); ++it)
1166         {
1167                 int res = it->second->checkFilter(it->first, *query);
1168                 if (res)
1169                 {
1170                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1171                         if (found.find(dvbnamespace) == found.end())
1172                         {
1173                                 found.insert(dvbnamespace);
1174                                 eServiceReferenceDVB ref;
1175                                 ref.setDVBNamespace(dvbnamespace);
1176                                 ref.flags=eServiceReference::flagDirectory;
1177                                 char buf[128];
1178                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1179
1180                                 ref.path=buf+source.path;
1181                                 unsigned int pos=ref.path.find("FROM");
1182                                 ref.path.erase(pos);
1183                                 ref.path+="ORDER BY name";
1184 //                              eDebug("ref.path now %s", ref.path.c_str());
1185                                 m_list.push_back(ref);
1186
1187                                 ref.path=buf+source.path;
1188                                 pos=ref.path.find("FROM");
1189                                 ref.path.erase(pos+5);
1190                                 ref.path+="PROVIDERS ORDER BY name";
1191 //                              eDebug("ref.path now %s", ref.path.c_str());
1192                                 m_list.push_back(ref);
1193
1194                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1195                                 ref.path=buf+source.path;
1196                                 pos=ref.path.find("FROM");
1197                                 ref.path.erase(pos);
1198                                 ref.path+="ORDER BY name";
1199 //                              eDebug("ref.path now %s", ref.path.c_str());
1200                                 m_list.push_back(ref);
1201                         }
1202                 }
1203         }
1204         m_cursor=m_list.begin();
1205 }
1206
1207 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1208         :eDVBDBListQuery(db, source, query)
1209 {
1210         std::set<std::string> found;
1211         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1212                 it != m_db->m_services.end(); ++it)
1213         {
1214                 int res = it->second->checkFilter(it->first, *query);
1215                 if (res)
1216                 {
1217                         const char *provider_name = it->second->m_provider_name.length() ?
1218                                 it->second->m_provider_name.c_str() :
1219                                 "Unknown";
1220                         if (found.find(std::string(provider_name)) == found.end())
1221                         {
1222                                 found.insert(std::string(provider_name));
1223                                 eServiceReferenceDVB ref;
1224                                 char buf[64];
1225                                 ref.name=provider_name;
1226                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1227                                 ref.path=buf+source.path;
1228                                 unsigned int pos = ref.path.find("FROM");
1229                                 ref.flags=eServiceReference::flagDirectory;
1230                                 ref.path.erase(pos);
1231                                 ref.path+="ORDER BY name";
1232 //                              eDebug("ref.path now %s", ref.path.c_str());
1233                                 m_list.push_back(ref);
1234                         }
1235                 }
1236         }
1237         m_cursor=m_list.begin();
1238 }
1239
1240 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1241
1242 static int decodeType(const std::string &type)
1243 {
1244         if (type == "name")
1245                 return eDVBChannelQuery::tName;
1246         else if (type == "provider")
1247                 return eDVBChannelQuery::tProvider;
1248         else if (type == "type")
1249                 return eDVBChannelQuery::tType;
1250         else if (type == "bouquet")
1251                 return eDVBChannelQuery::tBouquet;
1252         else if (type == "satellitePosition")
1253                 return eDVBChannelQuery::tSatellitePosition;
1254         else if (type == "channelID")
1255                 return eDVBChannelQuery::tChannelID;
1256         else if (type == "flags")
1257                 return eDVBChannelQuery::tFlags;
1258         else
1259                 return -1;
1260 }
1261
1262         /* never, NEVER write a parser in C++! */
1263 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1264 {
1265         std::list<std::string>::const_iterator end_of_exp;
1266         
1267         if (begin == end)
1268                 return 0;
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);