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