Пример #1
0
    def _get_tracks(self, html):

        soup = BeautifulSoup(html, 'lxml')
        tcs = soup.find_all('li', class_='track')
        count = 1

        tracks = []

        for item in tcs:
            new_track = Track()

            title = item.find('span', class_='buk-track-primary-title')
            title = title.text

            title_remixed = item.find('span', class_='buk-track-remixed')
            title = title + ' (' + title_remixed.text + ')'
            title = " ".join(title.split())

            artist_list = item.find('p', class_='buk-track-artists')
            artist_list = artist_list.text
            artist_list = artist_list.strip()
            artist_list = " ".join(artist_list.split())

            key = item.find('p', class_='buk-track-key')
            key = key.text
            key = self.ConvertKey(key)


            track_number = count
            count += 1

            new_track.Artist = artist_list
            new_track.Title = title
            new_track.Number = track_number
            new_track.Key = key

            tracks.append(new_track)

        return tracks
Пример #2
0
    def __init__(self, rel):
        
        # copy inherited object
        super().__init__()
        self.Name = rel.Name
        self.Catid = rel.Catid
        self.LabelName = rel.LabelName
        self.InfoPageLink = rel.InfoPageLink
        self.TrackList = deepcopy(rel.TrackList)

        # own members
        self.__ClassName = "ReleasePage"

        #
        # ask beatport api
        #
        conn = http.client.HTTPConnection("api.beatport.com")
        conn.request("GET", "/catalog/2/tracks?perPage=50&releaseId=" + str(self.InfoPageLink))
        r1 = conn.getresponse()
        
        mydict = json.loads(r1.read().decode())

        # No results 
        if len(mydict["results"]) == 0:
            return None
        #print(json.dumps(mydict["results"], sort_keys=True, indent=4))


        # get track info
        t_number = 1

        # we have to get the picture link from the first picture
        if mydict["results"][0]["images"]["large"]["url"]:
            self.PictureLink = mydict["results"][0]["images"]["large"]["url"]
            #print(self.PictureLink)

        for tr in mydict["results"]:
            cur_track = Track()

            #print(tr["artists"])

            if tr["artists"]:
                cur_track.Artist = ""
                for a in tr["artists"]:
                    if a["type"] == "artist":
                        cur_track.Artist += a["name"] + ", "

            cur_track.Artist = cur_track.Artist.rstrip(", ")
            
            if tr["title"]:
                cur_track.Title = tr["title"]

            cur_track.Number = t_number


            t_number += 1

            t_key = ""

            # get key 
            if tr["key"] and tr["key"]["standard"]:
                t_key += tr["key"]["standard"]["letter"]
                if tr["key"]["standard"]["sharp"] == True:
                    t_key += " Sharp"
                if tr["key"]["standard"]["flat"] == True:
                    t_key += " Flat"
                t_key += " " + tr["key"]["standard"]["chord"]

            cur_track.Key = self.ConvertKey(t_key)

            self.TrackList.append(cur_track)
