models.py 42.1 KB
Newer Older
1
#
David Trattnig's avatar
David Trattnig committed
2
# Aura Engine (https://gitlab.servus.at/aura/engine)
3
#
David Trattnig's avatar
David Trattnig committed
4
# Copyright (C) 2017-2020 - The Aura Engine Team.
5
#
David Trattnig's avatar
David Trattnig committed
6
7
8
9
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
10
#
David Trattnig's avatar
David Trattnig committed
11
12
13
14
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
15
#
David Trattnig's avatar
David Trattnig committed
16
17
18
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

19

20
import sys
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
21
import time
22
23
import logging
import datetime
24

25
26
import sqlalchemy as sa

David Trattnig's avatar
David Trattnig committed
27
from sqlalchemy.ext.declarative         import declarative_base
David Trattnig's avatar
David Trattnig committed
28
29
from sqlalchemy                         import orm
from sqlalchemy                         import BigInteger, Boolean, Column, DateTime, Integer, String, ForeignKey
David Trattnig's avatar
David Trattnig committed
30
from sqlalchemy.orm                     import relationship
David Trattnig's avatar
David Trattnig committed
31
from sqlalchemy.ext.hybrid              import hybrid_property
32

33

David Trattnig's avatar
David Trattnig committed
34
from modules.scheduling.types           import PlaylistType
David Trattnig's avatar
David Trattnig committed
35
from modules.base.config                import AuraConfig
David Trattnig's avatar
David Trattnig committed
36
from modules.base.utils                 import SimpleUtil, EngineUtil
David Trattnig's avatar
David Trattnig committed
37

38

David Trattnig's avatar
David Trattnig committed
39

David Trattnig's avatar
David Trattnig committed
40
41
42
# Init Config
config = AuraConfig()

David Trattnig's avatar
David Trattnig committed
43
# Initialize DB Model and session
David Trattnig's avatar
David Trattnig committed
44
engine = sa.create_engine(config.get_database_uri())
45
46
47
48
49
50
51
52
Base = declarative_base()
Base.metadata.bind = engine

class DB():
    session = orm.scoped_session(orm.sessionmaker())(bind=engine)
    Model = Base


53
54

class AuraDatabaseModel():
55
56
57
58
59
    """
    AuraDataBaseModel.

    Holding all tables and relationships for the engine.
    """
60
61
    logger = None

62

63
    def __init__(self):
64
65
66
        """
        Constructor.
        """
67
68
        self.logger = logging.getLogger("AuraEngine")

69

70
    def store(self, add=False, commit=False):
71
72
73
        """
        Store to the database
        """
74
        if add:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
75
            DB.session.add(self)
76
77
        else:
            DB.session.merge(self)
78
        if commit:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
79
            DB.session.commit()
80

81

82
    def delete(self, commit=False):
83
84
85
        """
        Delete from the database
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
86
        DB.session.delete(self)
87
        if commit:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
88
            DB.session.commit()
89

90

91
92
    def _asdict(self):
        return self.__dict__
93

94

95
96
    @staticmethod
    def recreate_db(systemexit = False):
97
98
99
        """
        Re-creates the database for developments purposes.
        """
100
101
        manualschedule = Schedule()
        manualschedule.schedule_id = 0
102
        manualschedule.show_name = "Manual Show"
103
104
105
106
        Base.metadata.drop_all()
        Base.metadata.create_all()

        
107
108
109
110
        # self.logger.debug("inserting manual scheduling possibility and fallback trackservice schedule")
        # DB.session.add(manualschedule)
        # db.session.add(fallback_trackservice_schedule)
        # self.logger.debug("all created. commiting...")
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
111
        DB.session.commit()
112

113
114
        if systemexit:
            sys.exit(0)
115

116

117
118

#
119
#   SCHEDULES & PLAYLISTS
120
121
#

122

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
123
class Schedule(DB.Model, AuraDatabaseModel):
124
    """
125
126
    One specific Schedule for a show on a timeslot.
    Holding references to playlists and fallback-playlists.
