calender_fetcher.py 14.6 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
import os
import sys
import urllib
import logging
import simplejson

from datetime import datetime, timedelta
#from modules.models.schedule import Schedule


class CalendarFetcher:
    url = dict()
    url_parameter = dict()
    config = None
    logging = None
    has_already_fetched = False
    fetched_schedule_data = None
    # another crutch because of the missing TANK
    used_random_playlist_ids = list()

    def __init__(self, config):
        self.config = config
        self.logger = logging.getLogger("AuraEngine")
        self.__set_url__("calendar")
        self.__set_url__("importer")

    def fetch(self):
        # fetch upcoming schedules from STEERING
        try:
            self.logger.debug("Fetching schedules from STEERING")
            self.__fetch_schedule_data__()
        except urllib.error.HTTPError as e:
            self.logger.critical("Cannot fetch from " + self.url["calendar"] + "! Reason: " + str(e))
34
35
            self.fetched_schedule_data = None
            return None
36
37
        except (urllib.error.URLError, IOError, ValueError) as e:
            self.logger.critical("Cannot connect to " + self.url["calendar"] + "! Reason: " + str(e))
38
39
            self.fetched_schedule_data = None
            return None
40
41
42
43
44
45
46

        # fetch playlist and fallbacks to the schedules from TANK
        try:
            self.logger.debug("Fetching playlists from TANK")
            self.__fetch_schedule_playlists__()
        except urllib.error.HTTPError as e:
            self.logger.critical("Cannot fetch from " + self.url["importer"] + "! Reason: " + str(e))
47
48
            self.fetched_schedule_data = None
            return None
49
50
        except (urllib.error.URLError, IOError, ValueError) as e:
            self.logger.critical("Cannot connect to " + self.url["importer"] + "! Reason: " + str(e))
51
52
            self.fetched_schedule_data = None
            return None
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

        return_data = []
        # gather returndata
        try:
            for schedule in self.fetched_schedule_data:
                # skip schedule if no start or end is given
                if "start" not in schedule:
                    self.logger.warning("No start of schedule given. skipping schedule: " + str(schedule))
                    schedule = None
                if "end" not in schedule:
                    self.logger.warning("No end of schedule given. skipping schedule: " + str(schedule))
                    schedule = None
                if "playlist" not in schedule:
                    self.logger.warning("No playlist for schedule given. skipping schedule: " + str(schedule))
                    schedule = None

                if schedule:
                    return_data.append(schedule)
        except TypeError as e:
            self.logger.error("Nothing fetched...")
