broadcasts.py 9.71 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

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

12

13
class Model:
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

45
46
47
48
        print("Recreating Database...")
        db.drop_all()
        print("all dropped. creating...")
        db.create_all()
49
50
        print("inserting manual scheduling possibility")
        db.session.add(manualschedule)
51
52
53
        print("all created. commiting...")
        db.session.commit()
        print("Database recreated!")
54

55
56
        if systemexit:
            sys.exit(0)
57

58

59
# ------------------------------------------------------------------------------------------ #
60
class Schedule(db.Model, Model):
61
    """
62
    One specific Schedule for a show on a timeslot
63
    """
64
65
    __tablename__ = 'schedule'
    schedule_id = Column(Integer, primary_key=True, autoincrement=False)
66
67
    show_id = Column(Integer)

68
69
    schedule_start = Column(DateTime) # can be null due to manual entries
    schedule_end = Column(DateTime) # can be null due to manual entries
70
71
72
73
74
75
76
77
78
    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))
79
80
81

    is_repetition = Column(Boolean())

82
83
84
85
86
    playlist_id = Column(Integer)
    timeslot_fallback_id = Column(Integer)
    show_fallback_id = Column(Integer)
    station_fallback_id = Column(Integer)

87
88
89
90
91
92
    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

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    @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
        }
108
109


110
# ------------------------------------------------------------------------------------------ #
111
class ScheduleEntry(db.Model, Model):
112
    """
113
    One schedule can have multiple entries
114
    """
115
116
117
118
119
120
    __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)
121
    entry_end = Column(DateTime)
122
123
124
125
126
127
128
    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
129
130
    year = Column(Integer())
    volume = Column(Integer, default=100)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
131
132
    entry_start_unix = 0
    entry_end_unix = 0
133
    programme_index = -1
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
134

135
136
    schedule = relationship("Schedule", foreign_keys=[schedule_id])

137
138
139
140
141
142
143
144
145
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
    # ------------------------------------------------------------------------------------------ #
    @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

210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225

#    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

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    @staticmethod
    def create_from_json(playlist_id, entry_num, schedule_id, entry_start, entry_end, source, artist, track, albumname, genre, tracknum, cdnum, year):
        e = ScheduleEntry()
        e.playlist_id = playlist_id
        e.entry_num = entry_num
        e.schedule_id = schedule_id
        e.entry_start = entry_start
        e.entry_end = entry_end
        e.source = source
        e.artist = artist
        e.track = track
        e.albumname = albumname
        e.genre = genre
        e.tracknum = tracknum
        e.cdnum = cdnum
        e.year = year
242
        return e
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
243
244
245
246
247
248
249
250
251
252

#    @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
#        }
253

254
255
256
257
258
259
260
261
262

# ------------------------------------------------------------------------------------------ #
class TrackServiceSchedule(db.Model):
    """
    Trackservice is tracking every schedule.
    """
    __tablename__ = 'trackservice_schedule'
    ts_schedule_id = Column(Integer, primary_key=True, autoincrement=True)
    schedule_id = Column(Integer, ForeignKey('schedule.schedule_id'))
263
264


265
266
267
268
269
270
271
272
# ------------------------------------------------------------------------------------------ #
class TrackServiceScheduleEntry(db.Model):
    """
    And a schedule can have multiple entries
    """
    __tablename__ = 'trackservice_entry'
    ts_entry_id = Column(Integer, primary_key=True, autoincrement=True)
    ts_schedule_id = Column(Integer, ForeignKey('trackservice_schedule.ts_schedule_id'))
273

274
#Model.recreate_db(True)