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