~vincent-vandevyvre/qarte/qarte-3

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
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
# -*- coding: utf-8 -*-

# loadingscheduler.py
# This file is part of Qarte-3
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2016-2017 Vincent Vande Vyvre
# Licence: GPL3
# Home page: https://launchpad.net/qarte
#
# Deferred downloading scheduler

import sys
import os
import time
import pwd
import json
import pickle
import locale
import logging
lgg = logging.getLogger(__name__)

from datetime import datetime
from threading import Thread

from PyQt5.QtWidgets import QApplication

from gui.schedulerdialog import SchedulerDialog
from pycrontab import PyCronTab

class LoadingScheduler:
    def __init__(self, core, video=None):
        self.core = core
        self.ui = core.ui
        self.video = video
        self.lang = core.cfg['lang']
        self.logfile = os.path.join(core.workspace['user'], 'daemon.log')
        self.cron_cmd = core.cfg['crontab_cmd']
        self.expired = []
        self.edit_tasks()
        self.load_task_file()
        self.dialog = SchedulerDialog(self, core.ui)
        if video:
            self.set_video_item(video)
        self.dialog.log_editor.set_log_filename(self.logfile)
        self.dialog.log_editor.load_log()
        self.dialog.show()
        self.show_tasks()
        rep = self.dialog.exec_()
        
    def create_task(self):
        if self.dialog.arteconcert_rdo.isChecked():
            self.create_concert_task()
            return

        order = self.get_new_order()
        dial = self.dialog
        new = {}
        if dial.fname_rdo.isChecked():
            new['title'] = self.video.title
            new['fname'] = self.sanitize_file_name(dial.fname_led.text())
            new['stream'] = self.video.streams[self.video.quality]["url"]
            new['quality'] = self.video.quality
            new['type'] = 0

        elif dial.serial_rdo.isChecked():
            name = dial.serials_cmb.currentText()
            if 'GEO' in name:
                new['kwords'] = '360 geo'
                new['type'] = 2

            else:
                new['title'] = dial.serials_cmb.currentText()
                new['type'] = 1
        else:
            kwords = self.get_keywords(dial.kwords_led.text())
            if not kwords:
                return

            new['kwords'] = kwords
            new['type'] = 2

        new['all'] = False
        if new['type']:
            new['all'] = dial.all_rdo.isChecked()

        if dial.date_rdo.isChecked():
            date, time = self.get_task_date()
            if not self.check_datetime(date, time):
                dial.set_invalid_date_warning()
                return

            new['date'] = (date.day(), date.month(), date.year())
            new['time'] = (time.hour(), time.minute())

        else:
            new['date'] = dial.week_cmb.currentIndex()
            time = dial.time_spb_2.time()
            new['time'] = (time.hour(), time.minute())

        self.tasks[order] = new
        self.save_task_file()
        self.register_task(order, new)

