~vincent-vandevyvre/qarte/trunk

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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# -*- coding: utf-8 -*-

# loaders.py
# This file is part of Qarte
#    
# Author : Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2011-2016 Vincent Vande Vyvre
# Licence: GPL3
# Home page : https://launchpad.net/qarte
#
# Movie's loaders for arte TV Guide and arte Live Web

import sys
import os
import time
import re
import subprocess
import select
import datetime
import shutil
import gettext
import logging
logger = logging.getLogger("loader")

from urllib import urlretrieve, ContentTooShortError
from urllib2 import URLError

from PyQt4.QtCore import QObject, pyqtSignal, QString, QLocale
from PyQt4.QtGui import QApplication


class PlusLoader(QObject):
    loadProgress = pyqtSignal(float)
    loadingFailed = pyqtSignal(str, str)
    loadingComplete = pyqtSignal()
    def __init__(self, main):
        super(PlusLoader, self).__init__()
        self.main = main
        self.lang = main.lang
        self.is_loading = False
        self.kill_request = False
        self.url = None
        self.target = None
        self.pid = None
        self.is_daemon = False

    def set_url(self, url):
        stream, path = url
        ptc , st = stream.split('://')
        hst, app = st.split('/', 1)
        if app.endswith('/'):
            app = app[:-1]
        pp = 'mp4:' + path
        self.cmd = ["rtmpdump", "--host", hst, "--port", "1935", "--protocol",
                     ptc, "--app", app, "--playpath", pp]

    def set_target(self, target):
        if self.is_daemon:
            # When python is invoked by cron the file system encoding
            # is not usable. Maybe related with this issue:
            # http://bugs.python.org/issue13643
            self.target = target.encode('utf-8', 'replace')

        else:
            self.target = target.encode(sys.getfilesystemencoding(), 'replace')

    def set_destination(self, dest):
        if self.is_daemon:
            self.dest = dest.encode('utf-8', 'replace')

        else:
            self.dest = dest.encode(sys.getfilesystemencoding(), 'replace')

    def load(self):
        cmd_dl = self.cmd[:]
        cmd_dl.extend(['-o', self.target])
        cmd_resume = self.cmd[:]
        cmd_resume.extend(['--resume', '-o', self.target])
        cmd_resume_skip = self.cmd[:]
        cmd_resume_skip.extend(['--resume', '--skip', '1', '-o', self.target])
        cmd = cmd_dl
        max_skip_cnt = 10
        percent_re = re.compile("\((.+)%\)$")
        self.display_usable_command(cmd_dl[:])
        self.print_(u"Downloading ......\n {0}".format(cmd))

        try:
            reply = subprocess.Popen(cmd, universal_newlines=True,
                                    stdout=subprocess.PIPE, 
                                    stderr=subprocess.STDOUT)
            self.is_loading = True

        except (IOError, OSError) as exc:
            self.print_(u"\nSubprocess ERROR: {0}".format(exc))
            self.loadingFailed.emit('Error', str(exc))
            self.is_loading = False
            return

        self.pid = reply.pid + 1
        logger.info("Run process pid: %s" % self.pid)
        percent = "0"
        duration = "0"
        err = ""
        while 1:
            text = reply.stdout.readline()[:-1]
            if type(text) != str or text == '' and reply.poll() != None:
                self.is_loading = False 
                break

            elif type(text) == str and len(text) > 6:
                if "ERROR:" in text:
                    if "SWFVerification" in text:
                        pass
                    else:
                        ch = u"Read packet error, maybe incomplete. ... continue."
                        self.print_(ch)

                elif " sec (" in text:
                    chains = text.split(" ")
                    try:
                        duration = chains[3]
                    except:
                        pass

                    try:
                        percent = float(chains[5][1:-2])
                    except Exception as exc:
                        percent = 2

                    self.loadProgress.emit(percent)

            if self.kill_request or self.main.abort_download:
                err = u"Loading aborted by user"
                self.abort_subprocess()
                # Avoid to kill the next subprocess
                time.sleep(0.5)
                self.loadingFailed.emit('Error', err)
                return

        self.is_loading = False
        self.rename_target()
        self.loadingComplete.emit()

    def abort_subprocess(self):
        """Kill the downloading process.

        This called by the user.
        """
        if self.pid is not None:
            logger.info("Kill subprocess pid: %s" % self.pid)
            try:
                # Kill first rtmpdump
                os.kill(self.pid-1, 15)    
            except Exception as why:
                logger.info(u"Kill process error: %s" % why)
            # then kill subprocess if it's alive
            try:
                os.kill(self.pid, 15)
            except:
                pass

    def remove_tempfile(self):
        try:
            os.unlink(self.target)
        except Exception as why:
            self.print_(u"Remove temp file {0}\n\tError: {1}"
                                    .format(self.target, why))

    def rename_target(self):
        count = 1
        dest = self.dest
        caput, cauda = os.path.splitext(dest)
        self.renamed = False

        while 1:
            if os.path.isfile(dest):
                dest = "".join([caput, '(', str(count), ')', cauda])
                count +=1
            else:
                break

        try:
            shutil.move(self.target, dest)
        except Exception as why:
            msg = u"Renaming error: \n\t\tfile: {0}\n\t    to: "\
                                "{1}\n\t    Reason: {2}"\
                                .format(self.target, dest, why)
            self.print_(msg)

        else:
            try:
                msg = u"File: {0}\n\t  Renamed: {1} ".format(self.target, dest)
            except:
                # syndrome fedora
                msg = u"File renamed"
            self.print_(msg)
            self.main.last_loaded = dest

    def display_usable_command(self, cmd):
        """Shows the command usable into a terminal.

        Debugging usage.
        """
        cmd[-3] = unicode("'%s'" % cmd[-3])
        try:
            l = u" ".join(cmd)
            sys.stdout.write("\nUse this command into a terminal:\n%s\n\n" % l)
        except:
            pass

    def print_(self, msg):
        if self.is_daemon:
            print u"{0}  {1}".format(time.time(), msg)

        else:
            logger.info(msg)


