add search function to epgcache to do similar broadcasting searches and text searches...
[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 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
764 {
765         eServiceID Sid(sid);
766         eTransportStreamID Tsid(tsid);
767         eOriginalNetworkID Onid(onid);
768         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
769                 sit != m_services.end(); ++sit)
770         {
771                 if (sit->first.getTransportStreamID() == Tsid &&
772                         sit->first.getOriginalNetworkID() == Onid &&
773                         sit->first.getServiceID() == Sid)
774                         return sit->first;
775         }
776         return eServiceReference();
777 }
778
779 DEFINE_REF(eDVBDBQueryBase);
780
781 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
782         :m_db(db), m_query(query), m_source(source)
783 {
784 }
785
786 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
787 {
788         ePtr<eDVBService> a_service, b_service;
789         
790         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
791         
792         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
793         {
794                 if (m_db->getService(a, a_service))
795                         return 1;
796                 if (m_db->getService(b, b_service))
797                         return 1;
798         }
799         
800         switch (sortmode)
801         {
802         case eDVBChannelQuery::tName:
803                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
804         case eDVBChannelQuery::tProvider:
805                 return a_service->m_provider_name < b_service->m_provider_name;
806         case eDVBChannelQuery::tType:
807                 return a.getServiceType() < b.getServiceType();
808         case eDVBChannelQuery::tBouquet:
809                 return 0;
810         case eDVBChannelQuery::tSatellitePosition:
811                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
812         default:
813                 return 1;
814         }
815         return 0;
816 }
817
818 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
819         :eDVBDBQueryBase(db, source, query)
820 {
821         m_cursor = m_db->m_services.begin();
822 }
823
824 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
825 {
826         while (m_cursor != m_db->m_services.end())
827         {
828                 ref = m_cursor->first;
829
830                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
831
832                 ++m_cursor;
833
834                 if (res)
835                         return 0;
836         }
837
838         ref.type = eServiceReference::idInvalid;
839
840         return 1;
841 }
842
843 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
844         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
845 {
846 }
847
848 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
849 {
850         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
851         std::list<eServiceReference> &list = bouquet.m_services;
852         while (m_cursor != list.end())
853         {
854                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
855
856                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
857                         m_db->m_services.find(ref);
858
859                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
860
861                 ++m_cursor;
862
863                 if (res)
864                         return 0;
865         }
866
867         ref.type = eServiceReference::idInvalid;
868
869         return 1;
870 }
871
872 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
873         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
874 {
875 }
876
877 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
878 {
879         if (m_cursor != m_list.end())
880         {
881                 ref = *m_cursor++;
882                 return 0;
883         }
884         ref.type = eServiceReference::idInvalid;
885         return 1;
886 }
887
888 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
889 {
890         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
891         {
892                 int x = (a.getDVBNamespace().get() >> 16);
893                 int y = (b.getDVBNamespace().get() >> 16);
894                 if ( x > 1800 )
895                         x -= 3600;
896                 if ( y > 1800 )
897                         y -= 3600;
898                 return x < y;
899         }
900         return a.name < b.name;
901 }
902
903 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
904         :eDVBDBListQuery(db, source, query)
905 {
906         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
907                 it != m_db->m_services.end(); ++it)
908         {
909                 int res = it->second->checkFilter(it->first, *query);
910                 if (res)
911                 {
912                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
913                         bool found=0;
914                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
915                                 if ( (i->getDVBNamespace().get()&0xFFFF0000) == dvbnamespace )
916                                 {
917                                         found=true;
918                                         break;
919                                 }
920                         if (!found)
921                         {
922                                 eServiceReferenceDVB ref;
923                                 ref.setDVBNamespace(dvbnamespace);
924                                 ref.flags=eServiceReference::flagDirectory;
925                                 char buf[64];
926                                 snprintf(buf, 64, "(satellitePosition == %d) && ", dvbnamespace>>16);
927
928                                 ref.path=buf+source.path;
929                                 unsigned int pos=ref.path.find("FROM");
930                                 ref.path.erase(pos);
931                                 ref.path+="ORDER BY name";
932 //                              eDebug("ref.path now %s", ref.path.c_str());
933                                 m_list.push_back(ref);
934
935                                 ref.path=buf+source.path;
936                                 pos=ref.path.find("FROM");
937                                 ref.path.erase(pos+5);
938                                 ref.path+="PROVIDERS ORDER BY name";
939 //                              eDebug("ref.path now %s", ref.path.c_str());
940                                 m_list.push_back(ref);
941                         }
942                 }
943         }
944         m_cursor=m_list.begin();
945 }
946
947 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
948         :eDVBDBListQuery(db, source, query)
949 {
950         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
951                 it != m_db->m_services.end(); ++it)
952         {
953                 int res = it->second->checkFilter(it->first, *query);
954                 if (res)
955                 {
956                         bool found=0;
957
958                         const char *provider_name = it->second->m_provider_name.length() ?
959                                 it->second->m_provider_name.c_str() :
960                                 "Unknown";
961
962                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
963                                 if (i->name == provider_name)
964                                 {
965                                         found=true;
966                                         break;
967                                 }
968                         if (!found)
969                         {
970                                 eServiceReferenceDVB ref;
971                                 char buf[64];
972                                 ref.name=provider_name;
973                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
974                                 ref.path=buf+source.path;
975                                 unsigned int pos = ref.path.find("FROM");
976                                 ref.flags=eServiceReference::flagDirectory;
977                                 ref.path.erase(pos);
978                                 ref.path+="ORDER BY name";
979 //                              eDebug("ref.path now %s", ref.path.c_str());
980                                 m_list.push_back(ref);
981                         }
982                 }
983         }
984         m_cursor=m_list.begin();
985 }
986
987 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
988
989 static int decodeType(const std::string &type)
990 {
991         if (type == "name")
992                 return eDVBChannelQuery::tName;
993         else if (type == "provider")
994                 return eDVBChannelQuery::tProvider;
995         else if (type == "type")
996                 return eDVBChannelQuery::tType;
997         else if (type == "bouquet")
998                 return eDVBChannelQuery::tBouquet;
999         else if (type == "satellitePosition")
1000                 return eDVBChannelQuery::tSatellitePosition;
1001         else if (type == "channelID")
1002                 return eDVBChannelQuery::tChannelID;
1003         else
1004                 return -1;
1005 }
1006
1007         /* never, NEVER write a parser in C++! */
1008 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1009 {
1010         std::list<std::string>::const_iterator end_of_exp;
1011         if (*begin == "(")
1012         {
1013                 end_of_exp = begin;
1014                 while (end_of_exp != end)
1015                         if (*end_of_exp == ")")
1016                                 break;
1017                         else
1018                                 ++end_of_exp;
1019         
1020                 if (end_of_exp == end)
1021                 {
1022                         eDebug("expression parse: end of expression while searching for closing brace");
1023                         return -1;
1024                 }
1025                 
1026                 ++begin;
1027                 // begin..end_of_exp
1028                 int r = parseExpression(res, begin, end_of_exp);
1029                 if (r)
1030                         return r;
1031                 ++end_of_exp;
1032                 
1033                         /* we had only one sub expression */
1034                 if (end_of_exp == end)
1035                 {
1036 //                      eDebug("only one sub expression");
1037                         return 0;
1038                 }
1039                 
1040                         /* otherwise we have an operator here.. */
1041                 
1042                 ePtr<eDVBChannelQuery> r2 = res;
1043                 res = new eDVBChannelQuery();
1044                 res->m_sort = 0;
1045                 res->m_p1 = r2;
1046                 res->m_inverse = 0;
1047                 r2 = 0;
1048                 
1049                 if (*end_of_exp == "||")
1050                         res->m_type = eDVBChannelQuery::tOR;
1051                 else if (*end_of_exp == "&&")
1052                         res->m_type = eDVBChannelQuery::tAND;
1053                 else
1054                 {
1055                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1056                         res = 0;
1057                         return 1;
1058                 }
1059                 
1060                 ++end_of_exp;
1061                 
1062                 return parseExpression(res->m_p2, end_of_exp, end);
1063         }
1064         
1065         // "begin" <op> "end"
1066         std::string type, op, val;
1067         
1068         res = new eDVBChannelQuery();
1069         res->m_sort = 0;
1070         
1071         int cnt = 0;
1072         while (begin != end)
1073         {
1074                 switch (cnt)
1075                 {
1076                 case 0:
1077                         type = *begin;
1078                         break;
1079                 case 1:
1080                         op = *begin;
1081                         break;
1082                 case 2:
1083                         val = *begin;
1084                         break;
1085                 case 3:
1086                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1087                         return 1;
1088                 }
1089                 ++begin;
1090                 ++cnt;
1091         }
1092         
1093         if (cnt != 3)
1094         {
1095                 eDebug("malformed query: missing stuff");
1096                 res = 0;
1097                 return 1;
1098         }
1099         
1100         res->m_type = decodeType(type);
1101         
1102         if (res->m_type == -1)
1103         {
1104                 eDebug("malformed query: invalid type %s", type.c_str());
1105                 res = 0;
1106                 return 1;
1107         }
1108         
1109         if (op == "==")
1110                 res->m_inverse = 0;
1111         else if (op == "!=")
1112                 res->m_inverse = 1;
1113         else
1114         {
1115                 eDebug("invalid operator %s", op.c_str());
1116                 res = 0;
1117                 return 1;
1118         }
1119         
1120         res->m_string = val;
1121         res->m_int = atoi(val.c_str());
1122 //      res->m_channelid = eDVBChannelID(val);
1123         
1124         return 0;
1125 }
1126
1127 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1128 {
1129         std::list<std::string> tokens;
1130         
1131         std::string current_token;
1132         std::string bouquet_name;
1133
1134 //      eDebug("splitting %s....", query.c_str());
1135         unsigned int i = 0;
1136         const char *splitchars="()";
1137         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1138         while (i <= query.size())
1139         {
1140                 int c = (i < query.size()) ? query[i] : ' ';
1141                 ++i;
1142                 
1143                 int issplit = !!strchr(splitchars, c);
1144                 int isaln = isalnum(c);
1145                 int iswhite = c == ' ';
1146                 int isquot = c == '\"';
1147                 
1148                 if (quotemode)
1149                 {
1150                         iswhite = issplit = 0;
1151                         isaln = lastalnum;
1152                 }
1153                 
1154                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1155                 {
1156                         if (current_token.size())
1157                                 tokens.push_back(current_token);
1158                         current_token.clear();
1159                 }
1160                 
1161                 if (!(iswhite || isquot))
1162                         current_token += c;
1163                 
1164                 if (isquot)
1165                         quotemode = !quotemode;
1166                 lastsplit = issplit;
1167                 lastalnum = isaln;
1168         }
1169         
1170 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1171 //      {
1172 //              printf("%s\n", a->c_str());
1173 //      }
1174
1175         int sort = eDVBChannelQuery::tName;
1176                 /* check for "ORDER BY ..." */
1177
1178         std::list<std::string>::iterator it = tokens.begin();
1179         while (it != tokens.end())
1180         {
1181                 if (*it == "ORDER")
1182                 {
1183                         tokens.erase(it++);
1184                         if (it != tokens.end() && *it == "BY")
1185                         {
1186                                 tokens.erase(it++);
1187                                 sort = decodeType(*it);
1188                                 tokens.erase(it++);
1189                         } else
1190                                 sort = -1;
1191                 }
1192                 else if (*it == "FROM")
1193                 {
1194                         tokens.erase(it++);
1195                         if (it != tokens.end() && *it == "BOUQUET")
1196                         {
1197                                 tokens.erase(it++);
1198                                 bouquet_name = *it;
1199                                 tokens.erase(it++);
1200                         }
1201                         else if (it != tokens.end() && *it == "SATELLITES")
1202                                 tokens.erase(it++);
1203                         else if (it != tokens.end() && *it == "PROVIDERS")
1204                                 tokens.erase(it++);
1205                         else
1206                         {
1207                                 eDebug("FROM unknown %s", (*it).c_str());
1208                                 tokens.erase(it++);
1209                         }
1210                 }
1211                 else
1212                         ++it;
1213         }
1214
1215         if (sort == -1)
1216         {
1217                 eWarning("ORDER BY .. string invalid.");
1218                 res = 0;
1219                 return -1;
1220         }
1221         
1222 //      eDebug("sort by %d", sort);
1223         
1224                 /* now we recursivly parse that. */
1225         int r = parseExpression(res, tokens.begin(), tokens.end());
1226         
1227         if (res)
1228         {
1229                 res->m_sort = sort;
1230                 res->m_bouquet_name = bouquet_name;
1231         }
1232
1233 //      eDebug("return: %d", r);
1234         return r;
1235 }
1236
1237 DEFINE_REF(eDVBChannelQuery);