models.py 18.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

27
28
29
30
31
32
33
34
35
from sqlalchemy.ext.declarative     import declarative_base
from sqlalchemy                     import orm
from sqlalchemy                     import BigInteger, Boolean, Column, DateTime, Integer, String, ForeignKey
from sqlalchemy.orm                 import relationship
from sqlalchemy.ext.hybrid          import hybrid_property

from src.base.config                import AuraConfig
from src.base.utils                 import SimpleUtil
from src.core.resources             import ResourceUtil
David Trattnig's avatar
David Trattnig committed
36

37

David Trattnig's avatar
David Trattnig committed
38

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

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

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


52
53

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

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

61

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

68

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

80

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

89

90
91
92
93
94
95
96
97
    def refresh(self):
        """
        Refreshes the currect record
        """
        DB.session.expire(self)
        DB.session.refresh(self)


98
99
    def _asdict(self):
        return self.__dict__
100

101

102
103
    @staticmethod
    def recreate_db(systemexit = False):
104
105
106
        """
        Re-creates the database for developments purposes.
        """
107
108
109
        manualtimeslot = Timeslot()
        manualtimeslot.timeslot_id = 0
        manualtimeslot.show_name = "Manual Show"
110
111
112
113
        Base.metadata.drop_all()
        Base.metadata.create_all()

        
114
115
116
        # self.logger.debug("inserting manual scheduling possibility and fallback trackservice timeslot")
        # DB.session.add(manualtimeslot)
        # db.session.add(fallback_trackservice_timeslot)
117
        # self.logger.debug("all created. commiting...")
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
118
        DB.session.commit()
119

120
121
        if systemexit:
            sys.exit(0)
122

123

124
125

#
126
#   SCHEDULES & PLAYLISTS
127
128
#

129

130
class Timeslot(DB.Model, AuraDatabaseModel):
131
    """
132
    One specific Timeslot for a show on a timeslot.
133
    Holding references to playlists and fallback-playlists.
134
    """
135
    __tablename__ = 'timeslot'
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
136

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

140
141
142
    timeslot_start = Column(DateTime, unique=True, index=True)
    timeslot_end = Column(DateTime, unique=True, index=True)
    timeslot_id = Column(Integer, unique=True)
143

144
    show_id = Column(Integer)
145
146
    show_name = Column(String(256))
    show_hosts = Column(String(256))
147
    funding_category = Column(String(256))
148
149
150
151
152
153
    comment = Column(String(512))
    languages = Column(String(256))
    type = Column(String(256))
    category = Column(String(256))
    topic = Column(String(256))
    musicfocus = Column(String(256))
154
155
156

    is_repetition = Column(Boolean())

157
    playlist_id = Column(Integer) #, ForeignKey("playlist.playlist_id"))
David Trattnig's avatar
David Trattnig committed
158
    schedule_fallback_id = Column(Integer)
159
160
    show_fallback_id = Column(Integer)
    station_fallback_id = Column(Integer)
David Trattnig's avatar
David Trattnig committed
161
    
162
    fadeouttimer = None # Used to fade-out the timeslot, even when entries are longer
163

164
    playlist = relationship("Playlist",
165
166
                            primaryjoin="and_(Timeslot.timeslot_start==Playlist.timeslot_start, Timeslot.playlist_id==Playlist.playlist_id, Timeslot.show_name==Playlist.show_name)",
                            back_populates="timeslot")
David Trattnig's avatar
David Trattnig committed
167
    schedule_fallback = relationship("Playlist",
168
169
                            primaryjoin="and_(Timeslot.timeslot_start==Playlist.timeslot_start, Timeslot.schedule_fallback_id==Playlist.playlist_id, Timeslot.show_name==Playlist.show_name)",
                            back_populates="timeslot")
170
    show_fallback = relationship("Playlist",
171
172
                            primaryjoin="and_(Timeslot.timeslot_start==Playlist.timeslot_start, Timeslot.show_fallback_id==Playlist.playlist_id, Timeslot.show_name==Playlist.show_name)",
                            back_populates="timeslot")
