Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#151 Le 05/04/2007, à 22:01

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

T'as récupéré la dernière version ? Faite il y a quelques semaines... je pense qu'elle doit toujours fonctionner !


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne

#152 Le 05/04/2007, à 22:06

juju8630

Re : [Programme] Télécharger la musique de RadioBlogClub

Alors Là c'est con et tres con ! ! !
j'avais passé pas mal d'heure à ajouter un bouton Lecture au soft ... et cela fonctionnait jusqu'a .... aujourd'hui, je comptais vous le soumettre dans qqes jours .... mouais c'est con !
et je n'ai pas trop d'idées pour le def search_url et surtout pas trop de temps


Bien à vous !

#153 Le 05/04/2007, à 22:13

juju8630

Re : [Programme] Télécharger la musique de RadioBlogClub

Foch, ba non la derniere version ne tourne pas

#154 Le 06/04/2007, à 00:44

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

Effectivement j'ai testé, et ca ne fonctionne plus roll
Je me penche sur le problème ce week end, je pense pas qu'il y ait grand chose à faire, certainement une expression régulière à changer.

Sinon je suis super interessé par ton bouton magique pour lire le son, tu peux m'envoyer le code par mail ? Je veux bien y jeter un coup d'oeil !
Et ca utilise quoi pour lire ? Ca appelle un player externe ou tu geres ca en interne ? (ce qui serait super classe, et certainement possible si les bonnes bibliotheques existent en python, ce dont je ne doute pas !)

PS: ca me gonfle moi aussi ces changements, ils pourraient au moins avoir la décence de me prévenir ! big_smile


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne

#155 Le 06/04/2007, à 07:18

juju8630

Re : [Programme] Télécharger la musique de RadioBlogClub

Salut floch !
Ci joint le code, ATTENTION il est à épurer car je débute (1semaine) le pyton donc c'est un peu à l'arrache ! !!

#!/usr/bin/env python

###
#
# RBCD - RadioBlogClub Downloader - Download songs from RadioBlogClub.
# Copyright (C) 2006 Julien Faucher <faucherj AT gmail DOT com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
###

__version__ = "2.0.1"
__date__ = "28/12/2006"

import urllib, re, sys, gobject, gtk, threading, os

# download folder
result_folder = "~/rbcd_result"

# icon file
icon_file = "/usr/share/icons/hicolor/24x24/apps/sound-juicer.png"

(COLUMN_NUMBER, COLUMN_DOWNLOAD, COLUMN_NAME) = range(3)


