download_db.py

00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 
00004 # ----------------------------------------------------------------------------
00005 # pyjama - python jamendo audioplayer
00006 # Copyright (c) 2008 Daniel Nögel
00007 #
00008 # This program is free software: you can redistribute it and/or modify
00009 # it under the terms of the GNU General Public License as published by
00010 # the Free Software Foundation, either version 3 of the License, or
00011 # (at your option) any later version.
00012 #
00013 # This program is distributed in the hope that it will be useful,
00014 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 # GNU General Public License for more details.
00017 # You should have received a copy of the GNU General Public License
00018 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
00019 # ----------------------------------------------------------------------------
00020 
00021 import pyjama_xml
00022 import simplejson
00023 import os
00024 from hashlib import md5
00025 
00026 import functions
00027 
00028 # Gettext - Übersetzung
00029 functions.translation_gettext()
00030 #def _(string):
00031 #    return string
00032 
00033 
00034 try:
00035     # pysqlite --> http://initd.org/tracker/pysqlite/wiki/pysqlite
00036     from pysqlite2 import dbapi2 as sqlite3
00037 except ImportError:
00038     # Ab Python 2.5
00039     import sqlite3
00040 
00041 
00042 class dump_tools():
00043     def __init__(self, parent=None):
00044         self.pyjama = parent
00045         self.home = functions.preparedirs()
00046         self.db = os.path.join(self.home, "pyjama.db")
00047 
00048         if self.pyjama:
00049             self.events = self.pyjama.Events
00050             self.events.add_event("dbtools_message")
00051 
00052         self.download_fkt = self.download_wget
00053         self.extract_fkt = self.extract_gzip
00054 
00055     def download(self, u, d):
00056         self.download_fkt(u, d)
00057 
00058         # Write hash of the database to disc
00059         hash_file = os.path.join(self.home, "database_hash")
00060 
00061         # get the content of the database
00062         try:
00063             fh = open(os.path.join(self.home, d), "rb")
00064         except IOError:
00065             print ("Unable to open the file in readmode:", d)
00066             return
00067 
00068         content = fh.read()
00069         fh.close()
00070 
00071         # get the hash of the content
00072         m = md5()
00073         m.update(content)
00074         local_hash = m.hexdigest()
00075 
00076         try:
00077             fh = open(hash_file, "w")
00078         except:
00079             print ("Unable to open the file in writemode:", hash_file)
00080             return
00081         if fh:
00082             fh.write(local_hash)
00083             fh.close()
00084 
00085     def set_download_fkt(self, function_to_call):
00086         self.download_fkt = function_to_call
00087 
00088     def download_wget(self, url, databasegz):
00089         os.system("wget -O \"%s\" \"%s\"" % (os.path.join(self.home, databasegz), url))
00090 
00091     def extract(self, archive, dest):
00092         self.extract_fkt(archive, dest)
00093 
00094     def extract_gzip(self, archive, dest):
00095         os.system("gunzip -f \"%s\"" % archive) # oder gzip -d
00096 
00097     ###################################################################
00098     #
00099     # create tables
00100     # RETURNS: n/A
00101     #
00102     def create_tables(self):
00103         # Verbindung herstellen
00104         self.conn = sqlite3.connect(self.db)
00105         print ("Creating Tables")
00106         if self.pyjama:
00107             self.events.raise_event("dbtools_message", "Creating Tables")
00108         # Tabellen erstellen
00109         # ARTISTS
00110 
00111         sql = """
00112         CREATE TABLE artists (
00113           uid INTEGER PRIMARY KEY,
00114           id INTEGER,
00115           name TEXT,
00116           country TEXT,
00117           image TEXT,
00118           mbgid TEXT,
00119           state TEXT,
00120           city TEXT,
00121           url TEXT,
00122           latitude TEXT,
00123           longitude TEXT,
00124           albumcount INTEGER
00125         )
00126         """
00127         self.conn.execute(sql)
00128         self.conn.commit()
00129 
00130         # ALBUMS
00131         sql = """
00132         CREATE TABLE albums (
00133           uid INTEGER PRIMARY KEY,
00134           id INTEGER,
00135           name TEXT,
00136           url TEXT,
00137           releasedate TEXT,
00138           filename TEXT,
00139           id3genre INTEGER,
00140           mbgid TEXT,
00141           license_artwork TEXT,
00142           artist_id INTEGER,
00143           trackcount INTEGER
00144         )
00145         """
00146         self.conn.execute(sql)
00147         self.conn.commit()
00148         # TRACKS
00149         sql = """
00150         CREATE TABLE tracks (
00151           uid INTEGER PRIMARY KEY,
00152           id INTEGER,
00153           name TEXT,
00154           duration INTEGER,
00155           album_id INTEGER,
00156           artist_id INTEGER,
00157           numalbum INTEGER,
00158           filename TEXT,
00159           mbgid TEXT,
00160           id3genre INTEGER,
00161           license TEXT
00162         )
00163         """
00164         self.conn.execute(sql)
00165         self.conn.commit()
00166         
00167         # TAGS
00168         sql = """
00169         CREATE TABLE tags (
00170           uid INTEGER PRIMARY KEY,
00171           artist_id INTEGER,
00172           album_id INTEGER,
00173           track_id INTEGER,
00174           idstr TEXT,
00175           weight FLOAT
00176         )
00177         """
00178         self.conn.execute(sql)
00179         self.conn.commit()
00180 
00181 
00182         self.conn.close()
00183 
00184 
00185     ###################################################################
00186     #
00187     # read out Jamendo's xml dump and fills the sql-database
00188     # RETURNS: n/A
00189     #
00190     def create_db(self, force_jamendo=False):
00191         self.databasegz = "dbdump_artistalbumtrack.xml.gz"
00192         self.database = "dbdump_artistalbumtrack.xml"
00193 
00194         print ("Downloading Database %s") % self.databasegz
00195         if force_jamendo:
00196             url = "http://img.jamendo.com/data/dbdump_artistalbumtrack.xml.gz"
00197         else:
00198             url = "http://xn--ngel-5qa.de/jamendo/download.php"
00199 
00200         self.download(url, self.databasegz)
00201 
00202         if self.pyjama:
00203             self.events.raise_event("dbtools_message", "Unzipping")
00204         print ("Unzipping DB %s") % self.databasegz
00205         self.extract(os.path.join(self.home, self.databasegz), self.db)
00206 
00207 #        import tarfile
00208 #        print os.path.join(self.home, self.databasegz)
00209 #        tar = tarfile.open(os.path.join(self.home, self.databasegz ),"r:gz")
00210 #        for tarfile.tarinfo in tar :
00211 #            tarball.extract(tarfile.tarinfo)
00212 
00213 ##        tar.extractall(self.home)
00214 #        tar.close()
00215 
00216         self.conn = sqlite3.connect(self.db)
00217 
00218         if self.pyjama:
00219             self.events.raise_event("dbtools_message", "Reading XML")
00220         print ("Reading XML- Database - this might take a while:")
00221         print ("Processing '%s'") % self.database
00222 #        artist, albums, tracks, tags = pyjama_xml.parse_xml(os.path.join(self.home, self.database))
00223         try:
00224             pyjama_xml.parse_xml(os.path.join(self.home, self.database), self)
00225         except IOError:
00226             return "nofile"
00227             print ("Apparently an error occured downloading the database.")
00228             print ("Try running pyjama with 'pyjama --update-jamendl")
00229 
00230     def insert_artists(self, artists):
00231 
00232         # WERTE EINTRAGEN
00233         # ARTISTS
00234         sql = """
00235         INSERT INTO artists (
00236             id,
00237             name,
00238             country,
00239             image,
00240             mbgid,
00241             state,
00242             city,
00243             url,
00244             latitude,
00245             longitude,
00246             albumcount
00247         ) VALUES (
00248             :id,
00249             :name,
00250             :country,
00251             :image,
00252             :mbgid,
00253             :state,
00254             :city,
00255             :url,
00256             :latitude,
00257             :longitude,
00258             :albumcount
00259         )
00260         """
00261 #        print ("Inserting Artists")
00262         if self.pyjama:
00263             self.events.raise_event("dbtools_message", "Inserting Artists")
00264         self.conn.executemany(sql, artists)
00265         self.conn.commit()
00266 
00267     def insert_albums(self, albums):
00268         
00269         #print "Converting Albums"
00270         #print "Converting some Objects to Strings"
00271         #for counter in xrange(len(albums)):
00272         #    albums[counter]['covers'] = simplejson.dumps(albums[counter]['covers'])
00273         #    albums[counter]['p2plinks'] = simplejson.dumps(albums[counter]['p2plinks'])
00274         # ALBUMS
00275         #self.conn.create_function('json', 1, txt)
00276 
00277         sql = """
00278         INSERT INTO albums (
00279             id,
00280             name,
00281             url,
00282             releasedate,
00283             filename,
00284             id3genre,
00285             mbgid,
00286             license_artwork,
00287             artist_id,
00288             trackcount
00289         ) VALUES (
00290             :id,
00291             :name,
00292             :url,
00293             :releasedate,
00294             :filename,
00295             :id3genre,
00296             :mbgid,
00297             :license_artwork,
00298             :artist_id,
00299             :trackcount
00300         )
00301         """
00302 #        print ("Inserting Albums")
00303         if self.pyjama:
00304             self.events.raise_event("dbtools_message", "Inserting Albums")
00305         self.conn.executemany(sql, albums)
00306         self.conn.commit()
00307 
00308         if self.pyjama:
00309             self.events.raise_event("dbtools_message", "Reading XML")
00310 
00311     def insert_tracks(self, tracks):
00312 
00313         # Tracks
00314         sql = """
00315         INSERT INTO tracks (
00316             id,
00317             name,
00318             duration,
00319             album_id,
00320             artist_id,
00321             numalbum,
00322             filename,
00323             mbgid,
00324             id3genre,
00325             license
00326         ) VALUES (
00327             :id,
00328             :name,
00329             :duration,
00330             :album_id,
00331             :artist_id,
00332             :numalbum,
00333             :filename,
00334             :mbgid,
00335             :id3genre,
00336             :license
00337         )
00338         """
00339 #        print ("Inserting Tracks")
00340         if self.pyjama:
00341             self.events.raise_event("dbtools_message", "Inserting Tracks")
00342         self.conn.executemany(sql, tracks)
00343         self.conn.commit()
00344 
00345         if self.pyjama:
00346             self.events.raise_event("dbtools_message", "Reading XML")
00347 
00348     def insert_tags(self, tags):
00349 
00350         # Tags
00351         sql = """
00352         INSERT INTO tags (
00353             artist_id,
00354             album_id,
00355             track_id,
00356             idstr,
00357             weight
00358         ) VALUES (
00359             :artist_id,
00360             :album_id,
00361             :track_id,
00362             :idstr,
00363             :weight
00364         )
00365         """
00366 #        print ("Inserting Tags")
00367         if self.pyjama:
00368             self.events.raise_event("dbtools_message", "Inserting Tags")
00369         self.conn.executemany(sql, tags)
00370         self.conn.commit()
00371 
00372         if self.pyjama:
00373             self.events.raise_event("dbtools_message", "Reading XML")
00374 
00375     def finish(self):
00376 
00377         # Verbindung schliessen (nur zum Testen)
00378         self.conn.close()
00379 
00380         if self.pyjama:
00381             self.events.raise_event("dbtools_message", "Removing old database")
00382         print ("Removing DB %s'") % self.database
00383         os.system("rm %s" % os.path.join(self.home, self.database))
00384 
00385         print ("Installation Finished")
00386         if self.pyjama:
00387             self.events.raise_event("dbtools_message", "Finished")
00388 
00389     ###################################################################
00390     #
00391     # delete sqlite-database
00392     # RETURNS: n/A
00393     #
00394     def delete_db(self):
00395         if self.pyjama:
00396             self.events.raise_event("dbtools_message", "Removing database")
00397         print ("removing old database...")
00398         if os.path.exists(self.db):
00399             try:
00400                 os.remove(self.db)
00401                 return True
00402             except:
00403                 if self.pyjama:
00404                     self.events.raise_event("error", "Could not delete old database")
00405                 return False
00406 
00407 #delete_db()
00408 #create_tables()
00409 #create_db()
00410         

Generated on Thu Jun 4 19:08:24 2009 for Pyjama by  doxygen 1.5.8