73
74
            self.fetched_schedule_data = None
            return None
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

        return return_data

    # ------------------------------------------------------------------------------------------ #
    def __set_url__(self, type):
        url = self.config.get(type+"url")
        pos = url.find("?")

        if pos > 0:
            self.url[type] = url[0:pos]
            self.url_parameter[type] = url[pos:]
        else:
            self.url[type] = url

    # ------------------------------------------------------------------------------------------ #
    def __fetch_schedule_data__(self):
        schedule = None

        # fetch data from steering
        html_response = self.__fetch_data__(self.url["calendar"])

        # response fails or is empty
        if not html_response:
            self.logger.debug("Got no response from pv!")

            # use testdata if wanted
            if self.config.get("use_test_data"):
                html_response = '[{"id":1,"schedule_id":1,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=0)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":9,"show_name":"TestData: FROzine","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":2,"schedule_fallback_id":12,"show_fallback_id":92,"station_fallback_id":1,"rtr_category":"string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"},' \
                                 '{"id":2,"schedule_id":2,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=2)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":10,"show_name":"TestData: FROMat","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":4,"schedule_fallback_id":22,"show_fallback_id":102,"station_fallback_id":1,"rtr_category":"TestData: string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"},' \
                                 '{"id":3,"schedule_id":3,"automation-id":1,"className":"TestData","memo":"TestData","show_fundingcategory":"TestData","start":"' + (datetime.now() + timedelta(hours=2)).strftime('%Y-%m-%dT%H:00:00') + '","end":"' + (datetime.now() + timedelta(hours=3)).strftime('%Y-%m-%dT%H:00:00') + '","show_id":11,"show_name":"TestData: Radio für Senioren","show_hosts":"TestData: Sandra Hochholzer, Martina Schweiger","title":"TestData:title","is_repetition":false,"playlist_id":6,"schedule_fallback_id":32,"show_fallback_id":112,"station_fallback_id":1,"rtr_category":"TestData: string","comment":"TestData: Kommentar","show_languages":"TestData: Sprachen","show_type":"TestData: Typ","show_categories":"TestData: Kategorie","show_topics":"TestData: Topic","show_musicfocus":"TestData: Fokus"}]'
                self.logger.critical("Hardcoded Response")
            else:
                html_response = "{}"

        # convert to dict
        schedule = simplejson.loads(html_response)

        # check data
        self.logger.critical("no JSON data checks. I believe what i get here")

        self.fetched_schedule_data = self.remove_unnecessary_data(schedule)

    # ------------------------------------------------------------------------------------------ #
    def __fetch_schedule_playlists__(self):
        # store fetched entries => do not have to fetch playlist_id more than once
        fetched_entries=[]

        self.logger.warning("only fetching normal playlists. no fallbacks")
        for schedule in self.fetched_schedule_data:
            # retrieve playlist and the fallbacks for every schedule
            # if a playlist (like station_fallback) is already fetched, it is not fetched again but reused
            schedule["playlist"]          = self.__fetch_schedule_playlist__(schedule, "playlist_id", fetched_entries)