173
    station_fallback = relationship("Playlist",
174
175
                            primaryjoin="and_(Timeslot.timeslot_start==Playlist.timeslot_start, Timeslot.station_fallback_id==Playlist.playlist_id, Timeslot.show_name==Playlist.show_name)",
                            back_populates="timeslot")
176

177

178
    @staticmethod
179
    def select_show_on_datetime(date_time):
180
        return DB.session.query(Timeslot).filter(Timeslot.timeslot_start == date_time).first()
181

182

183
    @staticmethod
184
185
    def select_programme(date_from=datetime.date.today()):
        """
186
        Select all timeslots starting from `date_from` or from today if no
187
188
189
        parameter is passed.

        Args:
190
            date_from (datetime):   Select timeslots from this date and time on
191
192

        Returns:
193
            ([Timeslot]):           List of timeslots
194
        """
195
196
197
        timeslots = DB.session.query(Timeslot).\
            filter(Timeslot.timeslot_start >= date_from).\
            order_by(Timeslot.timeslot_start).all()
198

199
        return timeslots
200

201

David Trattnig's avatar
David Trattnig committed
202
203
204
    @staticmethod
    def select_upcoming(n):
        """
205
        Selects the (`n`) upcoming timeslots.
David Trattnig's avatar
David Trattnig committed
206
207
208
        """
        now = datetime.datetime.now()
        DB.session.commit() # Required since independend session is used.
209
210
211
        timeslots = DB.session.query(Timeslot).\
            filter(Timeslot.timeslot_start > str(now)).\
            order_by(Timeslot.timeslot_start.asc()).limit(n).all()
David Trattnig's avatar
David Trattnig committed
212
        
213
        return timeslots
David Trattnig's avatar
David Trattnig committed
214
215


David Trattnig's avatar
David Trattnig committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    def get_playlist(self):
        """
        Returns the assigned playlist.
        """
        # TODO Refactor to avoid storing array of playlists.
        if self.playlist and self.playlist[0]:
            return self.playlist[0]
        return None


    def has_queued_entries(self):
        """
        Checks if entries of this timeslot have been queued at the engine.        
        """
        #TODO Make logic more transparent
        if hasattr(self, "queued_entries"):
            if len(self.queued_entries) > 0:    
                return True
        return False


David Trattnig's avatar
David Trattnig committed
237
238
239
    @hybrid_property
    def start_unix(self):
        """
240
        Start time of the timeslot in UNIX time.
David Trattnig's avatar
David Trattnig committed
241
        """
242
        return time.mktime(self.timeslot_start.timetuple())
David Trattnig's avatar
David Trattnig committed
243
244
245
246
247


    @hybrid_property
    def end_unix(self):
        """
248
        End time of the timeslot in UNIX time.
David Trattnig's avatar
David Trattnig committed
249
        """
250
        return time.mktime(self.timeslot_end.timetuple())
David Trattnig's avatar
David Trattnig committed
251
252


David Trattnig's avatar
David Trattnig committed
253
254
    def as_dict(self):
        """
255
        Returns the timeslot as a dictionary for serialization.
David Trattnig's avatar
David Trattnig committed
256
257
258
259
        """
        playlist = self.playlist

        return {
260
261
262
            "timeslot_id": self.timeslot_id,        
            "timeslot_start": self.timeslot_start.isoformat(),
            "timeslot_end": self.timeslot_end.isoformat(),
David Trattnig's avatar
David Trattnig committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

            "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,
                "host": self.show_hosts
            },

            "playlist": playlist
        }


285
286
287
288
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
289
290
        time_start = SimpleUtil.fmt_time(self.start_unix)
        time_end = SimpleUtil.fmt_time(self.end_unix)
291
        return "ID#%s [Show: %s, ShowID: %s | %s - %s ]" % (str(self.timeslot_id), self.show_name, str(self.show_id), time_start, time_end)
David Trattnig's avatar
David Trattnig committed
292
293


294

295
class Playlist(DB.Model, AuraDatabaseModel):
296
297
298
    """
    The playlist containing playlist entries.
    """
299
300
301
302
    __tablename__ = 'playlist'

    # pk,fk
    artificial_id = Column(Integer, primary_key=True)
303
    timeslot_start = Column(DateTime, ForeignKey("timeslot.timeslot_start"))
304
    # relationships