class UserInterface(gtk.Window):
    def __init__(self, parent=None):
        """ Create window and model """
        
        # create window, etc
        gtk.Window.__init__(self)
        try:
            self.set_screen(parent.get_screen())
        except AttributeError:
            self.connect('destroy', lambda *w: gtk.main_quit())
        self.set_title('RadioBlogClub Downloader')

        self.set_border_width(8)
        self.set_default_size(300, 250)

        vbox = gtk.VBox(False, 8)
        self.add(vbox)

        # top part of window
        box_top = gtk.HBox(False, 5)

        self.label = gtk.Label('Enter keywords :')
        self.entry = gtk.Entry(max=0)
        self.search = gtk.Button(stock=gtk.STOCK_FIND)
        self.select_all = gtk.Button("Select all")
        self.select_none = gtk.Button("Select none")
        self.select_website = gtk.combo_box_new_text()

        self.select_website.append_text("RadioBlogClub");
        self.select_website.append_text("My Bloop");

        box_top.pack_start(self.label, False, False)
        box_top.pack_start(self.entry, False, False)
        box_top.pack_start(self.search, False, False)
        box_top.pack_start(self.select_all , False, False)
        box_top.pack_start(self.select_none, False, False)
        box_top.pack_end(self.select_website, False, False)

        self.select_website.set_active(0)

        self.search.connect("clicked", self.searchSongs, None)
        self.entry.connect("activate", self.searchSongs, None)
        self.select_all.connect("clicked", self.selectAll, None)
        self.select_none.connect("clicked", self.selectNone, None)
        vbox.pack_start(box_top, False, False)

        # middle part of window
        sw = gtk.ScrolledWindow()
        sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        vbox.pack_start(sw)

        # create tree model
        self.model = gtk.ListStore(gobject.TYPE_INT,
                                   gobject.TYPE_BOOLEAN,
                                   gobject.TYPE_STRING)
        
        # create tree view
        self.treeview = gtk.TreeView(self.model)
        self.treeview.set_rules_hint(True)
        self.treeview.set_search_column(COLUMN_NAME)

        sw.add(self.treeview)

        # down part of window
        box_down = gtk.HBox(False, 5)
        
        self.state_label = gtk.Label('')
        download = gtk.Button('Telecharger')
        exitb = gtk.Button(stock=gtk.STOCK_QUIT)
        aboutb = gtk.Button(stock=gtk.STOCK_DIALOG_INFO)
        lecture = gtk.Button('Lecture')
        
        box_down.pack_end(exitb, False, False)
        box_down.pack_end(aboutb, False, False)   
        box_down.pack_end(download, False, False)
        box_down.pack_end(lecture, False, False)
        box_down.pack_start(self.state_label, False, False)
        
        exitb.connect_object("clicked", gtk.Widget.destroy, self)
        download.connect("clicked", self.download, None)
        aboutb.connect("clicked", self.about, None)
        lecture.connect("clicked", self.lecture, None)
        vbox.pack_start(box_down, False, False)

        # create columns
        self.add_columns(self.treeview)

        # change window size
        self.resize(800, 500)

        # set icon
        #self.set_icon_from_file(icon_file)

        # default website
        #self.website = RadioBlogClub(self)

        # print everything
        self.show_all()

    def add_columns(self, treeview):
        """ Add the 3 columns """

        # column for fixed toggles
        renderer = gtk.CellRendererToggle()
        renderer.connect('toggled', self.select_toggled, self.model)

        column = gtk.TreeViewColumn('Select', renderer, active=COLUMN_DOWNLOAD)

        # set this column to a fixed sizing(of 50 pixels)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
        column.set_fixed_width(50)
        treeview.append_column(column)
        
        # column for description
        column = gtk.TreeViewColumn('#', gtk.CellRendererText(),
                                     text=COLUMN_NUMBER)
        column.set_sort_column_id(COLUMN_NUMBER)
        treeview.append_column(column)
        
        # column for description
        column = gtk.TreeViewColumn('Song name', gtk.CellRendererText(),
                                     text=COLUMN_NAME)
        column.set_sort_column_id(COLUMN_NAME)
        treeview.append_column(column)

    def select_toggled(self, cell, path, model):
        """ Change the select status """
        
        # get toggled iter
        iter = model.get_iter((int(path),))
        download = model.get_value(iter, COLUMN_DOWNLOAD)
        lecture = model.get_value(iter, COLUMN_DOWNLOAD)
        # do something with the value
        download = not download
        lecture = not lecture

        # set new value
        model.set(iter, COLUMN_DOWNLOAD, download)
        model.set(iter, COLUMN_DOWNLOAD, lecture)
        
    def searchSongs(self, widget, data=None):
        """ Start searching songs according to the given key words """

        # get the selected website to use
        selected = self.select_website.get_active()
        if selected == 0:
            self.website = RadioBlogClub(self)
        else:
            self.website = MyBloop(self)

        try:
            search = Search(self, self.website, self.entry.get_text().split(" "))
            self.setStateText("Starting research...")
            print "Starting research..."
            search.start()
        except AssertionError, detail:
            self.setStateText(str(detail))
            print detail
        except IOError:
            self.setStateText("Could not connect.")
            
    def setSongList(self, songs, data):
        self.songs = songs
        self.data = data
        self.clearList()
        self.createList()
        self.setStateText("Research done.")
        print "Research done."

    def selectAll(self, widget, data=None):
        """ Select all the lines """
        
        # iter on all the paths
        iter = self.model.get_iter_first()
        while iter is not None:
            self.model.set_value(iter, 1, 1)
            iter = self.model.iter_next(iter)

    def selectNone(self, widget, data=None):
        """ Select no line """
        
        # iter on all the paths
        iter = self.model.get_iter_first()
        while iter is not None:
            self.model.set_value(iter, 1, 0)
            iter = self.model.iter_next(iter)
    
        

        
    def lecture(self, widget, data=None):
        print "hello"
        try:
            lecture = Lecture(self, self.website, self.songs, self.model)
            lecture.start()
            
        except AssertionError, detail:
            self.setStateText(str(detail))
           
          
    def download(self, widget, data=None):
        """ Start downloading the selected songs """
        
        try:
            down = Download(self, self.website, self.songs, self.model)
            down.start()
            
        except AssertionError, detail:
            self.setStateText(str(detail))
            print detail

    def createList(self):
        """ Create the song list """
        
        for item in self.data:
            iter = self.model.append()
            self.model.set(iter,
                           COLUMN_NUMBER, item[COLUMN_NUMBER],      
                           COLUMN_DOWNLOAD, item[COLUMN_DOWNLOAD],
                           COLUMN_NAME, Search.shortName(item[COLUMN_NAME]))

    def clearList(self):
        """ Clear the song list """
        
        self.model.clear()

    def setStateText(self, text):
        """ Change state text """
        
        self.state_label.set_text(text)

    def about(self, widget, data=None):
        """ Print an about dialog window"""
        
        dialog = gtk.AboutDialog()
        dialog.set_name("RBCD")
        dialog.set_comments("A program to download songs from RadioBlogClub")
        dialog.set_copyright("\302\251 Copyright 2006 Julien Faucher")
        dialog.set_website("http://www.dobitchu.info/blog")
        dialog.set_license('GNU General Public License version 2')
        dialog.set_version(__version__)
        dialog.set_authors(['Main programmer :', ' Julien Faucher <faucherj@gmail.com>',
                            ' ', 'and contributors :' ,' Guillaume86'])
        #dialog.set_icon_from_file(icon_file)
        # close dialog on user response
        dialog.connect("response", lambda d, r: d.destroy())
        dialog.show()

    def main(self):
        """ Main function, one to rule them all """
        
        # create download folder
        if not os.path.isdir(os.path.expanduser(result_folder)):
            os.mkdir (os.path.expanduser(result_folder)) 

        gobject.threads_init()
        
        gtk.gdk.threads_enter()
        gtk.main()
        gtk.gdk.threads_leave()
        
        return 0