127
    """
128
    __tablename__ = 'schedule'
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
129

130
131
132
133
134
135
    # Primary keys
    id = Column(Integer, primary_key=True, autoincrement=True)

    schedule_start = Column(DateTime, unique=True, index=True)
    schedule_end = Column(DateTime, unique=True, index=True)
    schedule_id = Column(Integer, unique=True)
136

137
    show_id = Column(Integer)
138
139
    show_name = Column(String(256))
    show_hosts = Column(String(256))
140
    funding_category = Column(String(256))
141
142
143
144
145
146
    comment = Column(String(512))
    languages = Column(String(256))
    type = Column(String(256))
    category = Column(String(256))
    topic = Column(String(256))
    musicfocus = Column(String(256))
147
148
149

    is_repetition = Column(Boolean())

150
    playlist_id = Column(Integer) #, ForeignKey("playlist.playlist_id"))
David Trattnig's avatar
David Trattnig committed
151
    schedule_fallback_id = Column(Integer)
152
153
    show_fallback_id = Column(Integer)
    station_fallback_id = Column(Integer)
154
    fallback_state = PlaylistType.DEFAULT
David Trattnig's avatar
David Trattnig committed
155
156
    
    fadeouttimer = None # Used to fade-out the schedule, even when entries are longer
157

158
159
160
    playlist = relationship("Playlist",
                            primaryjoin="and_(Schedule.schedule_start==Playlist.schedule_start, Schedule.playlist_id==Playlist.playlist_id, Schedule.show_name==Playlist.show_name)",
                            back_populates="schedule")
David Trattnig's avatar
David Trattnig committed
161
162
    schedule_fallback = relationship("Playlist",
                            primaryjoin="and_(Schedule.schedule_start==Playlist.schedule_start, Schedule.schedule_fallback_id==Playlist.playlist_id, Schedule.show_name==Playlist.show_name)",
163
164
165
166
167
168
169
                            back_populates="schedule")
    show_fallback = relationship("Playlist",
                            primaryjoin="and_(Schedule.schedule_start==Playlist.schedule_start, Schedule.show_fallback_id==Playlist.playlist_id, Schedule.show_name==Playlist.show_name)",
                            back_populates="schedule")
    station_fallback = relationship("Playlist",
                            primaryjoin="and_(Schedule.schedule_start==Playlist.schedule_start, Schedule.station_fallback_id==Playlist.playlist_id, Schedule.show_name==Playlist.show_name)",
                            back_populates="schedule")
170

171

172
    @staticmethod
173
174
    def select_show_on_datetime(date_time):
        return DB.session.query(Schedule).filter(Schedule.schedule_start == date_time).first()
175

176

177
    @staticmethod
178
179
    def select_programme(date_from=datetime.date.today()):
        """
180
        Select all schedules starting from `date_from` or from today if no
