Exemple #1
0
  def __init__(self, path):
    idb_path = os.path.join(path, IPOD_CTRL, 'iTunes', 'iTunesDB')
    mdate = datetime.datetime.fromtimestamp(os.path.getmtime(idb_path))
    if mdate < IPOD_BORN: mdate = datetime.datetime.now()

    self._mdate = mdate
    self._db = gpod.Database(path, None)
Exemple #2
0
 def get_db(self, mount_point):
     self.__lock.acquire()
     try:
         if mount_point in self.__db_list:
             log.debug('Getting DB in cache for %s' % (mount_point))
             db = self.__db_list[mount_point]
         else:
             if mount_point:
                 log.debug('Creating DB for %s' % mount_point)
                 db = gpod.Database(mount_point)
             else:
                 log.debug('Creating local DB')
                 db = gpod.Database(local=True)
             self.__db_list[mount_point] = db
             self.__db_locks[db] = threading.Lock()
         return db
     finally:
         self.__lock.release()
Exemple #3
0
 def open_db(self):
     if self.db:
         return
     else:
         self.db = gpod.Database(mountpoint=self.mountpoint)
Exemple #4
0
    # Handle cookies
    jar = cookielib.LWPCookieJar()
    cookies = FLAGS.cookie_file.replace('~', os.environ['HOME'])
    if os.path.isfile(cookies):
        jar.load(cookies)

    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
    urllib2.install_opener(opener)

    # Initialize the client
    readurl('%s/?user=%s&mp3_source=%s' %
            (FLAGS.mp3server, FLAGS.user, FLAGS.mp3cache.replace(
                '/', '%2F').replace(':', '%3A')))

    # Empty the iPod
    ipod_db = gpod.Database(argv[1])

    delete_passes = 0
    total_skips = 0
    total_plays = 0

    while len(ipod_db) > 0:
        delete_passes += 1
        print '%d tracks on iPod' % len(ipod_db)

        for t in ipod_db:
            total_skips += t['skipcount']
            total_plays += t['playcount']
            print 'Pass %d, %d skips, %d plays: %s' % (
                delete_passes, total_skips, total_plays, t['title'])
#!/usr/bin/python

import gpod

db = gpod.Database()

print db

for track in db[4:20]:
    print track
    print track['title']

for pl in db.Playlists:
    print pl
    for track in pl:
        print " ", track
Exemple #6
0
#!/usr/bin/python
import os
import gpod
import re
import pprint
import subprocess

db = gpod.Database("/media/JAMES' IPOD")

albums = {}
artists = {}

def normalize( name ):
    name = name.strip().upper()
    retname = ""
    inSpace = False
    for c in name:
        if c.isspace():
            if inSpace:
                continue
            inSpace = True
            retname = retname + "_"
        elif c.isalnum():
            inSpace = False
            retname = retname + c
    return retname


for track in db:
    album = track['album']
    artist = track['artist']
Exemple #7
0
 def __init__(self, path):
     self.path = path
     self.db = gpod.Database(self.path)
Exemple #8
0
 def __init__(self, path):
     self.db = gpod.Database(path)
     self.syncing = False
def get_database(mountpoint):
    return gpod.Database(mountpoint)
Exemple #10
0
                  "--playlist",
                  dest="playlist",
                  help="add tracks to PLAYLIST",
                  metavar="PLAYLIST")
parser.add_option("-p",
                  "--podcast",
                  dest="ispodcast",
                  action="store_true",
                  default=False,
                  help="add to podcast playlist")
(options, args) = parser.parse_args()

if len(args) == 0:
    parser.error("Requires an mp3 to add.")

db = gpod.Database(options.mountpoint)

playlist = None
if options.playlist:
    for pl in db.Playlists:
        if pl.name == options.playlist:
            playlist = pl
    if not playlist:
        playlist = db.new_Playlist(title=options.playlist)
        print "Created new playlist %s" % playlist