class RadioBlogClub:
    def __init__(self, parent):
        """ Init the thread """

        self.parent = parent

    @staticmethod
    def rename(file):
        """ Change the RBS extension to MP3 """
        
        name = file.split("/")[-1].split(".")

        # remove some extensions
        name = [part for part in name
                if not part.lower() in ("rbs", "mp3")]
            
        # the file is a mp3, add .mp3 at the end of the name
        name.append("mp3")
        return ".".join(name)

    def searchURL(self, i, params):
        """ Return the URL to search the MP3 """

        url = "http://www.radioblogclub.com/search/" + str(i) + "/" + params
        
        try:
            return urllib.urlopen(url).read()
        except IOError:
            print "Error : could not connect"
            raise #reraise exception
    
    def search(self, text):
        """ Do a research """

        # get the webpage data
        try:
            data = self.searchURL(0, "_".join(text))
        except IOError:
            gobject.idle_add(self.parent.setStateText, "Error : could not connect")
            gtk.gdk.threads_leave()
            return

        lines = data.split('\n')

        # regular expression to find the number of songs
        reg1 = re.compile('^.*of about <b>(.*)</b> tracks for.*$')

        n_songs = 0
    
        # get the number of songs
        for line in lines:
            if reg1.match(line):
                n_songs = int(reg1.search(line).groups()[0])
                break

        # if no song is found, exit
        if n_songs == 0:
            gobject.idle_add(self.parent.setSongList, [], [])
            gtk.gdk.threads_leave()
            return

        # get the number of pages to browse
        n_pages = n_songs / 50 + 1

        # inform the user
        gobject.idle_add(self.parent.setStateText, \
                         "Search started... (about %i songs)" % (n_songs,))

        # download the pages
        pages = []
        pages.append(lines)
        numbers = [i * 50 for i in range(1, n_pages)]

        try:
            for i in numbers:
                pages.append(self.searchURL(i, "_".join(text)).split('\n'))
        except IOError:
            gobject.idle_add(self.parent.setStateText, "Error : could not connect")
            gtk.gdk.threads_leave()
            return

        # regular expression to find the song URLs
        reg2 = re.compile('^.*<td><a href=\"(/open/.*)\">(.*)</a></td>.*$')
        songs = []
        data = []
        i = 0
    
        # parse the HTML data to find the songs and save in a list
        for page in pages:
            for line in page:
                if reg2.match(line):
                    result = reg2.search(line).groups()
                    try:
                        url = unicode(result[0], "utf-8")
                        name = unicode(result[1], "utf-8")
                        songs.append((url, name))
                        data.append((i + 1, False, name))
                        i += 1
                    except UnicodeDecodeError:
                        # encoding error: skip song
                        print "%i : Encoding error. Skipping song." % (i,)

        gobject.idle_add(self.parent.setSongList, songs, data)
        
    def lecture(self, songs, model):
        """ Download the files """
        
        # init the counters
        counter_ok = 0
        counter_all = 0

        # iter on all the paths
        iter = model.get_iter_first()
        while iter is not None:
            number = model.get_value(iter, 0)
            selected = model.get_value(iter, 1)
            iter = model.iter_next(iter)

            # if the song is selected for download...
            if selected:
                counter_all += 1
                name = songs[number - 1][1]
                name_search = name.replace('(', '\(').replace(')', '\)')\
                              .replace('[', '\[').replace(']', '\]')\
                              .replace('\'', '\\\\\'').replace('&', '\&')

                # change the extension to .mp3
                name = RadioBlogClub.rename(name)

                

                url = "http://www.radioblogclub.com" + songs[number - 1][0]\
                      .replace(' ', '%20')

                print "Downloading %s" % (name, )
                print "from %s" % (url, )

                # get the HTML file with the RBS adress
                playlist = urllib.urlopen(url).read().split('\n')

                # find the URL
		reg3 = re.compile('.*openRadio.*')
		# find the URL
		url = ""
		for line in playlist:
			if reg3.match(line):
     			    url = reg3.search(line).group(0).replace('</fieldset><div class="clearer" style="height:5px">&nbsp;</div><div><div style="float:left; margin-top:10px;width:100%;margin-right:3px;" class="button_off"><a class="button" style="height:24px;padding-top:12px;" href="javascript:openRadio(\'','').replace('?autoplay=\')">Click here to play</a></div></div><div class="clearer" style="height:15px; margin-bottom: 15px; border-bottom:dotted 1px #CCC">&nbsp;</div><div class="content" style="float:left;width:730px;"><h3 style="margin-bottom:0px;margin-top:-4px;">Radio.blog Playlist</h3><div class="clearer" style="height:10px">&nbsp;</div><div id="ads"><script type="text/javascript"><!--','').replace(' ','')+'/sounds/'+ name_search + '.rbs'
        		    url = url.replace('\\', '').replace(' ', '%20')
                                                    

                # the RBS file was not found
                if url == "":
                    state = "Song not found. (Maybe the file was a SWF)"
                    gobject.idle_add(self.parent.setStateText, state)
                    print state
                    continue

                # download the file
                try:
                    print "Downloading to %s..." % (result_folder, )
                    totem_cmd = url
                    from subprocess import Popen
                    import os
                 
                    Popen(("totem","--enqueue",totem_cmd))
                    mplayer_cmd = "totem"+" " + url
                    liste = " " + url
                    print url
                    ### TODO : check if the file is a valid mp3

                    counter_ok = 10
                    print "Download successful."
                   

                    

                    
                except IOError:
                    state = "Download failed."
                    gobject.idle_add(self.parent.setStateText, state)
                    print state

                print

        state = "Downloaded %i song%sout of %i." % (counter_ok,
                                                    counter_ok > 1 and 's ' or ' ',
                                                    counter_all)

        gobject.idle_add(self.parent.setStateText, state)
        
        
        print state   
        



    def download(self, songs, model):
        """ Download the files """
        
        # init the counters
        counter_ok = 0
        counter_all = 0

        # iter on all the paths
        iter = model.get_iter_first()
        while iter is not None:
            number = model.get_value(iter, 0)
            selected = model.get_value(iter, 1)
            iter = model.iter_next(iter)

            # if the song is selected for download...
            if selected:
                counter_all += 1
                name = songs[number - 1][1]
                name_search = name.replace('(', '\(').replace(')', '\)')\
                              .replace('[', '\[').replace(']', '\]')\
                              .replace('\'', '\\\\\'').replace('&', '\&')

                # change the extension to .mp3
                name = RadioBlogClub.rename(name)

                state = "Downloading %s..." % (Search.shortName(name), )
                gobject.idle_add(self.parent.setStateText, state)

                url = "http://www.radioblogclub.com" + songs[number - 1][0]\
                      .replace(' ', '%20')

                print "Downloading %s" % (name, )
                print "from the RadioBlog :\n%s" % (url, )

                # get the HTML file with the RBS adress
                playlist = urllib.urlopen(url).read().split('\n')

                # find the URL
                reg3 = re.compile('^.*javascript:openRadio\(\'(.*)\?autoplay.*$')

		# find the URL
		url = ""
		for line in playlist:
                    if reg3.match(line):
                        url = reg3.search(line).groups()[0] + 'sounds/' + name_search + '.rbs'
                        url = url.replace('\\', '').replace(' ', '%20')
                        print "File URL :\n%s" % (url, )

                # the RBS file was not found
                if url == "":
                    state = "Song not found. (Maybe the file was a SWF)"
                    gobject.idle_add(self.parent.setStateText, state)
                    print state
                    continue

                # download the file
                try:
                    print "Downloading to %s..." % (result_folder, )
                    dl_file = os.path.join(os.path.expanduser(result_folder), name)
                    urllib.urlretrieve(url, dl_file)

                    # hack : to check if the file is a valid mp3, we check its size
                    # if it's too small, it's probably a 404 HTML file
                    if os.path.getsize(dl_file) < min_size:
                        os.remove(dl_file)
                        raise IOError

                    counter_ok += 1
                    print "Download successful."
                    
                except (IOError, UnicodeError):
                    state = "Download failed."
                    gobject.idle_add(self.parent.setStateText, state)
                    print state

                print

        state = "Downloaded %i song%sout of %i." % (counter_ok,
                                                    counter_ok > 1 and 's ' or ' ',
                                                    counter_all)

        gobject.idle_add(self.parent.setStateText, state)

        print state   
        