181
182
183
184
185
186
187
188
189
190
191
        parameter is passed.

        Args:
            date_from (datetime):   Select schedules from this date and time on

        Returns:
            ([Schedule]):           List of schedules
        """
        schedules = DB.session.query(Schedule).\
            filter(Schedule.schedule_start >= date_from).\
            order_by(Schedule.schedule_start).all()
192

193
        return schedules
194

195

David Trattnig's avatar
David Trattnig committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    @staticmethod
    def select_upcoming(n):
        """
        Selects the (`n`) upcoming schedules.
        """
        now = datetime.datetime.now()
        DB.session.commit() # Required since independend session is used.
        schedules = DB.session.query(Schedule).\
            filter(Schedule.schedule_start > str(now)).\
            order_by(Schedule.schedule_start.asc()).limit(n).all()
        
        return schedules


David Trattnig's avatar
David Trattnig committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    @hybrid_property
    def start_unix(self):
        """
        Start time of the schedule in UNIX time.
        """
        return time.mktime(self.schedule_start.timetuple())


    @hybrid_property
    def end_unix(self):
        """
        End time of the schedule in UNIX time.
        """
        return time.mktime(self.schedule_end.timetuple())


David Trattnig's avatar
David Trattnig committed
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
    def as_dict(self):
        """
        Returns the schedule as a dictionary for serialization.
        """
        playlist = self.playlist

        return {
            "schedule_id": self.schedule_id,        
            "schedule_start": self.schedule_start.isoformat(),
            "schedule_end": self.schedule_end.isoformat(),

            "topic": self.topic,
            "musicfocus": self.musicfocus,
            "funding_category": self.funding_category,
            "is_repetition": self.is_repetition,
            "category": self.category,
            "languages": self.languages,
            "comment": self.comment,
            "playlist_id": self.playlist_id,
            "schedule_fallback_id": self.schedule_fallback_id,
            "show_fallback_id": self.show_fallback_id,
            "station_fallback_id": self.station_fallback_id,

            "show": {
                "name": self.show_name,
251
                "type": self.get_type(),
David Trattnig's avatar
David Trattnig committed
252
253
254
255
256
257
258
                "host": self.show_hosts
            },

            "playlist": playlist
        }


259
260
261
262
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
263
264
265
266
267
        time_start = SimpleUtil.fmt_time(self.start_unix)
        time_end = SimpleUtil.fmt_time(self.end_unix)
        return "ID#%s [Show: %s, ShowID: %s | %s - %s ]" % (str(self.schedule_id), self.show_name, str(self.show_id), time_start, time_end)


268

269
class Playlist(DB.Model, AuraDatabaseModel):
270
271
272
    """
    The playlist containing playlist entries.
    """
273
274
275
276
277
278
279
280
281
282
283
284
    __tablename__ = 'playlist'

    # pk,fk
    artificial_id = Column(Integer, primary_key=True)
    schedule_start = Column(DateTime, ForeignKey("schedule.schedule_start"))
    # relationships
    schedule = relationship("Schedule", uselist=False, back_populates="playlist")
    entries = relationship("PlaylistEntry", back_populates="playlist")
    # data
    playlist_id = Column(Integer, autoincrement=False)  # , ForeignKey("schedule.playlist_id"))
    show_name = Column(String(256))
    fallback_type = Column(Integer)
285
    entry_count = Column(Integer)
286

287

288
289
    @staticmethod
    def select_all():
290
291
292
        """
        Fetches all entries
        """
293
        all_entries = DB.session.query(Playlist).filter(Playlist.fallback_type == 0).all()
294
295
296
297
298
299
300
301

        cnt = 0
        for entry in all_entries:
            entry.programme_index = cnt
            cnt = cnt + 1

        return all_entries

302

303
    @staticmethod
304
    def select_playlist_for_schedule(datetime, playlist_id):
305
306
307
308
309
310
311
312
313
314
315
316
317
        """
        Retrieves the playlist for the given schedule identified by `start_date` and `playlist_id`

        Args:
            start_date (datetime):  Date and time when the playlist is scheduled
            playlist_id (Integer):  The ID of the playlist

        Returns:
            (Playlist):             The playlist, if existing for schedule

        Raises:
            Exception:              In case there a inconsistent database state, such es multiple playlists for given date/time.
        """
David Trattnig's avatar
David Trattnig committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
        playlist = None
        playlists = DB.session.query(Playlist).filter(Playlist.schedule_start == datetime).all()
        # FIXME There are unknown issues with the native SQL query by ID
        # playlists = DB.session.query(Playlist).filter(Playlist.schedule_start == datetime and Playlist.playlist_id == playlist_id).all()
        
        for p in playlists:
            if p.playlist_id == playlist_id:
                playlist = p
        # if playlists and len(playlists) > 1:
        #     raise Exception("Inconsistent Database State: Multiple playlists for given schedule '%s' and playlist id#%d available!" % (str(datetime), playlist_id))
        # if not playlists:
        #     return None
        # return playlists[0]
        return playlist
332

333

334
335
    @staticmethod
    def select_playlist(playlist_id):
336
337
338
339
340
341
342
343
344
        """
        Retrieves all paylists for that given playlist ID.

        Args:
            playlist_id (Integer):  The ID of the playlist
        
        Returns:
            (Array<Playlist>):      An array holding the playlists
        """
345
346
        return DB.session.query(Playlist).filter(Playlist.playlist_id == playlist_id).order_by(Playlist.schedule_start).all()
    
347

348
349
350
351
352
353
354
355
356
357
358
    @staticmethod
    def is_empty():
        """
        Checks if the given is empty
        """
        try:
            return not DB.session.query(Playlist).one_or_none()
        except sa.orm.exc.MultipleResultsFound:
            return False


359
360
    @hybrid_property
    def start_unix(self):
361
362
363
        """
        Start time of the playlist in UNIX time.
        """
364
365
        return time.mktime(self.schedule_start.timetuple())

366

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    @hybrid_property
    def end_unix(self):
        """
        End time of the playlist in UNIX time.
        """
        return time.mktime(self.schedule_start.timetuple()) + self.duration


    @hybrid_property
    def duration(self):
        """
        Returns the total length of the playlist in seconds.

        Returns:
            (Integer):  Length in seconds
        """
        total = 0

        for entry in self.entries:
            total += entry.duration
        return total


David Trattnig's avatar
David Trattnig committed
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
    def as_dict(self):
        """
        Returns the playlist as a dictionary for serialization.
        """
        entries = []
        for e in self.entries:
            entries.append(e.as_dict())

        playlist = {
            "playlist_id": self.playlist_id,
            "fallback_type": self.fallback_type,
            "entry_count": self.entry_count,
            "entries": entries
        }
        return playlist


407
408
409
410
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
411
412
413
414
        time_start = SimpleUtil.fmt_time(self.start_unix)
        time_end = SimpleUtil.fmt_time(self.end_unix)
        return "ID#%s [items: %s | %s - %s]" % (str(self.playlist_id), str(self.entry_count), str(time_start), str(time_end))

415
416


417
class PlaylistEntry(DB.Model, AuraDatabaseModel):
418
419
420
    """
    Playlist entries are the individual items of a playlist such as audio files.
    """
421
    __tablename__ = 'playlist_entry'
422

423
424
    # primary keys
    artificial_id = Column(Integer, primary_key=True)
425

426
427
428
    # foreign keys
    artificial_playlist_id = Column(Integer, ForeignKey("playlist.artificial_id"))
    entry_num = Column(Integer) # , primary_key=True)
429

430
431
    uri = Column(String(1024))
    duration = Column(BigInteger)
432
    source = Column(String(1024))
433
    entry_start = Column(DateTime)
434
    entry_start_actual = None # Assigned when the entry is actually played
435
    channel = None # Assigned when entry is actually played
436
    queue_state = None # Assigned when entry is about to be queued    
David Trattnig's avatar
David Trattnig committed
437
    status = None # Assigned when state changes
David Trattnig's avatar
David Trattnig committed
438
439
440
441
    
    switchtimer = None
    loadtimer = None
    fadeouttimer = None
442

443
444
    # relationships
    playlist = relationship("Playlist", uselist=False, back_populates="entries")
445
    meta_data = relationship("PlaylistEntryMetaData", uselist=False, back_populates="entry")
446

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
447
    @staticmethod
448
449
    def select_playlistentry_for_playlist(artificial_playlist_id, entry_num):
        return DB.session.query(PlaylistEntry).filter(PlaylistEntry.artificial_playlist_id == artificial_playlist_id, PlaylistEntry.entry_num == entry_num).first()
450

451
452
453
454
    @hybrid_property
    def entry_end(self):
        return self.entry_start + datetime.timedelta(seconds=self.duration)

455
456
457
458
459
460
    @hybrid_property
    def start_unix(self):
        return time.mktime(self.entry_start.timetuple())

    @hybrid_property
    def end_unix(self):
461
        return time.mktime(self.entry_end.timetuple())
462

463
    @hybrid_property
464
    def volume(self):
465
        return 100 # FIXME Make DB Column
466

467
    def get_type(self):
468
        return EngineUtil.get_channel_type(self.uri)
469

470

471
472
473
474
475
476
477
478
479
480
481
482
483
484
    def get_prev_entries(self):
        """
        Retrieves all previous entries as part of the current entry's playlist.

        Returns:
            (List):     List of PlaylistEntry
        """
        prev_entries = []
        for entry in self.playlist.entries:
            if entry.entry_start < self.entry_start:
                prev_entries.append(entry)
        return prev_entries


485
    def get_next_entries(self, schedule_sensitive=True):
David Trattnig's avatar
David Trattnig committed
486
        """
