From dcac58b2d00b704c634979da8f96bdda573b5800 Mon Sep 17 00:00:00 2001
From: David Trattnig <david.trattnig@o94.at>
Date: Thu, 30 Jan 2020 21:36:22 +0100
Subject: [PATCH] Store duration to DB and various fixes.

---
 modules/scheduling/calendar.py | 99 +++++++++++++++++++++++-----------
 1 file changed, 67 insertions(+), 32 deletions(-)

diff --git a/modules/scheduling/calendar.py b/modules/scheduling/calendar.py
index 4f394a49..98712e1b 100644
--- a/modules/scheduling/calendar.py
+++ b/modules/scheduling/calendar.py
@@ -133,10 +133,13 @@ class AuraCalendarService(threading.Thread):
             fetched_schedule_data = self.calendar_fetcher.fetch()
 
             # if nothing is fetched, return
-            if fetched_schedule_data is None:
+            if not fetched_schedule_data:
                 self.queue.put("fetching_aborted Nothing fetched")
                 return
-
+            
+            # Check what we've got
+            self.logger.debug("Schedule data: " + str(fetched_schedule_data))
+            
             ret_schedule = []
             #            for schedule in self.fetched_schedule_data:
             #                if "start" not in schedule:
@@ -147,15 +150,17 @@ class AuraCalendarService(threading.Thread):
             #                    continue
 
             for schedule in fetched_schedule_data:
-                # store the schedule
+                # Store the schedule
                 schedule_db = self.store_schedule(schedule)
 
-                # store playlists to play
-                self.logger.warning("only storing playlist")
+                # Store playlists to play
+                self.logger.warning("--- Storing playlist only ---")
                 self.store_playlist(schedule_db, schedule_db.playlist_id, schedule["playlist"])
-#                self.store_schedule_playlist(schedule_db, schedule, "schedule_fallback", 1)
-#                self.store_schedule_playlist(schedule_db, schedule, "show_fallback", 2)
-#                self.store_schedule_playlist(schedule_db, schedule, "station_fallback", 3)
+
+                #FIXME Store fallbacks in DB logic
+                # self.store_schedule_playlist(schedule_db, schedule, "schedule_fallback", 1)
+                # self.store_schedule_playlist(schedule_db, schedule, "show_fallback", 2)
+                # self.store_schedule_playlist(schedule_db, schedule, "station_fallback", 3)
 
                 ret_schedule.append(schedule_db)
 
@@ -175,7 +180,15 @@ class AuraCalendarService(threading.Thread):
 #        Schedule.drop_the_future(time_in_the_future)
 
     # ------------------------------------------------------------------------------------------ #
+
+
     def store_schedule(self, schedule):
+        """
+        Stores the given schedule to the database.
+
+        Args:
+            schedule (Schedule):    The schedule
+        """
         schedule_db = Schedule.select_show_on_datetime(schedule["start"])
         havetoadd = False
 
@@ -203,7 +216,9 @@ class AuraCalendarService(threading.Thread):
         schedule_db.musicfocus = schedule["show_musicfocus"]
 
         if schedule["playlist_id"] is None:
+            # FIXME Manually assigned playlist ID.
             schedule["playlist_id"] = 1
+
         schedule_db.playlist_id = schedule["playlist_id"]
         schedule_db.schedule_fallback_id = schedule["schedule_fallback_id"]
         schedule_db.show_fallback_id = schedule["show_fallback_id"]
@@ -215,6 +230,9 @@ class AuraCalendarService(threading.Thread):
 
     # ------------------------------------------------------------------------------------------ #
     def store_playlist(self, schedule_db, playlist_id, fetched_playlist, fallbackplaylist_type=0):
+        """
+        Stores the Playlist to the database.
+        """
         playlist_db = Playlist.select_playlist_for_schedule(schedule_db.schedule_start, playlist_id)
         havetoadd = False
 
@@ -222,13 +240,14 @@ class AuraCalendarService(threading.Thread):
             playlist_db = Playlist()
             havetoadd = True
 
+        self.logger.debug("Storing playlist %d for schedule (%s)" % (playlist_id, str(schedule_db)))
         playlist_db.playlist_id = playlist_id
         playlist_db.schedule_start = schedule_db.schedule_start
         playlist_db.show_name = schedule_db.show_name
         playlist_db.fallback_type = fallbackplaylist_type
         playlist_db.entry_count = len(fetched_playlist["entries"])
 
-        playlist_db.store(havetoadd, True)
+        playlist_db.store(havetoadd, commit=True)
 
         self.store_playlist_entries(playlist_db, fetched_playlist)
 
@@ -236,7 +255,12 @@ class AuraCalendarService(threading.Thread):
 
 
     def store_playlist_entries(self, playlist_db, fetched_playlist):
+        """
+        Stores the playlist entries to the database.
+        """
         entry_num = 0
+        time_marker = playlist_db.start_unix
+
         for entry in fetched_playlist["entries"]:
             playlistentry_db = PlaylistEntry.select_playlistentry_for_playlist(playlist_db.artificial_id, entry_num)
             havetoadd = False