Пример #3
0
    def Run(self):

        print()

        filled_tracks = []
        unfilled_tracks = []

        ##
        ## Handle Directories (Release Search)
        ##
        if self.Settings.HasDirs():

            # here we only link the files to specific dirs
            # the next loop then cares about and first makes
            # a search in a release cache

            idx = 0

            for folder in self.Settings.DirList:

                #
                # figure out the directory entries
                #
                file_list = os.listdir(folder)
                

                if not file_list:
                    ePrint(1, self.__ClassName, "Skipping directory " + folder)
                    continue

                ePrint(2, folder, "<-- Linking files")
                ePrint(2, "Containing: ", str(file_list) + "\n")

                # append them to the FileList
                for file_path in file_list:
                    f = File(os.path.join(folder, file_path))
                    f.RelDir = folder

                    f.RelDirIdx = idx
                    #ePrint(2, "Fileending: ", str(file_list) + "\n")
                    if f.Type in ["mp3", "flac", "wav", "wave", "ogg"]:
                        self.Settings.FileList.append(f)

                idx += 1


        ##
        ## Handle the FileList if existent
        ##
        if self.Settings.HasFiles():
            track_list = []
            
            for f in self.Settings.FileList:
                
                #
                # at first try to gather some data from the tags, so
                # create a track object
                #

                new_track = Track()
                
                # associate the track with its file and try to read
                # some info from the tags
                new_track.FileInstance = f
                new_track.FillFromFile()

                ePrint(1, ColorString(str(new_track.FileInstance.NameBody), "green"), "<-- Try to determine info")

                # if a track is fully filled continue with the next
                if (new_track.FilledEnough(self.Settings.Pattern)):
                    ePrint(1, self.__ClassName, "Track is filled enough: " + str(new_track) + "\n")
                    filled_tracks.append(new_track)
                    continue

                #
                # Look in the cache
                #
                rel_page = None

                for t in filled_tracks:
                    if new_track.FileInstance.RelDir != "" and \
                       new_track.FileInstance.RelDir == t.FileInstance.RelDir and \
                       t.Release:
                           ePrint(2, self.__ClassName, "Using cache")
                           rel_page = t.Release
                           break

                if not rel_page:
                    #
                    # look at chemical if nothing is found in tags or cache
                    #

                    # first we check for an explicit searchterm
                    idx = new_track.FileInstance.RelDirIdx
                    
                    if idx < len(self.Settings.SearchTermList):
                        search_term = self.Settings.SearchTermList[idx]
                    else:
                        # if we have artist and filename availible set this as searchterm
                        if new_track.Artist and new_track.Title:
                            search_term = new_track.Artist + " " + new_track.Title
                        else:
                            # otherwise create search_term from filename
                            search_term = new_track.FileInstance.NameBody
                            ePrint(2, self.__ClassName, "Setting searchterm: " + search_term)



                    # link it up on BeatportWeb
                    res_page = BeatportWeb.ResultPage(search_term)

                    # if we found nothing, we cut the searchterm
                    if not res_page.GetReleaseList():
                        # at first remove signs symbols and retry
                        search_term = ReplaceChars("/_()-.:,&?", " ", search_term)
                        # strip "feat" terms
                        p = re.compile(" feat ", re.IGNORECASE)
                        search_term = p.sub("", search_term)

                        res_page = BeatportWeb.ResultPage(search_term)

                        if not res_page.GetReleaseList():
                            # second remove numbers
                            search_term = ReplaceChars("0123456789", " ", search_term)
                            res_page = BeatportWeb.ResultPage(search_term)

                            # now strip words from the term
                            if not res_page.GetReleaseList():
                                search_term_word_list = search_term.split()
                                while len(search_term_word_list) > 1:
                                    search_term_word_list.pop()
                                    search_term = " ".join(search_term_word_list)
                                    res_page = BeatportWeb.ResultPage(search_term)
                                    if res_page.GetReleaseList():
                                        break
                                
                    
                    
                    # if we finally found nothing, skip
                    if not res_page.GetReleaseList():
                        ePrint(1, self.__ClassName, "Could not determine all fields for: " +
                               new_track.FileInstance.Basename + "\n")
                        unfilled_tracks.append(new_track)
                        continue
                    
                    #
                    # now we process the result list
                    #
                    release_list = res_page.GetReleaseList()
                    
                    # invoke the user if we have found more than one results
                    if len(release_list) > 1:
                        ePrint(1, self.__ClassName,
                               "Multiple possilble releases found for: " + new_track.FileInstance.Basename +
                               "Please type number. 0 to skip.")

                        # TODO print sorted
                        release_list = res_page.GetReleaseList()
                        
                        # sort the release list for better choosing
                        release_list = sorted(release_list, key = lambda rel: str(rel), reverse = False)

                        c = 1
                        for r in release_list:
                            print("{:4d} : {!s:.150}".format(c, r))
                            c += 1

                        choice = -1
                        while choice < 0 or choice > len(release_list):
                            choice = int(input(" <-- "))

                        if choice == 0:
                            ePrint(1, self.__ClassName, "Skipping: " + new_track.FileInstance.Basename + "\n")
                            unfilled_tracks.append(new_track)
                            continue

                        # choose result, pay attention on index
                        release_candidate = release_list[choice - 1]
                    else:
                        release_candidate = release_list[0]

                    # create a ReleasePage, from the release candidate . This determines all relevant 
                    # information for the release
                    rel_page = BeatportWeb.ReleasePage(release_candidate)


                #
                # identify the track in the release
                #

                # create a search term
                if new_track.Artist and new_track.Title:
                    search_term = new_track.Artist + " " + new_track.Title
                else:
                    search_term = new_track.FileInstance.NameBody
                
                search_term = ReplaceChars("/_()-.:,", " ", search_term)

                cor_track = rel_page.IdentifyTrack(search_term)
                ePrint(1, self.__ClassName, "corresponding track: " + ColorString(str(cor_track), 'green'))

                # since we only have a corresponding track copy on demand
                if not new_track.Artist:
                    new_track.Artist = cor_track.Artist
                if not new_track.Title:
                    new_track.Title = cor_track.Title
                if not new_track.Key:
                    new_track.Key = cor_track.Key
                if not new_track.Number:
                    new_track.Number = cor_track.Number

                if new_track.FilledEnough(self.Settings.Pattern):
                    ePrint(1, self.__ClassName, "Track is filled enough: " + str(new_track))
                    # link to the found release
                    new_track.Release = rel_page
                    filled_tracks.append(new_track)
                else:
                    ePrint(1, self.__ClassName, "Could not determine all fields for: " + new_track.FileInstance.Basename)
                    unfilled_tracks.append(new_track)

                print()

        #
        # Rename files
        #
        for track in filled_tracks:
            dest_name = self.Settings.Pattern.GetResolvedString(artist=track.Artist, title=track.Title,
                                                                number=track.Number, key=track.Key)

            # function only needs the basename without extension
            if self.Settings.MakeCopy:
                #track.FileInstance.Copy(dest_name)
                pass
            else:
                if self.Settings.Ask == True:
                    track.FileInstance.RenameQuery(dest_name)
                else:
                    track.FileInstance.Rename(dest_name)


        #
        # handle dir renaming
        #
        handled_dirs = []
        for track in filled_tracks:
            if track.FileInstance.RelDir and track.FileInstance.RelDir not in handled_dirs:
                #TODO remove code here
                # build a artist string, maximum 2
                #artists = ""
                #c = 0
                #for t in track.Release.TrackList:
                #    artists += t.Artist + " "
                #    if c >= 1:
                #        break
                #    c += 1

                #print("Artist name: " + artists)
                #
                ## create destination string
                #artists = artists.strip()
                #artists = ReplaceChars(" ", ".", artists)
                #artists = artists.lower()

                rel_name = track.Release.Name.strip()
                rel_name = ReplaceChars("/'", "", rel_name)
                rel_name = ReplaceChars(" ", ".", rel_name)
                rel_name = rel_name.lower()
                
                dest = track.Release.Catid.lower() + ".-." + rel_name
                ePrint(2, self.__ClassName, track.FileInstance.RelDir)
                ePrint(2, self.__ClassName, dest)

                # download artwork if necessary
                if self.Settings.GetImage == True:
                    image_path = os.path.join(track.FileInstance.RelDir, "artwork.jpg")
                    if os.path.exists(image_path):
                        ePrint(1, self.__ClassName, "Artwork already in release folder")
                    else:
                        ePrint(1, self.__ClassName, "Downloading Artwork")
                        DownloadFile(track.Release.PictureLink, image_path)


                RenameDirQuery(track.FileInstance.RelDir, dest)

                handled_dirs.append(track.FileInstance.RelDir)