487
        Retrieves all following entries as part of the current entry's playlist.
David Trattnig's avatar
David Trattnig committed
488

489
490
491
492
        Args:
            schedule_sensitive (Boolean):   If `True` entries which start after \
                the end of the schedule are excluded

David Trattnig's avatar
David Trattnig committed
493
494
495
496
497
498
        Returns:
            (List):     List of PlaylistEntry
        """
        next_entries = []
        for entry in self.playlist.entries:
            if entry.entry_start > self.entry_start:
499
500
501
502
503
                if schedule_sensitive:
                    if entry.entry_start < self.playlist.schedule.schedule_end:
                        next_entries.append(entry)
                else:
                    next_entries.append(entry)
David Trattnig's avatar
David Trattnig committed
504
505
        return next_entries

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
506

507
508
509
510
511
512
    def as_dict(self):
        """
        Returns the entry as a dictionary for serialization.
        """
        if self.meta_data:
            return {
David Trattnig's avatar
David Trattnig committed
513
                "id": self.artificial_id,
514
515
516
517
518
519
520
                "duration": self.duration,
                "artist": self.meta_data.artist,
                "album": self.meta_data.album,
                "title": self.meta_data.title
            }
        return None

521
522
523
524
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
525
526
        time_start = SimpleUtil.fmt_time(self.start_unix)
        time_end = SimpleUtil.fmt_time(self.end_unix)
527
528
        track = self.source[-25:]
        return "PlaylistEntry #%s [%s - %s | %ssec | Source: ...%s]" % (str(self.artificial_id), time_start, time_end, self.duration, track)
529

David Trattnig's avatar
David Trattnig committed
530

531

532

533
class PlaylistEntryMetaData(DB.Model, AuraDatabaseModel):
534
535
536
    """
    Metadata for a playlist entry such as the artist and track name.
    """
537
    __tablename__ = "playlist_entry_metadata"
538

539
540
    artificial_id = Column(Integer, primary_key=True)
    artificial_entry_id = Column(Integer, ForeignKey("playlist_entry.artificial_id"))
541

542
543
544
    artist = Column(String(256))
    title = Column(String(256))
    album = Column(String(256))
545

546
    entry = relationship("PlaylistEntry", uselist=False, back_populates="meta_data")
547

548
549
550
    @staticmethod
    def select_metadata_for_entry(artificial_playlistentry_id):
        return DB.session.query(PlaylistEntry).filter(PlaylistEntryMetaData.artificial_entry_id == artificial_playlistentry_id).first()
551

552

553
554
555
556
557
558

#
#   TRACK SERVICE
#


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
# class TrackService(DB.Model, AuraDatabaseModel):
#     """
#     TrackService holding track-service items consisting of
#     """
#     __tablename__ = 'trackservice'

