summaryrefslogtreecommitdiff
path: root/timer.c
blob: 6e6f63f572d4773924c997190e72eb6c4116165c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
/*
 * timer.c: EPG2VDR plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 */

#include <vdr/tools.h>
#include <vdr/menu.h>

#include "update.h"
#include "ttools.h"
#include "service.h"

//***************************************************************************
// Check Switch Timer
//***************************************************************************

int cUpdate::checkSwitchTimer()
{
   cMutexLock lock(&swTimerMutex);
   int res = fail;

   for (auto it = switchTimers.begin(); it != switchTimers.end(); )
   {
      SwitchTimer* swTimer = &(it->second);
      tChannelID channelId = tChannelID::FromString(swTimer->channelId.c_str());

#if APIVERSNUM >= 20301
      LOCK_CHANNELS_READ;
      const cChannels* channels = Channels;
      const cChannel* channel = channels->GetByChannelID(channelId, true);
#else
      cChannels* channels = &Channels;
      cChannel* channel = channels->GetByChannelID(channelId, true);
#endif

      if (time(0) < swTimer->start)
      {
         if (!swTimer->notified && Epg2VdrConfig.switchTimerNotifyTime && time(0) >= swTimer->start - Epg2VdrConfig.switchTimerNotifyTime)
         {
            char* buf;
            asprintf(&buf, tr("Switching in %ld seconds to '%s'"), swTimer->start-time(0),
                     channel ? channel->Name() : swTimer->channelId.c_str());
            Skins.QueueMessage(mtInfo, buf);
            free(buf);
            swTimer->notified = yes;
         }

         it++;
         continue;
      }

      if (!channel)
      {
         tell(0, "Switching to channel '%s' failed, channel not found!", swTimer->channelId.c_str());
      }
      else
      {
         tell(0, "Switching to channel '%s'", channel->Name());

         if (!cDevice::PrimaryDevice()->SwitchChannel(channel, true))
            Skins.QueueMessage(mtError, tr("Can't switch channel!"));
         else
            res = success;
      }

      timerDb->clear();
      timerDb->setValue("ID", it->first);
      timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

      if (timerDb->find())
      {
         timerDb->setCharValue("ACTION", taAssumed);
         timerDb->setCharValue("STATE", tsFinished);
         timerDb->getValue("INFO")->sPrintf("Swich %s", res == success ? "succeeded" : "failed");
         timerDb->store();
      }
      else
      {
         tell(0, "Can't find timer '%ld', ignoring update of record", it->first);
      }

      timerDb->reset();

      it = switchTimers.erase(it);
   }

   switchTimerTrigger = no;

   return done;
}

//***************************************************************************
// Has Timer Changed
//***************************************************************************

int cUpdate::hasTimerChanged()
{
   int maxSp = 0;
   int changed = no;

   selectMaxUpdSp->execute();
   maxSp = timerDb->getIntValue("UPDSP");

   if (timersTableMaxUpdsp != maxSp)
   {
      timersTableMaxUpdsp = maxSp;
      changed = yes;

      cPluginManager::CallAllServices(EPG2VDR_TIMER_UPDATED, &timersTableMaxUpdsp);
   }

   selectMaxUpdSp->freeResult();

   return changed;
}

//***************************************************************************
// Perform Timer Jobs
//***************************************************************************

