broadcasts.py 6.14 KB
Newer Older
1
2
3
__author__ = 'michel'
# -*- coding: utf-8 -*-

4
import datetime, os, urllib, sys
5
import decimal
6

7
8
from sqlalchemy import Boolean, Column, Date, DateTime, Float, Integer, String, Text, Time, ForeignKey
from libraries.database.database import db
9

10

11
class Model:
12
13
14
15
16
17
18
19
    def store(self, commit=False):
        db.session.add(self)
        if commit:
            self.commit()

    def commit(self):
        db.session.commit()

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#    def dump_datetime(self, value):
#        """Deserialize datetime object into string form for JSON processing."""
#        if value is None:
#            return None
#        return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

    def alchemy_encoder(obj):
        """JSON encoder function for SQLAlchemy special classes."""
        if isinstance(obj, datetime.date):
            return obj.isoformat()
        elif isinstance(obj, decimal.Decimal):
            return float(obj)

    def _asdict(self):
        return self.__dict__
35
36


37
# ------------------------------------------------------------------------------------------ #
38
class ScheduleModel(Model):
39
40
41
42
43
44
45
    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


46
47
# ------------------------------------------------------------------------------------------ #
class ScheduleEntryModel(Model):
48
49
50
    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def upcoming(datefrom=datetime.datetime.now()):
51
        upcomingtracks = ScheduleEntry.query.filter(ScheduleEntry.start > datefrom).all()
52
53
54
55
56
        return upcomingtracks

    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def select_all():
57
58
59
60
61
        return ScheduleEntry.query.filter().all()

    @staticmethod
    def select_one(playlist_id, entry_num):
        return ScheduleEntry.query.filter(ScheduleEntry.playlist_id == playlist_id, ScheduleEntry.entry_num == entry_num).first()
62
63

    def __str__(self):
64
65
        return "ScheduleEntry starts @ " + ScheduleEntry.entry_start + " and ends @ " + ScheduleEntry.entry_end + " and plays " + ScheduleEntry.source

66

67
# ------------------------------------------------------------------------------------------ #
68
class Schedule(db.Model, ScheduleModel):
69
    """
70
    One specific Schedule for a show on a timeslot
71
    """
72
73
    __tablename__ = 'schedule'
    schedule_id = Column(Integer, primary_key=True, autoincrement=False)
74
75
    show_id = Column(Integer)

76
77
78
79
80
81
82
83
84
85
86
    schedule_start = Column(DateTime, nullable=False)
    schedule_end = Column(DateTime, nullable=False)
    show_name = Column(String(256))
    show_hosts = Column(String(256))
    rtr_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))
87
88
89

    is_repetition = Column(Boolean())

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    playlist_id = Column(Integer)
    timeslot_fallback_id = Column(Integer)
    show_fallback_id = Column(Integer)
    station_fallback_id = Column(Integer)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'schedule_id': self.schedule_id,
            'show_id': self.show_id,
            'schedule_start': self.dump_datetime(self.schedule_start),
            'schedule_end': self.dump_datetime(self.schedule_end),
            'show_name': self.show_name,
            'show_hosts': self.show_hosts,
            'is_repetition': self.is_repetition,
            'fallback_playlist': self.fallback_playlist,
            'fallback_pool': self.fallback_pool,
            'station_fallback_pool': self.station_fallback_pool
        }
110
111


112
113
# ------------------------------------------------------------------------------------------ #
class ScheduleEntry(db.Model, ScheduleEntryModel):
114
    """
115
    One schedule can have multiple entries
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
    __tablename__ = 'schedule_entry'

    playlist_id = Column(Integer, primary_key=True, nullable=False, autoincrement=False)
    entry_num = Column(Integer, primary_key=True, nullable=False, autoincrement=False)
    schedule_id = Column(Integer, ForeignKey("schedule.schedule_id"))
    entry_start = Column(DateTime, nullable=False)
    entry_end = Column(DateTime, nullable=False)
    source = Column(String(256))
    artist = Column(String(256))
    track = Column(String(256))
    albumname = Column(String(256))
    genre = Column(String(256))
    tracknum = Column(String(256))
    cdnum = Column(String(256))
    year = Column(String(5)) # well should be int, but can also be ""

#    def __init__(self, playlist_id, entry_num, schedule_id, entry_start, entry_end, source, artist, track, albumname, genre, tracknum, cdnum, year):
#        self.playlist_id = playlist_id
#        self.entry_num = entry_num
#        self.schedule_id = schedule_id
#        self.entry_start = entry_start
#        self.entry_end = entry_end
#        self.source = source
#        self.artist = artist
#        self.track = track
#        self.albumname = albumname
#        self.genre = genre
#        self.tracknum = tracknum
#        self.cdnum = cdnum
#        self.year = year

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        return {
            'schedule_id': self.schedule_id,
            'entry_start': self.dump_datetime(self.entry_start),
            'entry_end': self.dump_datetime(self.entry_end),
            'source': self.source
        }
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

#class Trackservice(db.Model, Model):
#    """
#    Trackservice and Logging
#    """
#    __tablename__ = 'trackservice'
#    id = Column(Integer, primary_key=True)
#    show_id = Column(Integer, ForeignKey("timeslot.id"))


def recreateDB():
    print("Recreating Database...")
    db.drop_all()
    print("all dropped. creating...")
    db.create_all()
    print("all created. commiting...")
    db.session.commit()
    print("Database recreated!")
    sys.exit(0)

#recreateDB()