class LiveLoader(QObject):
    loadProgress = pyqtSignal(float)
    loadComplete = pyqtSignal(str)
    def __init__(self, main):
        super(LiveLoader, self).__init__()
        self.main = main
        self.is_loading = False
        self.kill_request = False
        self.is_daemon = False
        self.url = None
        self.target = None
        self.pattern = re.compile("(?P<scheme>[^:]*)://(?P<host>[^/^:]*):"
                                    "{0,1}(?P<port>[^/]*)/(?P<app>.*?)/"
                                    "(?P<playpath>\w*?\:.*)", re.DOTALL)

    def set_url(self, url):
        self.url = url

    def set_target(self, target):
        if self.is_daemon:
            # When python is invoked by cron the file system encoding
            # is not usable. Maybe related with this issue:
            # http://bugs.python.org/issue13643
            self.target = target.encode('utf-8', 'replace')

        else:
            self.target = target.encode(sys.getfilesystemencoding(), 'replace')

    def set_destination(self, dest):
        if self.is_daemon:
            self.dest = dest.encode('utf-8', 'replace')

        else:
            self.dest = dest.encode(sys.getfilesystemencoding(), 'replace')

    def format_command(self):
        match = re.match(self.pattern, self.url)
        cmd = ""
        if match != None:
            cmd = " ".join(['rtmpdump', '--host', '%host%', '--port', 
                            '%port%', '--protocol', '%scheme%', 
                            '--app %app%', '--playpath', '%playpath%'])
            cmd = cmd.replace('%scheme%', match.group('scheme'))\
                            .replace('%host%', match.group('host'))\
                            .replace('%app%', match.group('app'))\
                            .replace('%playpath%', match.group('playpath'))
            if( match.group('port') != ""):
                cmd = cmd.replace('%port%', match.group('port'))
            elif(self.url[ :6 ] == 'rtmpte'):
                cmd = cmd.replace('%port%', '80')
            elif(self.url[ :5 ] == 'rtmpe'):
                cmd = cmd.replace( '%port%', '1935')
            elif(self.url[ :5 ] == 'rtmps'):
                cmd = cmd.replace('%port%', '443')
            elif(self.url[ :5 ] == 'rtmpt'):
                cmd = cmd.replace('%port%', '80')
            else:
                cmd = cmd.replace('%port%', '1935')

        else:
            cmd = 'rtmpdump -r ' + self.url

        return cmd

    def load(self):
        """Download a video from the server arte Live Web.

        """
        if self.url.startswith(("http://artestras", "http://arteconcert")):
            # New server arte concert
            self.load_arte_concert()
            return

        if self.url[ :4 ] == "rtmp":
            cmd = self.format_command()
            cmd = "".join([cmd, " -o ", self.target])

        #else:
            #return

        arguments = cmd.split()
        self.print_(u"Downloading ......\n {0}".format(arguments))

        try:
            reply = subprocess.Popen(arguments, universal_newlines=True,
                                    stdout=subprocess.PIPE, 
                                    stderr=subprocess.STDOUT)
            self.is_loading = True

        except (IOError, OSError) as exc:
            self.print_(u"\nSubprocess ERROR: {0}".format(exc))
            self.loadComplete.emit(exc)
            self.is_loading = False
            return

        percent = "0"
        duration = "0"
        err = ""
        while 1:
            text = reply.stdout.readline()[:-1]
            if type(text) != str or text == '' and reply.poll() != None:
                self.is_loading = False 
                break

            elif type(text) == str and len(text) > 6:
                if "ERROR:" in text:
                    err = text
                    break

                elif " sec (" in text:
                    chains = text.split(" ")
                    try:
                        duration = chains[3]
                    except:
                        pass

                    try:
                        percent = float(chains[5][1:-2])
                    except Exception as exc:
                        percent = 2

                    self.loadProgress.emit(percent)

            if self.kill_request:
                err = "aborted"
                break

        try:
            reply.kill()
        except:
            pass

        self.is_loading = False
        self.rename_target()
        self.loadComplete.emit(err)

    def hook(self, blocks, size, filesize):
        """Callback handler for urlretrieve.

        Args:
        blocks --- number of blocks already loaded
        size -- size of the last block
        filesize -- the size of the file
        
        see: http://bugs.python.org/issue16409
        """
        if self.kill_request:
            # Downloading aborted by the user
            raise DownloadingAborted('Process killed intentionnaly')

        if filesize < 1:
            # When the file size is not returned by the server, filesize = -1
            self.loadProgress.emit(-1.0)

        else:
            self.amount_loaded += size
            percent = (self.amount_loaded * 100.0) / filesize
            if int(percent) > self.percent:
                self.loadProgress.emit(percent)
                self.percent = int(percent)

    def load_arte_concert(self):
        """Download a video from the server arte Concert.

        """
        self.print_(u"Downloading: {0}".format(self.url))
        self.amount_loaded = 0
        self.percent = 0
        err = ""
        try:
            tmpfile, headers = urlretrieve(self.url, self.target, self.hook)
        except URLError as why:
            self.print_(u"Downloading error: {0}".format(str(why)))
            self.loadComplete.emit(str(why))
            self.is_loading = False
            return

        except ContentTooShortError as why:
            self.print_(u"Interrupted at {0}".format(self.percent))
            self.loadComplete.emit(str(why))
            self.is_loading = False
            return

        except DownloadingAborted:
            err = 'aborted'

        self.is_loading = False
        self.rename_target()
        self.loadComplete.emit(err)

    def rename_target(self):
        """Rename the downloaded file.

        """
        count = 1
        dest = self.dest
        caput, cauda = os.path.splitext(dest)
        while 1:
            # If a file with the same name already exists, we add an indice
            if os.path.isfile(dest):
                dest = "".join([caput, '(', str(count), ')', cauda])
                count +=1
            else:
                break

        try:
            os.rename(self.target, dest)
        except Exception as why:
            self.print_(u"Renaming error: \n\t\t file: {0}\n\t    to: "\
                            "{1}\n\t    Reason: {2}"
                            .format(self.target, dest, why))

        else:
            self.print_(u"File: {0}\n\t   Renamed: {1} "
                            .format(self.target, dest))
            self.main.last_loaded = dest

    def print_(self, msg):
        if self.is_daemon:
            print u"{0}  {1}".format(time.time(), msg)

        else:
            logger.info(msg)

