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

4
import datetime, os, urllib, sys
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
5
import time
6
import decimal
7

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
8
from sqlalchemy import Boolean, Column, Date, DateTime, Float, Integer, String, Text, Time, ForeignKey, ForeignKeyConstraint
9
from sqlalchemy.orm import relationship
10
from libraries.database.database import db
11

12

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
13
class AuraDatabaseModel:
14
    def store(self, commit=False):
15
16
17
        obj_session = db.session.object_session(self)
        if obj_session is not None:
            obj_session.add(self)
18
            if commit:
19
20
21
22
23
                obj_session.commit()

        db.session.add(self)
        if commit:
            db.session.commit()
24
25

    def delete(self, commit=False):
26
        obj_session = db.session.object_session(self)
27

28
29
30
31
        if obj_session is not None:
            obj_session.delete(self)
            if commit:
                obj_session.commit()
32

33
34
35
        db.session.delete(self)
        if commit:
            db.session.commit()
36

37
38
    def _asdict(self):
        return self.__dict__
39

40
    @staticmethod
41
42
43
44
    def recreate_db(systemexit = False):
        manualschedule = Schedule()
        manualschedule.schedule_id = 0

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
45
46
47
        fallback_trackservice_schedule = TrackServiceSchedule()
        fallback_trackservice_schedule.ts_schedule_id = 0

48
49
50
51
        print("Recreating Database...")
        db.drop_all()
        print("all dropped. creating...")
        db.create_all()
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
52
        print("inserting manual scheduling possibility and fallback trackservice schedule")
53
        db.session.add(manualschedule)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
54
        db.session.add(fallback_trackservice_schedule)
55
56
57
        print("all created. commiting...")
        db.session.commit()
        print("Database recreated!")
58

59
60
        if systemexit:
            sys.exit(0)
61

62

63
# ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
64
class Schedule(db.Model, AuraDatabaseModel):
65
    """
66
    One specific Schedule for a show on a timeslot
67
    """
68
    __tablename__ = 'schedule'
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
69
70

    # primary and foreign keys
71
    schedule_id = Column(Integer, primary_key=True, autoincrement=False)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
72
    show_id = Column(Integer) # well, not needed..
73

74
75
    schedule_start = Column(DateTime) # can be null due to manual entries
    schedule_end = Column(DateTime) # can be null due to manual entries
76
77
78
79
80
81
82
83
84
    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))
85
86
87

    is_repetition = Column(Boolean())

88
89
90
91
92
    playlist_id = Column(Integer)
    timeslot_fallback_id = Column(Integer)
    show_fallback_id = Column(Integer)
    station_fallback_id = Column(Integer)

93
94
95
96
97
98
    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

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    @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
        }
114
115


116
# ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
117
class ScheduleEntry(db.Model, AuraDatabaseModel):
118
    """
119
    One schedule can have multiple entries
120
    """
121
122
    __tablename__ = 'schedule_entry'

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
123
    # primary and foreign keys
124
125
126
    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"))
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
127

128
    entry_start = Column(DateTime, nullable=False)
129
    entry_end = Column(DateTime)
130
131
132
133
134
135
136
    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))
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
137
138
    year = Column(Integer())
    volume = Column(Integer, default=100)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
139
140
    entry_start_unix = 0
    entry_end_unix = 0
141
    programme_index = -1
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
142

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
143
    ForeignKeyConstraint(['schedule_id'], ['schedule.schedule_id'])
