engine-api.py 12.8 KB
Newer Older
1
#!/usr/bin/env python3.7
2
3

#
David Trattnig's avatar
David Trattnig committed
4
5
6
# Aura Engine (https://gitlab.servus.at/aura/engine)
#
# Copyright (C) 2017-2020 - The Aura Engine Team.
7
8
9
10
11
#
# 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.
David Trattnig's avatar
David Trattnig committed
12
#
13
14
15
16
# 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.
David Trattnig's avatar
David Trattnig committed
17
#
18
19
20
21
22
23
# 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/>.


import logging
import os, os.path
David Trattnig's avatar
David Trattnig committed
24
25
import subprocess
import json
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

from datetime                       import datetime, date, timedelta

from flask                          import Flask, Response
from flask_caching                  import Cache
from flask_cors                     import CORS
from flask_sqlalchemy               import SQLAlchemy
from flask_marshmallow              import Marshmallow
from marshmallow                    import Schema, fields, post_dump
from flask_restful                  import Api, Resource, abort
from apispec                        import APISpec
from apispec.ext.marshmallow        import MarshmallowPlugin
from apispec_webframeworks.flask    import FlaskPlugin
# import werkzeug
from werkzeug.exceptions            import HTTPException, default_exceptions, Aborter

from modules.base.logger            import AuraLogger
from modules.base.config            import AuraConfig
David Trattnig's avatar
David Trattnig committed
44
from modules.database.model         import AuraDatabaseModel, Schedule, Playlist, PlaylistEntry, PlaylistEntryMetaData, TrackService
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




#
# Initialize the Aura Web App and API.
#

config = AuraConfig()
app = Flask(__name__,
    static_url_path='', 
    static_folder='web/')
    # static_folder='contrib/aura-player/public/')

app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = config.get_database_uri()
app.config["CACHE_TYPE"] = "simple"
app.config["CACHE_DEFAULT_TIMEOUT"] = 0
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
cache = Cache(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}}) # FIXME Update CORS for production use
db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)


#
# Werkzeug HTTP code mappings
#
class NoDataAvailable(HTTPException):
    code = 204
    description = "There is currently no content available."
default_exceptions[204] = NoDataAvailable
abort = Aborter()


class EngineApi:
    """
    Provides the Aura Engine API services.
    """
    config = None
    api = None
    logger = None

    # trackservice_schema = None


    def __init__(self, config, api):
        """ 
        Initializes the API.

        Args:
            config (AuraConfig):    The Engine configuration.
            api (Api):              The Flask restful API object.
        """
        self.config = config
        self.logger = AuraLogger(self.config, "engine-api")
        self.logger = logging.getLogger("engine-api")
        self.api = api

        # Generate HTML files
        self.generate_html("web/templates/clock.html", "web/clock.html")
        self.generate_html("web/templates/trackservice.html", "web/trackservice.html")

        # API Spec
        spec.components.schema("TrackService",  schema=TrackServiceSchema)
        spec.components.schema("Report",        schema=ReportSchema)
        spec.components.schema("Schedule",      schema=ScheduleSchema)
        spec.components.schema("Clock",         schema=ClockDataSchema)
David Trattnig's avatar
David Trattnig committed
114
        spec.components.schema("Status",        schema=StatusSchema)
115
116
117
118
119
120
121
122
123
124

        # TODO Generates HTML for specification
        #self.logger.info(spec.to_yaml())

        # Schema instances
        EngineApi.trackservice_schema = TrackServiceSchema(many=True)
        EngineApi.track_schema = TrackServiceSchema()
        EngineApi.report_schema = ReportSchema(many=True)
        EngineApi.schedule_schema = ScheduleSchema(many=True)
        EngineApi.clockdata_schema = ClockDataSchema()
125
        EngineApi.status_schema = StatusSchema()
126
127
128
129
130
131
132
133
134

        # Define API routes
        self.api.add_resource(TrackServiceResource,         config.api_prefix + "/trackservice/")
        self.api.add_resource(TrackResource,                config.api_prefix + "/trackservice/<int:track_id>")
        self.api.add_resource(CurrentTrackResource,         config.api_prefix + "/trackservice/current")
        self.api.add_resource(TracksByDayResource,          config.api_prefix + "/trackservice/date/<string:date_string>")
        self.api.add_resource(ReportResource,               config.api_prefix + "/report/<string:year_month>")
        self.api.add_resource(UpcomingSchedulesResource,    config.api_prefix + "/schedule/upcoming")
        self.api.add_resource(ClockDataResource,            config.api_prefix + "/clock")
David Trattnig's avatar
David Trattnig committed
135
        self.api.add_resource(StatusResource,               "/status")
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

        self.logger.info("Engine API routes successfully set!")

        # Static resources
        @app.route('/app/trackservice', methods=['GET'])
        def trackservice():
            content = open(os.path.join("web/", "trackservice.html"))
            return Response(content, mimetype="text/html")

        # Static resources
        @app.route('/app/clock', methods=['GET'])
        def clock():
            content = open(os.path.join("web/", "clock.html"))
            return Response(content, mimetype="text/html")


    def generate_html(self, src_file, target_file):
        """
        Generates HTML based on the configuration options and templates.

        Args:
            src_file (String):      The template file
            target_file (String):   The HTML file to be generated
        """
        src_file = open(src_file, "r")
        target_file = open(target_file, "w")
        content = src_file.read()

        config_options = {
            "CONFIG-STATION-NAME": config.station_name,
            "CONFIG-STATION-LOGO-URL": config.station_logo_url,
            "CONFIG-STATION-LOGO-SIZE": config.station_logo_size,
            "CONFIG-API-URL": config.exposed_api_url
        }

        for key, value in config_options.items():
            content = content.replace(":::"+key+":::", value)
                
        target_file.write(content)
        src_file.close()
        target_file.close()


    def run(self):
        """
        Starts the API server.
        """
        # Set debug=False if you want to use your native IDE debugger
        self.api.app.run(port=self.config.api_port, debug=False)