class MyBloop:
    def __init__(self, parent):
        """ Init the thread """

        self.parent = parent

    def searchURL(self, i, params):
        """ Return the URL to search the MP3 """

        url = "http://www.mybloop.com/search.o?q=" + params + "&e=files&tmus=1&p=" + str(i)

        try:
            return urllib.urlopen(url).read()
        except IOError:
            print "Error : could not connect"
            raise
        
    
    def search(self, text):
        """ Do a research """

        # get the webpage data
        try:
            data = self.searchURL(1, "+".join(text))
        except IOError:
            gobject.idle_add(self.parent.setStateText, "Error : could not connect")
            gtk.gdk.threads_leave()
            return

        lines = data.split('\n')

        # regular expression to find the number of songs
        reg1 = re.compile('^.*of <b>(.*)</b> result.*$')

        n_songs = 0
    
        # get the number of songs
        for line in lines:
            if reg1.match(line):
                n_songs = int(reg1.search(line).groups()[0])
                break

        # if no song is found, exit
        if n_songs == 0:
            gobject.idle_add(self.parent.setSongList, [], [])
            gtk.gdk.threads_leave()
            return

        # get the number of pages to browse   """ Download the files """
        
        # init the counters
        counter_ok = 0
        counter_all = 0

        # iter on all the paths
        iter = model.get_iter_first()
        while iter is not None:
            number = model.get_value(iter, 0)
            selected = model.get_value(iter, 1)
            iter = model.iter_next(iter)

            # if the song is selected for download...
            if selected:
                counter_all += 1
                name = songs[number - 1][1]
                name_search = name.replace('(', '\(').replace(')', '\)')\
                              .replace('[', '\[').replace(']', '\]')\
                              .replace('\'', '\\\\\'').replace('&', '\&')

                # change the extension to .mp3
                name = RadioBlogClub.rename(name)

                

                url = "http://www.radioblogclub.com" + songs[number - 1][0]\
                      .replace(' ', '%20')

                print "Downloading %s" % (name, )
                print "from %s" % (url, )

                # get the HTML file with the RBS adress
                playlist = urllib.urlopen(url).read().split('\n')

                # find the URL
		reg3 = re.compile('.*openRadio.*')
		# find the URL
		url = ""
		for line in playlist:
			if reg3.match(line):
     			    url = reg3.search(line).group(0).replace('</fieldset><div class="clearer" style="height:5px">&nbsp;</div><div><div style="float:left; margin-top:10px;width:100%;margin-right:3px;" class="button_off"><a class="button" style="height:24px;padding-top:12px;" href="javascript:openRadio(\'','').replace('?autoplay=\')">Click here to play</a></div></div><div class="clearer" style="height:15px; margin-bottom: 15px; border-bottom:dotted 1px #CCC">&nbsp;</div><div class="content" style="float:left;width:730px;"><h3 style="margin-bottom:0px;margin-top:-4px;">Radio.blog Playlist</h3><div class="clearer" style="height:10px">&nbsp;</div><div id="ads"><script type="text/javascript"><!--','').replace(' ','')+'/sounds/'+ name_search + '.rbs'
        		    url = url.replace('\\', '').replace(' ', '%20')
                                                    

                # the RBS file was not found
                if url == "":
                    state = "Song not found. (Maybe the file was a SWF)"
                    gobject.idle_add(self.parent.setStateText, state)
                    print state
                    continue

                # download the file
                try:
                    print "Downloading to %s..." % (result_folder, )
                    totem_cmd = url
                    from subprocess import Popen
                    import os
                 
                    Popen(("totem","--enqueue",totem_cmd))
                    mplayer_cmd = "totem"+" " + url
                    liste = " " + url
                    print liste
                    ### TODO : check if the file is a valid mp3

                    counter_ok = 10
                    print "Download successful."
                   

                    

                    
                except IOError:
                    state = "Download failed."
                    gobject.idle_add(self.parent.setStateText, state)
                    print state

                print

        state = "Downloaded %i song%sout of %i." % (counter_ok,
                                                    counter_ok > 1 and 's ' or ' ',
                                                    counter_all)

        gobject.idle_add(self.parent.setStateText, state)
        
        
        print state   
        

