~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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
# -*- coding: utf-8 -*-

# artePlus.py
# This file is part of Qarte
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2011-2015 Vincent Vande Vyvre
# Licence: GPL3
# Home page : https://launchpad.net/qarte
#
# arte+7 main class

import os
import sys
import shutil
import time
import pickle
import glob
import urllib2
import re
import gettext
import logging
logger = logging.getLogger(__name__)

try:
    import pynotify
    NOTIFY = True
except:
    NOTIFY = False

from threading import Thread, current_thread
from threading import enumerate as enumerate_

from PyQt4 import QtCore, QtGui

from parsers import ArteTVParser
from loaders import PlusLoader, RateCounter
from dwnlConfig import ArtePlusDownloadingConfig

class ArtePlus(object):
    def __init__(self, main):
        super(ArtePlus, self).__init__()
        self.main = main
        self.ui = main.ui
        self.cfg = main.cfg
        self.lang = self.cfg['lang']
        self.fatal_error = False
        self.user_fld = main.user_fld
        self.thumb_fld = main.thumb_fld
        self.folds = os.path.join(main.user_fld, 'videosPlus')
        self.summaries = None
        self.is_loading = False
        self.__set_connections()
        self.videos = []
        logger.info(u"arte+7 folder: {0}".format(self.cfg["plus_folder"]))

    def get_arte_page(self):
        """run the arte+7 page parsing.

        """
        self.all_videos = []

        def get_videos(*args):
            self.pprs.parse()

        self.ui.statusbar.showMessage(_("Connecting to http://videos.arte.tv ..."))
        self.pprs = ArteTVParser(self, self.cfg['lang'], self.all_videos)
        self.pprs.parsingFinished.connect(self.populate)
        self.pprs.updatingFinished.connect(self.clean_all)

        Thread(target=get_videos, args=(None,)).start()

    def populate(self, msg):
        """Show available movies in preview window.

        This function is a slot of 'parsingFinished' signal emitted by
        the parser.

        videos = [<VideoPlusItem> instance, <VideoPlusItem> instance, ...]
        VideoPlusItem.title -- title
                     .date -- date (also used for name thumbnail and summary)
                     .duration -- duration (may not be provided)
                     .link -- page url, needed for summary and rtmp url
                     .pix -- url for thumbnail
                     .pitch -- short description
                     .HD -- rtmp url
                     .outfile -- file name choosed by user for the video
                     .preview -- thumbnail file name, made with the date
                     .summary -- long description
                     .orig -- country origin, date of creation and duration in
                                one string

        Args:
        msg -- message if parsing fail
        """
        if msg[0] is not None:
            self.main.show_warning(3, msg)
            logger.warning(u"Parsing finished with message '{0}'".format(msg))
            return

        if not len(self.all_videos):
            self.ui.editor_plus.appendPlainText("No movies")
            logger.info(u"Parsing finished, no such videos")
            return

        self.ui.statusbar.showMessage(_("Reading contents ..."))
        self.display_videos()

    def display_videos(self, videos=None, startup=True):
        if videos is None:
            self.videos = self.all_videos

        else:
            self.videos = videos

        self.items = []
        self.thumbnails = []
        self.ui.preview.clear()

        for idx, video in enumerate(self.videos):
            thumb = self.get_thumbnail(video)
            self.thumbnails.append(thumb)
            self.next_thumbnail(idx, video, thumb)

        self.ui.statusbar.clearMessage()
        logger.info(u"Display thumbnails finished")
        if startup:
            self.main.check_parsing()
            #self.pprs.update_all()

    def next_thumbnail(self, idx, video, thumb):
        """Insert thumbnail in preview.

        Args:
        idx -- index of video in list videos
        video -- <VideoPlusItem> instance
        thumb -- path of thumbnail
        """
        th, img = self.create_icon(thumb)
        video.preview = img
        item = PreviewPlusItem(self, idx, video, th)
        self.ui.preview.addItem(item)
        QtCore.QCoreApplication.processEvents()
        self.items.append(item)

    def create_icon(self, path):
        """Create the thumbnails for preview.

        Thumbnails are painted on a background wich content the shadow and
        a white frame is painted around the image.

        Args:
        path -- image path

        Returns:
        thumbnail
        """
        back = QtGui.QPixmap("medias/shadow.png")
        img = QtGui.QPixmap(unicode(path)).scaled(QtCore.QSize(180, 102))
        w = float(QtCore.QSize.width(img.size()))
        h = float(QtCore.QSize.height(img.size()))
        # white frame
        brect = QtCore.QRect(0, 0, w+3, h+3)

        bckgrnd = back.scaled(QtCore.QSize(w+25, h+25))
        painter = QtGui.QPainter()
        painter.begin(bckgrnd)
        painter.setPen(QtGui.QPen(QtCore.Qt.white, 1,
                                  QtCore.Qt.SolidLine, QtCore.Qt.RoundCap,
                                  QtCore.Qt.MiterJoin))
        painter.drawRect(brect)
        rect = QtCore.QRect(2, 2, w, h)
        # painting source
        irect = QtCore.QRect(0.0, 0.0, w, h)
        painter.drawPixmap(rect, img, irect)
        painter.end()

        return (bckgrnd, img)

    def get_thumbnail(self, video):
        """Return thumbnail path. If thumbnail is not already into the previews
        folder, he's downloaded.

        Args:
        video -- instance of VideoItem

        Returns:
        path of thumbnail
        """
        # Thumbnails are named with date, i.e. '2013 05 16, 13h01.jpg'
        #date = video.date.strftime('%Y %m %d, %Hh%M')
        thumb = os.path.join(self.thumb_fld, video.date + ".jpg")

        if not os.path.isfile(thumb):
            if video.pix is not None:
                return self.fetch_picture(video.pix, thumb)

            else:
                return "medias/noPreview.png"

        return thumb

    def fetch_picture(self, url, path):
        """Get the image file for the thumbnail.

        Args:
        url -- image file URL
        path -- path where the file must be saved
        """
        try:
            with open(path, 'wb') as objfile:
                f = urllib2.urlopen(url)
                objfile.write(f.read())
            return path

        except:
            return "medias/noPreview.png"

    def show_pitch(self, idx=None):
        """Show the movie's summary.

        Summaries are stored into a dictionary 'self.summaries' where keys are
        the dates of each video.

        Args:
        idx -- index of listWidgetItem if item is clicked
        """
        if idx is None:
            idx = self.items.index(self.ui.preview.selectedItems()[0])

        self.ui.editor_plus.clear()

        summ = self.videos[idx].summary
        if not summ or summ is None:
            # if no summary, replace it by the pitch
            summ = self.videos[idx].pitch
            orig = None
            self.videos[idx].summary = summ
            self.videos[idx].orig = orig
            self.ui.statusbar.showMessage("")

        self.edit_summary(idx)

    def on_item_added(self, idx):
        """Called when a movie is added into the basket.

        Args:
        idx -- index of movie into preview list
        """
        streams = self.get_stream_link(self.videos[idx].link)
        if streams is None:
            self.main.show_warning(5, 'Unknow')
            self.cancel_selection()
            return

        if streams == 'unvalid':
            self.main.show_warning(5, 'Page not valid')
            self.cancel_selection()
            return

        elif streams == 'restricted':
            self.main.show_warning(11, self.videos[idx].title)
            self.cancel_selection()
            return

        # Sometime, the qualitie's keys are altered, i.e. 'RTMP_EQ' become
        # 'RTMP_EQ_1' or 'RTMP_EQ_2', so we normalise the keys.
        qualities = [u'RTMP_MQ_1', u'RTMP_EQ_1', u'RTMP_SQ_1', u'RTMP_LQ_1']
        self.parse_streams(streams, idx)

        # Set the quality from the user config, if exist
        qlt = self.cfg['quality']
        if qlt is not None and qlt in self.videos[idx].streams:
            self.videos[idx].stream = qlt

        else:
            # Choose the format into medium, medium+, hight and low qualities
            for k in qualities:
                if k in self.videos[idx].streams:
                    self.videos[idx].stream = k
                    break

        self.add_pitch(idx)

    def parse_streams(self, streams, idx):
        w = False
        for k in streams.keys():
            # remove HTTP_REACH streams, keep all variants of French/German/Original
            if not 'RTMP' in k:
                del streams[k]

        self.videos[idx].streams = streams

    def cancel_selection(self):
        """Remove the last video selected from the basket.

        The video must be removed when the stream url is not found or 
        is restricted.
        """
        idx = len(self.ui.basket_plus.lst_movies) - 1
        self.ui.basket_plus.remove_item(idx)

    def add_pitch(self, idx):
        """Add the summary of selected movie for download.

        Called when a movie is added in the basket.
        """
        self.videos[idx].summary = unicode(self.ui.editor_plus.toPlainText())

    def download_notify(self, state):
        """Handle the download status.

        Keyword arguments:
        state -- status of downloading : 1 : begin
                                         2 : no longer used
                                         3 : cancelled
                                         4 : streamer is stopped
                                       str : error
        """
        if state == 1:
            self.ui.dl_plus_wdg.progress_lbl.setText(_("Downloading ..."))
            self.ui.dl_plus_wdg.progress_lbl2.setText("")

        elif state == 3:
            self.ui.dl_plus_wdg.progress_lbl.setText("")
            self.is_loading = False
            self.stop = True
            self.ui.dl_plus_wdg.cancel_btn.setEnabled(False)
            self.ui.actionC_ancel.setEnabled(False)
            self.ui.dl_plus_wdg.dwnld_btn.setEnabled(True)
            self.ui.action_Download.setEnabled(True)

        elif state == 4:
            self.is_loading = False
            self.abort_download = False

            if self.ui.basket_plus.count():
                self.ui.dl_plus_wdg.dwnld_btn.setEnabled(True)
                self.ui.action_Download.setEnabled(True)

            self.ui.dl_plus_wdg.cancel_btn.setEnabled(False)
            self.ui.actionC_ancel.setEnabled(False)

        elif isinstance(state, str):
            self.ui.editor_plus.insertPlainText(_("Stopped on error : %s" % state))
            self.is_loading = False

    def on_loading_complete(self):
        self.stop = True
        self.is_loading = False
        time.sleep(0.2)
        self.ui.dl_plus_wdg.progressBar.setValue(0)
        self.ui.dl_plus_wdg.progress_lbl.setText(_(" complete."))
        self.ui.dl_plus_wdg.progress_lbl2.setText("")
        self.ui.dl_plus_wdg.cancel_btn.setEnabled(False)
        self.ui.actionC_ancel.setEnabled(False)
        item = self.ui.basket_plus.remove_item(0)

        if self.cfg['notify']:
            self.notify(item.title)

        if self.cfg["pitch_plus"]:
            self.save_pitch(item)

        if self.cfg['copythumb_plus']:
            self.copy_thumbnail(item)

        if len(self.ui.basket_plus.lst_movies):
            self.next_download()

    def save_pitch(self, movie):
        if self.cfg['pitch_plus_unique']:
            f = os.path.join(self.cfg["plus_folder"], "index")
            movie.summary = u"\n\n" + movie.summary

        else:
            f = self.fname[:-4]

        try:
            with open(f, "a") as objf:
                objf.write(movie.summary.decode('utf-8', 'replace'))
        except Exception, why:
            self.main.show_warning(4, why)

    def copy_thumbnail(self, item):
        """Place a copy of the video thumbnail into the downloading folder.

        This feature is useful for some medias server wich have an option
        'use sameNameAsVideo.jpg' for populate "cover art".

        Args:
        item -- VideoPlusItem instance
        """
        if not self.last_loaded:
            return

        try:
            thumb = self.get_thumbnail(item)
            name = self.last_loaded[:-4] + '.jpg'
        except Exception as why:
            logger.warning(u'Copy thumbnail error: {0}'.format(why))
            return

        logger.info(u'Copy thumbnail {0}'.format(name))
        try:
            shutil.copy(thumb, name)
        except Exception as why:
            logger.warning(u'Copy error: {0}'.format(why))

    def download(self):
        """Prepare to download video(s)

        """
        if not self.cfg['plus_folder']:
            self.main.edit_settings()
            return

        if not os.path.isdir(self.cfg['plus_folder']):
            try:
                os.mkdir(self.cfg['plus_folder'])
            except Exception, why:
                self.main.show_warning(10, (self.cfg['plus_folder'], why))
                return 

        self.downloads = []
        self.ui.basket_plus.clearSelection()
        self.ui.editor_plus.clear()
        self.next_download()

    def next_download(self):
        """Get the next video into the basket and start downloading.

        """
        def fetch_video(*args):
            ldr.load()

        if self.is_loading:
            #FIXME avoid erroneous signal
            return

        self.ui.dl_plus_wdg.progressBar.setValue(0)
        self.ui.dl_plus_wdg.progressBar.blockSignals(False)

        if not len(self.ui.basket_plus.lst_movies):
            self.reset_widgets(False)
            return

        movie = self.ui.basket_plus.lst_movies[0]
        self.ui.dl_plus_wdg.progress_lbl.setText(_("Checking URL ..."))
        stream_url = self.build_stream_url(movie)
        self.stop = False
        self.is_loading = True
        self.abort_download = False
        self.last_loaded = False
        self.reset_widgets(False)
        self.ui.dl_plus_wdg.cancel_btn.setEnabled(True)
        self.ui.actionC_ancel.setEnabled(True)
        self.download_notify(1)
        tmp = os.path.join(self.cfg['plus_folder'], self.get_temp_filename())
        self.fname = os.path.join(self.cfg['plus_folder'], 
                                    self.get_filename(movie))
        ldr = PlusLoader(self)
        ldr.loadProgress.connect(self.progress_notify)
        ldr.loadingFailed.connect(self.on_loading_failed)
        ldr.loadingComplete.connect(self.on_loading_complete)
        ldr.set_url(stream_url)
        ldr.set_destination(self.fname)
        ldr.set_target(tmp)
        self.rcount = RateCounter(self, tmp)
        self.ui.dl_plus_wdg.progress_lbl.setText("Downloading")
        self.ui.basket_plus.disable_settings()
        Thread(target=fetch_video, args=(None,)).start()

    def get_stream_link(self, link):
        """Returns all streams availables.

        Args:
        link -- the movie page (ends with '?autoplay=1')

        Returns:
        dict
        """
        logger.info(u"get_stream_link: {0}".format(link))
        return self.pprs.get_stream_urls(link)

    def build_stream_url(self, item):
        """Build the stream url for the format selected by the user.

        Args:
        item -- the item video

        Returns:
        str(url)
        """
        # item.streams is the dict with all the streams
        # item.stream is the key for the format selected
        frmt = item.streams[item.stream]
        rtmp = frmt[u'streamer']
        url = frmt[u'url']
        stream = ''.join([rtmp, 'mp4:', url])
        return rtmp, url

    def check_stream_validity(self, lnk, title):
        """Some videos are available only into range 23h00 - 05h00.

        Args:
        lnk -- video's url
        """
        if lnk is None:
            return False

        restricted_re = re.compile('carton_23h_..\.mp4')
        fallback_re = re.compile('fallback_..\.mp4')
        match = restricted_re.search(lnk)

        if match:
            self.ui.dl_plus_wdg.progress_lbl.setText("")
            self.main.show_warning(11, title)
            return False

        match = fallback_re.search(lnk)

        if match:
            self.ui.dl_plus_wdg.progress_lbl.setText("")
            self.main.show_warning(6, title)
            return False

        return True

    def progress_notify(self, val):
        """Update progress bar

        Args:
        val -- percent value
        """
        if int(val) == 100 and self.ui.dl_plus_wdg.progressBar.value() < 10:
            # Avoid the persistence of the thread
            return

        if int(val) != self.ui.dl_plus_wdg.progressBar.value():
            self.ui.dl_plus_wdg.progressBar.setValue(val)

            if not int(val) % 3:
                rate, rem = self.rcount.counter(val)
                self.ui.dl_plus_wdg.progress_lbl.setText(rate)
                self.ui.dl_plus_wdg.progress_lbl2.setText(rem)

    def on_progress(self, val):
        if val > 99.8:
            self.ui.dl_plus_wdg.progressBar.blockSignals(True)
            self.ui.dl_plus_wdg.progressBar.setValue(0)
            self.ui.dl_plus_wdg.progress_lbl.setText("")
            self.ui.dl_plus_wdg.progress_lbl2.setText("")
            self.download_notify(2)

    def cancel(self):
        """Cancel downloading on user's request."""
        if self.is_loading:
            self.ui.dl_plus_wdg.progress_lbl2.setText(_("Downloading cancelled."))
            self.abort_download = True
            self.stop = True
            self.download_notify(3)


    def on_loading_failed(self, why):
        if why != u"Loading aborted by user":
            self.ui.dl_plus_wdg.progress_lbl2.setText(_("Error."))
            logger.info(u"No reply from rtmp://artestras, loading aborted.")
            self.main.show_warning(12)

        item = self.ui.basket_plus.remove_item(0)
        self.download_notify(3)
        time.sleep(0.5)
        self.next_download()

    def get_temp_filename(self):
        """Return a temp file name build with time.

        """
        d = str(time.time()).replace(".", "")
        t = "".join(["plus", d, ".flv"])
        count = 1

        while 1:
            target = os.path.join(self.cfg['plus_folder'], t)
            if os.path.isfile(target):
                t = "".join(["plus", d, str(count), ".flv"])
                count += 1

            else:
                break

        return t

    def get_filename(self, mov):
        date = mov.date.replace(' ', '_').replace(',', '')
        if mov.outfile is not None:
            # File name modified by user
            f = "".join([mov.outfile, "-", date, ".flv"])

        else:
            f = "".join([mov.title, "-", date, ".flv"])

        for c in [u'»', u'«', u'/', u'\\', u'"']:
            f = f.replace(c, "_")

        return f

    def config_downloading(self, idx):
        """Call the downloading setting dialog box.

        Args:
        idx -- index of the video
        """
        movie = self.ui.basket_plus.lst_movies[idx]
        qlt = self.cfg['quality']
        obj = [movie.title, movie.outfile, movie.streams, movie.stream, 
                self.cfg['quality']]
        self.gui = ArtePlusDownloadingConfig(obj)
        reply = self.gui.exec_()
        movie.outfile = obj[1]
        movie.stream = obj[3]
        self.cfg['quality'] = obj[4]
        self.ui.basket_plus.rename(idx, obj[1])
        if qlt != self.cfg['quality']:
            self.main.save_config()

    def download_later(self, idx):
        """Call the differed download dialog.

        Called from context menu on an item.

        Args:
        idx -- item's index 
        """
        self.main.set_differed_tasks(self.videos[idx])

    def edit_summary(self, idx):
        """Show the summary.

        Args:
        idx -- video item index
        """
        if self.videos[idx].orig is None:
            self.videos[idx].orig = ""

        if self.videos[idx].summary is None:
            self.videos[idx].summary = u"No informations"

        summary = self.videos[idx].summary.decode('utf-8', 'replace')
        font = QtGui.QFont("sans", 10)
        c_form = QtGui.QTextCharFormat()
        c_form.setFont(font)
        font1 = QtGui.QFont("sans", 12)
        font1.setWeight(75)
        c_form1 = QtGui.QTextCharFormat()
        c_form1.setFont(font1)

        self.ui.editor_plus.setCurrentCharFormat(c_form1)
        self.ui.editor_plus.appendPlainText(self.videos[idx].title)

        self.ui.editor_plus.setCurrentCharFormat(c_form)
        t = "  %s " % self.videos[idx].date
        t += self.videos[idx].duration
        self.ui.editor_plus.insertPlainText(t)
        t = "".join([self.videos[idx].orig, "\n"])
        self.ui.editor_plus.appendPlainText(t)

        self.ui.editor_plus.appendHtml(summary)

        self.ui.editor_plus.verticalScrollBar().setValue(0)
        QtCore.QCoreApplication.processEvents()

        return False

    def on_item_selected(self, idx):
        """Check if selection mode is interactiv with differed download
        dialog.

        Args:
        idx -- item's index
        """
        if self.main.is_interact_with_dialog:
            self.main.send_item_to_download_later(self.videos[idx])

    def clean_all(self):
        """Purge the thumbnails folder and the summaries file.

        """
        logger.info(u"Purge old data")
        def clean(*args):
            oldest = glob.glob(os.path.join(self.thumb_fld, "*.jpg"))

            for old in oldest:
                if old not in self.thumbnails:

                    try:
                        os.remove(old)
                    except Exception, why:
                        logger.info(u"Remove old thumbnail {0} failed"
                                    .format(oldest))
                        logger.info(u"Reason: {0}".format(why))

            movies = []
            pitchs = self.summaries.keys()
            len1 = len(pitchs)
            for th in self.thumbnails:
                movies.append(os.path.splitext(os.path.basename(th))[0])

            for p in pitchs:
                if p not in movies:
                    del self.summaries[p]
            self.pprs.save_videos_infos()

        Thread(target=clean, args=(None,)).start()

    def reset_widgets(self, b):
        self.ui.dl_plus_wdg.dwnld_btn.setEnabled(b)
        self.ui.action_Download.setEnabled(b)
        self.ui.dl_plus_wdg.cancel_btn.setEnabled(b)
        self.ui.actionC_ancel.setEnabled(b)

    def notify(self, t):
        """Show GTK notification.

        Arguments :
        t -- title of video
        """
        if not NOTIFY:
            return
        img_uri = os.path.join(os.getcwd(), "medias/qarte_logo.png")
        pynotify.init("Arte+7 Recorder")
        notification = pynotify.Notification(t, "Download complete", img_uri)
        notification.show() 

    def __set_connections(self):
        self.ui.dl_plus_wdg.dwnld_btn.clicked.connect(self.main.download_plus)
        self.ui.dl_plus_wdg.cancel_btn.clicked.connect(self.main.cancel_plus)
        self.ui.basket_plus.itemAdded.connect(self.on_item_added)