305
    timeslot = relationship("Timeslot", uselist=False, back_populates="playlist")
306
307
    entries = relationship("PlaylistEntry", back_populates="playlist")
    # data
308
    playlist_id = Column(Integer, autoincrement=False)  # , ForeignKey("timeslot.playlist_id"))
309
    show_name = Column(String(256))
310
    entry_count = Column(Integer)
311

312

313
314
    @staticmethod
    def select_all():
315
316
317
        """
        Fetches all entries
        """
318
        all_entries = DB.session.query(Playlist).filter(Playlist.fallback_type == 0).all()
319
320
321
322
323
324
325
326

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

        return all_entries

327

328
    @staticmethod
329
    def select_playlist_for_timeslot(start_date, playlist_id):
330
        """
331
        Retrieves the playlist for the given timeslot identified by `start_date` and `playlist_id`
332
333
334
335
336
337

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

        Returns:
338
            (Playlist):             The playlist, if existing for timeslot
339
340
341
342

        Raises:
            Exception:              In case there a inconsistent database state, such es multiple playlists for given date/time.
        """
David Trattnig's avatar
David Trattnig committed
343
        playlist = None
344
        playlists = DB.session.query(Playlist).filter(Playlist.timeslot_start == start_date).all()
David Trattnig's avatar
David Trattnig committed
345
        # FIXME There are unknown issues with the native SQL query by ID
346
        # playlists = DB.session.query(Playlist).filter(Playlist.timeslot_start == datetime and Playlist.playlist_id == playlist_id).all()
David Trattnig's avatar
David Trattnig committed
347
348
349
350
        
        for p in playlists:
            if p.playlist_id == playlist_id:
                playlist = p
351

David Trattnig's avatar
David Trattnig committed
352
        return playlist
353

354

355
356
    @staticmethod
    def select_playlist(playlist_id):
357
358
359
360
361
362
363
364
365
        """
        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
        """
366
        return DB.session.query(Playlist).filter(Playlist.playlist_id == playlist_id).order_by(Playlist.timeslot_start).all()
367
    
368

369
370
371
372
373
374
375
376
377
378
379
    @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


380
381
    @hybrid_property
    def start_unix(self):
382
383
384
        """
        Start time of the playlist in UNIX time.
        """
385
        return time.mktime(self.timeslot_start.timetuple())
386

387

388
389
390
391
392
    @hybrid_property
    def end_unix(self):
        """
        End time of the playlist in UNIX time.
        """
393
        return time.mktime(self.timeslot_start.timetuple()) + self.duration
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410


    @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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
    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


428
429
430
431
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
432
433
434
435
        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))

436
437


438
class PlaylistEntry(DB.Model, AuraDatabaseModel):
439
440
441
    """
    Playlist entries are the individual items of a playlist such as audio files.
    """
442
    __tablename__ = 'playlist_entry'
443

444
445
    # primary keys
    artificial_id = Column(Integer, primary_key=True)
446

447
448
449
    # foreign keys
    artificial_playlist_id = Column(Integer, ForeignKey("playlist.artificial_id"))
    entry_num = Column(Integer) # , primary_key=True)
450

451
452
    uri = Column(String(1024))
    duration = Column(BigInteger)
453
    source = Column(String(1024))
454
    entry_start = Column(DateTime)
455
    entry_start_actual = None # Assigned when the entry is actually played
456
    channel = None # Assigned when entry is actually played
457
    queue_state = None # Assigned when entry is about to be queued    
David Trattnig's avatar
David Trattnig committed
458
    status = None # Assigned when state changes
David Trattnig's avatar
David Trattnig committed
459
460
461
462
    
    switchtimer = None
    loadtimer = None
    fadeouttimer = None
463

464
465
    # relationships
    playlist = relationship("Playlist", uselist=False, back_populates="entries")
466
    meta_data = relationship("PlaylistEntryMetaData", uselist=False, back_populates="entry")
467

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
468
    @staticmethod
469
    def select_playlistentry_for_playlist(artificial_playlist_id, entry_num):
470
471
472
        """
        Selects one entry identified by `playlist_id` and `entry_num`.
        """
473
        return DB.session.query(PlaylistEntry).filter(PlaylistEntry.artificial_playlist_id == artificial_playlist_id, PlaylistEntry.entry_num == entry_num).first()