int cUpdate::performTimerJobs()
{
   int createCount = 0;
   int modifyCount = 0;
   int deleteCount = 0;
   uint64_t start = cTimeMs::Now();

   // switch timers ...

   takeSwitchTimer();

   tell(1, "Checking pending timer actions ..");

   // check if timer pending
   {
      timerDb->clear();
      timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

      if (!selectPendingTimerActions->find())
      {
         selectPendingTimerActions->freeResult();
         tell(1, ".. nothing to do");
         timerJobsUpdateTriggered = no;
         return done;
      }

      selectPendingTimerActions->freeResult();
   }

   // recording timers ...

   GET_TIMERS_WRITE(timers);     // get timers lock
   GET_CHANNELS_READ(channels);  // get channels lock

   // get schedules lock

#if defined (APIVERSNUM) && (APIVERSNUM >= 20301)
   cStateKey schedulesKey;
   const cSchedules* schedules = cSchedules::GetSchedulesRead(schedulesKey, 100/*ms*/);
#else
   cSchedulesLock* schedulesLock = new cSchedulesLock(false, 100/*ms*/);
   const cSchedules* schedules = (cSchedules*)cSchedules::Schedules(*schedulesLock);
#endif

   if (!schedules)
   {
#if defined (APIVERSNUM) && (APIVERSNUM >= 20301)
      schedulesKey.Remove();
#else
      delete schedulesLock;
#endif
      tell(0, "Info: Can't get lock on schedules, skipping timer update!");
      return fail;
   }

   // move this to cUpdate::init()

   std::string user = "@";
   long int webLoginEnabled = no;
   long int osdTimerNotify = no;

   getParameter("webif", "needLogin", webLoginEnabled);

   if (webLoginEnabled)
      user += Epg2VdrConfig.user;

   getParameter(user.c_str(), "osdTimerNotify", osdTimerNotify);

   // iterate pending actions ...

   timerDb->clear();
   timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

   for (int f = selectPendingTimerActions->find(); f && dbConnected(); f = selectPendingTimerActions->fetch())
   {
      int timerid = timerDb->getIntValue("ID");
      int doneid = na;
      long eventid = timerDb->getValue("EVENTID")->isNull() ? na : timerDb->getIntValue("EVENTID");
      tChannelID channelId = tChannelID::FromString(timerDb->getStrValue("CHANNELID"));
      const cEvent* event = 0;
      char requetedAction = timerDb->getStrValue("ACTION")[0];
      cTimer* timer = getTimerById(timers, timerid);   // lookup VDRs timer object
      int insert = !timer;

      if (!timerDb->getValue("DONEID")->isEmpty())
         doneid = timerDb->getIntValue("DONEID");

      tell(1, "DEBUG: Pending Action '%c' for timer (%d), event %ld, doneid %d", requetedAction, timerid, eventid, doneid);

      // --------------------------------
      // Delete timer request

      if (requetedAction == taDelete || requetedAction == taReject)
      {
         if (timerDb->hasValue("VDRUUID", "any"))
         {
            tell(0, "Error: Ignoring delete/reject request of timer (%d) without VDRUUID", timerid);
            timerDb->getValue("INFO")->sPrintf("Error: Ignoring delete/reject request of timer (%d) without VDRUUID", timerid);
            timerDb->setCharValue("ACTION", taFailed);
            timerDb->setCharValue("STATE", tsError);
            timerDb->update();
            updateTimerDone(timerid, doneid, tdsTimerCreateFailed);
            continue;
         }

         // delete VDRs timer

         if (timer)
         {
            if (timer->Recording())
            {
               timer->Skip();
#if defined (APIVERSNUM) && (APIVERSNUM >= 20302)
               cRecordControls::Process(timers, time(0));
#else
               cRecordControls::Process(time(0));
#endif
            }

            timers->Del(timer);
            deleteCount++;
            tell(0, "Deleted timer %d", timerid);
         }
         else
         {
            tell(0, "Info: Timer (%d) not found, ignoring delete/reject request", timerid);
         }

         updateTimerDone(timerid, doneid, requetedAction == taDelete ? tdsTimerDeleted : tdsTimerRejected);
         timerDb->setCharValue("ACTION", taAssumed);
         timerDb->setCharValue("STATE", tsDeleted);
         timerDb->update();

         if (osdTimerNotify)
            Skins.QueueMessage(mtInfo, cString::sprintf("Timer '%s' deleted", timerDb->getStrValue("FILE")));
      }

      // --------------------------------
      // Create or Modify timer request

      else if (requetedAction == taModify || requetedAction == taAdjust || requetedAction == taCreate)
      {
         cSchedule* s = 0;

         if (!timer && (requetedAction == taModify || requetedAction == taAdjust))
         {
            tell(0, "Fatal: Timer (%d) not found, skipping modify request", timerid);

            timerDb->getValue("INFO")->sPrintf("Fatal: Timer (%d) not found, skipping modify request", timerid);
            timerDb->setCharValue("ACTION", taFailed);
            timerDb->setCharValue("STATE", tsError);
            timerDb->update();
            updateTimerDone(timerid, doneid, tdsTimerCreateFailed);
            continue;
         }

         // get schedule (channel) and optional the event

         if (!(s = (cSchedule*)schedules->GetSchedule(channelId)))
         {
            const cChannel* channel = channels->GetByChannelID(channelId);

            tell(0, "Error: Time (%d), missing channel '%s' (%s) or channel not found, ignoring request",
                 timerid, channel ? channel->Name() : "", timerDb->getStrValue("CHANNELID"));

            timerDb->getValue("INFO")->sPrintf("Error: Timer, (%d), missing channel '%s' (%s) or channel not found, ignoring request",
                                               timerid, channel ? channel->Name() : "", timerDb->getStrValue("CHANNELID"));
            timerDb->setCharValue("ACTION", taFailed);
            timerDb->setCharValue("STATE", tsError);
            timerDb->update();
            updateTimerDone(timerid, doneid, tdsTimerCreateFailed);

            // mark this channel as 'unknown'

            mapDb->clear();
            mapDb->setValue("CHANNELID", channelId.ToString());
            markUnknownChannel->execute();
            markUnknownChannel->freeResult();
            continue;
         }

         if (eventid > 0 && !(event = s->GetEvent(eventid)))
         {
            const cChannel* channel = channels->GetByChannelID(channelId);

            tell(0, "Error: Timer (%d), missing event '%ld' on channel '%s' (%s), ignoring request",
                 timerid, eventid, channel->Name(), timerDb->getStrValue("CHANNELID"));

            timerDb->getValue("INFO")->sPrintf("Error: Timer (%d), missing event '%ld' on channel '%s' (%s), ignoring request",
                                               timerid, eventid, channel->Name(), timerDb->getStrValue("CHANNELID"));
            timerDb->setCharValue("ACTION", taFailed);
            timerDb->setCharValue("STATE", tsError);
            timerDb->update();
            updateTimerDone(timerid, doneid, tdsTimerCreateFailed);

            // force reload of events

            tell(0, "Info: Trigger EPG full-reload due to missing event!");
            triggerEpgUpdate(yes);

            continue;
         }

         if (insert)
         {
            tell(1, "DEBUG: Create of timer %d for event %ld", timerid, eventid);

            // create timer ...

            if (event)
            {
               // event should run at least more the 2 Minutes

               if (getTimerByEvent(timers, event))
                  tell(0, "Warning: Timer for event (%d) '%s' already exist, creating additional timer due to request!",
                       event->EventID(), event->Title());

               if (event->StartTime() + event->Duration() - (2 * tmeSecondsPerMinute) <= time(0))
               {
                  tell(0, "Info: Event '%s' finished in the past, ignoring timer request!", event->Title());
                  timerDb->getValue("INFO")->sPrintf("Info: Event '%s' finished in the past, ignoring timer request!", event->Title());
                  timerDb->setCharValue("ACTION", taFailed);
                  timerDb->setCharValue("STATE", tsError);
                  timerDb->update();
                  updateTimerDone(timerid, doneid, tdsTimerCreateFailed);
                  continue;
               }

               timer = new cTimer(event);
            }
            else
            {
#if APIVERSNUM >= 20301
               const cChannel* channel = channels->GetByChannelID(channelId);
#else
               cChannel* channel = channels->GetByChannelID(channelId);
#endif
               timer = new cTimer(no, no, channel);  // timer without a event
            }

            // reset error message in 'reason'

            if (!timerDb->getValue("INFO")->isEmpty())
               timerDb->setValue("INFO", "");

            tell(1, "Create timer '%d'", timerid);

            if (timerDb->hasValue("VDRUUID", "any"))
            {
               tell(0, "Took timer (%d) for uuid 'any', event (%ld)", timerid, eventid);

               // mark 'any' record as assumed and create new with my UUID in primary key

               timerDb->setCharValue("ACTION", taAssumed);
               timerDb->setCharValue("STATE", tsIgnore);

               timerDb->update();

               // I take the timer -> new record will created!

               timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);
               timerDb->insert();

               // update timerid !!!

               int otid = timerid;
               timerid = timerDb->getLastInsertId();
               timerDb->setValue("ID", timerid);
               tell(0, "DEBUG: Copied timer (%d/%ld) to (%d/%ld)", otid, eventid, timerid, timerDb->getIntValue("EVENTID"));
            }
         }
         else
         {
            // modify timer ...

            if (timerDb->hasValue("VDRUUID", "any"))
            {
               tell(0, "Error: Ignoring modify request of timer (%d) without VDRUUID", timerid);
               timerDb->getValue("INFO")->sPrintf("Error: Ignoring modify request of timer (%d) without VDRUUID", timerid);
               timerDb->setCharValue("ACTION", taFailed);
               timerDb->setCharValue("STATE", tsError);
               timerDb->update();
               updateTimerDone(timerid, doneid, tdsTimerCreateFailed);
               continue;
            }

            tell(1, "Modify timer (%d), set event to (%d)", timerid, event->EventID());

// #TODO ?!?!
//             if (event && timer->Event() != event)
//                timer->SetEvent(event);
         }

         // update the timer with data from timers table ...

         updateTimerObjectFromRow(timer, timerDb->getRow(), event);

         // add / store ...

         if (insert)
         {
            timers->Add(timer);
            updateTimerDone(timerid, doneid, tdsTimerCreated);
            createCount++;
         }
         else
         {
            if (requetedAction == taAdjust && event)
            {
               // adjust time to given event ..

               cTimer* dummyTimer = new cTimer(event);
               timer->SetStart(dummyTimer->Start());
               timer->SetStop(dummyTimer->Stop());
               timer->SetDay(dummyTimer->Day());
               delete dummyTimer;
            }

            modifyCount++;
         }

         timerDb->setValue("AUX", timer->Aux());
         timerDb->setCharValue("ACTION", taAssumed);
         timerDb->setCharValue("STATE", tsPending);
         timerDb->store();

         if (osdTimerNotify)
            Skins.QueueMessage(mtInfo, cString::sprintf("Timer '%s' %s", timerDb->getStrValue("FILE"), insert ? "created" : "modified"));
      }
   }

   selectPendingTimerActions->freeResult();

   // schedules lock freigeben

