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