class MyBloop:
    def __init__(self, parent):
        """ Init the thread """

        self.parent = parent

    def searchURL(self, i, params):
        """ Return the URL to search the MP3 """

        url = "http://www.mybloop.com/search.o?q=" + params + "&e=files&tmus=1&p=" + str(i)

        try:
            return urllib.urlopen(url).read()
        except IOError:
            print "Error : could not connect"
            raise
        
    
    def search(self, text):
        """ Do a research """

        # get the webpage data
        try:
            data = self.searchURL(1, "+".join(text))
        except IOError:
            gobject.idle_add(self.parent.setStateText, "Error : could not connect")
            gtk.gdk.threads_leave()
            return

        lines = data.split('\n')

        # regular expression to find the number of songs
        reg1 = re.compile('^.*of <b>(.*)</b> result.*$')

        n_songs = 0
    
        # get the number of songs
        for line in lines:
            if reg1.match(line):
                n_songs = int(reg1.search(line).groups()[0])
                break

        # if no song is found, exit
        if n_songs == 0:
            gobject.idle_add(self.parent.setSongList, [], [])
            gtk.gdk.threads_leave()
            return

        # get the number of pages to browse
        n_pages = n_songs / 25 + 1

        # inform the user
        gobject.idle_add(self.parent.setStateText, \
                         "Search started... (about %i songs)" % (n_songs,))

        # download the pages
        pages = []
        pages.append(lines)
        n_pages = n_songs / 25 + 1

        # inform the user
        gobject.idle_add(self.parent.setStateText, \
                         "Search started... (about %i songs)" % (n_songs,))

        # download the pages
        pages = []
        pages.append(lines)

        try:
            for i in range(2, n_pages + 1):
                pages.append(self.searchURL(i, "+".join(text)).split('\n'))
        except IOError:
            gobject.idle_add(self.parent.setStateText, "Error : could not connect")
            gtk.gdk.threads_leave()
            return

        # regular expression to find the song URLs
        reg2 = re.compile('^.*<a href=\"http://www.mybloop.com/([^>]*)\">.*$')
        reg2b = re.compile('^.*<a href="javascript:showPlayer\(\'(.*)\'\)"><img.*$')

        songs = []
        data = []
        self.num = []
        i = 0

        # parse the HTML data to find the songs and save in a list
        for page in pages:
            for line in page:
                if reg2.match(line):
                    result = reg2.search(line).groups()      
                    url = result[0].split('/')[-1]
                    name = url.replace('_', ' ')
                    songs.append((url, name))
                    data.append((i + 1, False, name))
                    i += 1

                if reg2b.match(line):
                    resultb = reg2b.search(line).groups()
                    numero = resultb
                    self.num.append(numero)
                        
        gobject.idle_add(self.parent.setSongList, songs, data)

    def download(self, songs, model):
        """ Download the files """
       
        # init the counters
        counter_ok = 0
        counter_all = 0

        # iter on all the paths
        iter = model.get_iter_first()
        while iter is not None:
            number = model.get_value(iter, 0)
            selected = model.get_value(iter, 1)
            iter = model.iter_next(iter)

            # if the song is selected for download...
            if selected:
                counter_all += 1
                name = songs[number - 1][1]

                state = "Downloading %s..." % (Search.shortName(name), )
                gobject.idle_add(self.parent.setStateText, state)

                url = "http://www.mybloop.com/get/" + str(self.num[number - 1][0]) \
                      + "/" + songs[number - 1][0].replace('(', '\(').replace(')', '\)')\
                      .replace('&', '\&')
                
                print "Downloading %s" % (name, )
                print "from %s" % (url, )

                # get the HTML file
                playlist = urllib.urlopen(url).read().split('\n')

                # the file was not found
                if url == "":
                    state = "Song not found."
                    gobject.idle_add(self.parent.setStateText, state)
                    print state
                    continue

                # download the file
                print "Downloading to %s..." % (result_folder, )

                # it's not working with python lib, only with wget
                #urllib.urlretrieve(url, os.path.join(os.path.expanduser(result_folder), name))
                result = os.system("cd %s && wget %s" % (result_folder, url))
                
                
                if result == 0:
                    counter_ok += 1
                    print "Download successful."
                else:
                    print "Download failed."

                print

        state = "Downloaded %i song%sout of %i." % (counter_ok,
                                                    counter_ok > 1 and 's ' or ' ',
                                                    counter_all)

        gobject.idle_add(self.parent.setStateText, state)

        print state   
        
        