class DownloadingAborted(BaseException):
    pass

class RateCounter(object):
    def __init__(self, site, fname):
        """Calculate and show the downloading rate.

        Args :
        site -- ArtePlus or ArteLiveWeb instance
        movie -- instance of movie
        """
        self.site = site
        lang = QLocale.system().name()
        self.locale = QLocale(lang)
        self.target = fname
        self.time_base = time.time()
        self.size = 0
        if os.path.isfile(self.target):
            inf = os.stat(self.target)
            self.size = inf.st_size

    def counter(self, p):
        """Evaluate the rate of downloading.

        Args :
        p -- percent

        Returns:
        Bandwidth, estimated remaining time
        """
        loop = 0
        size = 0
        while loop < 3:
            try:
                size = os.path.getsize(self.target)
            except OSError, why:
                loop += 1
                time.sleep(0.3)

            else:
                break

        if not size:
            return "", ""

        delta = size - self.size
        t =  time.time() - self.time_base
        r = int ((size / t) / 1024)
        rate = self.locale.toString(r)
        rem = ((t / p) * 100) - t
        m, s = divmod(rem, 60)
        st = QString(_("Speed:"))
        st2 = QString(_("Remaining time:"))
        rate_txt = "%s %s Kio/sec." % (st, rate)
        rem_txt = "%s %s min. %s sec." % (st2, int(m), int(s))

        return rate_txt, rem_txt