factor out genSortName, cleanup comment
[enigma2.git] / lib / dvb / db.cpp
1 #include <errno.h>
2 #include <lib/dvb/db.h>
3 #include <lib/dvb/frontend.h>
4 #include <lib/base/eerror.h>
5 #include <lib/base/estring.h>
6 #include <dvbsi++/service_description_section.h>
7 #include <dvbsi++/descriptor_tag.h>
8 #include <dvbsi++/service_descriptor.h>
9 #include <dvbsi++/satellite_delivery_system_descriptor.h>
10
11 DEFINE_REF(eDVBService);
12
13 RESULT eBouquet::addService(const eServiceReference &ref)
14 {
15         list::iterator it =
16                 std::find(m_services.begin(), m_services.end(), ref);
17         if ( it != m_services.end() )
18                 return -1;
19         m_services.push_back(ref);
20         return 0;
21 }
22
23 RESULT eBouquet::removeService(const eServiceReference &ref)
24 {
25         list::iterator it =
26                 std::find(m_services.begin(), m_services.end(), ref);
27         if ( it == m_services.end() )
28                 return -1;
29         m_services.erase(it);
30         return 0;
31 }
32
33 RESULT eBouquet::moveService(const eServiceReference &ref, unsigned int pos)
34 {
35         if ( pos < 0 || pos >= m_services.size() )
36                 return -1;
37         list::iterator source=m_services.end();
38         list::iterator dest=m_services.end();
39         for (list::iterator it(m_services.begin()); it != m_services.end(); ++it)
40         {
41                 if (dest == m_services.end() && !pos--)
42                         dest = it;
43                 if (*it == ref)
44                         source = it;
45                 if (dest != m_services.end() && source != m_services.end())
46                         break;
47         }
48         if (dest == m_services.end() || source == m_services.end() || source == dest)
49                 return -1;
50         std::iter_swap(source,dest);
51         return 0;
52 }
53
54 RESULT eBouquet::flushChanges()
55 {
56         FILE *f=fopen(m_path.c_str(), "wt");
57         if (!f)
58                 return -1;
59         if ( fprintf(f, "#NAME %s\r\n", m_bouquet_name.c_str()) < 0 )
60                 goto err;
61         for (list::iterator i(m_services.begin()); i != m_services.end(); ++i)
62         {
63                 eServiceReference tmp = *i;
64                 std::string str = tmp.path;
65                 if ( (i->flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
66                 {
67                         unsigned int p1 = str.find("FROM BOUQUET \"");
68                         if (p1 == std::string::npos)
69                         {
70                                 eDebug("doof... kaputt");
71                                 continue;
72                         }
73                         str.erase(0, p1+14);
74                         p1 = str.find("\"");
75                         if (p1 == std::string::npos)
76                         {
77                                 eDebug("doof2... kaputt");
78                                 continue;
79                         }
80                         str.erase(p1);
81                         tmp.path=str;
82                 }
83                 if ( fprintf(f, "#SERVICE %s\r\n", tmp.toString().c_str()) < 0 )
84                         goto err;
85                 if ( i->name.length() )
86                         if ( fprintf(f, "#DESCRIPTION %s\r\n", i->name.c_str()) < 0 )
87                                 goto err;
88         }
89         fclose(f);
90         return 0;
91 err:
92         fclose(f);
93         eDebug("couldn't write file %s", m_path.c_str());
94         return -1;
95 }
96
97 eDVBService::eDVBService()
98 {
99 }
100
101 eDVBService::~eDVBService()
102 {
103 }
104
105 eDVBService &eDVBService::operator=(const eDVBService &s)
106 {
107         m_service_name = s.m_service_name;
108         m_service_name_sort = s.m_service_name_sort;
109         m_provider_name = s.m_provider_name;
110         m_flags = s.m_flags;
111         m_ca = s.m_ca;
112         m_cache = s.m_cache;
113         return *this;
114 }
115
116 void eDVBService::genSortName()
117 {
118         m_service_name_sort = removeDVBChars(m_service_name);
119         makeUpper(m_service_name_sort);
120         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
121                 m_service_name_sort.erase(0, 1);
122         
123                 /* put unnamed services at the end, not at the beginning. */
124         if (m_service_name_sort.empty())
125                 m_service_name_sort = "\xFF";
126 }
127
128 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
129 {
130         if (!ref.name.empty())
131                 name = ref.name;
132         else if (!m_service_name.empty())
133                 name = m_service_name;
134         else
135                 name = "(...)";
136         return 0;
137 }
138
139 int eDVBService::getLength(const eServiceReference &ref)
140 {
141         return -1;
142 }
143
144 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
145 {
146         int res = 0;
147         switch (query.m_type)
148         {
149         case eDVBChannelQuery::tName:
150                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
151                 break;
152         case eDVBChannelQuery::tProvider:
153                 res = m_provider_name.find(query.m_string) != std::string::npos;
154                 break;
155         case eDVBChannelQuery::tType:
156                 res = ref.getServiceType() == query.m_int;
157                 break;
158         case eDVBChannelQuery::tBouquet:
159                 res = 0;
160                 break;
161         case eDVBChannelQuery::tSatellitePosition:
162                 res = (ref.getDVBNamespace().get() >> 16) == query.m_int;
163                 break;
164         case eDVBChannelQuery::tChannelID:
165         {
166                 eDVBChannelID chid;
167                 ref.getChannelID(chid);
168                 res = chid == query.m_channelid;
169                 break;
170         }
171         case eDVBChannelQuery::tAND:
172                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
173                 break;
174         case eDVBChannelQuery::tOR:
175                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
176                 break;
177         }
178
179         if (query.m_inverse)
180                 return !res;
181         else
182                 return res;
183 }
184
185 int eDVBService::getCachePID(cacheID id)
186 {
187         std::map<int, int>::iterator it = m_cache.find(id);
188         if ( it != m_cache.end() )
189                 return it->second;
190         return -1;
191 }
192
193 void eDVBService::setCachePID(cacheID id, int pid)
194 {
195         m_cache[id] = pid;
196 }
197
198 DEFINE_REF(eDVBDB);
199
200         /* THIS CODE IS BAD. it should be replaced by somethine better. */
201 void eDVBDB::load()
202 {
203         eDebug("---- opening lame channel db");
204         FILE *f=fopen("lamedb", "rt");
205         if (!f)
206                 return;
207         char line[256];
208         if ((!fgets(line, 256, f)) || strncmp(line, "eDVB services", 13))
209         {
210                 eDebug("not a servicefile");
211                 fclose(f);
212                 return;
213         }
214         eDebug("reading services");
215         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
216         {
217                 eDebug("services invalid, no transponders");
218                 fclose(f);
219                 return;
220         }
221
222         // clear all transponders
223
224         while (!feof(f))
225         {
226                 if (!fgets(line, 256, f))
227                         break;
228                 if (!strcmp(line, "end\n"))
229                         break;
230                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
231                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
232                 if (original_network_id == -1)
233                         continue;
234                 eDVBChannelID channelid = eDVBChannelID(
235                         eDVBNamespace(dvb_namespace),
236                         eTransportStreamID(transport_stream_id),
237                         eOriginalNetworkID(original_network_id));
238
239                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
240                 while (!feof(f))
241                 {
242                         fgets(line, 256, f);
243                         if (!strcmp(line, "/\n"))
244                                 break;
245                         if (line[1]=='s')
246                         {
247                                 eDVBFrontendParametersSatellite sat;
248                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion;
249                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion);
250                                 sat.frequency = frequency;
251                                 sat.symbol_rate = symbol_rate;
252                                 sat.polarisation = polarisation;
253                                 sat.fec = fec;
254                                 sat.orbital_position = orbital_position;
255                                 sat.inversion = inversion;
256                                 feparm->setDVBS(sat);
257                         } else if (line[1]=='t')
258                         {
259                                 eDVBFrontendParametersTerrestrial ter;
260                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion;
261                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion);
262                                 ter.frequency = frequency;
263                                 ter.bandwidth = bandwidth;
264                                 ter.code_rate_HP = code_rate_HP;
265                                 ter.code_rate_LP = code_rate_LP;
266                                 ter.modulation = modulation;
267                                 ter.transmission_mode = transmission_mode;
268                                 ter.guard_interval = guard_interval;
269                                 ter.hierarchy = hierarchy;
270                                 ter.inversion = inversion;
271                                 
272                                 feparm->setDVBT(ter);
273                         } else if (line[1]=='c')
274                         {
275                                 int frequency, symbol_rate, inversion=0, modulation=3;
276                                 sscanf(line+2, "%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation);
277 //                              t.setCable(frequency, symbol_rate, inversion, modulation);
278                         }
279                 }
280                 addChannelToList(channelid, feparm);
281         }
282
283         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
284         {
285                 eDebug("services invalid, no services");
286                 return;
287         }
288
289         // clear all services
290
291         int count=0;
292
293         while (!feof(f))
294         {
295                 if (!fgets(line, 256, f))
296                         break;
297                 if (!strcmp(line, "end\n"))
298                         break;
299
300                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
301                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
302                 if (service_number == -1)
303                         continue;
304                 ePtr<eDVBService> s = new eDVBService;
305                 eServiceReferenceDVB ref =
306                                                 eServiceReferenceDVB(
307                                                 eDVBNamespace(dvb_namespace),
308                                                 eTransportStreamID(transport_stream_id),
309                                                 eOriginalNetworkID(original_network_id),
310                                                 eServiceID(service_id),
311                                                 service_type);
312                 count++;
313                 fgets(line, 256, f);
314                 if (strlen(line))
315                         line[strlen(line)-1]=0;
316
317                 s->m_service_name = line;
318                 s->genSortName();
319                  
320                 fgets(line, 256, f);
321                 if (strlen(line))
322                         line[strlen(line)-1]=0;
323
324                 std::string str=line;
325
326                 if (str[1]!=':')        // old ... (only service_provider)
327                 {
328                         s->m_provider_name=line;
329                 } else
330                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
331                         {
332                                 unsigned int c=str.find(',');
333                                 char p=str[0];
334                                 std::string v;
335                                 if (c == std::string::npos)
336                                 {
337                                         v=str.substr(2);
338                                         str="";
339                                 } else
340                                 {
341                                         v=str.substr(2, c-2);
342                                         str=str.substr(c+1);
343                                 }
344 //                              eDebug("%c ... %s", p, v.c_str());
345                                 if (p == 'p')
346                                         s->m_provider_name=v;
347                                 else if (p == 'f')
348                                 {
349                                         sscanf(v.c_str(), "%x", &s->m_flags);
350                                 } else if (p == 'c')
351                                 {
352                                         int cid, val;
353                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
354                                         s->m_cache[cid]=val;
355                                 } else if (p == 'C')
356                                 {
357                                         int val;
358                                         sscanf(v.c_str(), "%04x", &val);
359                                         s->m_ca.insert(val);
360                                 }
361                         }
362                 addService(ref, s);
363         }
364
365         eDebug("loaded %d services", count);
366
367         fclose(f);
368 }
369
370 void eDVBDB::save()
371 {
372         eDebug("---- saving lame channel db");
373         FILE *f=fopen("lamedb", "wt");
374         int channels=0, services=0;
375         if (!f)
376                 eFatal("couldn't save lame channel db!");
377         fprintf(f, "eDVB services /3/\n");
378         fprintf(f, "transponders\n");
379         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
380                         i != m_channels.end(); ++i)
381         {
382                 const eDVBChannelID &chid = i->first;
383                 const channel &ch = i->second;
384
385                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
386                                 chid.transport_stream_id.get(), chid.original_network_id.get());
387                 eDVBFrontendParametersSatellite sat;
388                 eDVBFrontendParametersTerrestrial ter;
389                 if (!ch.m_frontendParameters->getDVBS(sat))
390                 {
391                         fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
392                                 sat.frequency, sat.symbol_rate,
393                                 sat.polarisation, sat.fec, sat.orbital_position,
394                                 sat.inversion);
395                 }
396                 if (!ch.m_frontendParameters->getDVBT(ter))
397                 {
398                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
399                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
400                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
401                                 ter.guard_interval, ter.hierarchy, ter.inversion);
402                 }
403                 fprintf(f, "/\n");
404                 channels++;
405         }
406         fprintf(f, "end\nservices\n");
407
408         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
409                 i != m_services.end(); ++i)
410         {
411                 const eServiceReferenceDVB &s = i->first;
412                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
413                                 s.getServiceID().get(), s.getDVBNamespace().get(),
414                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
415                                 s.getServiceType(),
416                                 0);
417
418                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
419                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
420
421                 // write cached pids
422                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
423                         ca != i->second->m_cache.end(); ++ca)
424                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
425
426                 // write cached ca pids
427                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
428                         ca != i->second->m_ca.end(); ++ca)
429                         fprintf(f, ",C:%04x", *ca);
430
431                 fprintf(f, "\n");
432                 services++;
433         }
434         fprintf(f, "end\nHave a lot of bugs!\n");
435         eDebug("saved %d channels and %d services!", channels, services);
436         fclose(f);
437 }
438
439 void eDVBDB::loadBouquet(const char *path)
440 {
441         std::string bouquet_name = path;
442         if (!bouquet_name.length())
443         {
444                 eDebug("Bouquet load failed.. no path given..");
445                 return;
446         }
447         unsigned int pos = bouquet_name.rfind('/');
448         if ( pos != std::string::npos )
449                 bouquet_name.erase(0, pos+1);
450         if (bouquet_name.empty())
451         {
452                 eDebug("Bouquet load failed.. no filename given..");
453                 return;
454         }
455         eBouquet &bouquet = m_bouquets[bouquet_name];
456         bouquet.m_path = path;
457         std::list<eServiceReference> &list = bouquet.m_services;
458         list.clear();
459
460         eDebug("loading bouquet... %s", path);
461         FILE *fp=fopen(path, "rt");
462         int entries=0;
463         if (!fp)
464         {
465                 eDebug("failed to open.");
466                 if ( strstr(path, "bouquets.tv") )
467                 {
468                         eDebug("recreate bouquets.tv");
469                         bouquet.m_bouquet_name="Bouquets (TV)";
470                         bouquet.flushChanges();
471                 }
472                 else if ( strstr(path, "bouquets.radio") )
473                 {
474                         eDebug("recreate bouquets.radio");
475                         bouquet.m_bouquet_name="Bouquets (Radio)";
476                         bouquet.flushChanges();
477                 }
478                 return;
479         }
480         char line[256];
481         bool read_descr=false;
482         eServiceReference *e = NULL;
483         while (1)
484         {
485                 if (!fgets(line, 256, fp))
486                         break;
487                 line[strlen(line)-1]=0;
488                 if (strlen(line) && line[strlen(line)-1]=='\r')
489                         line[strlen(line)-1]=0;
490                 if (!line[0])
491                         break;
492                 if (line[0]=='#')
493                 {
494                         if (!strncmp(line, "#SERVICE ", 9) || !strncmp(line, "#SERVICE: ", 10))
495                         {
496                                 int offs = line[8] == ':' ? 10 : 9;
497                                 eServiceReference tmp(line+offs);
498                                 if (tmp.type != eServiceReference::idDVB)
499                                 {
500                                         eDebug("only DVB Bouquets supported");
501                                         continue;
502                                 }
503                                 if ( (tmp.flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
504                                 {
505                                         std::string str = tmp.path;
506                                         unsigned int pos = str.rfind('/');
507                                         if ( pos != std::string::npos )
508                                                 str.erase(0, pos+1);
509                                         if (str.empty())
510                                         {
511                                                 eDebug("Bouquet load failed.. no filename given..");
512                                                 continue;
513                                         }
514                                         loadBouquet(tmp.path.c_str());
515                                         char buf[256];
516                                         snprintf(buf, 256, "(type == %d) FROM BOUQUET \"%s\" ORDER BY bouquet", tmp.data[0], str.c_str());
517                                         tmp.path = buf;
518                                 }
519                                 list.push_back(tmp);
520                                 e = &list.back();
521                                 read_descr=true;
522                                 ++entries;
523                         }
524                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
525                         {
526                                 e->name = line+13;
527                                 read_descr=false;
528                         }
529                         else if (!strncmp(line, "#NAME ", 6))
530                                 bouquet.m_bouquet_name=line+6;
531                         continue;
532                 }
533         }
534         fclose(fp);
535         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
536 }
537
538 void eDVBDB::saveBouquet(const char *path)
539 {
540
541 }
542
543 void eDVBDB::loadBouquets()
544 {
545         loadBouquet("bouquets.tv");
546         loadBouquet("bouquets.radio");
547 // create default bouquets when missing
548         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
549         {
550                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
551                 b.m_path = "userbouquet.favourites.tv";
552                 b.m_bouquet_name = "Favourites (TV)";
553                 b.flushChanges();
554                 eServiceReference ref;
555                 memset(ref.data, 0, sizeof(ref.data));
556                 ref.type=1;
557                 ref.flags=7;
558                 ref.data[0]=1;
559                 ref.path="(type == 1) FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
560                 eBouquet &parent = m_bouquets["bouquets.tv"];
561                 parent.m_services.push_back(ref);
562                 parent.flushChanges();
563         }
564         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
565         {
566                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
567                 b.m_path = "userbouquet.favourites.radio";
568                 b.m_bouquet_name = "Favourites (Radio)";
569                 b.flushChanges();
570                 eServiceReference ref;
571                 memset(ref.data, 0, sizeof(ref.data));
572                 ref.type=1;
573                 ref.flags=7;
574                 ref.data[0]=1;
575                 ref.path="(type == 2) FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
576                 eBouquet &parent = m_bouquets["bouquets.radio"];
577                 parent.m_services.push_back(ref);
578                 parent.flushChanges();
579         }
580 }
581
582 void eDVBDB::saveBouquets()
583 {
584
585 }
586
587 eDVBDB::eDVBDB()
588 {
589         load();
590         loadBouquets();
591 }
592
593 eDVBDB::~eDVBDB()
594 {
595 //      save();
596 }
597
598 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
599 {
600         channel ch;
601         assert(feparm);
602         ch.m_frontendParameters = feparm;
603         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
604         return 0;
605 }
606
607 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
608 {
609         m_channels.erase(id);
610         return 0;
611 }
612
613 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
614 {
615         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
616         if (i == m_channels.end())
617         {
618                 parm = 0;
619                 return -ENOENT;
620         }
621         parm = i->second.m_frontendParameters;
622         return 0;
623 }
624
625 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
626 {
627         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
628         return 0;
629 }
630
631 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
632 {
633         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
634         i = m_services.find(reference);
635         if (i == m_services.end())
636         {
637                 service = 0;
638                 return -ENOENT;
639         }
640         service = i->second;
641         return 0;
642 }
643
644 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
645 {
646         std::string str = ref.path;
647         if (str.empty())
648         {
649                 eDebug("getBouquet failed.. no path given!");
650                 return -1;
651         }
652         unsigned int pos = str.find("FROM BOUQUET \"");
653         if ( pos != std::string::npos )
654         {
655                 str.erase(0, pos+14);
656                 pos = str.find('"');
657                 if ( pos != std::string::npos )
658                         str.erase(pos);
659                 else
660                         str.clear();
661         }
662         if (str.empty())
663         {
664                 eDebug("getBouquet failed.. couldn't parse bouquet name");
665                 return -1;
666         }
667         std::map<std::string, eBouquet>::iterator i =
668                 m_bouquets.find(str);
669         if (i == m_bouquets.end())
670         {
671                 bouquet = 0;
672                 return -ENOENT;
673         }
674         bouquet = &i->second;
675         return 0;
676 }
677
678 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
679 {
680         if ( q && q->m_bouquet_name.length() )
681                 query = new eDVBDBBouquetQuery(this, source, q);
682         else
683                 query = new eDVBDBQuery(this, source, q);
684         return 0;
685 }
686
687 DEFINE_REF(eDVBDBQueryBase);
688
689 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
690         :m_db(db), m_query(query), m_source(source)
691 {
692 }
693
694 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
695 {
696         ePtr<eDVBService> a_service, b_service;
697         
698         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
699         
700         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
701         {
702                 if (m_db->getService(a, a_service))
703                         return 1;
704                 if (m_db->getService(b, b_service))
705                         return 1;
706         }
707         
708         switch (sortmode)
709         {
710         case eDVBChannelQuery::tName:
711                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
712         case eDVBChannelQuery::tProvider:
713                 return a_service->m_provider_name < b_service->m_provider_name;
714         case eDVBChannelQuery::tType:
715                 return a.getServiceType() < b.getServiceType();
716         case eDVBChannelQuery::tBouquet:
717                 return 0;
718         case eDVBChannelQuery::tSatellitePosition:
719                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
720         default:
721                 return 1;
722         }
723         return 0;
724 }
725
726 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
727         :eDVBDBQueryBase(db, source, query)
728 {
729         m_cursor = m_db->m_services.begin();
730 }
731
732 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
733 {
734         while (m_cursor != m_db->m_services.end())
735         {
736                 ref = m_cursor->first;
737
738                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
739
740                 ++m_cursor;
741
742                 if (res)
743                         return 0;
744         }
745
746         ref.type = eServiceReference::idInvalid;
747
748         return 1;
749 }
750
751 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
752         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
753 {
754 }
755
756 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
757 {
758         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
759         std::list<eServiceReference> &list = bouquet.m_services;
760         while (m_cursor != list.end())
761         {
762                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
763
764                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
765                         m_db->m_services.find(ref);
766
767                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
768
769                 ++m_cursor;
770
771                 if (res)
772                         return 0;
773         }
774
775         ref.type = eServiceReference::idInvalid;
776
777         return 1;
778 }
779
780 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
781
782 static int decodeType(const std::string &type)
783 {
784         if (type == "name")
785                 return eDVBChannelQuery::tName;
786         else if (type == "provider")
787                 return eDVBChannelQuery::tProvider;
788         else if (type == "type")
789                 return eDVBChannelQuery::tType;
790         else if (type == "bouquet")
791                 return eDVBChannelQuery::tBouquet;
792         else if (type == "satellitePosition")
793                 return eDVBChannelQuery::tSatellitePosition;
794         else if (type == "channelID")
795                 return eDVBChannelQuery::tChannelID;
796         else
797                 return -1;
798 }
799
800         /* never, NEVER write a parser in C++! */
801 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
802 {
803         std::list<std::string>::const_iterator end_of_exp;
804         if (*begin == "(")
805         {
806                 end_of_exp = begin;
807                 while (end_of_exp != end)
808                         if (*end_of_exp == ")")
809                                 break;
810                         else
811                                 ++end_of_exp;
812         
813                 if (end_of_exp == end)
814                 {
815                         eDebug("expression parse: end of expression while searching for closing brace");
816                         return -1;
817                 }
818                 
819                 ++begin;
820                 // begin..end_of_exp
821                 int r = parseExpression(res, begin, end_of_exp);
822                 if (r)
823                         return r;
824                 ++end_of_exp;
825                 
826                         /* we had only one sub expression */
827                 if (end_of_exp == end)
828                 {
829 //                      eDebug("only one sub expression");
830                         return 0;
831                 }
832                 
833                         /* otherwise we have an operator here.. */
834                 
835                 ePtr<eDVBChannelQuery> r2 = res;
836                 res = new eDVBChannelQuery();
837                 res->m_sort = 0;
838                 res->m_p1 = r2;
839                 res->m_inverse = 0;
840                 r2 = 0;
841                 
842                 if (*end_of_exp == "||")
843                         res->m_type = eDVBChannelQuery::tOR;
844                 else if (*end_of_exp == "&&")
845                         res->m_type = eDVBChannelQuery::tAND;
846                 else
847                 {
848                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
849                         res = 0;
850                         return 1;
851                 }
852                 
853                 ++end_of_exp;
854                 
855                 return parseExpression(res->m_p2, end_of_exp, end);
856         }
857         
858         // "begin" <op> "end"
859         std::string type, op, val;
860         
861         res = new eDVBChannelQuery();
862         res->m_sort = 0;
863         
864         int cnt = 0;
865         while (begin != end)
866         {
867                 switch (cnt)
868                 {
869                 case 0:
870                         type = *begin;
871                         break;
872                 case 1:
873                         op = *begin;
874                         break;
875                 case 2:
876                         val = *begin;
877                         break;
878                 case 3:
879                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
880                         return 1;
881                 }
882                 ++begin;
883                 ++cnt;
884         }
885         
886         if (cnt != 3)
887         {
888                 eDebug("malformed query: missing stuff");
889                 res = 0;
890                 return 1;
891         }
892         
893         res->m_type = decodeType(type);
894         
895         if (res->m_type == -1)
896         {
897                 eDebug("malformed query: invalid type %s", type.c_str());
898                 res = 0;
899                 return 1;
900         }
901         
902         if (op == "==")
903                 res->m_inverse = 0;
904         else if (op == "!=")
905                 res->m_inverse = 1;
906         else
907         {
908                 eDebug("invalid operator %s", op.c_str());
909                 res = 0;
910                 return 1;
911         }
912         
913         res->m_string = val;
914         res->m_int = atoi(val.c_str());
915 //      res->m_channelid = eDVBChannelID(val);
916         
917         return 0;
918 }
919
920 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
921 {
922         std::list<std::string> tokens;
923         
924         std::string current_token;
925         std::string bouquet_name;
926
927 //      eDebug("splitting %s....", query.c_str());
928         unsigned int i = 0;
929         const char *splitchars="()";
930         int quotemode = 0, lastsplit = 0, lastalnum = 0;
931         while (i <= query.size())
932         {
933                 int c = (i < query.size()) ? query[i] : ' ';
934                 ++i;
935                 
936                 int issplit = !!strchr(splitchars, c);
937                 int isaln = isalnum(c);
938                 int iswhite = c == ' ';
939                 int isquot = c == '\"';
940                 
941                 if (quotemode)
942                 {
943                         iswhite = issplit = 0;
944                         isaln = lastalnum;
945                 }
946                 
947                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
948                 {
949                         if (current_token.size())
950                                 tokens.push_back(current_token);
951                         current_token.clear();
952                 }
953                 
954                 if (!(iswhite || isquot))
955                         current_token += c;
956                 
957                 if (isquot)
958                         quotemode = !quotemode;
959                 lastsplit = issplit;
960                 lastalnum = isaln;
961         }
962         
963 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
964 //      {
965 //              printf("%s\n", a->c_str());
966 //      }
967
968         int sort = eDVBChannelQuery::tName;
969                 /* check for "ORDER BY ..." */
970
971         while (tokens.size() > 2)
972         {
973                 std::list<std::string>::iterator it = tokens.end();
974                 --it; --it; --it;
975                 if (*it == "ORDER")
976                 {
977                         ++it;
978                         if (*it == "BY")
979                         {
980                                 ++it;
981                                 sort = decodeType(*it);
982                                 tokens.pop_back(); // ...
983                                 tokens.pop_back(); // BY
984                                 tokens.pop_back(); // ORDER
985                         } else
986                                 sort = -1;
987                 }
988                 else if (*it == "FROM")
989                 {
990                         ++it;
991                         if (*it == "BOUQUET")
992                         {
993                                 ++it;
994                                 bouquet_name = *it;
995                                 tokens.pop_back(); // ...
996                                 tokens.pop_back(); // FROM
997                                 tokens.pop_back(); // BOUQUET
998                         }
999                 }
1000                 else
1001                         break;
1002         }
1003
1004         if (sort == -1)
1005         {
1006                 eWarning("ORDER BY .. string invalid.");
1007                 res = 0;
1008                 return -1;
1009         }
1010         
1011 //      eDebug("sort by %d", sort);
1012         
1013                 /* now we recursivly parse that. */
1014         int r = parseExpression(res, tokens.begin(), tokens.end());
1015         
1016         if (res)
1017         {
1018                 res->m_sort = sort;
1019                 res->m_bouquet_name = bouquet_name;
1020         }
1021
1022 //      eDebug("return: %d", r);
1023         return r;
1024 }
1025
1026 DEFINE_REF(eDVBChannelQuery);