deleteWhenDone = []

for path in args:
    transport = urlparse.urlsplit(path)[0]
    if transport:
Exemple #11
0
Author: Thomas Perl <thpinfo.com>, 2008-03-28
"""

import gpod
import os.path
import sys

if len(sys.argv) == 1:
    print 'Usage: python %s /path/to/ipod' % os.path.basename(sys.argv[0])
    print __doc__
    sys.exit(-1)
else:
    mount_point = sys.argv[-1]

try:
    db = gpod.Database(mount_point)
except gpod.ipod.DatabaseException, dbe:
    print 'Error opening your iPod database: %s' % dbe
    sys.exit(-2)

(updated, count) = (0, len(db))

print 'Database opened: %d tracks to consider' % count
for track in db:
    # If the track has a ".mp3" title and no artist, try to fix it
    if track['title'].lower().endswith('.mp3') and track['artist'] is None:
        # Assume "Artist - Title.mp3" file names
        items = os.path.splitext(track['title'])[0].split(' - ')
        if len(items) == 2:
            (artist, title) = items
            print 'Correcting: %s' % track['title']
Exemple #12
0
#!/usr/bin/python

import gpod
import sys

if len(sys.argv) > 1:
    db = gpod.Database(sys.argv[1])
else:
    db = gpod.Database()

print db

for track in db[4:20]:
    print track
    print track['title']

for pl in db.Playlists:
    print pl
    for track in pl:
        print " ", track
Exemple #13
0
def main():
    corrupt_path = str(config.config.anontune.home_directory) + "/" + str(config.config.anontune.ipod_db.upload_directory) + "/corrupt_db"
    while 1:
	time.sleep(1)
        timestamp = str(int(time.time()))
        copy_path = ""
        search_path = ""
        try:
            os.chdir(str(config.config.anontune.home_directory))
            process_queue = os.listdir(str(config.config.anontune.home_directory) + "/" + str(config.config.anontune.ipod_db.upload_directory))
            if len(process_queue) <= 1:
                time.sleep(1) #Avoid killing the CPU.
            for username in process_queue:
                """
                Unfortunately, the localdb function doesn't work for all databases apparently.
                What works is creating a fake iPod directory structure, copying the databases
                there and then telling gpod the "mount" directory. So this will have to be
                done for all users.
                """
                #Skip hidden directories.
                if username[0] == ".":
                    continue
                #Skip special directories.
                if username == "corrupt_db":
                    continue
                
                print "> Now processing " + username + "'s iPod."
                
                #Mount ipod DB.
                search_path = str(config.config.anontune.home_directory) + "/" + str(config.config.anontune.ipod_db.upload_directory) + "/" + username
                copy_path = corrupt_path + "/" + username + "_" + timestamp
                ipod_db_path = search_path
                #print "1:", ipod_db_path
                try:
                    #print "a"
                    ipod_db = gpod.Database(ipod_db_path)
                    #print "B"
                    #Ugly code so it works on different ver of py + gpod
                    try:
                        print ipod_db
                        if ipod_db == None or type(ipod_db) == types.NoneType:
                            raise IndexError('')
                    except:
                        raise IndexError('')
                except:
                    try:
                        #print "d"
                        #Try use localdb.
                        ipod_db_path += "/iPod_Control/iTunes"
                        entities = os.listdir(ipod_db_path)
                        for entity in entities:
                            test_path = ipod_db_path + "/" + entity
                            if os.path.isfile(test_path):
                                ipod_db_path = test_path
                                found = 1
                                break
                        #print "e"
                        ipod_db = gpod.Database(localdb=ipod_db_path)
                        #print ipod_db_path
                        #print "f"
                        try:
                            print ipod_db
                            if ipod_db == None or type(ipod_db) == types.NoneType:
                                raise IndexError('')
                        except:
                            raise IndexError('')
                    except:
                            e_msg = "> Failed to open DB for user \"" + username + "\"."
                            print e_msg
                            log.exception(e_msg)
                            if os.path.exists(search_path):
                                shutil.copytree(search_path, copy_path)
                                shutil.rmtree(search_path)
                            exit()
                      
                #Insert music.
                #print "h0h0h0"
                #print ipod_db
                playlist_no = 0
                try:
                    libgpod_playlists = ipod_db.get_playlists()
                    print libgpod_playlists
                    if libgpod_playlists == None or type(libgpod_playlists) == types.NoneType:
                        raise IndexError('')
                except:
                    #No playlists.
                    ipod_db.new_Playlist(ipod_db, title="Anontune Songs") #One playlist to hold all songs.
                    libgpod_playlists = ipod_db.get_playlists() #Get reference to new playlist object.
                    for libgpod_playlist in libgpod_playlists:
                        for track in ipod_db:
                            libgpod_playlist.add(track) #Add all the tracks in the DB to new playlist.
                            
                playlists = []
                for libgpod_playlist in libgpod_playlists:
                    playlist_no += 1
                for libgpod_playlist in libgpod_playlists:
                    #Skip empty playlists.
                    if len(libgpod_playlist) == 0:
                        continue
                    #Skip playlists containing all songs (duplication.)
                    if playlist_no != 1 and len(libgpod_playlist) == len(ipod_db):
                        continue
                    playlist_name = str(libgpod_playlist.get_name())
                    tracks = []
                    for track in libgpod_playlist:
                        tracks.append(track)
                    playlists.append([playlist_name, tracks])
                if playlists == []:
                    playlist_name = "Anontune Songs"
                    tracks = []
                    for track in ipod_db:
                        tracks.append(track)
                    playlists.append([playlist_name, tracks])
                    
                #Add all if required.
                """
                found_all = false
                for playlist in playlists:
                    if playlist[0] == "Anontune Songs":
                        found_all = true
                if found_all == false:
                    tracks = []
                    playlist_name = "Anontune Songs"
                    for track in ipod_db:
                        tracks.append(track)
                    playlists.append([playlist_name, tracks])
                """
                
                #Playlist holding songs not in a playlist.
                not_in_playlist = []
                for ipod_track in ipod_db:
                    found = 0
                    for playlist in playlists:
                        for playlist_track in playlist[1]:
                            if playlist_track["title"] == ipod_track["title"] and playlist_track["artist"] == ipod_track["artist"]:
                                found = 1
                    if found == 0:
                        not_in_playlist.append(ipod_track)
                if not_in_playlist != []:
                    playlist = ["Not In Playlist", not_in_playlist]
                    playlists.append(playlist)
                    
                for playlist in playlists:
                    playlist_name = str(playlist[0])
                    #print playlist_name
                    playlist_id = insert_playlist(playlist_name, username)
                    #print "> Playlist: " + playlist_name
                    #print playlist_id
                    if int(playlist_id) == 0 or playlist_id == "" or playlist_id == None:
                        continue
                    for track in playlist[1]:
                        #print "Track: " + str(track["title"]) + " - " + str(track["artist"])
                        insert_track(track, username, playlist_id)
                        
                #Remove user database.
                shutil.rmtree(search_path)
                print "> Done processing " + username + "'s iPod."
                #Patch for weird error
                #Make sure auto_restart is running.
                exit()
        except Exception, err:
            the_error = "> Unknown exception occured while processing database for %s. The exception was %s." % (username, err)
            print the_error
            log.exception(the_error)
            #print the_error
            if os.path.exists(search_path):
                shutil.copytree(search_path, copy_path)
                shutil.rmtree(search_path)
                
            thread = threading.Thread(target=main, args=())
            thread.start()
            exit()
import gpod
t = gpod.
db = gpod.Database('/mnt/ipod')

print(db)

for track in db[4:20]:
    print(track)
    print(track['title'])

#for pl in db.Playlists:
#    print(pl)
#    for track in pl:
#        print( " ", track)