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