class Search(threading.Thread):
    instantiated = 0 # this class is a Singleton

    def __init__(self, parent, website, text):
        """ Init the thread """

        Search.instantiated += 1

        assert Search.instantiated == 1, \
               "Search already started."

        assert Download.instantiated == 0, \
               "Can't search while download in progress."

        threading.Thread.__init__(self)
        self.text = text
        self.parent = parent
        self.website = website

    def __del__(self):
        """ Destructor """
        
        Search.instantiated -= 1
            
    @staticmethod
    def shortName(name):
        """ Cut out too long name """
        
        if len(name) > 80:
            name = name[0:79] + "..."
        
        return name

    def run(self):
        """ Thread main function """
        
        gtk.gdk.threads_enter()

        self.website.search(self.text);
        
        gtk.gdk.threads_leave()

class Lecture(threading.Thread):
    instantiated = 0 # this class is a Singleton
    
    def __init__(self, parent, website, songs, model):
        """ Init the thread """
        
        Lecture.instantiated += 1

        assert Lecture.instantiated == 1, \
               "Download already started"

        assert Search.instantiated == 0, \
               "Can't download while search in progress."

        threading.Thread.__init__(self)

        self.parent = parent
        self.songs = songs
        self.model = model
        self.website = website
        
    def __del__(self):
        """ Destructor """
        
        Lecture.instantiated -= 1
        
        
    def run(self):
        """ Thread main function """
        
        gtk.gdk.threads_enter()

        self.website.lecture(self.songs, self.model)

        gtk.gdk.threads_leave()

class Download(threading.Thread):
    instantiated = 0 # this class is a Singleton
    
    def __init__(self, parent, website, songs, model):
        """ Init the thread """
        
        Download.instantiated += 1

        assert Download.instantiated == 1, \
               "Download already started"

        assert Search.instantiated == 0, \
               "Can't download while search in progress."

        threading.Thread.__init__(self)

        self.parent = parent
        self.songs = songs
        self.model = model
        self.website = website
        
    def __del__(self):
        """ Destructor """
        
        Download.instantiated -= 1
        Lecture.instantiated -= 1
        
    def run(self):
        """ Thread main function """
        
        gtk.gdk.threads_enter()

        self.website.download(self.songs, self.model)

        gtk.gdk.threads_leave()


# program entry point
if __name__ == "__main__":
    GUI = UserInterface()
    GUI.main()

#156 Le 06/04/2007, à 07:27

juju8630

Re : [Programme] Télécharger la musique de RadioBlogClub

comme tu peux le remarquer, il y adu copié collé ! ! ! et un print "hello" à virer .... si tu veux l'integrer dans ta version ... je pensais que le nom du logiciel pourrait devenir RBCDP, P pour player.
Les prochaines étapes :

- Il faudrait aussi faire un test de validité d'url (car totem affiche une grosse erreur pas belle et nous sommes obligés de faire ok pour continuer l'importation dans la playlist)
- intégrer une selection de player (totem, vlc, beepmedia, xine etc...) avec une boite à cocher pour activer la playlist ou pas ...

avant le changement de radioblog, je cherchais une astuce pour récupérer les infos de l'album sous wikipédia, ainsi que la pochette ... (je reve un peu)

Bon courage pour la recherche d'url !!!!

julien rat

#157 Le 06/04/2007, à 07:37

juju8630

Re : [Programme] Télécharger la musique de RadioBlogClub

aller j'arrete et je pars au boulot ! ! !
J'ai trouvé un exercice sur un site qui pourrait nous interresser pour le test d'url :
http://programmation-python.org/section … xercice-11