#     # Primary keys
#     id = Column(Integer, primary_key=True, autoincrement=True)

#     # Foreign keys
#     track_start = Column(DateTime)
#     track_end = Column(DateTime) # Currently not used, maybe later for timing checks and multi-entry avoidance.
#     artificial_schedule_id = Column(Integer, ForeignKey("schedule.id"))
#     artificial_playlist_entry_id = Column(Integer, ForeignKey("playlist_entry.artificial_id"), nullable=True)
#     single_entry_id = Column(Integer, ForeignKey("single_entry.id"), nullable=True)

#     # Data
#     schedule = relationship("Schedule", foreign_keys=[artificial_schedule_id], lazy="joined")
#     playlist_entry = relationship("PlaylistEntry", primaryjoin="and_(TrackService.artificial_playlist_entry_id==PlaylistEntry.artificial_id)", lazy="joined")
#     single_entry = relationship("SingleEntry", foreign_keys=[single_entry_id], lazy="joined")

#     fallback_type = Column(Integer, default=0)


#     def __init__(self, entry, fallback_type=0):
#         """
#         Initializes a trackservice entry based on a playlist entry.
#         """
#         self.track_start = datetime.datetime.now()
#         # if entry.duration:
#         #     self.track_end = self.track_start + datetime.timedelta(seconds=entry.duration)
#         self.fallback_type = fallback_type

#         if fallback_type < 4:
#             self.schedule_start = entry.playlist.schedule_start
#             self.artificial_playlist_entry_id = entry.artificial_id
#             self.playlist_entry = entry
#             self.schedule = entry.playlist.schedule
#         else:
#             self.single_entry = entry


#     @hybrid_property
#     def track(self):
#         """
#         Retrieves the track information as a dictionary.
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
#         Depending on possible fallback scenarios either `playlist_entry` or `single_entry` is used as a basis:

#             - Scenario 1: No fallback, all info is gathered via the playlist entry
#             - Scenario 2: Fallback-type > 0, info is also gathered via the defined playlist entry
#             - Scenario 3: This type of fallback didn't get scheduled; a single entry is played
#         """
#         if self.playlist_entry:
#             return self.playlist_entry.as_dict()
#         elif self.single_entry:
#             return self.single_entry.as_dict()
#         else:
#             return None


#     @hybrid_property
#     def show(self):
#         """
#         Retrieves show information based on the related schedule. If no schedule
#         is available (e.g. when the engine is in a fallback state), then the default
#         show properties from `AuraConfig` are returned.
#         """
#         show_info = {}

#         if self.schedule:
#             show_info["name"] = self.schedule.show_name
#             show_info["type"] = self.schedule.type
#             show_info["host"] = self.schedule.show_hosts
#         elif self.fallback_type == 4:
#             show_info["name"] = config.get("fallback_show_name")
#             show_info["type"] = config.get("fallback_show_type")
#             show_info["host"] = config.get("fallback_show_host")
David Trattnig's avatar
David Trattnig committed
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
#         return show_info