#if defined (APIVERSNUM) && (APIVERSNUM >= 20301)
   schedulesKey.Remove();
#else
   delete schedulesLock;
#endif

   if (createCount || modifyCount || deleteCount)
      timers->SetModified();

   timerJobsUpdateTriggered = no;

   tell(0, "Timer requests done, created %d, modified %d, deleted %d in %s",
        createCount, modifyCount, deleteCount, ms2Dur(cTimeMs::Now()-start).c_str());

   return success;
}

//***************************************************************************
// Take Switch Timer
//***************************************************************************

int cUpdate::takeSwitchTimer()
{
   cMutexLock lock(&swTimerMutex);

   tell(1, "Checking switch timer actions ..");

   // iterate pending switch timers ...

   timerDb->clear();
   timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

   for (int f = selectSwitchTimerActions->find(); f && dbConnected(); f = selectSwitchTimerActions->fetch())
   {
      long timerid = timerDb->getIntValue("ID");

      // to old?

      if (time(0) > timerDb->getIntValue("_STARTTIME"))
      {
         // to old, set to 'Finished'

         timerDb->setCharValue("ACTION", taAssumed);
         timerDb->setCharValue("STATE", tsFinished);
         timerDb->setValue("INFO", "Removed, to old");
         timerDb->store();
         continue;
      }

      // check state, did we have it already?

      auto it = switchTimers.find(timerid);

      // ACTION is delete?

      if (timerDb->hasCharValue("ACTION", taDelete))
      {
         if (it != switchTimers.end())
            switchTimers.erase(it);

         timerDb->setCharValue("ACTION", taAssumed);
         timerDb->setCharValue("STATE", tsDeleted);
         timerDb->store();
         continue;
      }

      // if already in map, ignore

      if (it != switchTimers.end())
         continue;

      // not in map, create it
      // independend if ACTION is 'pending', 'create' or 'modify' ore something else
      // that's special for switch timers since we have to get the 'pending' also after a vdr restart

      tell(1, "Got switch timer (%ld) for channel '%s' at '%s'",
           timerid, timerDb->getStrValue("CHANNELID"),
           l2pTime(timerDb->getIntValue("_STARTTIME")).c_str());

      switchTimers[timerid].eventId = timerDb->getIntValue("EVENTID");
      switchTimers[timerid].channelId = timerDb->getStrValue("CHANNELID");
      switchTimers[timerid].start = (timerDb->getIntValue("_STARTTIME") / 60) * 60;    // cut seconds
      switchTimers[timerid].notified = no;

      // and register timer for it

      timerThreads.push_back(new cTimerThread(&sendEvent, evtSwitchTimer,
                                              switchTimers[timerid].start, this));

      if (Epg2VdrConfig.switchTimerNotifyTime)
         timerThreads.push_back(new cTimerThread(&sendEvent, evtSwitchTimer,
                                                 switchTimers[timerid].start - Epg2VdrConfig.switchTimerNotifyTime,
                                                 this));

      // at  last confirm it

      timerDb->setCharValue("ACTION", taAssumed);
      timerDb->setCharValue("STATE", tsPending);
      timerDb->store();
   }

   selectSwitchTimerActions->freeResult();

   return done;
}

