File size: 12,379 Bytes
27867f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""
MIT License

Copyright (C) 2023 ROCKY4546
https://github.com/rocky4546

This file is part of Cabernet

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
"""

import base64
import binascii
import datetime
import logging
import requests
import string
import threading
import time
import urllib.request

import lib.common.exceptions as exceptions
from lib.db.db_scheduler import DBScheduler


class PluginObj:

    def __init__(self, _plugin):
        self.logger = logging.getLogger(__name__)
        self.plugin = _plugin
        self.plugins = None
        self.http_session = requests.session()
        # Disable the CERT unverified warnings
        requests.packages.urllib3.disable_warnings()
        self.config_obj = _plugin.config_obj
        self.namespace = _plugin.namespace
        self.def_trans = ''.join([
            string.ascii_uppercase,
            string.ascii_lowercase,
            string.digits,
            '+/'
        ]).encode()
        self.instances = {}
        self.scheduler_db = DBScheduler(self.config_obj.data)
        self.scheduler_tasks()
        self.enabled = True
        self.logger.debug('Initializing plugin {}'.format(self.namespace))

    def terminate(self):
        """
        Removes all has a object from the object and calls any subclasses to also terminate
        Not calling inherited class at this time
        """
        self.enabled = False
        for key, instance in self.instances.items():
            return instance.terminate()
        self.logger = None
        self.plugin = None
        self.plugins = None
        self.http_session = None
        self.config_obj = None
        self.namespace = None
        self.def_trans = None
        self.instances = None
        self.scheduler_db = None

    

    # INTERFACE METHODS
    # Plugin may have the following methods
    # used to interface to the app.

    ##############################
    # ## EXTERNAL STREAM METHODS
    ##############################

    def is_time_to_refresh_ext(self, _last_refresh, _instance):
        """
        External request to determine if the m3u8 stream uri needs to 
        be refreshed.
        Called from stream object.
        """
        self.check_logger_refresh()
        return False

    def get_channel_uri_ext(self, _sid, _instance=None):
        """
        External request to return the reference uri for a m3u8 stream.
        Called from stream object.
        """
        self.check_logger_refresh()
        return self.instances[_instance].get_channel_uri(_sid)

    def get_channel_ref_ext(self, _sid, _instance=None):
        """
        External request to return the uri for a m3u8 stream.
        Called from stream object.
        """
        self.check_logger_refresh()
        return self.instances[_instance].get_channel_ref(_sid)

    ##############################
    # ## EXTERNAL EPG METHODS
    ##############################

    def get_channel_day_ext(self, _zone, _uid, _day, _instance='default'):
        """
        External request to return the programs for the day requested 
        as an offset int from current time
        """
        self.check_logger_refresh()
        return self.instances[_instance].get_channel_day(_zone, _uid, _day)

    def get_program_info_ext(self, _prog_id, _instance='default'):
        """
        External request to return the program details
        either from provider or from database
        includes updating database if needed.
        """
        self.check_logger_refresh()
        return self.instances[_instance].get_program_info(_prog_id)

    def get_channel_list_ext(self, _zone_id, _ch_ids=None, _instance='default'):
        """
        External request to return the channe list based on the zone 
        and the list of channels requested
        """
        self.check_logger_refresh()
        return self.instances[_instance].get_channel_list(_zone_id, _ch_ids)

    # END OF INTERFACE METHODS

    def scheduler_tasks(self):
        """
        dummy routine that will be overridden by subclass
        """
        pass

    def enable_instance(self, _namespace, _instance, _instance_name='Instance'):
        """
        When one plugin is tied to another and requires it to be enabled,
        this method will enable the other instance and set this plugin to disabled until 
        everything is up
        Also used to create a new instance if missing.  When _instance is None, 
        will look for any instance, if not will create a default one.
        """
        name_config = _namespace.lower()
        # if _instance is None and config has no instance for namespace, add one
        if _instance is None:
            x = [ k for k in self.config_obj.data.keys() if k.startswith(name_config+'_')]
            if len(x):
                return
            else:
                _instance = 'Default'
        instance_config = name_config + '_' + _instance.lower()
        
        if self.config_obj.data.get(name_config):
            if self.config_obj.data.get(instance_config):
                if not self.config_obj.data[instance_config]['enabled']:
                    self.logger.warning('1. Enabling {}:{} plugin instance. Required by {}. Restart Required'
                                       .format(_namespace, _instance, self.namespace))
                    self.config_obj.write(
                        instance_config, 'enabled', True)
                    raise exceptions.CabernetException('{} plugin requested by {}.  Restart Required'
                                                       .format(_namespace, self.namespace))
            else:
                if _namespace != self.namespace:
                    self.logger.warning('2. Enabling {}:{} plugin instance. Required by {}. Restart Required'
                                       .format(_namespace, _instance, self.namespace))
                else:
                    self.logger.warning('3. Enabling {}:{} plugin instance. Restart Required'
                                       .format(_namespace, _instance, self.namespace))
                
                self.config_obj.write(
                    instance_config, 'Label', _namespace + ' ' + _instance_name)
                self.config_obj.write(
                    instance_config, 'enabled', True)
                raise exceptions.CabernetException('{} plugin requested by {}.  Restart Required'
                                                   .format(_namespace, self.namespace))
        else:
            self.logger.error('Requested Plugin {} by {} Missing'
                              .format(_namespace, self.namespace))
            raise exceptions.CabernetException('Requested Plugin {} by {} Missing'
                                               .format(_namespace, self.namespace))
        if _namespace not in self.plugins.keys():
            self.logger.warning('{}:{} not installed and requested by {} settings. Restart Required'
                               .format(_namespace, _instance, self.namespace))
            raise exceptions.CabernetException('{}:{} not enabled and requested by {} settings. Restart Required'
                                               .format(_namespace, _instance, self.namespace))

        if not self.plugins[_namespace].enabled:
            self.logger.warning('{}:{} not enabled and requested by {} settings. Restart Required'
                               .format(_namespace, _instance, self.namespace))
            raise exceptions.CabernetException('{}:{} not enabled and requested by {} settings. Restart Required'
                                               .format(_namespace, _instance, self.namespace))

    def refresh_obj(self, _topic, _task_name):
        if not self.enabled:
            self.logger.debug(
                '{} Plugin disabled, not refreshing {}'
                .format(self.plugin.name, _topic))
            return
        web_admin_url = 'http://localhost:' + \
                        str(self.config_obj.data['web']['web_admin_port'])
        task = self.scheduler_db.get_tasks(_topic, _task_name)[0]
        url = (web_admin_url + '/api/scheduler?action=runtask&taskid={}'
               .format(task['taskid']))
        req = urllib.request.Request(url)
        with urllib.request.urlopen(req) as resp:
            result = resp.read()

        # wait for the last run to update indicating the task has completed.
        while True:
            task_status = self.scheduler_db.get_task(task['taskid'])
            x = datetime.datetime.utcnow() - task_status['lastran']
            # If updated in the last 20 minutes, then ignore
            # Many media servers will request this multiple times.
            if x.total_seconds() < 1200:
                break
            time.sleep(0.5)

    def refresh_channels(self, _instance=None):
        """
        Called from the scheduler
        """
        return self.refresh_it('Channels', _instance)

    def refresh_epg(self, _instance=None):
        """
        Called from the scheduler
        """
        return self.refresh_it('EPG', _instance)

    def refresh_it(self, _what_to_refresh, _instance=None):
        """
        _what_to_refresh is either 'EPG' or 'Channels' for now
        """
        try:
            if not self.enabled:
                self.logger.debug(
                    '{} Plugin disabled, not refreshing {}'
                    .format(self.plugin.name, _what_to_refresh))
                return False
            if _instance is None:
                for key, instance in self.instances.items():
                    if _what_to_refresh == 'EPG':
                        instance.refresh_epg()
                    elif _what_to_refresh == 'Channels':
                        instance.refresh_channels()
            else:
                if _what_to_refresh == 'EPG':
                    self.instances[_instance].refresh_epg()
                elif _what_to_refresh == 'Channels':
                    self.instances[_instance].refresh_channels()
            return True
        except exceptions.CabernetException:
            self.logger.debug('Setting plugin {} to disabled'.format(self.plugin.name))
            self.enabled = False
            self.plugin.enabled = False
            return False

    def utc_to_local_time(self, _hours):
        """
        Used for scheduler on events
        """
        tz_delta = datetime.datetime.now() - datetime.datetime.utcnow()
        tz_hours = round(tz_delta.total_seconds() / 3610)
        local_hours = tz_hours + _hours
        if local_hours < 0:
            local_hours += 24
        elif local_hours > 23:
            local_hours -= 24
        return local_hours

    def compress(self, _data):
        if type(_data) is str:
            _data = _data.encode()
        return base64.b64encode(_data).translate(
            _data.maketrans(self.def_trans,
                            self.config_obj.data['main']['plugin_data'].encode()))

    def uncompress(self, _data):
        if type(_data) is str:
            _data = _data.encode()
        self.config_obj.data['main']['plugin_data'].encode()
        try:
            return base64.b64decode(_data.translate(_data.maketrans(
                self.config_obj.data['main']['plugin_data']
                .encode(), self.def_trans))) \
                .decode()
        except (binascii.Error, UnicodeDecodeError):
            self.logger.error('Uncompression Error, invalid string {}'.format(_data))
            return None

    def check_logger_refresh(self):
        if not self.logger.isEnabledFor(40):
            self.logger = logging.getLogger(__name__ + str(threading.get_ident()))
            for inst, inst_obj in self.instances.items():
                inst_obj.check_logger_refresh()

    @property
    def name(self):
        return self.namespace