#158 Le 06/04/2007, à 12:29

Zoolonly

Re : [Programme] Télécharger la musique de RadioBlogClub

@juju8630 :
Pour lire la video tu peux utiliser mplayer. Je sais pas trop comment faire en python , mais il existe des programme qui le lance en tache de fond (sans interface) et lui envoie des signals (PAUSE , NEXT , PREV, ... , ?). exemple de prog libre python : freevo.
Pareil pour les covers il existe un plugin pour freevo qui permet de les recuperer ! Tu pouras donc copier-coller les expressions regulieres et faire ce que tu veux avec !
Je suis pas mal interesser pour t'aider a coder tout ca ! Mais comme je le dit plus haut, j'ai pas mal de boulot, a la fac ca se passe pas vraiment bien, donc faut que je bosse les matieres theoriques ! Mais bon je te tiens au courant quand meme .


De toute facon il faut absolument modifier la reg-exp , pour refaire marcher le script et cela avant tout !

[EDIT] C'est vraiment trop bien le libre ! big_smile:D

Dernière modification par Zoolonly (Le 06/04/2007, à 12:32)

Hors ligne

#159 Le 07/04/2007, à 09:53

ferreol

Re : [Programme] Télécharger la musique de RadioBlogClub

oui chez moi non plus cela ne marche plus . vous avez deja trouvé une solution?

Hors ligne

#160 Le 07/04/2007, à 13:02

emixam

Re : [Programme] Télécharger la musique de RadioBlogClub

on peut pas demander une api à radioblogclub pour récupérer la liste en xml par exemple ? à moins que ça soit contraire à leur politique


http://emixam.website.free.fr
http://playing-community.codingteam.net
"Linux is just like an indian tent: no Gates, no Windows and an Apache inside..."

Hors ligne

#161 Le 07/04/2007, à 13:47

tshirtman

Re : [Programme] Télécharger la musique de RadioBlogClub

je suppose que ça ne correspondrais pas a leur politique et que même dans le cas contraire, ça n'arrangerais pas leur situation judiciaire (il se font un peu poursuivre par les majors je crois). hmm

Hors ligne

#162 Le 11/04/2007, à 13:36

bloub

Re : [Programme] Télécharger la musique de RadioBlogClub

bonjour tlm lol j'utilise radioblog et heu j'arriv a chopé les son ossi en changean l'extension mai le truc c qu'avec vista les fichiers .rbs s'affiche pa ds les fichiers temporaires dc je voulai savoir si kelkun pouvai me dire komen les affichés svp merci

#163 Le 11/04/2007, à 14:46

tshirtman

Re : [Programme] Télécharger la musique de RadioBlogClub

@bloub, même si tu est sous vista (on te pardone et on te plaint wink) le programme donné par l'auteur de cette discution devrait marcher a condition que python soit installé sur ta machine. (prends la version "windows installer").

Hors ligne

#164 Le 11/04/2007, à 21:10

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

Ayai c'est corrigé !

http://www.dobitchu.info/rbcd/rbcd-gtk

c'était un bug ridicule, risible même : ils avaient remplacé le texte qui indiquait le nombre de chansons (ils avaient viré le mot tracks) alors forcément ma regexp ne fonctionnait plus ::lol:

Sinon pas moyen de faire fonctionner mon script sous vista, parce que ca m'étonnerait qu'il existe la bibliothèque pygtk pour cette infamie !

EDIT: juju j'ai regarde ce que tu as fait, a priori c'est base sur totem, tu penses pas que ca serait mieux de le lire directement dans le programme ? tu peux jeter un oeil la dessus : http://www.afpy.org/python/forum_python/forum_general/911506177193
Bon forcément c'est plus dur, mais bien plus élégant ! Et si tu veux le faire, base toi plutot sur la dernière version du programme !

Dernière modification par foch (Le 11/04/2007, à 21:36)


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne

#165 Le 12/04/2007, à 00:39

Guillaume86

Re : [Programme] Télécharger la musique de RadioBlogClub

foch a écrit :

Ayai c'est corrigé !

http://www.dobitchu.info/rbcd/rbcd-gtk

c'était un bug ridicule, risible même : ils avaient remplacé le texte qui indiquait le nombre de chansons (ils avaient viré le mot tracks) alors forcément ma regexp ne fonctionnait plus ::lol:

Sinon pas moyen de faire fonctionner mon script sous vista, parce que ca m'étonnerait qu'il existe la bibliothèque pygtk pour cette infamie !

EDIT: juju j'ai regarde ce que tu as fait, a priori c'est base sur totem, tu penses pas que ca serait mieux de le lire directement dans le programme ? tu peux jeter un oeil la dessus : http://www.afpy.org/python/forum_python/forum_general/911506177193
Bon forcément c'est plus dur, mais bien plus élégant ! Et si tu veux le faire, base toi plutot sur la dernière version du programme !

Bah c'est dispo sous xp donc ca doit marcher aussi sur vista, j'ai pas envie de rebooter sur cette ***** pour tester mais ca doit aller...

Hors ligne

#166 Le 12/04/2007, à 01:18

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

Bon j'ai pris un coup de speed et j'ai aussi corrigé la version en ligne de commande : http://www.dobitchu.info/rbcd/rbcd