#{order: {title: bla,
#         fname: file/name, no file name with serial and kwords
#         type: 0=video name, 1=serial name, 2=kwords, 3=concert
#         all: True, False
#         date: date as tuple(D, M, Y) or weekly
#         time: time as tuple(H, M), None
#         mp4url: http:........,
#         quality: if not mp4url,
#         kwords: []}}

    def create_concert_task(self):
        order = self.get_new_order()
        dial = self.dialog
        new = {}
        new['title'] = self.video.title
        new['fname'] = self.sanitize_file_name(dial.fname_led.text())
        new['stream'] = self.video.qualities[self.video.quality]["url"]
        new['type'] = 3
        self.tasks[order] = new
        date, time = self.get_task_date()
        if not self.check_datetime(date, time):
            dial.set_invalid_date_warning()
            return

        new['date'] = (date.day(), date.month(), date.year())
        new['time'] = (time.hour(), time.minute())
        self.tasks[order] = new
        self.save_task_file()
        self.register_task(order, new)

    def get_task_date(self):
        date = self.dialog.date_spb.date()
        time = self.dialog.time_spb.time()
        return date, time

    def get_stream_url(self):
        quality = self.dialog.quality_cmb.currentText()
        return quality

    def load_task_file(self):
        fld = self.core.workspace['user']
        path = os.path.join(fld, 'tasks.json')
        self.tasks = False
        if os.path.isfile(path):
            lgg.info('Load task file: %s' % path)
            try:
                with open(path, 'r') as objfile:
                    cnt = objfile.read()
                    self.tasks = json.loads(cnt)
            except Exception as why:
                lgg.warning("Read error from: {0},".format(path))
                lgg.warning("reason: {0}.".format(why))

        if self.tasks:
            self.clean_tasks()

        else:
            self.tasks = {}

    def save_task_file(self):
        fld = self.core.workspace['user']
        path = os.path.join(fld, 'tasks.json')
        lgg.info('Save task file: %s' % path)
        jsn = json.dumps(self.tasks, sort_keys=True, indent=4, 
                         separators=(',', ': '), ensure_ascii=False)
        try:
            with open(path, 'wb') as outfile:
                outfile.write(jsn.encode('utf-8', 'replace'))
        except Exception as why:
            lgg.warning("Write error: {0}".format(path))
            lgg.warning("reason: {0}".format(why))

    def set_video_item(self, video):
        self.video = video
        self.dialog.configure(video)

    def get_new_order(self):
        if not self.tasks:
            return '001'

        last = sorted(self.tasks.keys())[-1]
        return "%03d" % (int(last) + 1)

    def sanitize_file_name(self, name):
        return name

    def get_keywords(self, line):
        return [i.lower() for i in line.split(' ')]

    def check_datetime(self, d, t):
        """Check if date and time of cron are not too short.

        Args:
        d -- QDate
        t -- QTime

        Returns:
        False if datetime is too short, True otherwise
        """
        now = datetime.now()
        dt = datetime(d.year(), d.month(), d.day(), t.hour(), t.minute(), 0)
        if now >= dt:
            return False

        return True

    def clean_tasks(self):
        expired = []
        for key, value in self.tasks.items():
            if isinstance(value['date'], int):
                # Permanent task
                continue
            d, m, y = value['date']
            h, mn = value['time']
            if datetime(y, m, d, h, mn, 0) < datetime.now():
                expired.append(key)

        if expired:
            for key in expired:
                self.tasks.pop(key)
                self.tab.remove_task(key)
            self.tab.write_crontab()

        self.tab.clean_crontab(self.tasks.keys())

    def show_tasks(self):
        lgg.info('Show tasks: %s' % len(self.tasks))
        keys = sorted(self.tasks.keys())
        for key in keys:
            self.dialog.tasks_tree.set_single_task(key, self.tasks[key])

    def set_selection_mode(self):
        lgg.info('Enter in selection mode')
        self.core.is_interact_with_dialog = True
        self.dialog.hide()

    def call_settings_dialog(self):
        try:
            _ = self.video.category
            self.core.artelive.configure_downloading(self.video)
        except AttributeError:
            self.core.artetv.configure_downloading(self.video)

    def edit_tasks(self):
        self.tab = PyCronTab()
        isread = self.tab.read_crontab()
        if isread is not None:
            lgg.warning('Error when reading crontab:\n\t%s' % isread)

    def register_task(self, idx, task):
        lgg.info('Register task: %s' % idx)
        cmd = self.get_command(idx)
        self.tab.add_new_task(cmd, task['date'], task['time'])
        self.tab.write_crontab()
        self.dialog.tasks_tree.set_single_task(idx, task)

    def remove_task(self, idx):
        self.tasks.pop(idx)
        self.tab.remove_task(idx)
        self.tab.write_crontab()

    def get_command(self, index):
        """Create the command for crontab.

        """
        #'export DISPLAY=:0 & LC_CTYPE="<lang>" Lang="<lang>" 
        #                           qarte -a <ID> >> "<log>" 2>&1'
        #'export DISPLAY=:0 & LC_CTYPE="fr_BE.utf-8" Lang="fr_BE.utf-8" 
        #                           qarte -a 002 >> "path/to/log.log" 2>&1'
        lng, cod = locale.getdefaultlocale()
        lang = ".".join([lng, cod.lower()])
        return self.cron_cmd.replace('<lang>', lang)\
                            .replace('<ID>', index)\
                            .replace('<log>', self.logfile)


# Devel usage
class TaskEditor(object):
    def _write(self):
        def write(*args):
            self.tab.write()

        # To avoid an 'error: (4, 'System call interrupted')' the crontab
        # must be created in separate process
        Thread(target=write, args=(None,)).start()

class Core:
    def __init__(self):
        self.ui = None
        ws = os.path.expanduser("~") + "/qarte-3/wspace"
        self.workspace = {'user': ws}
        self.cfg = {'lang': 'fr',
                    'crontab_cmd': 'export DISPLAY=:0 & LC_CTYPE="<lang>" Lang="<lang>"'\
                                   ' <root> -a <ID> >> "<log>" 2>&1'}
        video = {'id': '047593-001-A', 'title': 'Mousson'}
        item = TVItem(video)
        ls = LoadingScheduler(self, item)

class TVItem:
    """Define a video item.

    """
    def __init__(self, attr, lang='fr'):
        self.idx = attr['id']
        self.title = attr['title']
        # Very short description
        #self.teaser = attr['teaser']
        #self.sched = attr['scheduled_on']
        #self.expire = self.format_expiration_date(attr['rights_end'])
        self.date = '2016-05-18 13:34:52' 
        self.duration = '43 min. 7 sec.'
        self.url = 'http://www.arte.tv/guide/fr/047593-001-A/mousson?autoplay=1'
        #self.subtitle = attr['subtitle']
        #self.adult = attr['adult']
        #self.pix_url = attr['thumbnail_url']
        #self.pixmap = None
        # description, origin and anno must be extracted from the video page
        #self.description = ''
        #self.origin = ''
        #self.anno = ''
        #self.views = attr['views']
        self.streams = {'HTTP_MP4_EQ_1': {'url': 'http://arte.gl-systemhaus.de/am/tvguide/ALL/066311-002-A_EQ_2_VOF-STF_02373307_MP4-1500_AMM-Tvguide.mp4'}}
        self.quality = 'HTTP_MP4_EQ_1'
        self.lang = lang
        self.set_file_name()

    def set_file_name(self):
        f = self.title.replace('/', '-').replace('»', '_').replace('«', '_')
        self.fname = f.replace('\\', ' ')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    c = Core()