#            schedule["schedule_fallback"] = self.__fetch_schedule_playlist__(schedule, "schedule_fallback_id", fetched_entries)
#            schedule["show_fallback"]     = self.__fetch_schedule_playlist__(schedule, "show_fallback_id", fetched_entries)
#            schedule["station_fallback"]  = self.__fetch_schedule_playlist__(schedule, "station_fallback_id", fetched_entries)

    # ------------------------------------------------------------------------------------------ #
    def __fetch_schedule_playlist__(self, schedule, id_name, fetched_schedule_entries):
        # set playlist_id (in testenvironment always null => no idea)
        if id_name not in schedule or schedule[id_name] is None:
            playlist_id = 1
        else:
            playlist_id = schedule[id_name]

        # set url
        #url = self.url["importer"] + schedule["show_name"] + "/playlists/" + str(playlist_id)
        url = self.url["importer"] + "public" + "/playlists/" + str(playlist_id)

        # fetch data from importer
        json_response = self.__fetch_data__(url)

        # use testdata if wanted
        if not json_response and self.config.get("use_test_data"):
            json_response = self.create_test_data(id_name, schedule)

        # convert to list
        schedule_entries = simplejson.loads(json_response)

        if "entries" in schedule_entries:
            for entry in schedule_entries["entries"]:
                if entry["uri"].startswith("file"):
                    entry["filename"] = self.convert_to_filename(entry["uri"])

            fetched_schedule_entries.append(schedule_entries)

        return schedule_entries

    def convert_to_filename(self, uri):
        # convert to normal filename
        e = self.config.get("audiofolder") + "/" + uri[7:] + ".flac"
        if not os.path.isfile(e):
            self.logger.warning("File", e, "does not exist!")
        return e

    # ------------------------------------------------------------------------------------------ #
    def __fetch_data__(self, url, parameter = ""):
        # init html_response
        html_response = b''

        # open an url and read the data
        if parameter == "":
            request = urllib.request.Request(url)
        else:
            request = urllib.request.Request(url, parameter)

        response = urllib.request.urlopen(request)
        html_response = response.read()

        self.has_already_fetched = True
        return html_response.decode("utf-8")

    # ------------------------------------------------------------------------------------------ #
    def remove_unnecessary_data(self, schedule):
        reduced_schedule = self.remove_data_more_than_24h_in_the_future(self.remove_data_in_the_past(schedule))
        return reduced_schedule

    # ------------------------------------------------------------------------------------------ #
    def remove_data_more_than_24h_in_the_future(self, schedule_from_pv):
        act_list = []
        now = datetime.now()
        now_plus_24hours = now + timedelta(hours=24)

        for s in schedule_from_pv:
            date_start = datetime.strptime(s["start"], "%Y-%m-%dT%H:%M:%S")

            # append only elements which are close enough to now
            if date_start <= now_plus_24hours and date_start >= now - timedelta(hours=1):
                act_list.append(s)

        return act_list

    # ------------------------------------------------------------------------------------------ #
    def remove_data_in_the_past(self, schedule_from_pv):
        act_list = []
        now = datetime.now()

        for index,curr in enumerate(schedule_from_pv[:-1]):
            date_start = datetime.strptime(curr["start"], "%Y-%m-%dT%H:%M:%S")
            date_next_start = datetime.strptime(schedule_from_pv[index+1]["start"], "%Y-%m-%dT%H:%M:%S")

            # append all elements in the future
            if date_start >= now:
                act_list.append(curr)
            # append the one which is now playing
            if date_start <= now and date_next_start >= now:
                act_list.append(curr)

        return act_list

    # ------------------------------------------------------------------------------------------ #
    def create_test_data(self, id_name, schedule):
        import random
        rand_id = random.randint(1, 10000)

        while rand_id in self.used_random_playlist_ids:
            rand_id = random.randint(1, 10000)

        self.used_random_playlist_ids.append(rand_id)

        # HARDCODED Testdata
        if id_name != "playlist_id":
            # FALLBACK TESTDATA

            if rand_id % 3 == 0:  # playlist fallback
                json_response = '{"playlist_id":' + str(
                    rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/02 - Only Child - Breakneck.flac"}]}'
            elif rand_id % 2 == 0:  # stream fallback
                json_response = '{"playlist_id":' + str(
                    rand_id) + ',"entries":[{"source":"http://chill.out.airtime.pro:8000/chill_a"}]}'
            else:  # pool fallback
                json_response = '{"playlist_id":' + str(rand_id) + ',"entries":[{"source":"pool:///liedermacherei"}]}'

            schedule[id_name] = rand_id

        elif schedule[id_name] == 0 or schedule[id_name] is None:
            # this happens when playlist id is not filled out in pv
            # json_response = '{"playlist_id": 0}'

            if rand_id % 4 == 0:  # playlist with two files
                json_response = '{"playlist_id":' + str(
                    rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/02 - Only Child - Breakneck.flac"}]}'
            elif rand_id % 3 == 0:  # playlist with jingle and then linein
                json_response = '{"playlist_id":' + str(
                    rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"linein://1"}]}'
            elif rand_id % 2 == 0:  # playlist with jingle and then http stream
                json_response = '{"playlist_id":' + str(
                    rand_id) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"http://chill.out.airtime.pro:8000/chill_a"}]}'
            else:  # pool playlist
                json_response = '{"playlist_id":' + str(rand_id) + ',"entries":[{"source":"pool:///hiphop"}]}'

            schedule[id_name] = rand_id

        elif schedule[id_name] % 4 == 0:  # playlist with two files
            json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"file:///var/audio/fallback/NightmaresOnWax/DJ-Kicks/01 - Type - Slow Process.flac"}]}'
        elif schedule[id_name] % 3 == 0:  # playlist with jingle and then http stream
            json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"linein://0"}]}'
        elif schedule[id_name] % 2 == 0:  # playlist with jingle and then linein
            json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"file:///var/audio/fallback/music.flac"},{"source":"http://stream.fro.at:80/fro-128.ogg"}]}'
        else:  # pool playlist
            json_response = '{"playlist_id":' + str(schedule[id_name]) + ',"entries":[{"source":"pool:///chillout"}]}'

        self.logger.info("Using 'randomized' playlist: " + json_response + " for " + id_name[:-3] + " for show " + schedule["show_name"] + " starting @ " + schedule["start"])

        return json_response