#     @staticmethod
#     def select_one(id):
#         """
#         Select one specific track-service item by ID. 
#         """
#         DB.session.commit() # Required since independend session is used.
#         track = DB.session.query(TrackService).filter(TrackService.id == id).first()
#         return track


#     @staticmethod
#     def select_current():
#         """
#         Selects the currently playing track.
#         """
#         now = datetime.datetime.now()
#         DB.session.commit() # Required since independend session is used.
#         track = DB.session.query(TrackService).\
#             filter(TrackService.track_start <= str(now)).\
#             order_by(TrackService.track_start.desc()).first()
#         return track


#     @staticmethod
#     def select_last_hours(n):
#         """
#         Selects the tracks playing in the past (`n`) hours.
#         """
#         last_hours = datetime.datetime.today() - datetime.timedelta(hours=n)
#         DB.session.commit() # Required since independend session is used.
#         tracks = DB.session.query(TrackService).filter(TrackService.track_start >= str(last_hours)).all()
#         for track in tracks:
#             track = TrackService.select_one(track.id)
#         return tracks


#     @staticmethod
#     def select_by_day(day):
#         """
#         Select the track-service items for a day.
#         """
#         day_plus_one = day + datetime.timedelta(days=1)
#         DB.session.commit() # Required since independend session is used.
#         tracks = DB.session.query(TrackService).\
#             filter(TrackService.track_start >= str(day), TrackService.track_start < str(day_plus_one)).\
#             order_by(TrackService.track_start.desc()).all()
687
        
688
689
690
691
#         res = []
#         for item in tracks:
#             if item.track: res.append(item)
#         return res
692
693
    

694
695
696
697
698
699
700
701
702
#     @staticmethod
#     def select_by_range(from_day, to_day):
#         """
#         Selects the track-service items for a day range.
#         """
#         DB.session.commit()
#         tracks = DB.session.query(TrackService).filter(TrackService.track_start >= str(from_day),
#                                                        TrackService.track_start < str(to_day)).all()
#         return tracks
703
704
    

705
706
707
708
709
#     def __str__(self):
#         """
#         Convert to String.
#         """
#         return "TrackID: #%s [track_start: %s, artificial_playlist_entry_id: %s]" % (str(self.id), str(self.track_start), str(self.artificial_playlist_entry_id))
710
711
712



713
714
715
716
717
# class SingleEntry(DB.Model, AuraDatabaseModel):
#     """
#     An entry played in case of e.g. a local fallback or custom programming without a playlist nor schedule.
#     """
#     __tablename__ = 'single_entry'
718

719
720
#     # Primary keys
#     id = Column(Integer, primary_key=True)
721
    
722
723
724
#     # Relationships
#     trackservice_id = Column(Integer) #, ForeignKey("trackservice.id"))
#     meta_data_id = Column(Integer) #, ForeignKey("trackservice.id"))
725

726
727
#     trackservice = relationship("TrackService", uselist=False, back_populates="single_entry")
#     meta_data = relationship("SingleEntryMetaData", uselist=False, back_populates="entry")
728

729
730
731
732
733
#     # Data
#     uri = Column(String(1024))
#     duration = Column(BigInteger)
#     source = Column(String(1024))
#     entry_start = Column(DateTime)
734

735
736
737
#     queue_state = None # Assigned when entry is about to be queued
#     channel = None # Assigned when entry is actually played
#     status = None # Assigned when state changes
David Trattnig's avatar
David Trattnig committed
738

739

740
741
742
#     @hybrid_property
#     def entry_end(self):
#         return self.entry_start + datetime.timedelta(seconds=self.duration)
743

744
745
746
#     @hybrid_property
#     def start_unix(self):
#         return time.mktime(self.entry_start.timetuple())
747

748
749
750
#     @hybrid_property
#     def end_unix(self):
#         return time.mktime(self.entry_start.timetuple()) + self.duration
751

752
753
754
#     @hybrid_property
#     def volume(self):
#         return 100
755

756
757
758
#     @hybrid_property
#     def type(self):
#         return EngineUtil.get_channel_type(self.uri)
759

760

761
762
763
764
765
766
767
768
769
770
771
772
#     def as_dict(self):
#         """
#         Returns the entry as a dictionary for serialization.
#         """
#         if self.meta_data:
#             return {
#                 "duration": self.duration,
#                 "artist": self.meta_data.artist,
#                 "album": self.meta_data.album,
#                 "title": self.meta_data.title
#             }
#         return None
773
774