//***************************************************************************
// Timer Done to Failed
//***************************************************************************

int cUpdate::updateTimerDone(int timerid, int doneid, char state)
{
   if (doneid == na)
      return done;

   timerDoneDb->clear();
   timerDoneDb->setValue("ID", doneid);

   if (timerDoneDb->find())
   {
      // don't toggle 'D'eleted by user to re'J'ected

      if (timerDoneDb->hasCharValue("STATE", tdsTimerDeleted) && state == tdsTimerRejected)
         return done;

      timerDoneDb->setValue("TIMERID", timerid);
      timerDoneDb->setCharValue("STATE", state);
      timerDoneDb->update();
   }
   else
   {
      tell(0, "Warning: Id (%d) in timersdone for timer (%d) not found.",
           doneid, timerid);
   }

   return done;
}

//***************************************************************************
// Update Timer Table
//***************************************************************************

int cUpdate::updateTimerTable()
{
   cMutexLock lock(&timerMutex);
   int timerMod = 0;
   int cnt = 0;

   tell(1, "Updating table timers (and remove deleted and finished timers older than 2 days)");

   timerDb->deleteWhere("%s < unix_timestamp() - %d and %s in ('D','F','-')",
                        timerDb->getField("UPDSP")->getDbName(),
                        2 * tmeSecondsPerDay,
                        timerDb->getField("STATE")->getDbName());

   connection->startTransaction();

   // --------------------------
   // get timers lock

#if defined (APIVERSNUM) && (APIVERSNUM >= 20301)
   LOCK_TIMERS_WRITE;
   cTimers* timers = Timers;
#else
   cTimers* timers = &Timers;
#endif

   // --------------------------
   // remove deleted timers

   timerDb->clear();
   timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

   for (int f = selectMyTimer->find(); f && dbConnected(); f = selectMyTimer->fetch())
   {
      int exist = no;

      // delete only assumed timers

      if (!timerDb->getValue("ACTION")->isEmpty() && !timerDb->hasCharValue("ACTION", taAssumed))
         continue;

      // ignore switch timer here

      if (timerDb->hasCharValue("TYPE", ttView))
         continue;

      // count my timers to detect truncated (epmty) table
      //  -> on empty table ignore known timer ids

      cnt++;

      for (const cTimer* t = timers->First(); t; t = timers->Next(t))
      {
         if (!t->Local())
            continue;

         int timerid = getTimerIdOf(t);

         // compare by timerid

         if (timerid != na && timerDb->getIntValue("ID") == timerid)
         {
            exist = yes;
            break;
         }

         // compare by start-time and channelid

         if (t->StartTime() == timerDb->getIntValue("STARTTIME") &&
             strcmp(t->Channel()->GetChannelID().ToString(), timerDb->getStrValue("CHANNELID")) == 0)
         {
            exist = yes;
            break;
         }
      }

      if (!exist)
      {
         int doneid = timerDb->getIntValue("DONEID");

         if (!timerDb->hasCharValue("STATE", tsFinished) &&
             !timerDb->hasCharValue("STATE", tsRunning) &&
             !timerDb->hasCharValue("STATE", tsError))
         {
            timerDb->setCharValue("STATE", tsDeleted);
            timerDb->update();
         }

         if (doneid > 0)
         {
            timerDoneDb->clear();
            timerDoneDb->setValue("ID", doneid);

            if (timerDoneDb->find() &&
                (timerDoneDb->hasCharValue("STATE", tdsTimerCreated) || timerDoneDb->hasCharValue("STATE", tdsTimerRequested)))
            {
               timerDoneDb->setCharValue("STATE", tdsTimerDeleted);
               timerDoneDb->update();
            }
         }
      }
   }

   selectMyTimer->freeResult();

   if (!cnt && timers->Count())
      tell(0, "No timer of my uuid found, assuming cleared table and ignoring the known timerids");

   // --------------------------
   // update timers

   for (cTimer* t = timers->First(); t && dbConnected(); t = timers->Next(t))
   {
      int insert = yes;
      int timerId = getTimerIdOf(t);

      if (!t->Local())
         continue;

      // no timer id or not in table -> handle as insert!

      timerDb->clear();

      if (timerId != na && cnt)
      {
         timerDb->setValue("ID", timerId);
         timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

         insert = !timerDb->find();
         timerDb->clearChanged();
      }

      // update only assumed timers

      if (!insert)
      {
         if (!timerDb->getValue("ACTION")->isEmpty() && !timerDb->hasCharValue("ACTION", taAssumed))
            continue;
      }

      updateRowByTimer(timerDb->getRow(), t);

      if (insert)
      {
         timerDb->setCharValue("TYPE", ttRecord);
         timerDb->setCharValue("STATE", tsPending);
         timerDb->insert();

         // get timerid of auto increment field and store to timers 'aux' data

         timerId = timerDb->getLastInsertId();
         setTimerId(t, timerId);
         timerMod++;
      }
      else if (!timerDb->getValue("STATE")->isEmpty() && strchr("DE", timerDb->getStrValue("STATE")[0]))
      {
         timerDb->setValue("STATE", "P");   // timer pending
      }

      if (insert || timerDb->getChanges())
      {
         timerDb->setValue("ID", timerId);  // set ID for update!!
         timerDb->update();                 // at least for aux (on insert case)

         tell(1, "'%s' timer for event %u '%s' at database",
              insert ? "Insert" : "Update",
              t->Event() ? t->Event()->EventID() : na,
              t->Event() ? t->Event()->Title() : t->File());
      }
      else
      {
         tell(3, "Nothing changed ... skipping db update");
      }

      timerDb->reset();
   }

   connection->commit();
   timerTableUpdateTriggered = no;

   if (timerMod)
      timers->SetModified();

   tell(1, "Updating table timers done");

   return success;
}