Forcément elle est moins poussée que l'autre mais elle fait son boulot... Prochaine étape, trouver comment m'affranchir des problèmes d'encodage (et je hais vraiment les problèmes d'encodage) pour pouvoir télécharger des fichiers avec des accents.


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne

#167 Le 13/04/2007, à 18:43

pyro

Re : [Programme] Télécharger la musique de RadioBlogClub

salut voila je suis débutant mais completement sous ubuntu et j'aurais voulu savoir ilfaut faire quoi avec le script, le mettre ou?

Hors ligne

#168 Le 13/04/2007, à 18:51

Zoolonly

Re : [Programme] Télécharger la musique de RadioBlogClub

@foch : Merci pour les correctifs !

@pyro :
Pour executer un script  il faut dans un terminal :
chmod +x tonscript
./tonscript

[EDIT] : Un .deb ?
J'en ai fait un pour mon grand pere LOL !!!!
HS : http://landale.dyndns.org/~zoolonly/tmp/radioblog.deb
USE :http://zoolonly.free.fr/radioblog.deb

C'est pas le bon nom ! mais pour mon grand pere radioblog sonnait mieux que rdcd ...
Voila double click et ensuite dans le menu Appllis => Video Audio => RadioBlog
et y a pas d'icone aussi ... [EDIT] en faite si !

Dernière modification par Zoolonly (Le 15/04/2007, à 09:29)

Hors ligne

#169 Le 13/04/2007, à 19:26

pyro

Re : [Programme] Télécharger la musique de RadioBlogClub

desolé mais je suis vraiment debutant donc je voulais savoir on doit le copier coller dans un document texte ou on le laisse la ou il faut? si il faut le copier coller faut t'il tout prnedre ou pas comment sais t'on si le script a été executé ? moi il m'ouvre le script avec des mots en différentes couleur

Hors ligne

#170 Le 13/04/2007, à 19:46

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

Hey justement je cherchais un packageur pour mon projet, je sais pas comment faire pour les scripts !
Tu peux me passer le deb src pour que j'ai une base de départ ?
merci !

@pyro: télécharge plutot le .deb et double clic dessus pour l'installer !


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne

#171 Le 13/04/2007, à 20:09

Guillaume86

Re : [Programme] Télécharger la musique de RadioBlogClub

Je pense qu'aprés la correction de l'encodage, ca serait cool de threader un peu le programme, je verrai ça un peu a la emule, 2 onglets (recherche et téléchargement), le téléchargement ne bloque pas la recherche comme ca, et on peut ajouter des téléchargements a la volée même si il y en a déja en cours. J'ai un peu cherché sur le net ( ICI), la gestion des threads a pas l'air compliquée en python c'est faisable wink. Une barre de progression aussi ça serait bien utile. J'ai vraiment pas le temps de regarder a ça moi même pour le moment (je code déja assez pour mes projets a la fac...) mais je suis un grand fan de ce script j'espère qu'il va encore s'améliorer tongue.

Hors ligne

#172 Le 13/04/2007, à 20:17

pyro

Re : [Programme] Télécharger la musique de RadioBlogClub

et une derniere question apres je trouve ou la zik dowloader je c que vous aviez donné le nom d'un fichier mais je le trouve pas merc d'avance

Hors ligne

#173 Le 13/04/2007, à 20:23

bloub

Re : [Programme] Télécharger la musique de RadioBlogClub

tt dabord merci a tshirtman mm si jcompren rien de rien lol heu un script je c mm pa se ke c et heu ba jvé me demerder sur un autre pc ss xp parce ke ya pa besoin de fair tte une affaire pr recup du son sur radioblog lol et heu merci kom mm mai jcomprend rien kan vs parler lol

#174 Le 13/04/2007, à 20:25

pyro

Re : [Programme] Télécharger la musique de RadioBlogClub

quelqu'un sait ou< c'est qu'on retrouve sa zik?

Hors ligne

#175 Le 13/04/2007, à 20:31

foch

Re : [Programme] Télécharger la musique de RadioBlogClub

bloub a écrit :

tt dabord merci a tshirtman mm si jcompren rien de rien lol heu un script je c mm pa se ke c et heu ba jvé me demerder sur un autre pc ss xp parce ke ya pa besoin de fair tte une affaire pr recup du son sur radioblog lol et heu merci kom mm mai jcomprend rien kan vs parler lol

Moi non plus je comprends rien à ce que tu racontes, mais c'est peut-être parce qu'ici on parle français !

@pyro: si tu lisais les pages précédentes du topic, tu saurais qu'on les trouve dans ton dossier perso, et dans le sous-dossier rbcd_result

@guillaume86: heu ouais mais non, comme je l'ai déjà dit plusieurs fois, j'ai pas envie de passer trop de temps sur un programme qui dépend d'un site qui peut fermer à tout moment. Par contre le script est sous GPL, tu sais ce que ça veut dire ! Et il est déjà multi-threadé, les téléchargements se font dans un thread à part sinon ca bloquerait l'interface graphique. smile


De retour sous Ubuntu après quelques années sous ArchLinux.

Programme de téléchargement de musique qui ne marche plus vraiment.

Hors ligne