@@ -244,18 +268,27 @@ class AuraCalendarService(threading.Thread):
                 playlistentry_db = PlaylistEntry()
                 havetoadd = True
 
+            # Nano-seconds to seconds
+            duration = int(float(entry["file"]["duration"]) / 1000000000) 
+
+            playlistentry_db.duration = duration
+            playlistentry_db.entry_start = datetime.fromtimestamp(time_marker)
             playlistentry_db.artificial_playlist_id = playlist_db.artificial_id
             playlistentry_db.entry_num = entry_num
             playlistentry_db.uri = entry["uri"]
             playlistentry_db.filename = entry["filename"]
-            playlistentry_db.duration = entry["file"]["duration"]
-            playlistentry_db.store(havetoadd, True)
+
+            playlistentry_db.store(havetoadd, commit=True)
 
             self.store_playlist_entry_metadata(playlistentry_db, entry["file"]["metadata"])
 
             entry_num = entry_num + 1
+            time_marker += duration
 
     def store_playlist_entry_metadata(self, playlistentry_db, metadata):
+        """
+        Stores the meta-data for a PlaylistEntry.
+        """
         playlistentrymetadata_db = PlaylistEntryMetaData.select_metadata_for_entry(playlistentry_db.artificial_id)
         havetoadd = False
         if not playlistentrymetadata_db:
@@ -272,36 +305,38 @@ class AuraCalendarService(threading.Thread):
         if "album" in metadata:
             playlistentrymetadata_db.album = metadata["album"]
 
-        playlistentrymetadata_db.store(havetoadd, True)
+        playlistentrymetadata_db.store(havetoadd, commit=True)
 
     # ------------------------------------------------------------------------------------------ #
-    def store_playlist_entry(self, schedule_db, playlist, entry, lastentry, entrynum, fallbackplaylist_type=0):
-        schedule_entry_db = Playlist.select_one().select_one_playlist_entry_for_show(schedule_db.schedule_id, fallbackplaylist_type, entrynum)
-        havetoadd = False
 
-        if not schedule_entry_db:
-            self.logger.debug("no scheduleentry with id " + str(playlist["id"]) + " and pos " + str(entrynum) + " in database => creating a new one")
-            # FIXME Needed? No active class declaration
-            #schedule_entry_db = ScheduleEntry()
-            havetoadd = True
+    # FIXME Needed?
+    # def store_playlist_entry(self, schedule_db, playlist, entry, lastentry, entrynum, fallbackplaylist_type=0):
+    #     schedule_entry_db = Playlist.select_one().select_one_playlist_entry_for_show(schedule_db.schedule_id, fallbackplaylist_type, entrynum)
+    #     havetoadd = False
+
+    #     if not schedule_entry_db:
+    #         self.logger.debug("no scheduleentry with id " + str(playlist["id"]) + " and pos " + str(entrynum) + " in database => creating a new one")
+    #         # FIXME Needed? No active class declaration
+    #         #schedule_entry_db = ScheduleEntry()
+    #         havetoadd = True
 
 
-        schedule_entry_db.playlist_id = playlist["id"]
-        schedule_entry_db.entry_num = entrynum
-        schedule_entry_db.schedule_id = schedule_db.schedule_id
-        schedule_entry_db.uri = entry["uri"]
-        schedule_entry_db.fallback_type = fallbackplaylist_type
-        schedule_entry_db.entry_start = schedule_db.schedule_start + timedelta(seconds=self.get_length(lastentry))
+    #     schedule_entry_db.playlist_id = playlist["id"]
+    #     schedule_entry_db.entry_num = entrynum
+    #     schedule_entry_db.schedule_id = schedule_db.schedule_id
+    #     schedule_entry_db.uri = entry["uri"]
+    #     schedule_entry_db.fallback_type = fallbackplaylist_type
+    #     schedule_entry_db.entry_start = schedule_db.schedule_start + timedelta(seconds=self.get_length(lastentry))
 
-        schedule_entry_db.calc_unix_times()
-        if havetoadd:
-            schedule_entry_db.define_clean_source()
+    #     schedule_entry_db.calc_unix_times()
+    #     if havetoadd:
+    #         schedule_entry_db.define_clean_source()
 
-        self.logger.debug("Storing entries... playlist_id: " + str(playlist["id"]) + " schedule_id: " + str(schedule_db.schedule_id) + " num: " + str(entrynum))
+    #     self.logger.debug("Storing entries... playlist_id: " + str(playlist["id"]) + " schedule_id: " + str(schedule_db.schedule_id) + " num: " + str(entrynum))
 
-        schedule_entry_db.store(add=havetoadd, commit=True)
+    #     schedule_entry_db.store(add=havetoadd, commit=True)
 
-        return schedule_entry_db
+    #     return schedule_entry_db
 
     # ------------------------------------------------------------------------------------------ #
     def __calc_date_to__(self):
-- 
GitLab