//***************************************************************************
// Recording Changed
//***************************************************************************

int cUpdate::recordingChanged()
{
   cMutexLock lock(&runningRecMutex);

   cRunningRecording* rr = runningRecordings.First();

   tell(3, "recording changed; rr = %p", (void*)rr);

   while (rr && dbConnected())
   {
      int timerWasDeleted = no;

      // first: update timer state ..

      if (!rr->aux.empty())
      {
         int timerid = getTimerIdOf(rr->aux.c_str());
         timerDb->clear();
         timerDb->setValue("ID", timerid);
         timerDb->setValue("VDRUUID", Epg2VdrConfig.uuid);

         tell(1, "Try to lookup timer with id %d", timerid);

         if (timerDb->find())
         {
            tell(1, "Found timer %ld", timerDb->getIntValue("ID"));

            if (timerDb->hasCharValue("STATE", tsDeleted))
               timerWasDeleted = yes;
            else
               timerDb->setCharValue("STATE", rr->failed ? tsError : rr->finished ? tsFinished : tsRunning);

            timerDb->setValue("INFO", rr->info.c_str());
            timerDb->store();
         }
         else
            tell(0, "Error: Can't lookup timer, id %d not found!", timerid);

         timerDb->reset();
      }

      // second: update done entry and remove from 'running' if 'finished' ..

      if (rr->finished)
      {
         if (rr->doneid != na)
         {
            timerDoneDb->clear();
            timerDoneDb->setValue("ID", rr->doneid);

            if (timerDoneDb->find())
            {
               if (timerWasDeleted)
                  timerDoneDb->setCharValue("STATE", tdsTimerDeleted);     // -> Recording deleted
               else if (rr->failed)
                  timerDoneDb->setCharValue("STATE", tdsRecordingFailed);  // -> Recording failed
               else
                  timerDoneDb->setCharValue("STATE", tdsRecordingDone);    // -> Recording done

               tell(1, "Update 'done state' for doneid %ld to %s", rr->doneid, timerDoneDb->getStrValue("STATE"));

               timerDoneDb->update();
            }
            else
            {
               tell(0, "Error: Can't update timersdone state, doneid %ld not found!", rr->doneid);
            }
         }

         cRunningRecording* rrNext = runningRecordings.Next(rr);
         runningRecordings.Del(rr);
         rr = rrNext;

         continue;
      }

      rr = runningRecordings.Next(rr);
   }

   return done;
}