775
776
777
778
779
780
781
782
#     def __str__(self):
#         """
#         String representation of the object.
#         """
#         time_start = SimpleUtil.fmt_time(self.start_unix)
#         time_end = SimpleUtil.fmt_time(self.end_unix)
#         track = self.source[-25:]
#         return "SingleEntry #%s [%s - %s | %ssec | Source: ...%s]" % (str(self.id), time_start, time_end, self.duration, track)
783
784
785



786
787
788
789
790
# class SingleEntryMetaData(DB.Model, AuraDatabaseModel):
#     """
#     Metadata for a autonomous entry such as the artist and track name.
#     """
#     __tablename__ = "single_entry_metadata"
791

792
793
#     id = Column(Integer, primary_key=True)
#     single_entry_id = Column(Integer, ForeignKey("single_entry.id"))
794

795
796
797
#     artist = Column(String(256))
#     title = Column(String(256))
#     album = Column(String(256))
798

799
#     entry = relationship("SingleEntry", uselist=False, back_populates="meta_data")
800

801
802
803
#     @staticmethod
#     def select_metadata_for_entry(single_entry_id):
#         return DB.session.query(SingleEntry).filter(SingleEntryMetaData.id == single_entry_id).first()
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894


#
#   LEGACY CLASSES
#



# ------------------------------------------------------------------------------------------ #
# class Schedule(DB.Model, AuraDatabaseModel):
#     """
#     One specific Schedule for a show on a timeslot
#     """
#     __tablename__ = 'schedule'
#
#     # primary and foreign keys
#     schedule_start = Column(DateTime, primary_key=True)
#
#     schedule_end = Column(DateTime)
#     schedule_id = Column(Integer) #, primary_key=True, autoincrement=False)
#     show_id = Column(Integer)  # well, in fact not needed..
#     show_name = Column(String(256))
#     show_hosts = Column(String(256))
#     funding_category = Column(String(256))
#     comment = Column(String(512))
#     languages = Column(String(256))
#     type = Column(String(256))
#     category = Column(String(256))
#     topic = Column(String(256))
#     musicfocus = Column(String(256))
#
#     is_repetition = Column(Boolean())
#
#     playlist_id = Column(Integer, ForeignKey("playlist.playlist_id"))
#     timeslot_fallback_id = Column(Integer)
#     show_fallback_id = Column(Integer)
#     station_fallback_id = Column(Integer)
#
#     playlist = relationship("Playlist", foreign_keys=[playlist_id], lazy="joined")
#  #    timeslot_fallback = relationship("Playlist", foreign_keys=[timeslot_fallback_id], lazy="joined")
#  #    show_fallback = relationship("Playlist", foreign_keys=[show_fallback_id], lazy="joined")
#  #    station_fallback = relationship("Playlist", foreign_keys=[station_fallback_id], lazy="joined")
#
#     @staticmethod
#     def select_all():
#          # fetching all entries
#         all_entries = DB.session.query(Schedule).filter().order_by(Schedule.schedule_start).all()
#         return all_entries
#
#     @staticmethod
#     def select_by_id(id):
#         entry = DB.session.query(Schedule).filter(Schedule.schedule_id == id).first()
#         return entry
#     @staticmethod
#     def select_act_programme():
#          #DB.session.query(Schedule).filter
#          # fetching all from today to ..
#         today = datetime.date.today()
#         all_entries = DB.session.query(Schedule).filter(Schedule.schedule_start >= today).order_by(Schedule.schedule_start).all()
#
#         return all_entries
#

#
#     @staticmethod
#     def drop_the_future(timedelta):
#         then = datetime.datetime.now() + timedelta
#
#         # is this really necessary?
#         future_entries = DB.session.query(Schedule).filter(Schedule.schedule_start > then)
#         for e in future_entries:
#             e.delete()
#         DB.session.commit()
#
#     def get_length(self):
#         sec1 = int(datetime.datetime.strptime(self.start[0:16].replace(" ", "T"), "%Y-%m-%dT%H:%M").strftime("%s"))
#         sec2 = int(datetime.datetime.strptime(self.end[0:16].replace(" ", "T"), "%Y-%m-%dT%H:%M").strftime("%s"))
#         len = sec2 - sec1
#         return len
#
#     # ------------------------------------------------------------------------------------------ #
#     def __str__(self):
#         return "ScheduleID: #" + str(self.schedule_id) + " Showname: " + self.show_name + " starts @ " + str(self.schedule_start)