#
# API SPEC
#


spec = APISpec(
    title="Swagger API Specification for Aura Engine",
    version="1.0.0",
    openapi_version="3.0.2",
    plugins=[FlaskPlugin(), MarshmallowPlugin()],
)


#
# API SCHEMA
#


class TrackServiceSchema(ma.Schema):
    class Meta:
        fields = (
            "id", 
            "schedule.schedule_id",
            "schedule.schedule_start",
            "schedule.schedule_end",
            "schedule.languages",
            "schedule.type",
            "schedule.category",
            "schedule.topic",
            "schedule.musicfocus",
            "schedule.is_repetition",

            "track",
            "track_start",

            "show"
            )


class ClockDataSchema(ma.Schema):
    class Meta:
        fields = (
            "current",
            "next",
            "track_id",
            "track_start",
            "track"
            )


class ScheduleSchema(ma.Schema):
    class Meta:
        fields = (
            "id", 
            "schedule_id",
            "schedule_start",
            "schedule",

            "show_id",
            "show_name",
            "show_hosts",
            "show_type"
            )



class ReportSchema(ma.Schema):
    class Meta:
        fields = (
            "id", 
            "schedule.schedule_id",
            "schedule.schedule_start",
            "schedule.schedule_end",
            "schedule.languages",
            "schedule.type",
            "schedule.category",
            "schedule.topic",
            "schedule.musicfocus",
            "schedule.is_repetition",

            "schedule.show_id",
            "schedule.show_name",
            "schedule.show_hosts",
            "schedule.show_type",
            "schedule.show_funding_category",

            "track",
            "track_start",

            "playlist_id",
            "fallback_type",
            "schedule_fallback_id",
            "show_fallback_id",
            "station_fallback_id"
            )


286
287
288
class StatusSchema(ma.Schema):
    class Meta:
        fields = (
David Trattnig's avatar
David Trattnig committed
289
290
291
292
293
                "engine",
                "soundsystem",
                "api",
                "redis_ready",
                "audio_store"
294
295
            )

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

#
# API RESOURCES
#


class TrackServiceResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self):
        today = date.today()
        today = datetime(today.year, today.month, today.day)
        tracks = TrackService.select_by_day(today)
        return EngineApi.trackservice_schema.dump(tracks)


class TrackResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self, track_id):
        track = TrackService.select_one(track_id)
        return EngineApi.track_schema.dump(track)


class ClockDataResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self):
        item = TrackService.select_current()
        next_schedule = Schedule.select_upcoming(1)
        if next_schedule:
            next_schedule = next_schedule[0].as_dict()
            next_schedule["playlist"] = None
        else:
            next_schedule = {}

        clockdata = {
            "track_id": item.id,
            "track_start": item.track_start,
            "track": item.track,
            "current": {},
            "next": next_schedule
        }

        if item.schedule:
            clockdata["current"] = item.schedule.as_dict()
            if item.schedule.playlist:
                clockdata["current"]["playlist"] = item.schedule.playlist[0].as_dict()

        clockdata["current"]["show"] = item.show
        return EngineApi.clockdata_schema.dump(clockdata)


class CurrentTrackResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self):
        track = TrackService.select_current()
        if not track:
            return abort(204) # No content available
        return EngineApi.track_schema.dump(track)


class TracksByDayResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self, date_string):
        date = datetime.strptime(date_string, "%Y-%m-%d")
        self.logger.debug("Query track-service by day: %s" % str(date))
        tracks = TrackService.select_by_day(date)
        if not tracks:
            return abort(204) # No content available
        return EngineApi.trackservice_schema.dump(tracks)


class UpcomingSchedulesResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self):
        now = datetime.now()
        self.logger.debug("Query upcoming schedules after %s" % str(now))
        schedules = Schedule.select_upcoming(3)
        if not schedules:
            return abort(204) # No content available
        return EngineApi.schedule_schema.dump(schedules)


class ReportResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self, year_month):
        year = int(year_month.split("-")[0])
        month = int(year_month.split("-")[1])
        
        first_day = datetime(year, month, 1)    
        next_month = first_day.replace(day=28) + timedelta(days=4)
        next_month - timedelta(days=next_month.day)

        self.logger.debug("Query report for month: %s - %s" % (str(first_day), str(next_month)))
        report = TrackService.select_by_range(first_day, next_month)
        if not report:
            return abort(204) # No content available
        return EngineApi.report_schema.dump(report)


422
423
424
425
426
427
428
class StatusResource(Resource):
    logger = None
    
    def __init__(self):
        self.logger = logging.getLogger("engine-api")

    def get(self):
David Trattnig's avatar
David Trattnig committed
429
430
431
        status = subprocess.check_output(["python3", "guru.py", "-s", "-q"])
        status = status.decode("utf-8").replace("'", '"')
        status = json.loads(status, strict=False)
432
433
434
435
436

        if not status:
            return abort(204) # No content available
        return EngineApi.status_schema.dump(status)

437
438
439
440
441
442
443
444
445
446
447


#
# Initialization calls
#


engine_api = EngineApi(config, api)

if __name__ == "__main__":
    engine_api.run()