fix write
[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 <xmlccwrap/xmlccwrap.h>
9 #include <dvbsi++/service_description_section.h>
10 #include <dvbsi++/descriptor_tag.h>
11 #include <dvbsi++/service_descriptor.h>
12 #include <dvbsi++/satellite_delivery_system_descriptor.h>
13
14 DEFINE_REF(eDVBService);
15
16 RESULT eBouquet::addService(const eServiceReference &ref, eServiceReference before)
17 {
18         list::iterator it =
19                 std::find(m_services.begin(), m_services.end(), ref);
20         if ( it != m_services.end() )
21                 return -1;
22         if (before.valid())
23         {
24                 it = std::find(m_services.begin(), m_services.end(), before);
25                 m_services.insert(it, ref);
26         }
27         else
28                 m_services.push_back(ref);
29         return 0;
30 }
31
32 RESULT eBouquet::removeService(const eServiceReference &ref)
33 {
34         list::iterator it =
35                 std::find(m_services.begin(), m_services.end(), ref);
36         if ( it == m_services.end() )
37                 return -1;
38         m_services.erase(it);
39         return 0;
40 }
41
42 RESULT eBouquet::moveService(const eServiceReference &ref, unsigned int pos)
43 {
44         if ( pos < 0 || pos >= m_services.size() )
45                 return -1;
46         ++pos;
47         list::iterator source=m_services.end();
48         list::iterator dest=m_services.end();
49         bool forward = false;
50         for (list::iterator it(m_services.begin()); it != m_services.end(); ++it)
51         {
52                 if (dest == m_services.end() && !--pos)
53                         dest = it;
54                 if (*it == ref)
55                 {
56                         source = it;
57                         forward = pos>0;
58                 }
59                 if (dest != m_services.end() && source != m_services.end())
60                         break;
61         }
62         if (dest == m_services.end() || source == m_services.end() || source == dest)
63                 return -1;
64         while (source != dest)
65         {
66                 if (forward)
67                         std::iter_swap(source++, source);
68                 else
69                         std::iter_swap(source--, source);
70         }
71         return 0;
72 }
73
74 RESULT eBouquet::flushChanges()
75 {
76         FILE *f=fopen((CONFIGDIR"/enigma2/"+m_filename).c_str(), "w");
77         if (!f)
78                 return -1;
79         if ( fprintf(f, "#NAME %s\r\n", m_bouquet_name.c_str()) < 0 )
80                 goto err;
81         for (list::iterator i(m_services.begin()); i != m_services.end(); ++i)
82         {
83                 eServiceReference tmp = *i;
84                 std::string str = tmp.path;
85                 if ( fprintf(f, "#SERVICE %s\r\n", tmp.toString().c_str()) < 0 )
86                         goto err;
87                 if ( i->name.length() )
88                         if ( fprintf(f, "#DESCRIPTION %s\r\n", i->name.c_str()) < 0 )
89                                 goto err;
90         }
91         fclose(f);
92         return 0;
93 err:
94         fclose(f);
95         eDebug("couldn't write file %s", m_filename.c_str());
96         return -1;
97 }
98
99 RESULT eBouquet::setListName(const std::string &name)
100 {
101         m_bouquet_name = name;
102         return 0;
103 }
104
105 eDVBService::eDVBService()
106         :m_cache(0), m_flags(0)
107 {
108 }
109
110 eDVBService::~eDVBService()
111 {
112         delete [] m_cache;
113 }
114
115 eDVBService &eDVBService::operator=(const eDVBService &s)
116 {
117         m_service_name = s.m_service_name;
118         m_service_name_sort = s.m_service_name_sort;
119         m_provider_name = s.m_provider_name;
120         m_flags = s.m_flags;
121         m_ca = s.m_ca;
122         copyCache(s.m_cache);
123         return *this;
124 }
125
126 void eDVBService::genSortName()
127 {
128         m_service_name_sort = removeDVBChars(m_service_name);
129         makeUpper(m_service_name_sort);
130         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
131                 m_service_name_sort.erase(0, 1);
132
133                 /* put unnamed services at the end, not at the beginning. */
134         if (m_service_name_sort.empty())
135                 m_service_name_sort = "\xFF";
136 }
137
138 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
139 {
140         if (!ref.name.empty())
141                 name = ref.name; // use renamed service name..
142         else if (!m_service_name.empty())
143                 name = m_service_name;
144         else
145                 name = "(...)";
146         return 0;
147 }
148
149 RESULT eDVBService::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &ptr, time_t start_time)
150 {
151         return eEPGCache::getInstance()->lookupEventTime(ref, start_time, ptr);
152 }
153
154 int eDVBService::isPlayable(const eServiceReference &ref, const eServiceReference &ignore)
155 {
156         ePtr<eDVBResourceManager> res_mgr;
157         if ( eDVBResourceManager::getInstance( res_mgr ) )
158                 eDebug("isPlayble... no res manager!!");
159         else
160         {
161                 eDVBChannelID chid, chid_ignore;
162                 ((const eServiceReferenceDVB&)ref).getChannelID(chid);
163                 ((const eServiceReferenceDVB&)ignore).getChannelID(chid_ignore);
164                 return res_mgr->canAllocateChannel(chid, chid_ignore);
165         }
166         return 0;
167 }
168
169 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
170 {
171         int res = 0;
172         switch (query.m_type)
173         {
174         case eDVBChannelQuery::tName:
175                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
176                 break;
177         case eDVBChannelQuery::tProvider:
178                 res = m_provider_name.find(query.m_string) != std::string::npos;
179                 break;
180         case eDVBChannelQuery::tType:
181                 res = ref.getServiceType() == query.m_int;
182                 break;
183         case eDVBChannelQuery::tBouquet:
184                 res = 0;
185                 break;
186         case eDVBChannelQuery::tSatellitePosition:
187                 res = ((unsigned int)ref.getDVBNamespace().get())>>16 == (unsigned int)query.m_int;
188                 break;
189         case eDVBChannelQuery::tFlags:
190                 res = (m_flags & query.m_int) == query.m_int;
191                 break;
192         case eDVBChannelQuery::tChannelID:
193         {
194                 eDVBChannelID chid;
195                 ref.getChannelID(chid);
196                 res = chid == query.m_channelid;
197                 break;
198         }
199         case eDVBChannelQuery::tAND:
200                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
201                 break;
202         case eDVBChannelQuery::tOR:
203                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
204                 break;
205         case eDVBChannelQuery::tAny:
206                 res = 1;
207                 break;
208         }
209
210         if (query.m_inverse)
211                 return !res;
212         else
213                 return res;
214 }
215
216 bool eDVBService::cacheEmpty()
217 {
218         if (m_cache)
219                 for (int i=0; i < cacheMax; ++i)
220                         if (m_cache[i] != -1)
221                                 return false;
222         return true;
223 }
224
225 void eDVBService::initCache()
226 {
227         m_cache = new int[cacheMax];
228         memset(m_cache, -1, sizeof(int) * cacheMax);
229 }
230
231 void eDVBService::copyCache(int *source)
232 {
233         if (source)
234         {
235                 if (!m_cache)
236                         m_cache = new int[cacheMax];
237                 memcpy(m_cache, source, cacheMax * sizeof(int));
238         }
239         else
240         {
241                 delete [] m_cache;
242                 m_cache = 0;
243         }
244 }
245
246 int eDVBService::getCacheEntry(cacheID id)
247 {
248         if (id >= cacheMax || !m_cache)
249                 return -1;
250         return m_cache[id];
251 }
252
253 void eDVBService::setCacheEntry(cacheID id, int pid)
254 {
255         if (!m_cache)
256                 initCache();
257         if (id < cacheMax)
258                 m_cache[id] = pid;
259 }
260
261 DEFINE_REF(eDVBDB);
262
263 void eDVBDB::reloadServicelist()
264 {
265         loadServicelist(CONFIGDIR"/enigma2/lamedb");
266 }
267
268         /* THIS CODE IS BAD. it should be replaced by somethine better. */
269 void eDVBDB::loadServicelist(const char *file)
270 {
271         eDebug("---- opening lame channel db");
272         FILE *f=fopen(file, "rt");
273         if (!f && strcmp(file, CONFIGDIR"/enigma2/lamedb") == 0)
274         {
275                 struct stat s;
276                 if ( !stat("lamedb", &s) )
277                 {
278                         if ( !stat(CONFIGDIR"/enigma2", &s) )
279                         {
280                                 rename("lamedb", CONFIGDIR"/enigma2/lamedb" );
281                                 reloadServicelist();
282                         }
283                 }
284                 return;
285         }
286         char line[256];
287         int version=3;
288         if ((!fgets(line, 256, f)) || sscanf(line, "eDVB services /%d/", &version) != 1)
289         {
290                 eDebug("not a valid servicefile");
291                 fclose(f);
292                 return;
293         }
294         eDebug("reading services (version %d)", version);
295         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
296         {
297                 eDebug("services invalid, no transponders");
298                 fclose(f);
299                 return;
300         }
301
302         // clear all transponders
303
304         while (!feof(f))
305         {
306                 if (!fgets(line, 256, f))
307                         break;
308                 if (!strcmp(line, "end\n"))
309                         break;
310                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
311                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
312                 if (original_network_id == -1)
313                         continue;
314                 eDVBChannelID channelid = eDVBChannelID(
315                         eDVBNamespace(dvb_namespace),
316                         eTransportStreamID(transport_stream_id),
317                         eOriginalNetworkID(original_network_id));
318
319                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
320                 while (!feof(f))
321                 {
322                         fgets(line, 256, f);
323                         if (!strcmp(line, "/\n"))
324                                 break;
325                         if (line[1]=='s')
326                         {
327                                 eDVBFrontendParametersSatellite sat;
328                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion,
329                                         flags=0,
330                                         system=eDVBFrontendParametersSatellite::System::DVB_S,
331                                         modulation=eDVBFrontendParametersSatellite::Modulation::QPSK,
332                                         rolloff=eDVBFrontendParametersSatellite::RollOff::alpha_0_35,
333                                         pilot=eDVBFrontendParametersSatellite::Pilot::Unknown;
334                                 if (version == 3)
335                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &system, &modulation, &rolloff, &pilot);
336                                 else
337                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &flags, &system, &modulation, &rolloff, &pilot);
338                                 sat.frequency = frequency;
339                                 sat.symbol_rate = symbol_rate;
340                                 sat.polarisation = polarisation;
341                                 sat.fec = fec;
342                                 sat.orbital_position =
343                                         orbital_position < 0 ? orbital_position + 3600 : orbital_position;
344                                 sat.inversion = inversion;
345                                 sat.system = system;
346                                 sat.modulation = modulation;
347                                 sat.rolloff = rolloff;
348                                 sat.pilot = pilot;
349                                 feparm->setDVBS(sat);
350                                 feparm->setFlags(flags);
351                         } else if (line[1]=='t')
352                         {
353                                 eDVBFrontendParametersTerrestrial ter;
354                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion, flags=0;
355                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion, &flags);
356                                 ter.frequency = frequency;
357                                 ter.bandwidth = bandwidth;
358                                 ter.code_rate_HP = code_rate_HP;
359                                 ter.code_rate_LP = code_rate_LP;
360                                 ter.modulation = modulation;
361                                 ter.transmission_mode = transmission_mode;
362                                 ter.guard_interval = guard_interval;
363                                 ter.hierarchy = hierarchy;
364                                 ter.inversion = inversion;
365                                 feparm->setDVBT(ter);
366                                 feparm->setFlags(flags);
367                         } else if (line[1]=='c')
368                         {
369                                 eDVBFrontendParametersCable cab;
370                                 int frequency, symbol_rate,
371                                         inversion=eDVBFrontendParametersCable::Inversion::Unknown,
372                                         modulation=eDVBFrontendParametersCable::Modulation::Auto,
373                                         fec_inner=eDVBFrontendParametersCable::FEC::fAuto,
374                                         flags=0;
375                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation, &fec_inner, &flags);
376                                 cab.frequency = frequency;
377                                 cab.fec_inner = fec_inner;
378                                 cab.inversion = inversion;
379                                 cab.symbol_rate = symbol_rate;
380                                 cab.modulation = modulation;
381                                 feparm->setDVBC(cab);
382                                 feparm->setFlags(flags);
383                         }
384                 }
385                 addChannelToList(channelid, feparm);
386         }
387
388         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
389         {
390                 eDebug("services invalid, no services");
391                 return;
392         }
393
394         // clear all services
395
396         int count=0;
397
398         while (!feof(f))
399         {
400                 if (!fgets(line, 256, f))
401                         break;
402                 if (!strcmp(line, "end\n"))
403                         break;
404
405                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
406                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
407                 if (service_number == -1)
408                         continue;
409                 ePtr<eDVBService> s = new eDVBService;
410                 eServiceReferenceDVB ref =
411                                                 eServiceReferenceDVB(
412                                                 eDVBNamespace(dvb_namespace),
413                                                 eTransportStreamID(transport_stream_id),
414                                                 eOriginalNetworkID(original_network_id),
415                                                 eServiceID(service_id),
416                                                 service_type);
417                 count++;
418                 fgets(line, 256, f);
419                 if (strlen(line))
420                         line[strlen(line)-1]=0;
421
422                 s->m_service_name = line;
423                 s->genSortName();
424
425                 fgets(line, 256, f);
426                 if (strlen(line))
427                         line[strlen(line)-1]=0;
428                 std::string str=line;
429
430                 if (str[1]!=':')        // old ... (only service_provider)
431                 {
432                         s->m_provider_name=line;
433                 } else
434                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
435                         {
436                                 size_t c=str.find(',');
437                                 char p=str[0];
438                                 std::string v;
439                                 if (c == std::string::npos)
440                                 {
441                                         v=str.substr(2);
442                                         str="";
443                                 } else
444                                 {
445                                         v=str.substr(2, c-2);
446                                         str=str.substr(c+1);
447                                 }
448 //                              eDebug("%c ... %s", p, v.c_str());
449                                 if (p == 'p')
450                                         s->m_provider_name=v;
451                                 else if (p == 'f')
452                                 {
453                                         sscanf(v.c_str(), "%x", &s->m_flags);
454                                 } else if (p == 'c')
455                                 {
456                                         int cid, val;
457                                         sscanf(v.c_str(), "%02d%x", &cid, &val);
458                                         s->setCacheEntry((eDVBService::cacheID)cid,val);
459                                 } else if (p == 'C')
460                                 {
461                                         int val;
462                                         sscanf(v.c_str(), "%04x", &val);
463                                         s->m_ca.push_front((uint16_t)val);
464                                 }
465                         }
466                 addService(ref, s);
467         }
468
469         eDebug("loaded %d services", count);
470
471         fclose(f);
472 }
473
474 void eDVBDB::saveServicelist(const char *file)
475 {
476         eDebug("---- saving lame channel db");
477         FILE *f=fopen(file, "w");
478         int channels=0, services=0;
479         if (!f)
480                 eFatal("couldn't save lame channel db!");
481         fprintf(f, "eDVB services /4/\n");
482         fprintf(f, "transponders\n");
483         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
484                         i != m_channels.end(); ++i)
485         {
486                 const eDVBChannelID &chid = i->first;
487                 const channel &ch = i->second;
488
489                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
490                                 chid.transport_stream_id.get(), chid.original_network_id.get());
491                 eDVBFrontendParametersSatellite sat;
492                 eDVBFrontendParametersTerrestrial ter;
493                 eDVBFrontendParametersCable cab;
494                 unsigned int flags;  // flagOnlyFree yet..
495                 ch.m_frontendParameters->getFlags(flags);
496                 if (!ch.m_frontendParameters->getDVBS(sat))
497                 {
498                         if (sat.system == eDVBFrontendParametersSatellite::System::DVB_S2)
499                         {
500                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d:%d:%d:%d",
501                                         sat.frequency, sat.symbol_rate,
502                                         sat.polarisation, sat.fec,
503                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
504                                         sat.inversion,
505                                         flags,
506                                         sat.system,
507                                         sat.modulation,
508                                         sat.rolloff);
509                                 if (sat.modulation == eDVBFrontendParametersSatellite::Modulation::M8PSK)
510                                         fprintf(f, ":%d\n", sat.pilot);
511                                 else
512                                         fprintf(f, "\n");
513                         }
514                         else
515                         {
516                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d\n",
517                                         sat.frequency, sat.symbol_rate,
518                                         sat.polarisation, sat.fec,
519                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
520                                         sat.inversion, flags);
521                         }
522                 }
523                 else if (!ch.m_frontendParameters->getDVBT(ter))
524                 {
525                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d:%d\n",
526                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
527                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
528                                 ter.guard_interval, ter.hierarchy, ter.inversion, flags);
529                 }
530                 else if (!ch.m_frontendParameters->getDVBC(cab))
531                 {
532                         fprintf(f, "\tc %d:%d:%d:%d:%d:%d\n",
533                                 cab.frequency, cab.symbol_rate, cab.inversion, cab.modulation, cab.fec_inner, flags);
534                 }
535                 fprintf(f, "/\n");
536                 channels++;
537         }
538         fprintf(f, "end\nservices\n");
539
540         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
541                 i != m_services.end(); ++i)
542         {
543                 const eServiceReferenceDVB &s = i->first;
544                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
545                                 s.getServiceID().get(), s.getDVBNamespace().get(),
546                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
547                                 s.getServiceType(),
548                                 0);
549
550                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
551
552                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
553
554                 // write cached pids
555                 for (int x=0; x < eDVBService::cacheMax; ++x)
556                 {
557                         int entry = i->second->getCacheEntry((eDVBService::cacheID)x);
558                         if (entry != -1)
559                                 fprintf(f, ",c:%02d%04x", x, entry);
560                 }
561
562                 // write cached ca pids
563                 for (CAID_LIST::const_iterator ca(i->second->m_ca.begin());
564                         ca != i->second->m_ca.end(); ++ca)
565                         fprintf(f, ",C:%04x", *ca);
566
567                 if (i->second->m_flags)
568                         fprintf(f, ",f:%x", i->second->m_flags);
569
570                 fprintf(f, "\n");
571                 services++;
572         }
573         fprintf(f, "end\nHave a lot of bugs!\n");
574         eDebug("saved %d channels and %d services!", channels, services);
575         fclose(f);
576 }
577
578 void eDVBDB::saveServicelist()
579 {
580         saveServicelist(CONFIGDIR"/enigma2/lamedb");
581 }
582
583 void eDVBDB::loadBouquet(const char *path)
584 {
585         std::string bouquet_name = path;
586         if (!bouquet_name.length())
587         {
588                 eDebug("Bouquet load failed.. no path given..");
589                 return;
590         }
591         size_t pos = bouquet_name.rfind('/');
592         if ( pos != std::string::npos )
593                 bouquet_name.erase(0, pos+1);
594         if (bouquet_name.empty())
595         {
596                 eDebug("Bouquet load failed.. no filename given..");
597                 return;
598         }
599         eBouquet &bouquet = m_bouquets[bouquet_name];
600         bouquet.m_filename = bouquet_name;
601         std::list<eServiceReference> &list = bouquet.m_services;
602         list.clear();
603
604         std::string p = CONFIGDIR"/enigma2/";
605         p+=path;
606         eDebug("loading bouquet... %s", p.c_str());
607         FILE *fp=fopen(p.c_str(), "rt");
608         int entries=0;
609         if (!fp)
610         {
611                 struct stat s;
612                 if ( !stat(path, &s) )
613                 {
614                         rename(path, p.c_str() );
615                         loadBouquet(path);
616                         return;
617                 }
618                 eDebug("failed to open.");
619                 if ( strstr(path, "bouquets.tv") )
620                 {
621                         eDebug("recreate bouquets.tv");
622                         bouquet.m_bouquet_name="Bouquets (TV)";
623                         bouquet.flushChanges();
624                 }
625                 else if ( strstr(path, "bouquets.radio") )
626                 {
627                         eDebug("recreate bouquets.radio");
628                         bouquet.m_bouquet_name="Bouquets (Radio)";
629                         bouquet.flushChanges();
630                 }
631                 return;
632         }
633         char line[256];
634         bool read_descr=false;
635         eServiceReference *e = NULL;
636         while (1)
637         {
638                 if (!fgets(line, 256, fp))
639                         break;
640                 line[strlen(line)-1]=0;
641                 if (strlen(line) && line[strlen(line)-1]=='\r')
642                         line[strlen(line)-1]=0;
643                 if (!line[0])
644                         break;
645                 if (line[0]=='#')
646                 {
647                         if (!strncmp(line, "#SERVICE", 8))
648                         {
649                                 int offs = line[8] == ':' ? 10 : 9;
650                                 eServiceReference tmp(line+offs);
651                                 if (tmp.type != eServiceReference::idDVB)
652                                 {
653                                         eDebug("only DVB Bouquets supported");
654                                         continue;
655                                 }
656                                 if ( tmp.flags&eServiceReference::canDescent )
657                                 {
658                                         size_t pos = tmp.path.rfind('/');
659                                         char buf[256];
660                                         std::string path = tmp.path;
661                                         if ( pos != std::string::npos )
662                                                 path.erase(0, pos+1);
663                                         if (path.empty())
664                                         {
665                                                 eDebug("Bouquet load failed.. no filename given..");
666                                                 continue;
667                                         }
668                                         pos = path.find("FROM BOUQUET ");
669                                         if (pos != std::string::npos)
670                                         {
671                                                 char endchr = path[pos+13];
672                                                 if (endchr != '"')
673                                                 {
674                                                         eDebug("ignore invalid bouquet '%s' (only \" are allowed)",
675                                                                 tmp.toString().c_str());
676                                                         continue;
677                                                 }
678                                                 char *beg = &path[pos+14];
679                                                 char *end = strchr(beg, endchr);
680                                                 path.assign(beg, end - beg);
681                                         }
682                                         else
683                                         {
684                                                 snprintf(buf, 256, "FROM BOUQUET \"%s\" ORDER BY bouquet", path.c_str());
685                                                 tmp.path = buf;
686                                         }
687                                         loadBouquet(path.c_str());
688                                 }
689                                 list.push_back(tmp);
690                                 e = &list.back();
691                                 read_descr=true;
692                                 ++entries;
693                         }
694                         else if (read_descr && !strncmp(line, "#DESCRIPTION", 12))
695                         {
696                                 int offs = line[12] == ':' ? 14 : 13;
697                                 e->name = line+offs;
698                                 read_descr=false;
699                         }
700                         else if (!strncmp(line, "#NAME ", 6))
701                                 bouquet.m_bouquet_name=line+6;
702                         continue;
703                 }
704         }
705         fclose(fp);
706         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
707 }
708
709 void eDVBDB::reloadBouquets()
710 {
711         m_bouquets.clear();
712         loadBouquet("bouquets.tv");
713         loadBouquet("bouquets.radio");
714 // create default bouquets when missing
715         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
716         {
717                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
718                 b.m_filename = "userbouquet.favourites.tv";
719                 b.m_bouquet_name = "Favourites (TV)";
720                 b.flushChanges();
721                 eServiceReference ref;
722                 memset(ref.data, 0, sizeof(ref.data));
723                 ref.type=1;
724                 ref.flags=7;
725                 ref.data[0]=1;
726                 ref.path="FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
727                 eBouquet &parent = m_bouquets["bouquets.tv"];
728                 parent.m_services.push_back(ref);
729                 parent.flushChanges();
730         }
731         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
732         {
733                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
734                 b.m_filename = "userbouquet.favourites.radio";
735                 b.m_bouquet_name = "Favourites (Radio)";
736                 b.flushChanges();
737                 eServiceReference ref;
738                 memset(ref.data, 0, sizeof(ref.data));
739                 ref.type=1;
740                 ref.flags=7;
741                 ref.data[0]=2;
742                 ref.path="FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
743                 eBouquet &parent = m_bouquets["bouquets.radio"];
744                 parent.m_services.push_back(ref);
745                 parent.flushChanges();
746         }
747 }
748
749 eDVBDB *eDVBDB::instance;
750
751 using namespace xmlcc;
752
753 eDVBDB::eDVBDB()
754 {
755         instance = this;
756         reloadServicelist();
757 }
758
759 PyObject *eDVBDB::readSatellites(ePyObject sat_list, ePyObject sat_dict, ePyObject tp_dict)
760 {
761         if (!PyDict_Check(tp_dict)) {
762                 PyErr_SetString(PyExc_StandardError,
763                         "type error");
764                         eDebug("arg 2 is not a python dict");
765                 return NULL;
766         }
767         else if (!PyDict_Check(sat_dict))
768         {
769                 PyErr_SetString(PyExc_StandardError,
770                         "type error");
771                         eDebug("arg 1 is not a python dict");
772                 return NULL;
773         }
774         else if (!PyList_Check(sat_list))
775         {
776                 PyErr_SetString(PyExc_StandardError,
777                         "type error");
778                         eDebug("arg 0 is not a python list");
779                 return NULL;
780         }
781         XMLTree tree;
782         tree.setFilename("/etc/tuxbox/satellites.xml");
783         tree.read();
784         Element *root = tree.getRoot();
785         if (!root)
786         {
787                 eDebug("couldn't open /etc/tuxbox/satellites.xml!!");
788                 Py_INCREF(Py_False);
789                 return Py_False;
790         }
791         int tmp, *dest = NULL,
792                 modulation, system, freq, sr, pol, fec, inv, pilot, rolloff;
793         char *end_ptr;
794         const Attribute *at;
795         std::string name;
796         const ElementList &root_elements = root->getElementList();
797         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
798         {
799 //              eDebug("element: %s", (*it)->name().c_str());
800                 const Element *el = *it;
801                 const ElementList &sat_elements = el->getElementList();
802                 const AttributeList &sat_attributes = el->getAttributeList();
803                 ePyObject sat_name;
804                 ePyObject sat_pos;
805                 ePyObject sat_flags;
806                 for (AttributeConstIterator it(sat_attributes.begin()); it != sat_attributes.end(); ++it)
807                 {
808 //                      eDebug("\tattr: %s", at->name().c_str());
809                         at = *it;
810                         name = at->name();
811                         if (name == "name")
812                                 sat_name = PyString_FromString(at->value().c_str());
813                         else if (name == "flags")
814                         {
815                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
816                                 if (!*end_ptr)
817                                         sat_flags = PyInt_FromLong(tmp);
818                         }
819                         else if (name == "position")
820                         {
821                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
822                                 if (!*end_ptr)
823                                 {
824                                         if (tmp < 0)
825                                                 tmp = 3600 + tmp;
826                                         sat_pos = PyInt_FromLong(tmp);
827                                 }
828                         }
829                 }
830                 if (sat_pos && sat_name)
831                 {
832                         ePyObject tplist = PyList_New(0);
833                         ePyObject tuple = PyTuple_New(3);
834                         if (!sat_flags)
835                                 sat_flags = PyInt_FromLong(0);
836                         PyTuple_SET_ITEM(tuple, 0, sat_pos);
837                         PyTuple_SET_ITEM(tuple, 1, sat_name);
838                         PyTuple_SET_ITEM(tuple, 2, sat_flags);
839                         PyList_Append(sat_list, tuple);
840                         Py_DECREF(tuple);
841                         PyDict_SetItem(sat_dict, sat_pos, sat_name);
842                         PyDict_SetItem(tp_dict, sat_pos, tplist);
843                         for (ElementConstIterator it(sat_elements.begin()); it != sat_elements.end(); ++it)
844                         {
845 //                              eDebug("\telement: %s", (*it)->name().c_str());
846                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
847                                 AttributeConstIterator end = tp_attributes.end();
848                                 modulation = 1; // QPSK default
849                                 system = 0; // DVB-S default
850                                 freq = 0;
851                                 sr = 0;
852                                 pol = -1;
853                                 fec = 0; // AUTO default
854                                 inv = 2; // AUTO default
855                                 pilot = 2; // AUTO default
856                                 rolloff = 0; // alpha 0.35
857                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
858                                 {
859 //                                      eDebug("\t\tattr: %s", at->name().c_str());
860                                         at = *it;
861                                         name = at->name();
862                                         if (name == "modulation") dest = &modulation;
863                                         else if (name == "system") dest = &system;
864                                         else if (name == "frequency") dest = &freq;
865                                         else if (name == "symbol_rate") dest = &sr;
866                                         else if (name == "polarization") dest = &pol;
867                                         else if (name == "fec_inner") dest = &fec;
868                                         else if (name == "inversion") dest = &inv;
869                                         else if (name == "rolloff") dest = &rolloff;
870                                         else if (name == "pilot") dest = &pilot;
871                                         if (dest)
872                                         {
873                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
874                                                 if (!*end_ptr)
875                                                         *dest = tmp;
876                                         }
877                                 }
878                                 if (freq && sr && pol != -1)
879                                 {
880                                         tuple = PyTuple_New(10);
881                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(0));
882                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
883                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
884                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(pol));
885                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
886                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(system));
887                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(modulation));
888                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(inv));
889                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(rolloff));
890                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(pilot));
891                                         PyList_Append(tplist, tuple);
892                                         Py_DECREF(tuple);
893                                 }
894                         }
895                         Py_DECREF(tplist);
896                 }
897                 else
898                 {
899                         if (sat_pos)
900                                 Py_DECREF(sat_pos);
901                         if (sat_name)
902                                 Py_DECREF(sat_name);
903                         if (sat_flags)
904                                 Py_DECREF(sat_flags);
905                 }
906         }
907         Py_INCREF(Py_True);
908         return Py_True;
909 }
910
911 PyObject *eDVBDB::readCables(ePyObject cab_list, ePyObject tp_dict)
912 {
913         if (!PyDict_Check(tp_dict)) {
914                 PyErr_SetString(PyExc_StandardError,
915                         "type error");
916                         eDebug("arg 1 is not a python dict");
917                 return NULL;
918         }
919         else if (!PyList_Check(cab_list))
920         {
921                 PyErr_SetString(PyExc_StandardError,
922                         "type error");
923                         eDebug("arg 0 is not a python list");
924                 return NULL;
925         }
926         XMLTree tree;
927         tree.setFilename("/etc/tuxbox/cables.xml");
928         tree.read();
929         Element *root = tree.getRoot();
930         if (!root)
931         {
932                 eDebug("couldn't open /etc/tuxbox/cables.xml!!");
933                 Py_INCREF(Py_False);
934                 return Py_False;
935         }
936         const Attribute *at;
937         int tmp, *dest,
938                 modulation, fec, freq, sr;
939         std::string name;
940         char *end_ptr;
941         const ElementList &root_elements = root->getElementList();
942         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
943         {
944 //              eDebug("element: %s", el->name().c_str());
945                 const Element *el = *it;
946                 const ElementList &cab_elements = el->getElementList();
947                 const AttributeList &cab_attributes = el->getAttributeList();
948                 ePyObject cab_name;
949                 ePyObject cab_flags;
950                 for (AttributeConstIterator it(cab_attributes.begin()); it != cab_attributes.end(); ++it)
951                 {
952 //                      eDebug("\tattr: %s", at->name().c_str());
953                         at = *it;
954                         name = at->name();
955                         if (name == "name")
956                                 cab_name = PyString_FromString(at->value().c_str());
957                         else if (name == "flags")
958                         {
959                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
960                                 if (!*end_ptr)
961                                         cab_flags = PyInt_FromLong(tmp);
962                         }
963                 }
964                 if (cab_name)
965                 {
966                         ePyObject tplist = PyList_New(0);
967                         ePyObject tuple = PyTuple_New(2);
968                         if (!cab_flags)
969                                 cab_flags = PyInt_FromLong(0);
970                         PyTuple_SET_ITEM(tuple, 0, cab_name);
971                         PyTuple_SET_ITEM(tuple, 1, cab_flags);
972                         PyList_Append(cab_list, tuple);
973                         Py_DECREF(tuple);
974                         PyDict_SetItem(tp_dict, cab_name, tplist);
975                         for (ElementConstIterator it(cab_elements.begin()); it != cab_elements.end(); ++it)
976                         {
977 //                              eDebug("\telement: %s", (*it)->name().c_str());
978                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
979                                 AttributeConstIterator end = tp_attributes.end();
980                                 modulation = 3; // QAM64 default
981                                 fec = 0; // AUTO default
982                                 freq = 0;
983                                 sr = 0;
984                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
985                                 {
986 //                                      eDebug("\t\tattr: %s", at->name().c_str());
987                                         at = *it;
988                                         dest = 0;
989                                         name = at->name();
990                                         if (name == "modulation") dest = &modulation;
991                                         else if (name == "frequency") dest = &freq;
992                                         else if (name == "symbol_rate") dest = &sr;
993                                         else if (name == "fec_inner") dest = &fec;
994                                         if (dest)
995                                         {
996                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
997                                                 if (!*end_ptr)
998                                                         *dest = tmp;
999                                         }
1000                                 }
1001                                 if (freq && sr)
1002                                 {
1003                                         while (freq > 999999)
1004                                                 freq /= 10;
1005                                         tuple = PyTuple_New(5);
1006                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(1));
1007                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1008                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
1009                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(modulation));
1010                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
1011                                         PyList_Append(tplist, tuple);
1012                                         Py_DECREF(tuple);
1013                                 }
1014                         }
1015                         Py_DECREF(tplist);
1016                 }
1017                 else if (cab_flags)
1018                         Py_DECREF(cab_flags);
1019         }
1020         Py_INCREF(Py_True);
1021         return Py_True;
1022 }
1023
1024 PyObject *eDVBDB::readTerrestrials(ePyObject ter_list, ePyObject tp_dict)
1025 {
1026         if (!PyDict_Check(tp_dict)) {
1027                 PyErr_SetString(PyExc_StandardError,
1028                         "type error");
1029                         eDebug("arg 1 is not a python dict");
1030                 return NULL;
1031         }
1032         else if (!PyList_Check(ter_list))
1033         {
1034                 PyErr_SetString(PyExc_StandardError,
1035                         "type error");
1036                         eDebug("arg 0 is not a python list");
1037                 return NULL;
1038         }
1039         XMLTree tree;
1040         tree.setFilename("/etc/tuxbox/terrestrial.xml");
1041         tree.read();
1042         Element *root = tree.getRoot();
1043         if (!root)
1044         {
1045                 eDebug("couldn't open /etc/tuxbox/terrestrial.xml!!");
1046                 Py_INCREF(Py_False);
1047                 return Py_False;
1048         }
1049         const Attribute *at;
1050         std::string name;
1051         int tmp, *dest,
1052                 freq, bw, constellation, crh = 5, crl = 5, guard = 4, transm, hierarchy, inv = 2;
1053         char *end_ptr;
1054         const ElementList &root_elements = root->getElementList();
1055         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
1056         {
1057 //              eDebug("element: %s", el->name().c_str());
1058                 const Element *el = *it;
1059                 const ElementList &ter_elements = el->getElementList();
1060                 const AttributeList &ter_attributes = el->getAttributeList();
1061                 ePyObject ter_name;
1062                 ePyObject ter_flags;
1063                 for (AttributeConstIterator it(ter_attributes.begin()); it != ter_attributes.end(); ++it)
1064                 {
1065 //                      eDebug("\tattr: %s", at->name().c_str());
1066                         at = *it;
1067                         name = at->name();
1068                         if (name == "name")
1069                                 ter_name = PyString_FromString(at->value().c_str());
1070                         else if (name == "flags")
1071                         {
1072                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1073                                 if (!*end_ptr)
1074                                         ter_flags = PyInt_FromLong(tmp);
1075                         }
1076                 }
1077                 if (ter_name)
1078                 {
1079                         ePyObject tplist = PyList_New(0);
1080                         ePyObject tuple = PyTuple_New(2);
1081                         if (!ter_flags)
1082                                 ter_flags = PyInt_FromLong(0);
1083                         PyTuple_SET_ITEM(tuple, 0, ter_name);
1084                         PyTuple_SET_ITEM(tuple, 1, ter_flags);
1085                         PyList_Append(ter_list, tuple);
1086                         Py_DECREF(tuple);
1087                         PyDict_SetItem(tp_dict, ter_name, tplist);
1088                         for (ElementConstIterator it(ter_elements.begin()); it != ter_elements.end(); ++it)
1089                         {
1090 //                              eDebug("\telement: %s", (*it)->name().c_str());
1091                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
1092                                 AttributeConstIterator end = tp_attributes.end();
1093                                 freq = 0;
1094                                 bw = 3; // AUTO
1095                                 constellation = 1; // AUTO
1096                                 crh = 5; // AUTO
1097                                 crl = 5; // AUTO
1098                                 guard = 4; // AUTO
1099                                 transm = 2; // AUTO
1100                                 hierarchy = 4; // AUTO
1101                                 inv = 2; // AUTO
1102                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
1103                                 {
1104 //                                      eDebug("\t\tattr: %s", at->name().c_str());
1105                                         at = *it;
1106                                         dest = 0;
1107                                         name = at->name();
1108                                         if (name == "centre_frequency") dest = &freq;
1109                                         else if (name == "bandwidth") dest = &bw;
1110                                         else if (name == "constellation") dest = &constellation;
1111                                         else if (name == "code_rate_hp") dest = &crh;
1112                                         else if (name == "code_rate_lp") dest = &crl;
1113                                         else if (name == "guard_interval") dest = &guard;
1114                                         else if (name == "transmission_mode") dest = &transm;
1115                                         else if (name == "hierarchy_information") dest = &hierarchy;
1116                                         else if (name == "inversion") dest = &inv;
1117                                         if (dest)
1118                                         {
1119                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1120                                                 if (!*end_ptr)
1121                                                         *dest = tmp;
1122                                         }
1123                                 }
1124                                 if (freq)
1125                                 {
1126                                         if (crh > 5) // our terrestrial.xml is buggy... 6 for AUTO
1127                                                 crh = 5;
1128                                         if (crl > 5) // our terrestrial.xml is buggy... 6 for AUTO
1129                                                 crl = 5;
1130                                         tuple = PyTuple_New(10);
1131                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1132                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1133                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(bw));
1134                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(constellation));
1135                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(crh));
1136                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(crl));
1137                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(guard));
1138                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(transm));
1139                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(hierarchy));
1140                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(inv));
1141                                         PyList_Append(tplist, tuple);
1142                                         Py_DECREF(tuple);
1143                                 }
1144                         }
1145                         Py_DECREF(tplist);
1146                 }
1147                 else if (ter_flags)
1148                         Py_DECREF(ter_flags);
1149         }
1150         Py_INCREF(Py_True);
1151         return Py_True;
1152 }
1153
1154 eDVBDB::~eDVBDB()
1155 {
1156         instance=NULL;
1157 }
1158
1159 RESULT eDVBDB::removeService(const eServiceReference &ref)
1160 {
1161         if (ref.type == eServiceReference::idDVB)
1162         {
1163                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1164                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1165                 if (it != m_services.end())
1166                 {
1167                         m_services.erase(it);
1168                         return 0;
1169                 }
1170         }
1171         return -1;
1172 }
1173
1174 RESULT eDVBDB::removeServices(int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1175 {
1176         return removeServices(eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1177 }
1178
1179 RESULT eDVBDB::removeServices(eDVBChannelID chid, unsigned int orbpos)
1180 {
1181         RESULT ret=-1;
1182         eDVBNamespace eNs;
1183         eTransportStreamID eTsid;
1184         eOriginalNetworkID eOnid;
1185         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1186         std::set<eDVBChannelID> removed_chids;
1187         while (it != m_channels.end())
1188         {
1189                 const eDVBChannelID &ch = it->first;
1190                 bool remove=true;
1191                 int system;
1192                 it->second.m_frontendParameters->getSystem(system);
1193                 if ( system == iDVBFrontend::feSatellite )
1194                 {
1195                         eDVBFrontendParametersSatellite sat;
1196                         it->second.m_frontendParameters->getDVBS(sat);
1197                         if ((unsigned int)sat.orbital_position != orbpos)
1198                                 remove=false;
1199                 }
1200                 if ( remove && chid.dvbnamespace != eNs )
1201                 {
1202                         if (system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000)
1203                                 ;
1204                         else if (system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000)
1205                                 ;
1206                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1207                                 remove=false;
1208                 }
1209                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1210                         remove=false;
1211                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1212                         remove=false;
1213                 if ( remove )
1214                 {
1215                         eDebug("remove %08x %04x %04x",
1216                                 ch.dvbnamespace.get(),
1217                                 ch.original_network_id.get(),
1218                                 ch.transport_stream_id.get());
1219                         removed_chids.insert(it->first);
1220                         m_channels.erase(it++);
1221                 }
1222                 else
1223                         ++it;
1224         }
1225         if (!removed_chids.empty())
1226         {
1227                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1228                 while(service != m_services.end())
1229                 {
1230                         eDVBChannelID chid;
1231                         service->first.getChannelID(chid);
1232                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1233                         if (it != removed_chids.end())
1234                                 m_services.erase(service++);
1235                         else
1236                                 ++service;
1237                         ret=0;
1238                 }
1239         }
1240         return ret;
1241 }
1242
1243 RESULT eDVBDB::removeServices(iDVBFrontendParameters *feparm)
1244 {
1245         int ret = -1;
1246         std::set<eDVBChannelID> removed_chids;
1247         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1248         while (it != m_channels.end())
1249         {
1250                 int diff;
1251                 if (!feparm->calculateDifference(&(*it->second.m_frontendParameters), diff, false))
1252                 {
1253                         if (diff < 4000)
1254                         {
1255                                 removed_chids.insert(it->first);
1256                                 m_channels.erase(it++);
1257                         }
1258                         else
1259                                 ++it;
1260                 }
1261                 else
1262                         ++it;
1263         }
1264         if (!removed_chids.empty())
1265         {
1266                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1267                 while(service != m_services.end())
1268                 {
1269                         eDVBChannelID chid;
1270                         service->first.getChannelID(chid);
1271                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1272                         if (it != removed_chids.end())
1273                                 m_services.erase(service++);
1274                         else
1275                                 ++service;
1276                 }
1277                 ret = 0;
1278         }
1279         return ret;
1280 }
1281
1282 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
1283 {
1284         if (ref.type == eServiceReference::idDVB)
1285         {
1286                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1287                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1288                 if (it != m_services.end())
1289                         it->second->m_flags |= ~flagmask;
1290                 return 0;
1291         }
1292         return -1;
1293 }
1294
1295 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
1296 {
1297         if (ref.type == eServiceReference::idDVB)
1298         {
1299                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1300                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1301                 if (it != m_services.end())
1302                         it->second->m_flags &= ~flagmask;
1303                 return 0;
1304         }
1305         return -1;
1306 }
1307
1308 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1309 {
1310         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1311 }
1312
1313 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
1314 {
1315         eDVBNamespace eNs;
1316         eTransportStreamID eTsid;
1317         eOriginalNetworkID eOnid;
1318         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1319         std::set<eDVBChannelID> removed_chids;
1320         while (it != m_channels.end())
1321         {
1322                 const eDVBChannelID &ch = it->first;
1323                 bool remove=true;
1324                 int system;
1325                 it->second.m_frontendParameters->getSystem(system);
1326                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
1327                 {
1328                         eDVBFrontendParametersSatellite sat;
1329                         it->second.m_frontendParameters->getDVBS(sat);
1330                         if ((unsigned int)sat.orbital_position != orbpos)
1331                                 remove=false;
1332                 }
1333                 if ( remove && chid.dvbnamespace != eNs )
1334                 {
1335                         if (system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000)
1336                                 ;
1337                         else if (system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000)
1338                                 ;
1339                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1340                                 remove=false;
1341                 }
1342                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1343                         remove=false;
1344                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1345                         remove=false;
1346                 if ( remove )
1347                         removed_chids.insert(it->first);
1348                 ++it;
1349         }
1350         if (!removed_chids.empty())
1351         {
1352                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1353                 while(service != m_services.end())
1354                 {
1355                         eDVBChannelID chid;
1356                         service->first.getChannelID(chid);
1357                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1358                         if (it != removed_chids.end())
1359                                 service->second->m_flags &= ~flagmask;
1360                         ++service;
1361                 }
1362         }
1363         return 0;
1364 }
1365
1366 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
1367 {
1368         channel ch;
1369         std::map<eDVBChannelID, channel>::iterator it = m_channels.find(id);
1370         assert(feparm);
1371         ch.m_frontendParameters = feparm;
1372         if (it != m_channels.end())
1373                 it->second = ch;
1374         else
1375                 m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
1376         return 0;
1377 }
1378
1379 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
1380 {
1381         m_channels.erase(id);
1382         return 0;
1383 }
1384
1385 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
1386 {
1387         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
1388         if (i == m_channels.end())
1389         {
1390                 parm = 0;
1391                 return -ENOENT;
1392         }
1393         parm = i->second.m_frontendParameters;
1394         return 0;
1395 }
1396
1397 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
1398 {
1399         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
1400         if (it == m_services.end())
1401                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
1402         return 0;
1403 }
1404
1405 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
1406 {
1407         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
1408         i = m_services.find(reference);
1409         if (i == m_services.end())
1410         {
1411                 service = 0;
1412                 return -ENOENT;
1413         }
1414         service = i->second;
1415         return 0;
1416 }
1417
1418 RESULT eDVBDB::flush()
1419 {
1420         saveServicelist();
1421         return 0;
1422 }
1423
1424 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
1425 {
1426         std::string str = ref.path;
1427         if (str.empty())
1428         {
1429                 eDebug("getBouquet failed.. no path given!");
1430                 return -1;
1431         }
1432         size_t pos = str.find("FROM BOUQUET \"");
1433         if ( pos != std::string::npos )
1434         {
1435                 str.erase(0, pos+14);
1436                 pos = str.find('"');
1437                 if ( pos != std::string::npos )
1438                         str.erase(pos);
1439                 else
1440                         str.clear();
1441         }
1442         if (str.empty())
1443         {
1444                 eDebug("getBouquet failed.. couldn't parse bouquet name");
1445                 return -1;
1446         }
1447         std::map<std::string, eBouquet>::iterator i =
1448                 m_bouquets.find(str);
1449         if (i == m_bouquets.end())
1450         {
1451                 bouquet = 0;
1452                 return -ENOENT;
1453         }
1454         bouquet = &i->second;
1455         return 0;
1456 }
1457
1458 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
1459 {
1460         if ( source.path.find("FROM") != std::string::npos )
1461         {
1462                 if ( source.path.find("BOUQUET") != std::string::npos )
1463                         query = new eDVBDBBouquetQuery(this, source, q);
1464                 else if ( source.path.find("SATELLITES") != std::string::npos )
1465                         query = new eDVBDBSatellitesQuery(this, source, q);
1466                 else if ( source.path.find("PROVIDERS") != std::string::npos )
1467                         query = new eDVBDBProvidersQuery(this, source, q);
1468                 else
1469                         eFatal("invalid query %s", source.toString().c_str());
1470         }
1471         else
1472                 query = new eDVBDBQuery(this, source, q);
1473         return 0;
1474 }
1475
1476 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
1477 {
1478         eServiceID Sid(sid);
1479         eTransportStreamID Tsid(tsid);
1480         eOriginalNetworkID Onid(onid);
1481         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
1482                 sit != m_services.end(); ++sit)
1483         {
1484                 if (sit->first.getTransportStreamID() == Tsid &&
1485                         sit->first.getOriginalNetworkID() == Onid &&
1486                         sit->first.getServiceID() == Sid)
1487                         return sit->first;
1488         }
1489         return eServiceReference();
1490 }
1491
1492 DEFINE_REF(eDVBDBQueryBase);
1493
1494 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1495         :m_db(db), m_query(query), m_source(source)
1496 {
1497 }
1498
1499 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1500 {
1501         ePtr<eDVBService> a_service, b_service;
1502         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1503         
1504         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1505         {
1506                 if (a.name.empty() && m_db->getService(a, a_service))
1507                         return 1;
1508                 if (b.name.empty() && m_db->getService(b, b_service))
1509                         return 1;
1510         }
1511         
1512         switch (sortmode)
1513         {
1514         case eDVBChannelQuery::tName:
1515                 if (a_service)
1516                 {
1517                         if (b_service)
1518                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1519                         else
1520                         {
1521                                 std::string str = b.name;
1522                                 makeUpper(str);
1523                                 return a_service->m_service_name_sort < str;
1524                         }
1525                 }
1526                 else if (b_service)
1527                 {
1528                         std::string str = a.name;
1529                         makeUpper(str);
1530                         return str < b_service->m_service_name_sort;
1531                 }
1532                 else
1533                 {
1534                         std::string aa = a.name, bb = b.name;
1535                         makeUpper(aa);
1536                         makeUpper(bb);
1537                         return aa < bb;
1538                 }
1539         case eDVBChannelQuery::tProvider:
1540                 return a_service->m_provider_name < b_service->m_provider_name;
1541         case eDVBChannelQuery::tType:
1542                 return a.getServiceType() < b.getServiceType();
1543         case eDVBChannelQuery::tBouquet:
1544                 return 0;
1545         case eDVBChannelQuery::tSatellitePosition:
1546                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1547         default:
1548                 return 1;
1549         }
1550         return 0;
1551 }
1552
1553 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1554         :eDVBDBQueryBase(db, source, query)
1555 {
1556         m_cursor = m_db->m_services.begin();
1557 }
1558
1559 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1560 {
1561         while (m_cursor != m_db->m_services.end())
1562         {
1563                 ePtr<eDVBService> service = m_cursor->second;
1564                 if (service->isHidden())
1565                         ++m_cursor;
1566                 else
1567                 {
1568                         ref = m_cursor->first;
1569
1570                         int res = (!m_query) || service->checkFilter(ref, *m_query);
1571
1572                         ++m_cursor;
1573
1574                         if (res)
1575                                 return 0;
1576                 }
1577         }
1578
1579         ref.type = eServiceReference::idInvalid;
1580
1581         return 1;
1582 }
1583
1584 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1585         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1586 {
1587 }
1588
1589 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1590 {
1591         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1592         std::list<eServiceReference> &list = bouquet.m_services;
1593         while (m_cursor != list.end())
1594         {
1595                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1596
1597                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1598                         m_db->m_services.find(ref);
1599
1600                 int res = (!m_query) || it == m_db->m_services.end() || !(it->second->isHidden() && it->second->checkFilter(ref, *m_query));
1601
1602                 ++m_cursor;
1603
1604                 if (res)
1605                         return 0;
1606         }
1607
1608         ref.type = eServiceReference::idInvalid;
1609
1610         return 1;
1611 }
1612
1613 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1614         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1615 {
1616 }
1617
1618 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1619 {
1620         if (m_cursor != m_list.end())
1621         {
1622                 ref = *m_cursor++;
1623                 return 0;
1624         }
1625         ref.type = eServiceReference::idInvalid;
1626         return 1;
1627 }
1628
1629 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1630 {
1631         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1632         {
1633                 int x = (a.getDVBNamespace().get() >> 16);
1634                 int y = (b.getDVBNamespace().get() >> 16);
1635                 if ( x > 1800 )
1636                         x -= 3600;
1637                 if ( y > 1800 )
1638                         y -= 3600;
1639                 return x < y;
1640         }
1641         std::string aa = a.name, bb = b.name;
1642         makeUpper(aa);
1643         makeUpper(bb);
1644         return aa < bb;
1645 }
1646
1647 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1648         :eDVBDBListQuery(db, source, query)
1649 {
1650         std::set<unsigned int> found;
1651         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1652                 it != m_db->m_services.end(); ++it)
1653         {
1654                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1655                 if (res)
1656                 {
1657                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1658                         if (found.find(dvbnamespace) == found.end())
1659                         {
1660                                 found.insert(dvbnamespace);
1661                                 eServiceReferenceDVB ref;
1662                                 ref.setDVBNamespace(dvbnamespace);
1663                                 ref.flags=eServiceReference::flagDirectory;
1664                                 char buf[128];
1665                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1666
1667                                 ref.path=buf+source.path;
1668                                 unsigned int pos=ref.path.find("FROM");
1669                                 ref.path.erase(pos);
1670                                 ref.path+="ORDER BY name";
1671 //                              eDebug("ref.path now %s", ref.path.c_str());
1672                                 m_list.push_back(ref);
1673
1674                                 ref.path=buf+source.path;
1675                                 pos=ref.path.find("FROM");
1676                                 ref.path.erase(pos+5);
1677                                 ref.path+="PROVIDERS ORDER BY name";
1678 //                              eDebug("ref.path now %s", ref.path.c_str());
1679                                 m_list.push_back(ref);
1680
1681                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1682                                 ref.path=buf+source.path;
1683                                 pos=ref.path.find("FROM");
1684                                 ref.path.erase(pos);
1685                                 ref.path+="ORDER BY name";
1686 //                              eDebug("ref.path now %s", ref.path.c_str());
1687                                 m_list.push_back(ref);
1688                         }
1689                 }
1690         }
1691         m_cursor=m_list.begin();
1692 }
1693
1694 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1695         :eDVBDBListQuery(db, source, query)
1696 {
1697         std::set<std::string> found;
1698         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1699                 it != m_db->m_services.end(); ++it)
1700         {
1701                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1702                 if (res)
1703                 {
1704                         const char *provider_name = it->second->m_provider_name.length() ?
1705                                 it->second->m_provider_name.c_str() :
1706                                 "Unknown";
1707                         if (found.find(std::string(provider_name)) == found.end())
1708                         {
1709                                 found.insert(std::string(provider_name));
1710                                 eServiceReferenceDVB ref;
1711                                 char buf[64];
1712                                 ref.name=provider_name;
1713                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1714                                 ref.path=buf+source.path;
1715                                 unsigned int pos = ref.path.find("FROM");
1716                                 ref.flags=eServiceReference::flagDirectory;
1717                                 ref.path.erase(pos);
1718                                 ref.path+="ORDER BY name";
1719 //                              eDebug("ref.path now %s", ref.path.c_str());
1720                                 m_list.push_back(ref);
1721                         }
1722                 }
1723         }
1724         m_cursor=m_list.begin();
1725 }
1726
1727 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1728
1729 static int decodeType(const std::string &type)
1730 {
1731         if (type == "name")
1732                 return eDVBChannelQuery::tName;
1733         else if (type == "provider")
1734                 return eDVBChannelQuery::tProvider;
1735         else if (type == "type")
1736                 return eDVBChannelQuery::tType;
1737         else if (type == "bouquet")
1738                 return eDVBChannelQuery::tBouquet;
1739         else if (type == "satellitePosition")
1740                 return eDVBChannelQuery::tSatellitePosition;
1741         else if (type == "channelID")
1742                 return eDVBChannelQuery::tChannelID;
1743         else if (type == "flags")
1744                 return eDVBChannelQuery::tFlags;
1745         else
1746                 return -1;
1747 }
1748
1749         /* never, NEVER write a parser in C++! */
1750 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1751 {
1752         std::list<std::string>::const_iterator end_of_exp;
1753         
1754         if (begin == end)
1755                 return 0;
1756         
1757         if (*begin == "(")
1758         {
1759                 end_of_exp = begin;
1760                 while (end_of_exp != end)
1761                         if (*end_of_exp == ")")
1762                                 break;
1763                         else
1764                                 ++end_of_exp;
1765         
1766                 if (end_of_exp == end)
1767                 {
1768                         eDebug("expression parse: end of expression while searching for closing brace");
1769                         return -1;
1770                 }
1771                 
1772                 ++begin;
1773                 // begin..end_of_exp
1774                 int r = parseExpression(res, begin, end_of_exp);
1775                 if (r)
1776                         return r;
1777                 ++end_of_exp;
1778                 
1779                         /* we had only one sub expression */
1780                 if (end_of_exp == end)
1781                 {
1782 //                      eDebug("only one sub expression");
1783                         return 0;
1784                 }
1785                 
1786                         /* otherwise we have an operator here.. */
1787                 
1788                 ePtr<eDVBChannelQuery> r2 = res;
1789                 res = new eDVBChannelQuery();
1790                 res->m_sort = 0;
1791                 res->m_p1 = r2;
1792                 res->m_inverse = 0;
1793                 r2 = 0;
1794                 
1795                 if (*end_of_exp == "||")
1796                         res->m_type = eDVBChannelQuery::tOR;
1797                 else if (*end_of_exp == "&&")
1798                         res->m_type = eDVBChannelQuery::tAND;
1799                 else
1800                 {
1801                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1802                         res = 0;
1803                         return 1;
1804                 }
1805                 
1806                 ++end_of_exp;
1807                 
1808                 return parseExpression(res->m_p2, end_of_exp, end);
1809         }
1810         
1811         // "begin" <op> "end"
1812         std::string type, op, val;
1813         
1814         res = new eDVBChannelQuery();
1815         res->m_sort = 0;
1816         
1817         int cnt = 0;
1818         while (begin != end)
1819         {
1820                 switch (cnt)
1821                 {
1822                 case 0:
1823                         type = *begin;
1824                         break;
1825                 case 1:
1826                         op = *begin;
1827                         break;
1828                 case 2:
1829                         val = *begin;
1830                         break;
1831                 case 3:
1832                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1833                         return 1;
1834                 }
1835                 ++begin;
1836                 ++cnt;
1837         }
1838         
1839         if (cnt != 3)
1840         {
1841                 eDebug("malformed query: missing stuff");
1842                 res = 0;
1843                 return 1;
1844         }
1845         
1846         res->m_type = decodeType(type);
1847         
1848         if (res->m_type == -1)
1849         {
1850                 eDebug("malformed query: invalid type %s", type.c_str());
1851                 res = 0;
1852                 return 1;
1853         }
1854         
1855         if (op == "==")
1856                 res->m_inverse = 0;
1857         else if (op == "!=")
1858                 res->m_inverse = 1;
1859         else
1860         {
1861                 eDebug("invalid operator %s", op.c_str());
1862                 res = 0;
1863                 return 1;
1864         }
1865         
1866         res->m_string = val;
1867
1868         if (res->m_type == eDVBChannelQuery::tChannelID)
1869         {
1870                 int ns, tsid, onid;
1871                 if (sscanf(val.c_str(), "%08x%04x%04x", &ns, &tsid, &onid) == 3)
1872                         res->m_channelid = eDVBChannelID(eDVBNamespace(ns), eTransportStreamID(tsid), eOriginalNetworkID(onid));
1873                 else
1874                         eDebug("couldn't parse channelid !! format should be hex NNNNNNNNTTTTOOOO (namespace, tsid, onid)");
1875         }
1876         else
1877                 res->m_int = atoi(val.c_str());
1878
1879         return 0;
1880 }
1881
1882 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1883 {
1884         std::list<std::string> tokens;
1885         
1886         std::string current_token;
1887         std::string bouquet_name;
1888
1889 //      eDebug("splitting %s....", query.c_str());
1890         unsigned int i = 0;
1891         const char *splitchars="()";
1892         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1893         while (i <= query.size())
1894         {
1895                 int c = (i < query.size()) ? query[i] : ' ';
1896                 ++i;
1897                 
1898                 int issplit = !!strchr(splitchars, c);
1899                 int isaln = isalnum(c);
1900                 int iswhite = c == ' ';
1901                 int isquot = c == '\"';
1902                 
1903                 if (quotemode)
1904                 {
1905                         iswhite = issplit = 0;
1906                         isaln = lastalnum;
1907                 }
1908                 
1909                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1910                 {
1911                         if (current_token.size())
1912                                 tokens.push_back(current_token);
1913                         current_token.clear();
1914                 }
1915                 
1916                 if (!(iswhite || isquot))
1917                         current_token += c;
1918                 
1919                 if (isquot)
1920                         quotemode = !quotemode;
1921                 lastsplit = issplit;
1922                 lastalnum = isaln;
1923         }
1924         
1925 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1926 //      {
1927 //              printf("%s\n", a->c_str());
1928 //      }
1929
1930         int sort = eDVBChannelQuery::tName;
1931                 /* check for "ORDER BY ..." */
1932
1933         std::list<std::string>::iterator it = tokens.begin();
1934         while (it != tokens.end())
1935         {
1936                 if (*it == "ORDER")
1937                 {
1938                         tokens.erase(it++);
1939                         if (it != tokens.end() && *it == "BY")
1940                         {
1941                                 tokens.erase(it++);
1942                                 sort = decodeType(*it);
1943                                 tokens.erase(it++);
1944                         } else
1945                                 sort = -1;
1946                 }
1947                 else if (*it == "FROM")
1948                 {
1949                         tokens.erase(it++);
1950                         if (it != tokens.end() && *it == "BOUQUET")
1951                         {
1952                                 tokens.erase(it++);
1953                                 bouquet_name = *it;
1954                                 tokens.erase(it++);
1955                         }
1956                         else if (it != tokens.end() && *it == "SATELLITES")
1957                                 tokens.erase(it++);
1958                         else if (it != tokens.end() && *it == "PROVIDERS")
1959                                 tokens.erase(it++);
1960                         else
1961                         {
1962                                 eDebug("FROM unknown %s", (*it).c_str());
1963                                 tokens.erase(it++);
1964                         }
1965                 }
1966                 else
1967                         ++it;
1968         }
1969
1970         if (sort == -1)
1971         {
1972                 eWarning("ORDER BY .. string invalid.");
1973                 res = 0;
1974                 return -1;
1975         }
1976         
1977 //      eDebug("sort by %d", sort);
1978         
1979                 /* now we recursivly parse that. */
1980         int r = parseExpression(res, tokens.begin(), tokens.end());
1981         
1982                 /* we have an empty (but valid!) expression */
1983         if (!r && !res)
1984         {
1985                 res = new eDVBChannelQuery();
1986                 res->m_inverse = 0;
1987                 res->m_type = eDVBChannelQuery::tAny;
1988         }
1989         
1990         if (res)
1991         {
1992                 res->m_sort = sort;
1993                 res->m_bouquet_name = bouquet_name;
1994         }
1995
1996 //      eDebug("return: %d", r);
1997         return r;
1998 }
1999
2000 DEFINE_REF(eDVBChannelQuery);