broadcasts.py 9.88 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
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
219
220
221
222
223
224
225
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
__author__ = 'michel'
# -*- coding: utf-8 -*-

import datetime, os, urllib
import pprint

from flask_sqlalchemy import SQLAlchemy
from flask_babel import Babel, get_locale
from flask import Flask

#from modules.web import db
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Boolean, Column, Date, DateTime, Float, Integer, String, Text, Time, ForeignKey
from libraries.base.config import ConfigReader

Base = declarative_base()


#### DATABASE CONN ####
config = ConfigReader()
ini_path = "/etc/comba/comba.ini"
config.set('configpath', ini_path)
config.loadConfig()
install_dir = config.get(str("install_dir"))

app = Flask(__name__, template_folder=install_dir+'/modules/web/templates')
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://comba:comba@localhost/comba?charset=utf8"
app.config['BABEL_DEFAULT_LOCALE'] = 'de'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.debug = True
db = SQLAlchemy(app)
babel = Babel(app)
#### END DATABASE CONN ####

# ------------------------------------------------------------------------------------------ #
class BroadcastModel:
    def store(self, commit=False):
        db.session.add(self)
        if commit:
            self.commit()

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


# ------------------------------------------------------------------------------------------ #
class TimeSlotModel:
    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


# ------------------------------------------------------------------------------------------ #
class Format(db.Model, BroadcastModel):
    """
    ID of show format # Sendungsformat
    """
    __tablename__ = 'format'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))


# ------------------------------------------------------------------------------------------ #
class Timeslot_PlaylistEntry(db.Model, BroadcastModel, TimeSlotModel):
    """
    playlist settings
    """
    __tablename__ = 'timeslot_playlistentry'
    id = Column(Integer, primary_key=True, autoincrement=False)
    location = Column(String(255))
    start = Column(DateTime)
    end = Column(DateTime)
    timeslot_id = Column(Integer, ForeignKey("timeslot.id"))


# ------------------------------------------------------------------------------------------ #
class Timeslot(db.Model, BroadcastModel, TimeSlotModel):
    """
    One specific Show
    """
    __tablename__ = 'timeslot'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))  # showname
    shortdesc = Column(Text())  # very optional
    playlist_id = Column(String(255))  # file:///, http:///, live:///

    repetition_id = Column(Integer, ForeignKey("timeslot.id"), nullable=True)

    start = Column(DateTime, nullable=False)  # when the show starts
    end = Column(DateTime, nullable=False)  # when the show stops

    fallback_pool = Column(String(255))  # if silence => fallback_pool is played
    fallback_playlist = Column(String(255))  # if fallback_pool is silent => fallback_playlist is played

    #def __repr__(self):
    #
    def pretty_print(self):
        return pprint.pprint(self)
        #value = "id: "+str(self.id)+" !!! name: "+str(self.name)+" !!! shortdesc: "+str(self.shortdesc)+" !!! playlist_id: "+str(self.playlist_id)+" !!! repetition_id: "+str(self.repetition_id)+" !!! start: "+str(self.start)+" !!! end: "+str(self.end)
        #return value

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

# ------------------------------------------------------------------------------------------ #
class BroadcastPeriod(db.Model, BroadcastModel):
    """
    Daten werden noch in der scheduling.xml gehalten
    """
    __tablename__  = 'broadcast_period'

    identifier = Column(Integer, primary_key=True)
    start = Column(DateTime)
    end = Column(DateTime)

    meta = {
        'ordering': ['+start']
    }