144
145
    schedule = relationship("Schedule", foreign_keys=[schedule_id])

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
    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def select_all():
        # when deleting all entries, and fetching new programmes, the entries are stored and commited in the code.
        # but sqlalchemy thinks somehow it is not commit and returns an empty set

        print("WARNING: broadcasts.py This commit before SELECT is a BAND-AID & UGLY-HACK. Why the hell is there a transaction pending and not commited?")
        db.session.commit()

        # fetching all
        # all_entries = ScheduleEntry.query.filter().all()
        all_entries = db.session.query(ScheduleEntry).filter().all()

        # BAND-AID debug output. The model and db session are different. crap
        print("SELECT ALL ScheduleEntry.q.session == db.session?")
        print(ScheduleEntry.query.session == db.session)
        print("SELECT ALL ScheduleEntry.q.s.conn == db.s.conn?")
        print(ScheduleEntry.query.session.connection() == db.session.connection())

        cnt = 0
        for entry in all_entries:
            entry.programme_index = cnt
            entry.entry_start_unix = time.mktime(entry.entry_start.timetuple())
            if entry.entry_end is not None:
                entry.entry_end_unix = time.mktime(entry.entry_end.timetuple())
            cnt = cnt + 1

        return all_entries

    @staticmethod
    def select_next_manual_entry_num():
        from sqlalchemy import func
        # damn BAND-AID
        db.session.commit()

        #subqry = db.session.query(func.max(ScheduleEntry.entry_num)).filter(ScheduleEntry.schedule_id = 0)
        #qry = db.session.query(Data).filter(Data.user_id == user_id, Data.counter == subqry)

        max_manual_entry_num = db.session.query(func.max(ScheduleEntry.entry_num)).filter(ScheduleEntry.schedule_id == 0).first()
        print(max_manual_entry_num)

        if max_manual_entry_num[0] is None:
            return 0
        else:
            return int(max_manual_entry_num[0])+1

#        print("returning", res)

#        return res

    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def upcoming(datefrom=datetime.datetime.now()):
        # damn BAND-AID
        db.session.commit()

        upcomingtracks = db.session.query(ScheduleEntry).filter(ScheduleEntry.start > datefrom).all()
        #upcomingtracks = ScheduleEntry.query.filter(ScheduleEntry.start > datefrom).all()
        return upcomingtracks

    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def select_one(playlist_id, entry_num):
        # damn BAND-AID
        db.session.commit()

        one = db.session.query(ScheduleEntry).filter(ScheduleEntry.playlist_id == playlist_id, ScheduleEntry.entry_num == entry_num).first()
        return one

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

219

220
# ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
221
class TrackServiceSchedule(db.Model, AuraDatabaseModel):
222
223
224
225
    """
    Trackservice is tracking every schedule.
    """
    __tablename__ = 'trackservice_schedule'
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
226
227

    # primary and foreign keys
228
    ts_schedule_id = Column(Integer, primary_key=True, autoincrement=True)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
229
230
231
232
233
234
235
236
237
    schedule_id = Column(Integer, ForeignKey("schedule.schedule_id"))

    # ------------------------------------------------------------------------------------------ #
    @staticmethod
    def select_one(schedule_id):
        # damn BAND-AID
        db.session.commit()

        return db.session.query(ScheduleEntry).filter(TrackServiceSchedule.schedule_id == schedule_id).first()
238
239


240
# ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
241
class TrackServiceScheduleEntry(db.Model, AuraDatabaseModel):
242
243
244
245
    """
    And a schedule can have multiple entries
    """
    __tablename__ = 'trackservice_entry'
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
246
247

    # primary and foreign keys. the foreign keys here can be null, because of fallback stuff
248
    ts_entry_id = Column(Integer, primary_key=True, autoincrement=True)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
249
250
251
252
253
254
255
256
257
258
259
    ts_schedule_id = Column(Integer, ForeignKey("trackservice_schedule.ts_schedule_id"), nullable=True)
    playlist_id = Column(Integer, nullable=True)
    entry_num = Column(Integer, nullable=True)

    fallback = Column(Boolean, default=False)
    fallback_start = Column(DateTime, nullable=True, default=None)
    source = Column(String(256), nullable=True, default=None)

    # foreign key definitions
    ForeignKeyConstraint(['playlist_id', 'entry_num'], ['schedule_entry.playlist_id', 'schedule_entry.entry_num'])

260

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
261
#AuraDatabaseModel.recreate_db(True)