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