enable private epg
[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
318                                 feparm->setDVBT(ter);
319                         } else if (line[1]=='c')
320                         {
321                                 int frequency, symbol_rate, inversion=0, modulation=3;
322                                 sscanf(line+2, "%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation);
323 //                              t.setCable(frequency, symbol_rate, inversion, modulation);
324                         }
325                 }
326                 addChannelToList(channelid, feparm);
327         }
328
329         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
330         {
331                 eDebug("services invalid, no services");
332                 return;
333         }
334
335         // clear all services
336
337         int count=0;
338
339         while (!feof(f))
340         {
341                 if (!fgets(line, 256, f))
342                         break;
343                 if (!strcmp(line, "end\n"))
344                         break;
345
346                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
347                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
348                 if (service_number == -1)
349                         continue;
350                 ePtr<eDVBService> s = new eDVBService;
351                 eServiceReferenceDVB ref =
352                                                 eServiceReferenceDVB(
353                                                 eDVBNamespace(dvb_namespace),
354                                                 eTransportStreamID(transport_stream_id),
355                                                 eOriginalNetworkID(original_network_id),
356                                                 eServiceID(service_id),
357                                                 service_type);
358                 count++;
359                 fgets(line, 256, f);
360                 if (strlen(line))
361                         line[strlen(line)-1]=0;
362
363                 s->m_service_name = line;
364                 s->genSortName();
365
366                 fgets(line, 256, f);
367                 if (strlen(line))
368                         line[strlen(line)-1]=0;
369                 std::string str=line;
370
371                 if (str[1]!=':')        // old ... (only service_provider)
372                 {
373                         s->m_provider_name=line;
374                 } else
375                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
376                         {
377                                 unsigned int c=str.find(',');
378                                 char p=str[0];
379                                 std::string v;
380                                 if (c == std::string::npos)
381                                 {
382                                         v=str.substr(2);
383                                         str="";
384                                 } else
385                                 {
386                                         v=str.substr(2, c-2);
387                                         str=str.substr(c+1);
388                                 }
389 //                              eDebug("%c ... %s", p, v.c_str());
390                                 if (p == 'p')
391                                         s->m_provider_name=v;
392                                 else if (p == 'f')
393                                 {
394                                         sscanf(v.c_str(), "%x", &s->m_flags);
395                                 } else if (p == 'c')
396                                 {
397                                         int cid, val;
398                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
399                                         s->m_cache[cid]=val;
400                                 } else if (p == 'C')
401                                 {
402                                         int val;
403                                         sscanf(v.c_str(), "%04x", &val);
404                                         s->m_ca.insert(val);
405                                 }
406                         }
407                 addService(ref, s);
408         }
409
410         eDebug("loaded %d services", count);
411
412         fclose(f);
413 }
414
415 void eDVBDB::saveServicelist()
416 {
417         eDebug("---- saving lame channel db");
418         FILE *f=fopen(CONFIGDIR"/enigma2/lamedb", "w");
419         int channels=0, services=0;
420         if (!f)
421                 eFatal("couldn't save lame channel db!");
422         fprintf(f, "eDVB services /3/\n");
423         fprintf(f, "transponders\n");
424         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
425                         i != m_channels.end(); ++i)
426         {
427                 const eDVBChannelID &chid = i->first;
428                 const channel &ch = i->second;
429
430                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
431                                 chid.transport_stream_id.get(), chid.original_network_id.get());
432                 eDVBFrontendParametersSatellite sat;
433                 eDVBFrontendParametersTerrestrial ter;
434                 if (!ch.m_frontendParameters->getDVBS(sat))
435                 {
436                         fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
437                                 sat.frequency, sat.symbol_rate,
438                                 sat.polarisation, sat.fec,
439                                 sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
440                                 sat.inversion);
441                 }
442                 if (!ch.m_frontendParameters->getDVBT(ter))
443                 {
444                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
445                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
446                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
447                                 ter.guard_interval, ter.hierarchy, ter.inversion);
448                 }
449                 fprintf(f, "/\n");
450                 channels++;
451         }
452         fprintf(f, "end\nservices\n");
453
454         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
455                 i != m_services.end(); ++i)
456         {
457                 const eServiceReferenceDVB &s = i->first;
458                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
459                                 s.getServiceID().get(), s.getDVBNamespace().get(),
460                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
461                                 s.getServiceType(),
462                                 0);
463
464                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
465                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
466
467                 // write cached pids
468                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
469                         ca != i->second->m_cache.end(); ++ca)
470                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
471
472                 // write cached ca pids
473                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
474                         ca != i->second->m_ca.end(); ++ca)
475                         fprintf(f, ",C:%04x", *ca);
476
477                 fprintf(f, "\n");
478                 services++;
479         }
480         fprintf(f, "end\nHave a lot of bugs!\n");
481         eDebug("saved %d channels and %d services!", channels, services);
482         fclose(f);
483 }
484
485 void eDVBDB::loadBouquet(const char *path)
486 {
487         std::string bouquet_name = path;
488         if (!bouquet_name.length())
489         {
490                 eDebug("Bouquet load failed.. no path given..");
491                 return;
492         }
493         unsigned int pos = bouquet_name.rfind('/');
494         if ( pos != std::string::npos )
495                 bouquet_name.erase(0, pos+1);
496         if (bouquet_name.empty())
497         {
498                 eDebug("Bouquet load failed.. no filename given..");
499                 return;
500         }
501         eBouquet &bouquet = m_bouquets[bouquet_name];
502         bouquet.m_filename = bouquet_name;
503         std::list<eServiceReference> &list = bouquet.m_services;
504         list.clear();
505
506         std::string p = CONFIGDIR"/enigma2/";
507         p+=path;
508         eDebug("loading bouquet... %s", p.c_str());
509         FILE *fp=fopen(p.c_str(), "rt");
510         int entries=0;
511         if (!fp)
512         {
513                 struct stat s;
514                 if ( !stat(path, &s) )
515                 {
516                         rename(path, p.c_str() );
517                         loadBouquet(path);
518                         return;
519                 }
520                 eDebug("failed to open.");
521                 if ( strstr(path, "bouquets.tv") )
522                 {
523                         eDebug("recreate bouquets.tv");
524                         bouquet.m_bouquet_name="Bouquets (TV)";
525                         bouquet.flushChanges();
526                 }
527                 else if ( strstr(path, "bouquets.radio") )
528                 {
529                         eDebug("recreate bouquets.radio");
530                         bouquet.m_bouquet_name="Bouquets (Radio)";
531                         bouquet.flushChanges();
532                 }
533                 return;
534         }
535         char line[256];
536         bool read_descr=false;
537         eServiceReference *e = NULL;
538         while (1)
539         {
540                 if (!fgets(line, 256, fp))
541                         break;
542                 line[strlen(line)-1]=0;
543                 if (strlen(line) && line[strlen(line)-1]=='\r')
544                         line[strlen(line)-1]=0;
545                 if (!line[0])
546                         break;
547                 if (line[0]=='#')
548                 {
549                         if (!strncmp(line, "#SERVICE ", 9) || !strncmp(line, "#SERVICE: ", 10))
550                         {
551                                 int offs = line[8] == ':' ? 10 : 9;
552                                 eServiceReference tmp(line+offs);
553                                 if (tmp.type != eServiceReference::idDVB)
554                                 {
555                                         eDebug("only DVB Bouquets supported");
556                                         continue;
557                                 }
558                                 if ( (tmp.flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
559                                 {
560                                         unsigned int pos = tmp.path.rfind('/');
561                                         if ( pos != std::string::npos )
562                                                 tmp.path.erase(0, pos+1);
563                                         if (tmp.path.empty())
564                                         {
565                                                 eDebug("Bouquet load failed.. no filename given..");
566                                                 continue;
567                                         }
568                                         loadBouquet(tmp.path.c_str());
569                                         char buf[256];
570                                         snprintf(buf, 256, "(type == %d) FROM BOUQUET \"%s\" ORDER BY bouquet", tmp.data[0], tmp.path.c_str());
571                                         tmp.path = buf;
572                                 }
573                                 list.push_back(tmp);
574                                 e = &list.back();
575                                 read_descr=true;
576                                 ++entries;
577                         }
578                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
579                         {
580                                 e->name = line+13;
581                                 read_descr=false;
582                         }
583                         else if (!strncmp(line, "#NAME ", 6))
584                                 bouquet.m_bouquet_name=line+6;
585                         continue;
586                 }
587         }
588         fclose(fp);
589         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
590 }
591
592 void eDVBDB::reloadBouquets()
593 {
594         m_bouquets.clear();
595         loadBouquet("bouquets.tv");
596         loadBouquet("bouquets.radio");
597 // create default bouquets when missing
598         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
599         {
600                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
601                 b.m_filename = "userbouquet.favourites.tv";
602                 b.m_bouquet_name = "Favourites (TV)";
603                 b.flushChanges();
604                 eServiceReference ref;
605                 memset(ref.data, 0, sizeof(ref.data));
606                 ref.type=1;
607                 ref.flags=7;
608                 ref.data[0]=1;
609                 ref.path="(type == 1) FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
610                 eBouquet &parent = m_bouquets["bouquets.tv"];
611                 parent.m_services.push_back(ref);
612                 parent.flushChanges();
613         }
614         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
615         {
616                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
617                 b.m_filename = "userbouquet.favourites.radio";
618                 b.m_bouquet_name = "Favourites (Radio)";
619                 b.flushChanges();
620                 eServiceReference ref;
621                 memset(ref.data, 0, sizeof(ref.data));
622                 ref.type=1;
623                 ref.flags=7;
624                 ref.data[0]=2;
625                 ref.path="(type == 2) FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
626                 eBouquet &parent = m_bouquets["bouquets.radio"];
627                 parent.m_services.push_back(ref);
628                 parent.flushChanges();
629         }
630 }
631
632 eDVBDB *eDVBDB::instance;
633
634 eDVBDB::eDVBDB()
635 {
636         instance = this;
637         reloadServicelist();
638 }
639
640 eDVBDB::~eDVBDB()
641 {
642         instance=NULL;
643 }
644
645 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
646 {
647         channel ch;
648         assert(feparm);
649         ch.m_frontendParameters = feparm;
650         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
651         return 0;
652 }
653
654 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
655 {
656         m_channels.erase(id);
657         return 0;
658 }
659
660 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
661 {
662         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
663         if (i == m_channels.end())
664         {
665                 parm = 0;
666                 return -ENOENT;
667         }
668         parm = i->second.m_frontendParameters;
669         return 0;
670 }
671
672 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
673 {
674         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
675         return 0;
676 }
677
678 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
679 {
680         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
681         i = m_services.find(reference);
682         if (i == m_services.end())
683         {
684                 service = 0;
685                 return -ENOENT;
686         }
687         service = i->second;
688         return 0;
689 }
690
691 RESULT eDVBDB::flush()
692 {
693         saveServicelist();
694         return 0;
695 }
696
697 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
698 {
699         std::string str = ref.path;
700         if (str.empty())
701         {
702                 eDebug("getBouquet failed.. no path given!");
703                 return -1;
704         }
705         unsigned int pos = str.find("FROM BOUQUET \"");
706         if ( pos != std::string::npos )
707         {
708                 str.erase(0, pos+14);
709                 pos = str.find('"');
710                 if ( pos != std::string::npos )
711                         str.erase(pos);
712                 else
713                         str.clear();
714         }
715         if (str.empty())
716         {
717                 eDebug("getBouquet failed.. couldn't parse bouquet name");
718                 return -1;
719         }
720         std::map<std::string, eBouquet>::iterator i =
721                 m_bouquets.find(str);
722         if (i == m_bouquets.end())
723         {
724                 bouquet = 0;
725                 return -ENOENT;
726         }
727         bouquet = &i->second;
728         return 0;
729 }
730
731 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
732 {
733         if ( source.path.find("FROM") != std::string::npos )
734         {
735                 if ( source.path.find("BOUQUET") != std::string::npos )
736                         query = new eDVBDBBouquetQuery(this, source, q);
737                 else if ( source.path.find("SATELLITES") != std::string::npos )
738                         query = new eDVBDBSatellitesQuery(this, source, q);
739                 else if ( source.path.find("PROVIDERS") != std::string::npos )
740                         query = new eDVBDBProvidersQuery(this, source, q);
741                 else
742                         eFatal("invalid query %s", source.toString().c_str());
743         }
744         else
745                 query = new eDVBDBQuery(this, source, q);
746         return 0;
747 }
748
749 DEFINE_REF(eDVBDBQueryBase);
750
751 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
752         :m_db(db), m_query(query), m_source(source)
753 {
754 }
755
756 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
757 {
758         ePtr<eDVBService> a_service, b_service;
759         
760         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
761         
762         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
763         {
764                 if (m_db->getService(a, a_service))
765                         return 1;
766                 if (m_db->getService(b, b_service))
767                         return 1;
768         }
769         
770         switch (sortmode)
771         {
772         case eDVBChannelQuery::tName:
773                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
774         case eDVBChannelQuery::tProvider:
775                 return a_service->m_provider_name < b_service->m_provider_name;
776         case eDVBChannelQuery::tType:
777                 return a.getServiceType() < b.getServiceType();
778         case eDVBChannelQuery::tBouquet:
779                 return 0;
780         case eDVBChannelQuery::tSatellitePosition:
781                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
782         default:
783                 return 1;
784         }
785         return 0;
786 }
787
788 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
789         :eDVBDBQueryBase(db, source, query)
790 {
791         m_cursor = m_db->m_services.begin();
792 }
793
794 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
795 {
796         while (m_cursor != m_db->m_services.end())
797         {
798                 ref = m_cursor->first;
799
800                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
801
802                 ++m_cursor;
803
804                 if (res)
805                         return 0;
806         }
807
808         ref.type = eServiceReference::idInvalid;
809
810         return 1;
811 }
812
813 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
814         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
815 {
816 }
817
818 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
819 {
820         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
821         std::list<eServiceReference> &list = bouquet.m_services;
822         while (m_cursor != list.end())
823         {
824                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
825
826                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
827                         m_db->m_services.find(ref);
828
829                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
830
831                 ++m_cursor;
832
833                 if (res)
834                         return 0;
835         }
836
837         ref.type = eServiceReference::idInvalid;
838
839         return 1;
840 }
841
842 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
843         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
844 {
845 }
846
847 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
848 {
849         if (m_cursor != m_list.end())
850         {
851                 ref = *m_cursor++;
852                 return 0;
853         }
854         ref.type = eServiceReference::idInvalid;
855         return 1;
856 }
857
858 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
859 {
860         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
861         {
862                 int x = (a.getDVBNamespace().get() >> 16);
863                 int y = (b.getDVBNamespace().get() >> 16);
864                 if ( x > 1800 )
865                         x -= 3600;
866                 if ( y > 1800 )
867                         y -= 3600;
868                 return x < y;
869         }
870         return a.name < b.name;
871 }
872
873 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
874         :eDVBDBListQuery(db, source, query)
875 {
876         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
877                 it != m_db->m_services.end(); ++it)
878         {
879                 int res = it->second->checkFilter(it->first, *query);
880                 if (res)
881                 {
882                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
883                         bool found=0;
884                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
885                                 if ( (i->getDVBNamespace().get()&0xFFFF0000) == dvbnamespace )
886                                 {
887                                         found=true;
888                                         break;
889                                 }
890                         if (!found)
891                         {
892                                 eServiceReferenceDVB ref;
893                                 ref.setDVBNamespace(dvbnamespace);
894                                 ref.flags=eServiceReference::flagDirectory;
895                                 char buf[64];
896                                 snprintf(buf, 64, "(satellitePosition == %d) && ", dvbnamespace>>16);
897
898                                 ref.path=buf+source.path;
899                                 unsigned int pos=ref.path.find("FROM");
900                                 ref.path.erase(pos);
901                                 ref.path+="ORDER BY name";
902 //                              eDebug("ref.path now %s", ref.path.c_str());
903                                 m_list.push_back(ref);
904
905                                 ref.path=buf+source.path;
906                                 pos=ref.path.find("FROM");
907                                 ref.path.erase(pos+5);
908                                 ref.path+="PROVIDERS ORDER BY name";
909 //                              eDebug("ref.path now %s", ref.path.c_str());
910                                 m_list.push_back(ref);
911                         }
912                 }
913         }
914         m_cursor=m_list.begin();
915 }
916
917 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
918         :eDVBDBListQuery(db, source, query)
919 {
920         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
921                 it != m_db->m_services.end(); ++it)
922         {
923                 int res = it->second->checkFilter(it->first, *query);
924                 if (res)
925                 {
926                         bool found=0;
927
928                         const char *provider_name = it->second->m_provider_name.length() ?
929                                 it->second->m_provider_name.c_str() :
930                                 "Unknown";
931
932                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
933                                 if (i->name == provider_name)
934                                 {
935                                         found=true;
936                                         break;
937                                 }
938                         if (!found)
939                         {
940                                 eServiceReferenceDVB ref;
941                                 char buf[64];
942                                 ref.name=provider_name;
943                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
944                                 ref.path=buf+source.path;
945                                 unsigned int pos = ref.path.find("FROM");
946                                 ref.flags=eServiceReference::flagDirectory;
947                                 ref.path.erase(pos);
948                                 ref.path+="ORDER BY name";
949 //                              eDebug("ref.path now %s", ref.path.c_str());
950                                 m_list.push_back(ref);
951                         }
952                 }
953         }
954         m_cursor=m_list.begin();
955 }
956
957 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
958
959 static int decodeType(const std::string &type)
960 {
961         if (type == "name")
962                 return eDVBChannelQuery::tName;
963         else if (type == "provider")
964                 return eDVBChannelQuery::tProvider;
965         else if (type == "type")
966                 return eDVBChannelQuery::tType;
967         else if (type == "bouquet")
968                 return eDVBChannelQuery::tBouquet;
969         else if (type == "satellitePosition")
970                 return eDVBChannelQuery::tSatellitePosition;
971         else if (type == "channelID")
972                 return eDVBChannelQuery::tChannelID;
973         else
974                 return -1;
975 }
976
977         /* never, NEVER write a parser in C++! */
978 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
979 {
980         std::list<std::string>::const_iterator end_of_exp;
981         if (*begin == "(")
982         {
983                 end_of_exp = begin;
984                 while (end_of_exp != end)
985                         if (*end_of_exp == ")")
986                                 break;
987                         else
988                                 ++end_of_exp;
989         
990                 if (end_of_exp == end)
991                 {
992                         eDebug("expression parse: end of expression while searching for closing brace");
993                         return -1;
994                 }
995                 
996                 ++begin;
997                 // begin..end_of_exp
998                 int r = parseExpression(res, begin, end_of_exp);
999                 if (r)
1000                         return r;
1001                 ++end_of_exp;
1002                 
1003                         /* we had only one sub expression */
1004                 if (end_of_exp == end)
1005                 {
1006 //                      eDebug("only one sub expression");
1007                         return 0;
1008                 }
1009                 
1010                         /* otherwise we have an operator here.. */
1011                 
1012                 ePtr<eDVBChannelQuery> r2 = res;
1013                 res = new eDVBChannelQuery();
1014                 res->m_sort = 0;
1015                 res->m_p1 = r2;
1016                 res->m_inverse = 0;
1017                 r2 = 0;
1018                 
1019                 if (*end_of_exp == "||")
1020                         res->m_type = eDVBChannelQuery::tOR;
1021                 else if (*end_of_exp == "&&")
1022                         res->m_type = eDVBChannelQuery::tAND;
1023                 else
1024                 {
1025                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1026                         res = 0;
1027                         return 1;
1028                 }
1029                 
1030                 ++end_of_exp;
1031                 
1032                 return parseExpression(res->m_p2, end_of_exp, end);
1033         }
1034         
1035         // "begin" <op> "end"
1036         std::string type, op, val;
1037         
1038         res = new eDVBChannelQuery();
1039         res->m_sort = 0;
1040         
1041         int cnt = 0;
1042         while (begin != end)
1043         {
1044                 switch (cnt)
1045                 {
1046                 case 0:
1047                         type = *begin;
1048                         break;
1049                 case 1:
1050                         op = *begin;
1051                         break;
1052                 case 2:
1053                         val = *begin;
1054                         break;
1055                 case 3:
1056                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1057                         return 1;
1058                 }
1059                 ++begin;
1060                 ++cnt;
1061         }
1062         
1063         if (cnt != 3)
1064         {
1065                 eDebug("malformed query: missing stuff");
1066                 res = 0;
1067                 return 1;
1068         }
1069         
1070         res->m_type = decodeType(type);
1071         
1072         if (res->m_type == -1)
1073         {
1074                 eDebug("malformed query: invalid type %s", type.c_str());
1075                 res = 0;
1076                 return 1;
1077         }
1078         
1079         if (op == "==")
1080                 res->m_inverse = 0;
1081         else if (op == "!=")
1082                 res->m_inverse = 1;
1083         else
1084         {
1085                 eDebug("invalid operator %s", op.c_str());
1086                 res = 0;
1087                 return 1;
1088         }
1089         
1090         res->m_string = val;
1091         res->m_int = atoi(val.c_str());
1092 //      res->m_channelid = eDVBChannelID(val);
1093         
1094         return 0;
1095 }
1096
1097 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1098 {
1099         std::list<std::string> tokens;
1100         
1101         std::string current_token;
1102         std::string bouquet_name;
1103
1104 //      eDebug("splitting %s....", query.c_str());
1105         unsigned int i = 0;
1106         const char *splitchars="()";
1107         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1108         while (i <= query.size())
1109         {
1110                 int c = (i < query.size()) ? query[i] : ' ';
1111                 ++i;
1112                 
1113                 int issplit = !!strchr(splitchars, c);
1114                 int isaln = isalnum(c);
1115                 int iswhite = c == ' ';
1116                 int isquot = c == '\"';
1117                 
1118                 if (quotemode)
1119                 {
1120                         iswhite = issplit = 0;
1121                         isaln = lastalnum;
1122                 }
1123                 
1124                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1125                 {
1126                         if (current_token.size())
1127                                 tokens.push_back(current_token);
1128                         current_token.clear();
1129                 }
1130                 
1131                 if (!(iswhite || isquot))
1132                         current_token += c;
1133                 
1134                 if (isquot)
1135                         quotemode = !quotemode;
1136                 lastsplit = issplit;
1137                 lastalnum = isaln;
1138         }
1139         
1140 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1141 //      {
1142 //              printf("%s\n", a->c_str());
1143 //      }
1144
1145         int sort = eDVBChannelQuery::tName;
1146                 /* check for "ORDER BY ..." */
1147
1148         std::list<std::string>::iterator it = tokens.begin();
1149         while (it != tokens.end())
1150         {
1151                 if (*it == "ORDER")
1152                 {
1153                         tokens.erase(it++);
1154                         if (it != tokens.end() && *it == "BY")
1155                         {
1156                                 tokens.erase(it++);
1157                                 sort = decodeType(*it);
1158                                 tokens.erase(it++);
1159                         } else
1160                                 sort = -1;
1161                 }
1162                 else if (*it == "FROM")
1163                 {
1164                         tokens.erase(it++);
1165                         if (it != tokens.end() && *it == "BOUQUET")
1166                         {
1167                                 tokens.erase(it++);
1168                                 bouquet_name = *it;
1169                                 tokens.erase(it++);
1170                         }
1171                         else if (it != tokens.end() && *it == "SATELLITES")
1172                                 tokens.erase(it++);
1173                         else if (it != tokens.end() && *it == "PROVIDERS")
1174                                 tokens.erase(it++);
1175                         else
1176                         {
1177                                 eDebug("FROM unknown %s", (*it).c_str());
1178                                 tokens.erase(it++);
1179                         }
1180                 }
1181                 else
1182                         ++it;
1183         }
1184
1185         if (sort == -1)
1186         {
1187                 eWarning("ORDER BY .. string invalid.");
1188                 res = 0;
1189                 return -1;
1190         }
1191         
1192 //      eDebug("sort by %d", sort);
1193         
1194                 /* now we recursivly parse that. */
1195         int r = parseExpression(res, tokens.begin(), tokens.end());
1196         
1197         if (res)
1198         {
1199                 res->m_sort = sort;
1200                 res->m_bouquet_name = bouquet_name;
1201         }
1202
1203 //      eDebug("return: %d", r);
1204         return r;
1205 }
1206
1207 DEFINE_REF(eDVBChannelQuery);