class PreviewPlusItem(QtGui.QListWidgetItem):
    def __init__(self, plus, idx, item, img, parent=None):
        super(PreviewPlusItem, self).__init__()
        self.plus = plus
        self.idx = idx
        self.is_double_clicked = False
        self.setIcon(QtGui.QIcon(img))
        text = self.set_thumbnail_text(item.title)
        self.setText(text)
        self.setTextAlignment(QtCore.Qt.AlignHCenter)
        self.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

    def set_thumbnail_text(self, txt):
        """Format the movie's title.

        Args:
        txt -- title

        Returns:
        Formated text
        """
        if len(txt) < 21:
            return txt

        form = ""
        while 1:
            chain = txt[:21]
            count = len(chain) - 1

            while 1:
                if chain[count] == " ":
                    break

                count -= 1
                if count == 0:
                    count = len(chain) - 1
                    break

            form = form + chain[:count] + "\n"
            txt = txt[count+1:]

            if not txt:
                break

            elif len(txt) < 21:
                form = form + txt + "\n"
                break

        return form[:-1]

    def show_context_menu(self, pos):
        self.__show_menu(pos)

    def __show_menu(self, pos):
        """Build and show context menu.

        Keyword arguments:
        pos -- event.pos()
        """
        self.menu = QtGui.QMenu()
        self.act_add = QtGui.QAction(self.menu)
        self.act_add.setText(_("Add to download list"))
        self.menu.addAction(self.act_add)
        self.act_show = QtGui.QAction(self.menu)
        self.act_show.setText(_("Show summary"))
        self.menu.addAction(self.act_show)
        self.act_diff = QtGui.QAction(self.menu)
        self.act_diff.setText(_("Differed download"))
        self.menu.addAction(self.act_diff)
        self.act_add.triggered.connect(self.add_to_download)
        self.act_show.triggered.connect(self.show_pitch)
        self.act_diff.triggered.connect(self.set_cron_job)
        self.menu.setStyleSheet(self.plus.ui.menu_style)
        self.menu.popup(pos)

    def add_to_download(self):
        """Append video to download basket.

        """
        self.plus.ui.basket_plus.add_object(self.idx)

    def show_pitch(self):
        """Show the summary.

        """
        self.plus.show_pitch(self.idx)

    def set_cron_job(self):
        """Set a differed download.

        """
        self.plus.download_later(self.idx)