add ability to read e1 bouquets
[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) || !strncmp(line, "#NAME: ", 7))
672                         {
673                                 int offs = line[5] == ':' ? 7 : 6;
674                                 bouquet.m_bouquet_name=line+offs;
675                         }
676                         continue;
677                 }
678         }
679         fclose(fp);
680         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
681 }
682
683 void eDVBDB::reloadBouquets()
684 {
685         m_bouquets.clear();
686         loadBouquet("bouquets.tv");
687         loadBouquet("bouquets.radio");
688 // create default bouquets when missing
689         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
690         {
691                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
692                 b.m_filename = "userbouquet.favourites.tv";
693                 b.m_bouquet_name = "Favourites (TV)";
694                 b.flushChanges();
695                 eServiceReference ref;
696                 memset(ref.data, 0, sizeof(ref.data));
697                 ref.type=1;
698                 ref.flags=7;
699                 ref.data[0]=1;
700                 ref.path="FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
701                 eBouquet &parent = m_bouquets["bouquets.tv"];
702                 parent.m_services.push_back(ref);
703                 parent.flushChanges();
704         }
705         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
706         {
707                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
708                 b.m_filename = "userbouquet.favourites.radio";
709                 b.m_bouquet_name = "Favourites (Radio)";
710                 b.flushChanges();
711                 eServiceReference ref;
712                 memset(ref.data, 0, sizeof(ref.data));
713                 ref.type=1;
714                 ref.flags=7;
715                 ref.data[0]=2;
716                 ref.path="FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
717                 eBouquet &parent = m_bouquets["bouquets.radio"];
718                 parent.m_services.push_back(ref);
719                 parent.flushChanges();
720         }
721 }
722
723 eDVBDB *eDVBDB::instance;
724
725 eDVBDB::eDVBDB()
726 {
727         instance = this;
728         reloadServicelist();
729 }
730
731 eDVBDB::~eDVBDB()
732 {
733         instance=NULL;
734 }
735
736 RESULT eDVBDB::removeService(const eServiceReference &ref)
737 {
738         if (ref.type == eServiceReference::idDVB)
739         {
740                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
741                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
742                 if (it != m_services.end())
743                 {
744                         m_services.erase(it);
745                         return 0;
746                 }
747         }
748         return -1;
749 }
750
751 RESULT eDVBDB::removeServices(int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
752 {
753         return removeServices(eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
754 }
755
756 RESULT eDVBDB::removeServices(eDVBChannelID chid, unsigned int orbpos)
757 {
758         RESULT ret=-1;
759         eDVBNamespace eNs;
760         eTransportStreamID eTsid;
761         eOriginalNetworkID eOnid;
762         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
763         std::set<eDVBChannelID> removed_chids;
764         while (it != m_channels.end())
765         {
766                 const eDVBChannelID &ch = it->first;
767                 bool remove=true;
768                 int system;
769                 it->second.m_frontendParameters->getSystem(system);
770                 if ( system == iDVBFrontend::feSatellite )
771                 {
772                         eDVBFrontendParametersSatellite sat;
773                         it->second.m_frontendParameters->getDVBS(sat);
774                         if ((unsigned int)sat.orbital_position != orbpos)
775                                 remove=false;
776                 }
777                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
778                         remove=false;
779                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
780                         remove=false;
781                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
782                         remove=false;
783                 if ( remove )
784                 {
785                         eDebug("remove %08x %04x %04x",
786                                 ch.dvbnamespace.get(),
787                                 ch.original_network_id.get(),
788                                 ch.transport_stream_id.get());
789                         removed_chids.insert(it->first);
790                         m_channels.erase(it++);
791                 }
792                 else
793                         ++it;
794         }
795         if (!removed_chids.empty())
796         {
797                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
798                 while(service != m_services.end())
799                 {
800                         eDVBChannelID chid;
801                         service->first.getChannelID(chid);
802                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
803                         if (it != removed_chids.end())
804                                 m_services.erase(service++);
805                         else
806                                 ++service;
807                         ret=0;
808                 }
809         }
810         return ret;
811 }
812
813 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
814 {
815         if (ref.type == eServiceReference::idDVB)
816         {
817                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
818                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
819                 if (it != m_services.end())
820                         it->second->m_flags |= ~flagmask;
821                 return 0;
822         }
823         return -1;
824 }
825
826 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
827 {
828         if (ref.type == eServiceReference::idDVB)
829         {
830                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
831                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
832                 if (it != m_services.end())
833                         it->second->m_flags &= ~flagmask;
834                 return 0;
835         }
836         return -1;
837 }
838
839 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
840 {
841         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
842 }
843
844 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
845 {
846         eDVBNamespace eNs;
847         eTransportStreamID eTsid;
848         eOriginalNetworkID eOnid;
849         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
850         std::set<eDVBChannelID> removed_chids;
851         while (it != m_channels.end())
852         {
853                 const eDVBChannelID &ch = it->first;
854                 bool remove=true;
855                 int system;
856                 it->second.m_frontendParameters->getSystem(system);
857                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
858                 {
859                         eDVBFrontendParametersSatellite sat;
860                         it->second.m_frontendParameters->getDVBS(sat);
861                         if ((unsigned int)sat.orbital_position != orbpos)
862                                 remove=false;
863                 }
864                 if ( remove && chid.dvbnamespace != eNs && chid.dvbnamespace != ch.dvbnamespace )
865                         remove=false;
866                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
867                         remove=false;
868                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
869                         remove=false;
870                 if ( remove )
871                         removed_chids.insert(it->first);
872                 ++it;
873         }
874         if (!removed_chids.empty())
875         {
876                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
877                 while(service != m_services.end())
878                 {
879                         eDVBChannelID chid;
880                         service->first.getChannelID(chid);
881                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
882                         if (it != removed_chids.end())
883                                 service->second->m_flags &= ~flagmask;
884                         ++service;
885                 }
886         }
887         return 0;
888 }
889
890 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
891 {
892         channel ch;
893         assert(feparm);
894         ch.m_frontendParameters = feparm;
895         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
896         return 0;
897 }
898
899 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
900 {
901         m_channels.erase(id);
902         return 0;
903 }
904
905 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
906 {
907         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
908         if (i == m_channels.end())
909         {
910                 parm = 0;
911                 return -ENOENT;
912         }
913         parm = i->second.m_frontendParameters;
914         return 0;
915 }
916
917 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
918 {
919         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
920         if (it == m_services.end())
921                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
922         return 0;
923 }
924
925 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
926 {
927         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
928         i = m_services.find(reference);
929         if (i == m_services.end())
930         {
931                 service = 0;
932                 return -ENOENT;
933         }
934         service = i->second;
935         return 0;
936 }
937
938 RESULT eDVBDB::flush()
939 {
940         saveServicelist();
941         return 0;
942 }
943
944 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
945 {
946         std::string str = ref.path;
947         if (str.empty())
948         {
949                 eDebug("getBouquet failed.. no path given!");
950                 return -1;
951         }
952         unsigned int pos = str.find("FROM BOUQUET \"");
953         if ( pos != std::string::npos )
954         {
955                 str.erase(0, pos+14);
956                 pos = str.find('"');
957                 if ( pos != std::string::npos )
958                         str.erase(pos);
959                 else
960                         str.clear();
961         }
962         if (str.empty())
963         {
964                 eDebug("getBouquet failed.. couldn't parse bouquet name");
965                 return -1;
966         }
967         std::map<std::string, eBouquet>::iterator i =
968                 m_bouquets.find(str);
969         if (i == m_bouquets.end())
970         {
971                 bouquet = 0;
972                 return -ENOENT;
973         }
974         bouquet = &i->second;
975         return 0;
976 }
977
978 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
979 {
980         if ( source.path.find("FROM") != std::string::npos )
981         {
982                 if ( source.path.find("BOUQUET") != std::string::npos )
983                         query = new eDVBDBBouquetQuery(this, source, q);
984                 else if ( source.path.find("SATELLITES") != std::string::npos )
985                         query = new eDVBDBSatellitesQuery(this, source, q);
986                 else if ( source.path.find("PROVIDERS") != std::string::npos )
987                         query = new eDVBDBProvidersQuery(this, source, q);
988                 else
989                         eFatal("invalid query %s", source.toString().c_str());
990         }
991         else
992                 query = new eDVBDBQuery(this, source, q);
993         return 0;
994 }
995
996 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
997 {
998         eServiceID Sid(sid);
999         eTransportStreamID Tsid(tsid);
1000         eOriginalNetworkID Onid(onid);
1001         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
1002                 sit != m_services.end(); ++sit)
1003         {
1004                 if (sit->first.getTransportStreamID() == Tsid &&
1005                         sit->first.getOriginalNetworkID() == Onid &&
1006                         sit->first.getServiceID() == Sid)
1007                         return sit->first;
1008         }
1009         return eServiceReference();
1010 }
1011
1012 DEFINE_REF(eDVBDBQueryBase);
1013
1014 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1015         :m_db(db), m_query(query), m_source(source)
1016 {
1017 }
1018
1019 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1020 {
1021         ePtr<eDVBService> a_service, b_service;
1022         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1023         
1024         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1025         {
1026                 if (a.name.empty() && m_db->getService(a, a_service))
1027                         return 1;
1028                 if (b.name.empty() && m_db->getService(b, b_service))
1029                         return 1;
1030         }
1031         
1032         switch (sortmode)
1033         {
1034         case eDVBChannelQuery::tName:
1035                 if (a_service)
1036                 {
1037                         if (b_service)
1038                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1039                         else
1040                         {
1041                                 std::string str = b.name;
1042                                 makeUpper(str);
1043                                 return a_service->m_service_name_sort < str;
1044                         }
1045                 }
1046                 else if (b_service)
1047                 {
1048                         std::string str = a.name;
1049                         makeUpper(str);
1050                         return str < b_service->m_service_name_sort;
1051                 }
1052                 else
1053                 {
1054                         std::string aa = a.name, bb = b.name;
1055                         makeUpper(aa);
1056                         makeUpper(bb);
1057                         return aa < bb;
1058                 }
1059         case eDVBChannelQuery::tProvider:
1060                 return a_service->m_provider_name < b_service->m_provider_name;
1061         case eDVBChannelQuery::tType:
1062                 return a.getServiceType() < b.getServiceType();
1063         case eDVBChannelQuery::tBouquet:
1064                 return 0;
1065         case eDVBChannelQuery::tSatellitePosition:
1066                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1067         default:
1068                 return 1;
1069         }
1070         return 0;
1071 }
1072
1073 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1074         :eDVBDBQueryBase(db, source, query)
1075 {
1076         m_cursor = m_db->m_services.begin();
1077 }
1078
1079 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1080 {
1081         while (m_cursor != m_db->m_services.end())
1082         {
1083                 ref = m_cursor->first;
1084
1085                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
1086
1087                 ++m_cursor;
1088
1089                 if (res)
1090                         return 0;
1091         }
1092
1093         ref.type = eServiceReference::idInvalid;
1094
1095         return 1;
1096 }
1097
1098 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1099         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1100 {
1101 }
1102
1103 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1104 {
1105         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1106         std::list<eServiceReference> &list = bouquet.m_services;
1107         while (m_cursor != list.end())
1108         {
1109                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1110
1111                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1112                         m_db->m_services.find(ref);
1113
1114                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
1115
1116                 ++m_cursor;
1117
1118                 if (res)
1119                         return 0;
1120         }
1121
1122         ref.type = eServiceReference::idInvalid;
1123
1124         return 1;
1125 }
1126
1127 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1128         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1129 {
1130 }
1131
1132 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1133 {
1134         if (m_cursor != m_list.end())
1135         {
1136                 ref = *m_cursor++;
1137                 return 0;
1138         }
1139         ref.type = eServiceReference::idInvalid;
1140         return 1;
1141 }
1142
1143 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1144 {
1145         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1146         {
1147                 int x = (a.getDVBNamespace().get() >> 16);
1148                 int y = (b.getDVBNamespace().get() >> 16);
1149                 if ( x > 1800 )
1150                         x -= 3600;
1151                 if ( y > 1800 )
1152                         y -= 3600;
1153                 return x < y;
1154         }
1155         std::string aa = a.name, bb = b.name;
1156         makeUpper(aa);
1157         makeUpper(bb);
1158         return aa < bb;
1159 }
1160
1161 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1162         :eDVBDBListQuery(db, source, query)
1163 {
1164         std::set<unsigned int> found;
1165         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1166                 it != m_db->m_services.end(); ++it)
1167         {
1168                 int res = it->second->checkFilter(it->first, *query);
1169                 if (res)
1170                 {
1171                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1172                         if (found.find(dvbnamespace) == found.end())
1173                         {
1174                                 found.insert(dvbnamespace);
1175                                 eServiceReferenceDVB ref;
1176                                 ref.setDVBNamespace(dvbnamespace);
1177                                 ref.flags=eServiceReference::flagDirectory;
1178                                 char buf[128];
1179                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1180
1181                                 ref.path=buf+source.path;
1182                                 unsigned int pos=ref.path.find("FROM");
1183                                 ref.path.erase(pos);
1184                                 ref.path+="ORDER BY name";
1185 //                              eDebug("ref.path now %s", ref.path.c_str());
1186                                 m_list.push_back(ref);
1187
1188                                 ref.path=buf+source.path;
1189                                 pos=ref.path.find("FROM");
1190                                 ref.path.erase(pos+5);
1191                                 ref.path+="PROVIDERS ORDER BY name";
1192 //                              eDebug("ref.path now %s", ref.path.c_str());
1193                                 m_list.push_back(ref);
1194
1195                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1196                                 ref.path=buf+source.path;
1197                                 pos=ref.path.find("FROM");
1198                                 ref.path.erase(pos);
1199                                 ref.path+="ORDER BY name";
1200 //                              eDebug("ref.path now %s", ref.path.c_str());
1201                                 m_list.push_back(ref);
1202                         }
1203                 }
1204         }
1205         m_cursor=m_list.begin();
1206 }
1207
1208 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1209         :eDVBDBListQuery(db, source, query)
1210 {
1211         std::set<std::string> found;
1212         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1213                 it != m_db->m_services.end(); ++it)
1214         {
1215                 int res = it->second->checkFilter(it->first, *query);
1216                 if (res)
1217                 {
1218                         const char *provider_name = it->second->m_provider_name.length() ?
1219                                 it->second->m_provider_name.c_str() :
1220                                 "Unknown";
1221                         if (found.find(std::string(provider_name)) == found.end())
1222                         {
1223                                 found.insert(std::string(provider_name));
1224                                 eServiceReferenceDVB ref;
1225                                 char buf[64];
1226                                 ref.name=provider_name;
1227                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1228                                 ref.path=buf+source.path;
1229                                 unsigned int pos = ref.path.find("FROM");
1230                                 ref.flags=eServiceReference::flagDirectory;
1231                                 ref.path.erase(pos);
1232                                 ref.path+="ORDER BY name";
1233 //                              eDebug("ref.path now %s", ref.path.c_str());
1234                                 m_list.push_back(ref);
1235                         }
1236                 }
1237         }
1238         m_cursor=m_list.begin();
1239 }
1240
1241 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1242
1243 static int decodeType(const std::string &type)
1244 {
1245         if (type == "name")
1246                 return eDVBChannelQuery::tName;
1247         else if (type == "provider")
1248                 return eDVBChannelQuery::tProvider;
1249         else if (type == "type")
1250                 return eDVBChannelQuery::tType;
1251         else if (type == "bouquet")
1252                 return eDVBChannelQuery::tBouquet;
1253         else if (type == "satellitePosition")
1254                 return eDVBChannelQuery::tSatellitePosition;
1255         else if (type == "channelID")
1256                 return eDVBChannelQuery::tChannelID;
1257         else if (type == "flags")
1258                 return eDVBChannelQuery::tFlags;
1259         else
1260                 return -1;
1261 }
1262
1263         /* never, NEVER write a parser in C++! */
1264 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1265 {
1266         std::list<std::string>::const_iterator end_of_exp;
1267         
1268         if (begin == end)
1269                 return 0;
1270         
1271         if (*begin == "(")
1272         {
1273                 end_of_exp = begin;
1274                 while (end_of_exp != end)
1275                         if (*end_of_exp == ")")
1276                                 break;
1277                         else
1278                                 ++end_of_exp;
1279         
1280                 if (end_of_exp == end)
1281                 {
1282                         eDebug("expression parse: end of expression while searching for closing brace");
1283                         return -1;
1284                 }
1285                 
1286                 ++begin;
1287                 // begin..end_of_exp
1288                 int r = parseExpression(res, begin, end_of_exp);
1289                 if (r)
1290                         return r;
1291                 ++end_of_exp;
1292                 
1293                         /* we had only one sub expression */
1294                 if (end_of_exp == end)
1295                 {
1296 //                      eDebug("only one sub expression");
1297                         return 0;
1298                 }
1299                 
1300                         /* otherwise we have an operator here.. */
1301                 
1302                 ePtr<eDVBChannelQuery> r2 = res;
1303                 res = new eDVBChannelQuery();
1304                 res->m_sort = 0;
1305                 res->m_p1 = r2;
1306                 res->m_inverse = 0;
1307                 r2 = 0;
1308                 
1309                 if (*end_of_exp == "||")
1310                         res->m_type = eDVBChannelQuery::tOR;
1311                 else if (*end_of_exp == "&&")
1312                         res->m_type = eDVBChannelQuery::tAND;
1313                 else
1314                 {
1315                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1316                         res = 0;
1317                         return 1;
1318                 }
1319                 
1320                 ++end_of_exp;
1321                 
1322                 return parseExpression(res->m_p2, end_of_exp, end);
1323         }
1324         
1325         // "begin" <op> "end"
1326         std::string type, op, val;
1327         
1328         res = new eDVBChannelQuery();
1329         res->m_sort = 0;
1330         
1331         int cnt = 0;
1332         while (begin != end)
1333         {
1334                 switch (cnt)
1335                 {
1336                 case 0:
1337                         type = *begin;
1338                         break;
1339                 case 1:
1340                         op = *begin;
1341                         break;
1342                 case 2:
1343                         val = *begin;
1344                         break;
1345                 case 3:
1346                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1347                         return 1;
1348                 }
1349                 ++begin;
1350                 ++cnt;
1351         }
1352         
1353         if (cnt != 3)
1354         {
1355                 eDebug("malformed query: missing stuff");
1356                 res = 0;
1357                 return 1;
1358         }
1359         
1360         res->m_type = decodeType(type);
1361         
1362         if (res->m_type == -1)
1363         {
1364                 eDebug("malformed query: invalid type %s", type.c_str());
1365                 res = 0;
1366                 return 1;
1367         }
1368         
1369         if (op == "==")
1370                 res->m_inverse = 0;
1371         else if (op == "!=")
1372                 res->m_inverse = 1;
1373         else
1374         {
1375                 eDebug("invalid operator %s", op.c_str());
1376                 res = 0;
1377                 return 1;
1378         }
1379         
1380         res->m_string = val;
1381         res->m_int = atoi(val.c_str());
1382 //      res->m_channelid = eDVBChannelID(val);
1383         
1384         return 0;
1385 }
1386
1387 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1388 {
1389         std::list<std::string> tokens;
1390         
1391         std::string current_token;
1392         std::string bouquet_name;
1393
1394 //      eDebug("splitting %s....", query.c_str());
1395         unsigned int i = 0;
1396         const char *splitchars="()";
1397         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1398         while (i <= query.size())
1399         {
1400                 int c = (i < query.size()) ? query[i] : ' ';
1401                 ++i;
1402                 
1403                 int issplit = !!strchr(splitchars, c);
1404                 int isaln = isalnum(c);
1405                 int iswhite = c == ' ';
1406                 int isquot = c == '\"';
1407                 
1408                 if (quotemode)
1409                 {
1410                         iswhite = issplit = 0;
1411                         isaln = lastalnum;
1412                 }
1413                 
1414                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1415                 {
1416                         if (current_token.size())
1417                                 tokens.push_back(current_token);
1418                         current_token.clear();
1419                 }
1420                 
1421                 if (!(iswhite || isquot))
1422                         current_token += c;
1423                 
1424                 if (isquot)
1425                         quotemode = !quotemode;
1426                 lastsplit = issplit;
1427                 lastalnum = isaln;
1428         }
1429         
1430 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1431 //      {
1432 //              printf("%s\n", a->c_str());
1433 //      }
1434
1435         int sort = eDVBChannelQuery::tName;
1436                 /* check for "ORDER BY ..." */
1437
1438         std::list<std::string>::iterator it = tokens.begin();
1439         while (it != tokens.end())
1440         {
1441                 if (*it == "ORDER")
1442                 {
1443                         tokens.erase(it++);
1444                         if (it != tokens.end() && *it == "BY")
1445                         {
1446                                 tokens.erase(it++);
1447                                 sort = decodeType(*it);
1448                                 tokens.erase(it++);
1449                         } else
1450                                 sort = -1;
1451                 }
1452                 else if (*it == "FROM")
1453                 {
1454                         tokens.erase(it++);
1455                         if (it != tokens.end() && *it == "BOUQUET")
1456                         {
1457                                 tokens.erase(it++);
1458                                 bouquet_name = *it;
1459                                 tokens.erase(it++);
1460                         }
1461                         else if (it != tokens.end() && *it == "SATELLITES")
1462                                 tokens.erase(it++);
1463                         else if (it != tokens.end() && *it == "PROVIDERS")
1464                                 tokens.erase(it++);
1465                         else
1466                         {
1467                                 eDebug("FROM unknown %s", (*it).c_str());
1468                                 tokens.erase(it++);
1469                         }
1470                 }
1471                 else
1472                         ++it;
1473         }
1474
1475         if (sort == -1)
1476         {
1477                 eWarning("ORDER BY .. string invalid.");
1478                 res = 0;
1479                 return -1;
1480         }
1481         
1482 //      eDebug("sort by %d", sort);
1483         
1484                 /* now we recursivly parse that. */
1485         int r = parseExpression(res, tokens.begin(), tokens.end());
1486         
1487                 /* we have an empty (but valid!) expression */
1488         if (!r && !res)
1489         {
1490                 res = new eDVBChannelQuery();
1491                 res->m_inverse = 0;
1492                 res->m_type = eDVBChannelQuery::tAny;
1493         }
1494         
1495         if (res)
1496         {
1497                 res->m_sort = sort;
1498                 res->m_bouquet_name = bouquet_name;
1499         }
1500
1501 //      eDebug("return: %d", r);
1502         return r;
1503 }
1504
1505 DEFINE_REF(eDVBChannelQuery);