474

475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
    @staticmethod
    def delete_entry(artificial_playlist_id, entry_num):
        """
        Deletes the playlist entry and associated metadata.
        """
        entry = PlaylistEntry.select_playlistentry_for_playlist(artificial_playlist_id, entry_num)
        metadata = PlaylistEntryMetaData.select_metadata_for_entry(entry.artificial_id)
        metadata.delete()
        entry.delete()
        DB.session.commit()

    @staticmethod
    def count_entries(artificial_playlist_id):
        """
        Returns the count of all entries.
        """
        result = DB.session.query(PlaylistEntry).filter(PlaylistEntry.artificial_playlist_id == artificial_playlist_id).count()
        return result

494
495
496
497
    @hybrid_property
    def entry_end(self):
        return self.entry_start + datetime.timedelta(seconds=self.duration)

498
499
500
501
502
503
    @hybrid_property
    def start_unix(self):
        return time.mktime(self.entry_start.timetuple())

    @hybrid_property
    def end_unix(self):
504
        return time.mktime(self.entry_end.timetuple())
505

506
    @hybrid_property
507
    def volume(self):
508
        return 100 # FIXME Make DB Column
509

David Trattnig's avatar
David Trattnig committed
510
511
    def get_content_type(self):
        return ResourceUtil.get_content_type(self.uri)
512

513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
    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


528
    def get_next_entries(self, timeslot_sensitive=True):
David Trattnig's avatar
David Trattnig committed
529
        """
530
        Retrieves all following entries as part of the current entry's playlist.
David Trattnig's avatar
David Trattnig committed
531

532
        Args:
533
534
            timeslot_sensitive (Boolean):   If `True` entries which start after \
                the end of the timeslot are excluded
535

David Trattnig's avatar
David Trattnig committed
536
537
538
539
540
541
        Returns:
            (List):     List of PlaylistEntry
        """
        next_entries = []
        for entry in self.playlist.entries:
            if entry.entry_start > self.entry_start:
542
543
                if timeslot_sensitive:
                    if entry.entry_start < self.playlist.timeslot.timeslot_end:
544
545
546
                        next_entries.append(entry)
                else:
                    next_entries.append(entry)
David Trattnig's avatar
David Trattnig committed
547
548
        return next_entries

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
549

550
551
552
553
554
555
    def as_dict(self):
        """
        Returns the entry as a dictionary for serialization.
        """
        if self.meta_data:
            return {
David Trattnig's avatar
David Trattnig committed
556
                "id": self.artificial_id,
557
558
559
560
561
562
563
                "duration": self.duration,
                "artist": self.meta_data.artist,
                "album": self.meta_data.album,
                "title": self.meta_data.title
            }
        return None

564
565
566
567
    def __str__(self):
        """
        String representation of the object.
        """
David Trattnig's avatar
David Trattnig committed
568
569
        time_start = SimpleUtil.fmt_time(self.start_unix)
        time_end = SimpleUtil.fmt_time(self.end_unix)
570
571
        track = self.source[-25:]
        return "PlaylistEntry #%s [%s - %s | %ssec | Source: ...%s]" % (str(self.artificial_id), time_start, time_end, self.duration, track)
572

David Trattnig's avatar
David Trattnig committed
573

574

575

576
class PlaylistEntryMetaData(DB.Model, AuraDatabaseModel):
577
578
579
    """
    Metadata for a playlist entry such as the artist and track name.
    """
580
    __tablename__ = "playlist_entry_metadata"
581

582
583
    artificial_id = Column(Integer, primary_key=True)
    artificial_entry_id = Column(Integer, ForeignKey("playlist_entry.artificial_id"))
584

585
586
587
    artist = Column(String(256))
    title = Column(String(256))
    album = Column(String(256))
588

589
    entry = relationship("PlaylistEntry", uselist=False, back_populates="meta_data")
590

591
592
    @staticmethod
    def select_metadata_for_entry(artificial_playlistentry_id):
593
        return DB.session.query(PlaylistEntryMetaData).filter(PlaylistEntryMetaData.artificial_entry_id == artificial_playlistentry_id).first()
594
595