# ------------------------------------------------------------------------------------------ #
class BroadcastEvent(db.Model, BroadcastModel):
    """
    Definiert eine Sendung mit Start- und End-Datum
    """
    __tablename__ = 'broadcast_event'

    identifier = Column(Integer, primary_key=True, autoincrement=True) # Unique (o)id
    id_ext = Column(String(30)) #
    location = Column(String(512)) # archived audio file, will be available when the broadcast event is over
    reccurrence_id = Column(Integer) # Unique id of event to be repeated
    duration = Column(Integer) # duration in seconds
    start = Column(DateTime, nullable=False, default=datetime.datetime.now())  # start date
    end = Column(DateTime, nullable=False, default=datetime.datetime.now()+datetime.timedelta(minutes=60))  # end date
    rerun = Column(Boolean, default=False)  # true, if the event is a rerun
    replay_of_datetime = Column(DateTime)
    replay_of = Column(Integer, ForeignKey('broadcast_event.identifier'))
    programme_id = Column(String(100))
    station_name = Column(String(100))
    station_id = Column(String(100))
    title = Column(String(100))
    subject = Column(String(200))
    description = Column(String(300))
    overwrite_event = Column(Integer, ForeignKey('broadcast_event.identifier'))
    state = Column(String(50), default='created')
    created = Column(DateTime, default=datetime.datetime.now)
    modified = Column(DateTime, default=datetime.datetime.now)
    modified_by = Column(String(50))
    text = Column(String(400))
    #data = DictField(required=False)

    meta = {
        'ordering': ['+start'],
        'indexes': [
            {'fields': ['title', "subject"],
             'default_language': 'german',
             'weight': {'title': 10, 'subject': 2}
             }
        ]
    }

    def fileExists(self):
        return os.path.exists(str(self.location).replace('file://', ''))


# ------------------------------------------------------------------------------------------ #
class BroadcastEventTrack(db.Model, BroadcastModel):
    """
    Track, der einem BroadcastEvent zugeordnet ist
    """
    __tablename__ = 'broadcast_event_track'

    identifier = Column(Integer, primary_key=True) # Unique id
    location = Column(String(512))  # audio location (url or file)
    length = Column(Float) # duration in seconds
    start = Column(DateTime) # start date
    end = Column(DateTime) # end date
    record_at = Column(DateTime) # The date on which the recording has to start.
    broadcast_event = Column(Integer, ForeignKey('broadcast_event.identifier')) # the BroadcastEvent the track refers to

    meta = {
        'ordering': ['+start']
    }

    def isLast(self):
        return self == BroadcastEventTrack.objects(broadcast_event=self.broadcast_event).order_by('-start').first()

    def fileExists(self):
        return os.path.exists(str(self.location).replace('file://', ''))

    def totalLength(self):
        tracks = BroadcastEventTrack.objects(broadcast_event=self.broadcast_event)
        length = 0
        for track in tracks:
            length = length + track.length if track.length else length
        return length#


# ------------------------------------------------------------------------------------------ #
class BroadcastEventOverride(db.Model, BroadcastModel): # Base
    """
    Ein Track, der in die Sendeautomatisierung eingeblendet wird
    Muss manuell erstellt werden
    """
    __tablename__ = 'broadcast_event_override'

    identifier = Column(Integer, primary_key=True) # Unique id
    location = Column(String(512)) # audio location (url or file)
    mimetype = Column(String(100)) # audio mime
    bitrate = Column(Integer) # bitrate
    channels = Column(Integer) # number of channels
    length = Column(Float) # duration in seconds
    start = Column(DateTime) # start date
    end = Column(DateTime) # end date
    seek = Column(Integer) # TODO: seconds to seek into the audio
    ordering = Column(Integer, default=0)  # track sorting
    #data = DictField(required=False) # additional data
    broadcast_event = Column(Integer, ForeignKey('broadcast_event.identifier'))  # the BroadcastEvent the track refers to

    meta = {
        'ordering': ['+ordering']
    }

    def nextOrdering(self):
        """
        Return number of next track in tracklist
        @return:  int ordering
        """
        lastOverride = BroadcastEventOverride.objects(broadcast_event=self.broadcast_event)\
            .order_by('-ordering')\
            .first()

        if lastOverride:
            return lastOverride.ordering + 1
        else:
            return 1

    def filled(self):
        """
        what percent of the broadcast event is allready filled with audio
        @return:  percent filled with audio
        """
        object = self.broadcast_event
        parent_total = (object.end - object.start).total_seconds()
        proc = 0
        try:
            proc = (self.totalLength() / parent_total) * 100
        except:
            proc = 0
        return int(proc)

    def totalLength(self):
        """
        Get the total length of audio in the track list
        @return:  total length of audio
        """
        tracks = BroadcastEventOverride.objects(broadcast_event=self.broadcast_event)
        length = 0
        for track in tracks:
            if track.length:
                length = length + track.length
        return length

    def fileExists(self):
        request = urllib.Request(self.location)
        request.get_method = lambda: 'HEAD'
        try:
            response = urllib.urlopen(request)
            return True
        except:
            return False


#print("Recreating Database...")
#db.drop_all()
#db.create_all()
#db.session.commit()
#print("Database recreated!")