# ------------------------------------------------------------------------------------------ #



895
# ------------------------------------------------------------------------------------------ #
896
897
898
899
900
901
902
903
904
#class PlaylistEntry(DB.Model, AuraDatabaseModel):
    # __tablename__ = 'playlist_entry'
    #
    # # primary and foreign keys
    # playlist_id = Column(Integer, ForeignKey("playlist.playlist_id"), primary_key=True, nullable=False, autoincrement=True)
    # entry_num = Column(Integer, primary_key=True, nullable=False, autoincrement=False)
    #
    # uri = Column(String(1024))
    #
905
    # source = ""
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
    # cleansource = ""
    # cleanprotocol = ""
    # type = None
    # fadeintimer = None
    # fadeouttimer = None
    # switchtimer = None
    #
    # meta_data = relationship("PlaylistEntryMetaData", primaryjoin="and_(PlaylistEntry.playlist_id==PlaylistEntryMetaData.playlist_id, PlaylistEntry.entry_num==PlaylistEntryMetaData.entry_num)", lazy="joined")
    #
    # # normal constructor
    # def __init__(self, **kwargs):
    #     super(PlaylistEntry, self).__init__(**kwargs)
    #     self.calc_unix_times()
    #     self.define_clean_source()
    #
    # # constructor like - called from sqlalchemy
    # @orm.reconstructor
    # def reconstructor(self):
    #     self.calc_unix_times()
    #     self.define_clean_source()
    #     self.set_entry_type()
    #
    # def define_clean_source(self):
    #     if self.uri is None:
    #         return None
    #
    #     if self.uri.startswith("http"):
    #         self.cleanprotocol = self.uri[:7]
    #         self.cleansource = self.uri
    #
    #     elif self.uri.startswith("linein"):
    #         self.cleanprotocol = self.uri[:9]
    #         self.cleansource = self.uri[9:]
    #
    #     elif self.uri.startswith("pool") or self.uri.startswith("file") or self.uri.startswith("live"):
    #         self.cleanprotocol = self.uri[:7]
    #         self.cleansource = self.uri[7:]
    #
    #     elif self.uri.startswith("playlist"):
    #         self.cleanprotocol = self.uri[:11]
    #         self.cleansource = self.uri[11:]
    #
    #     else:
    #         self.logger.error("Unknown source protocol")
    #
    # def set_entry_type(self):
    #     if self.uri.startswith("http"):
David Trattnig's avatar
David Trattnig committed
953
    #         self.type = ScheduleEntryType.HTTP
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    #     if self.uri.startswith("pool") or self.uri.startswith("playlist") or self.uri.startswith("file"):
    #         self.type = ScheduleEntryType.FILESYSTEM
    #     if self.uri.startswith("live") or self.uri.startswith("linein"):
    #         if self.cleansource == "0":
    #             self.type = ScheduleEntryType.LIVE_0
    #         elif self.cleansource == "1":
    #             self.type = ScheduleEntryType.LIVE_1
    #         elif self.cleansource == "2":
    #             self.type = ScheduleEntryType.LIVE_2
    #         elif self.cleansource == "3":
    #             self.type = ScheduleEntryType.LIVE_3
    #         elif self.cleansource == "4":
    #             self.type = ScheduleEntryType.LIVE_4




    # def calc_unix_times(self):
    #     if self.entry_start is not None:
    #         self.entry_start_unix = time.mktime(self.entry_start.timetuple())
    #
    #
    #
    # # ------------------------------------------------------------------------------------------ #
    # @staticmethod
    # def select_all():
    #     # fetching all entries
    #     all_entries = DB.session.query(Playlist).filter(Playlist.fallback_type == 0).order_by(Playlist.entry_start).all()
    #
    #     cnt = 0
    #     for entry in all_entries:
    #         entry.programme_index = cnt
    #         cnt = cnt + 1
    #
    #     return all_entries
    #
    # @staticmethod
    # def select_act_programme(include_act_playing = True):
    #     # fetching all from today to ..
    #     today = datetime.date.today()
    #     all_entries = DB.session.query(Playlist).filter(Playlist.entry_start >= today, Playlist.fallback_type == 0).order_by(Playlist.entry_start).all()
    #
    #     cnt = 0
    #     for entry in all_entries:
    #         entry.programme_index = cnt
    #         cnt = cnt + 1
    #