def compare_simple(model, iter1, iter2, user_data): a_basename = GLib.path_get_basename(model[iter1][user_data]).lower() b_basename = GLib.path_get_basename(model[iter2][user_data]).lower() if a_basename < b_basename: return -1 # Each element is unique, there is a strict order. return 1
def build_item(user_dir): return { "indexer": self, "name": GLib.path_get_basename(user_dir), "description": user_dir, "icon": icon, "words": [GLib.path_get_basename(user_dir)], }
def do_window_removed(self, window): Gtk.Application.do_window_removed(self, window) if window.filename is None: return basename = GLib.path_get_basename(window.filename) other_windows = [ w for w in self.get_windows() if w.filename is not None and w is not window and GLib.path_get_basename(w.filename) == basename ] if len(other_windows) == 1: other_windows[0].props.title = basename
def get_title(self, tags, filepath): """ Return title for tags @param tags as Gst.TagList @param filepath as string @return title as string """ if tags is None: return GLib.path_get_basename(filepath) (exists, title) = tags.get_string_index('title', 0) if not exists: title = GLib.path_get_basename(filepath) return title
def compare_basename(model, iter1, iter2, unused_user_data): """ Compare the model elements identified by the L{Gtk.TreeIter} elements. """ uri1 = model[iter1][COL_URI] uri2 = model[iter2][COL_URI] basename1 = GLib.path_get_basename(uri1).lower() basename2 = GLib.path_get_basename(uri2).lower() if basename1 < basename2: return -1 if basename1 == basename2: if uri1 < uri2: return -1 return 1
def get_title(self, tags, filepath): """ Return title for tags @param tags as Gst.TagList @param filepath as string @return title as string """ if tags is None: return GLib.path_get_basename(filepath) (exists, title) = tags.get_string_index("title", 0) # We need to check tag is not just spaces if not exists or not title.strip(" "): title = GLib.path_get_basename(filepath) return title
def _runningFromSource(): fileName = sys.argv[0] prgName = GLib.path_get_basename(fileName) binary = Gio.File.new_for_path(fileName) sourceBinary = Gio.File.new_for_path('./src/' + prgName) return binary.equal(sourceBinary)
def ___reset_database(self, track_ids, count, history, progress): """ Backup database and reset @param track ids as [int] @param count as int @param history as History @param progress as Gtk.ProgressBar """ if track_ids: track_id = track_ids.pop(0) uri = Lp().tracks.get_uri(track_id) filepath = GLib.filename_from_uri(uri)[0] name = GLib.path_get_basename(filepath) album_id = Lp().tracks.get_album_id(track_id) popularity = Lp().tracks.get_popularity(track_id) ltime = Lp().tracks.get_ltime(track_id) mtime = Lp().albums.get_mtime(album_id) duration = Lp().tracks.get_duration(track_id) album_popularity = Lp().albums.get_popularity(album_id) history.add(name, duration, popularity, ltime, mtime, album_popularity) progress.set_fraction((count - len(track_ids))/count) GLib.idle_add(self.___reset_database, track_ids, count, history, progress) else: Lp().db.del_tracks(Lp().tracks.get_ids()) progress.hide() Lp().db = Database() Lp().window.show_genres(Lp().settings.get_value('show-genres')) Lp().window.update_db() progress.get_toplevel().set_deletable(True)
def _del_from_db(self, filepath): """ Delete track from db @param filepath as str """ name = GLib.path_get_basename(filepath) track_id = Lp().tracks.get_id_by_path(filepath) album_id = Lp().tracks.get_album_id(track_id) genre_ids = Lp().tracks.get_genre_ids(track_id) album_artist_ids = Lp().albums.get_artist_ids(album_id) artist_ids = Lp().tracks.get_artist_ids(track_id) popularity = Lp().tracks.get_popularity(track_id) ltime = Lp().tracks.get_ltime(track_id) mtime = Lp().albums.get_mtime(album_id) duration = Lp().tracks.get_duration(track_id) album_popularity = Lp().albums.get_popularity(album_id) self._history.add(name, duration, popularity, ltime, mtime, album_popularity) Lp().tracks.remove(track_id) Lp().tracks.clean(track_id) modified = Lp().albums.clean(album_id) if modified: with SqlCursor(Lp().db) as sql: sql.commit() GLib.idle_add(self.emit, 'album-update', album_id) for artist_id in album_artist_ids + artist_ids: Lp().artists.clean(artist_id) for genre_id in genre_ids: Lp().genres.clean(genre_id)
def _reset_database(self, track_ids, count, history, progress): """ Backup database and reset @param track ids as [int] @param count as int @param history as History @param progress as Gtk.ProgressBar """ if track_ids: track_id = track_ids.pop(0) filepath = self.tracks.get_path(track_id) name = GLib.path_get_basename(filepath) album_id = self.tracks.get_album_id(track_id) popularity = self.tracks.get_popularity(track_id) ltime = self.tracks.get_ltime(track_id) mtime = self.albums.get_mtime(album_id) duration = self.tracks.get_duration(track_id) album_popularity = self.albums.get_popularity(album_id) history.add(name, duration, popularity, ltime, mtime, album_popularity) progress.set_fraction((count - len(track_ids))/count) GLib.idle_add(self._reset_database, track_ids, count, history, progress) else: progress.hide() for artist in self.artists.get([]): self.art.emit('artist-artwork-changed', artist[1]) os.remove(Database.DB_PATH) self.db = Database() self.window.show_genres(self.settings.get_value('show-genres')) self.window.show() self.window.update_db() progress.get_toplevel().set_deletable(True)
def __del_from_db(self, uri): """ Delete track from db @param uri as str """ path = GLib.filename_from_uri(uri)[0] name = GLib.path_get_basename(path) track_id = Lp().tracks.get_id_by_uri(uri) album_id = Lp().tracks.get_album_id(track_id) genre_ids = Lp().tracks.get_genre_ids(track_id) album_artist_ids = Lp().albums.get_artist_ids(album_id) artist_ids = Lp().tracks.get_artist_ids(track_id) popularity = Lp().tracks.get_popularity(track_id) ltime = Lp().tracks.get_ltime(track_id) mtime = Lp().albums.get_mtime(album_id) duration = Lp().tracks.get_duration(track_id) album_popularity = Lp().albums.get_popularity(album_id) self.__history.add(name, duration, popularity, ltime, mtime, album_popularity) Lp().tracks.remove(track_id) Lp().tracks.clean(track_id) modified = Lp().albums.clean(album_id) if modified: with SqlCursor(Lp().db) as sql: sql.commit() GLib.idle_add(self.emit, 'album-updated', album_id) for artist_id in album_artist_ids + artist_ids: ret = Lp().artists.clean(artist_id) if ret: GLib.idle_add(self.emit, 'artist-updated', artist_id, album_id, False) for genre_id in genre_ids: ret = Lp().genres.clean(genre_id) if ret: GLib.idle_add(self.emit, 'genre-updated', genre_id, False)
def _runningFromSource(): fileName = sys.argv[0] prgName = GLib.path_get_basename(fileName) binary = Gio.File.new_for_path(fileName) sourceBinary = Gio.File.new_for_path("./src/" + prgName) return binary.equal(sourceBinary)
def __append_playlists(self, playlists, files_list=[]): """ Append a playlist @param playlists as [(int, str)] @internal files_list """ if playlists and not self.__stop: # Cache directory playlists if not files_list: try: d = Gio.File.new_for_uri(self._uri) infos = d.enumerate_children( "standard::name,standard::type", Gio.FileQueryInfoFlags.NONE, None) for info in infos: if info.get_file_type() != Gio.FileType.DIRECTORY: f = infos.get_child(info) if f.get_uri().endswith(".m3u"): files_list.append( GLib.path_get_basename(f.get_path())) except: pass playlist = playlists.pop(0) selected = playlist[1] + ".m3u" in files_list self.__model.append([selected, playlist[1], playlist[0]]) GLib.idle_add(self.__append_playlists, playlists, files_list)
def __append_playlists(self, playlists, files_list=[]): """ Append a playlist @param playlists as [(int, str)] @internal files_list """ if playlists and not self.__stop: # Cache directory playlists if not files_list: try: d = Lio.File.new_for_uri(self._uri) infos = d.enumerate_children( 'standard::name,standard::type', Gio.FileQueryInfoFlags.NONE, None) for info in infos: if info.get_file_type() != Gio.FileType.DIRECTORY: f = infos.get_child(info) if f.get_uri().endswith(".m3u"): files_list.append( GLib.path_get_basename(f.get_path())) except: pass playlist = playlists.pop(0) selected = playlist[1] + ".m3u" in files_list self.__model.append([selected, playlist[1], playlist[0]]) GLib.idle_add(self.__append_playlists, playlists, files_list)
def title(self): if self.asset: tags = self.asset.get_info().get_tags() if tags: (exists, title) = tags.get_string_index("title", 0) if exists and title.strip(): return title return GLib.path_get_basename(self.filepath.get_path())
def reply_request(self, message, status, form_info): try: basename = GLib.path_get_basename(self.shared_file) except: basename = None form = get_form(self.allow_upload, form_info, self.archive_state, basename, GLib.get_real_name()) message.set_response("text/html", Soup.MemoryUse.COPY, form) message.set_status(status)
def get_executable(argv): executable_path = argv[1] if not executable_path: return None filename = GLib.path_get_basename(executable_path) return {"path": executable_path, "filename": filename}
def __get_basenames(self, window): """ Return the basenames of the filenames of all windows that have filenames, except ‘window’. """ return { GLib.path_get_basename(w.filename) for w in self.get_windows() if w is not window and w.filename is not None }
def _launcherUsage(_flags): print('Usage:') name = GLib.path_get_basename(sys.argv[0]) if flags & Gio.ApplicationFlags.HANDLES_OPEN: print(' ' + name + ' [OPTION...] [FILE...]\n') else: print(' ' + name + ' [OPTION...]\n') print('Options:') print(' -h, --help Show this help message') print(' --version Show the application version')
def _launcherUsage(_flags): print("Usage:") name = GLib.path_get_basename(sys.argv[0]) if flags & Gio.ApplicationFlags.HANDLES_OPEN: print(" " + name + " [OPTION...] [FILE...]\n") else: print(" " + name + " [OPTION...]\n") print("Options:") print(" -h, --help Show this help message") print(" --version Show the application version")
def create_archive(self, files, callback): temp_dir = tempfile.mkdtemp("", "ffs-") if len(files) == 1: archive_name = os.path.join(temp_dir, GLib.path_get_basename(files[0])) else: archive_name = os.path.join(temp_dir, "archive.zip") cmd = ["7z", "-y", "-tzip", "-bd", "-mx=7", "a", archive_name] flags = GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD result = GLib.spawn_async(cmd + files, [], GLib.get_current_dir(), flags, None, None, False, True, False) self.out_7z = GLib.IOChannel(result[2]) self.out_7z.set_close_on_unref(True) GLib.child_watch_add(result[0], self.on_child_process_exit, callback) return archive_name
def do_window_added(self, window): Gtk.Application.do_window_added(self, window) windows = self.get_windows() if window.filename is None: window.props.title = _('New File {:d}').format( self.__unnamed_window_number) self.__unnamed_window_number += 1 else: basenames = self.__get_basenames(window) basename = GLib.path_get_basename(window.filename) if basename in basenames: for w in windows: self.__maybe_set_window_title(w, basename) else: window.props.title = basename
def load_external(self, uri, name=''): """ Load external tracks @param uri as str @param name as string """ track = Track() track.set_album_artists([name]) track.set_uri(uri) if track.uri.startswith('file://'): track.id = Type.EXTERNALS track.name = GLib.path_get_basename(GLib.filename_from_uri(uri)[0]) else: track.name = uri track.id = Type.RADIOS self._external_tracks.append(track)
def get_stats(self, path, duration): """ Get stats for track with filename and duration @param path as str @param duration as int @return (popularity, mtime) as (int, int) """ with SqlCursor(Lp().db) as sql: name = GLib.path_get_basename(path) result = sql.execute("SELECT popularity, ltime\ FROM tracks\ WHERE filepath LIKE ?\ AND duration=?", ('%' + name + '%', duration)) v = result.fetchone() if v is not None: return v return None
def on_save_clicked(self, button): chooser = Gtk.FileChooserNative.new('Save Log', self, Gtk.FileChooserAction.SAVE, None, None) chooser.set_do_overwrite_confirmation(True) script_path = self.path_entry.get_text() script_name = GLib.path_get_basename(script_path) if len(script_name) > 0: chooser.set_current_name(script_name + '.log') res = chooser.run() if res != Gtk.ResponseType.ACCEPT: return path = chooser.get_filename() start, end = self.output_buffer.get_bounds() buffer_text = self.output_buffer.get_text(start, end, True) # FIXME: Catch errors here and print them? GLib.file_set_contents(path, buffer_text.encode('utf-8'))
def handle_download_request(self, message, path): # could handle multiple files here ... if path != "/1" or not self.shared_file: self.reply_request(message, Status.NOT_FOUND, FormInfo.DOWNLOAD_NOT_FOUND) return if self.archive_state == ArchiveState.PREPARING: self.reply_request(message, Status.ACCEPTED, FormInfo.PREPARING_DOWNLOAD) return shared_content = GLib.file_get_contents(self.shared_file)[1] message.set_status(Status.OK) attachment = {"filename": GLib.path_get_basename(self.shared_file)} message.response_headers.set_content_disposition("attachment", attachment) message.response_body.append_buffer(Soup.Buffer.new(shared_content)) message.connect("wrote-body", self.on_soup_message_wrote_body) self.download_count += 1 self.change_callback()
def __init__(self, download, finished): """ Init row @param download as WebKit2.Download @param finished as bool """ Gtk.ListBoxRow.__init__(self) self.__download = download self.__finished = finished self.__download_previous_time = None self.__download_bytes = 0 self.__avg_download_rates = [] self.__uri = self.__download.get_request().get_uri() builder = Gtk.Builder() builder.add_from_resource("/org/gnome/Eolie/RowDownload.ui") builder.connect_signals(self) self.__preview = builder.get_object("preview") self.__progress = builder.get_object("progress") self.__label = builder.get_object("label") self.__sublabel = builder.get_object("sublabel") destination = download.get_destination() filename = None if destination is not None: filename = GLib.filename_from_uri(destination) if filename is not None: self.__label.set_label(GLib.path_get_basename(filename[0])) else: self.__label.set_label(download.get_destination()) self.__label.set_ellipsize(Pango.EllipsizeMode.START) self.__button = builder.get_object("button") self.__button_image = builder.get_object("button_image") if finished: self.__on_finished(download) else: progress = download.get_estimated_progress() if progress is not None: self.__progress.set_fraction(progress) self.add(builder.get_object("row")) self.connect("map", self.__on_map) self.connect("unmap", self.__on_unmap)
def __populate(self, tracks): """ Populate popover @param tracks as [Track] @thread safe """ for track in tracks: if track.duration == 0.0: try: info = self.__tagreader.get_info(track.uri) track_name = GLib.path_get_basename( GLib.filename_from_uri(track.uri)[0]) if info is not None: tags = info.get_tags() track.duration = info.get_duration()/1000000000 track.name = self.__tagreader.get_title(tags, track_name) track.artist_names = self.__tagreader.get_artists(tags) else: track.name = track_name except Exception as e: print("ExternalsPopover::__populate(): %s" % e) track.name = track_name GLib.idle_add(self.__add_track, track)
def update_ui(self, should_grab=False): if self.server == None: self.share_button.set_label("Share files") if self.config_port == 0: self.sharing_label.set_text("Failed to start the web server.") else: self.sharing_label.set_text("Failed to start the web server on port %d." % self.config_port) self.set_sensitive(False) return # always show the local address self.local_ip_label.set_text("http://%s:%d" % (self.server.local_ip, self.server.get_port())) # only show the port-forwarded opened address if we know it works ... if self.server.upnp_ip_state == IPState.AVAILABLE: self.upnp_ip_label.set_text("http://%s:%d" % (self.server.upnp_ip, self.server.upnp_port)) self.upnp_ip_label.set_visible(True) self.upnp_info_label.set_visible(True) if should_grab: self.upnp_ip_label.grab_focus() else: self.upnp_ip_label.set_visible(False) self.upnp_info_label.set_visible(False) if should_grab: self.local_ip_label.grab_focus() if not self.server.allow_upload and self.server.upload_count == 0: self.upload_label.set_text("Allow uploads:\n") elif self.server.upload_count == 0: self.upload_label.set_text("Allow uploads:\n(No uploads yet)") elif self.server.upload_count == 1: self.upload_label.set_markup( "Allow uploads:\n(<a href='file://%s' title='Open containing folder'>One upload</a> so far, %s)" % (self.server.upload_dir, get_human_readable_bytes(self.server.upload_bytes)) ) elif self.server.upload_count > 1: self.upload_label.set_markup( "Allow uploads:\n(<a href='file://%s' title='Open containing folder'>%d uploads</a> so far, totalling %s)" % (self.server.upload_dir, self.server.upload_count, get_human_readable_bytes(self.server.upload_bytes)) ) if self.server.shared_file == None: self.share_button.set_label("Share files") if self.server.archive_state == ArchiveState.FAILED: self.sharing_label.set_text("Failed to create the archive.") else: self.sharing_label.set_text("Currently sharing nothing.") return self.share_button.set_label("Stop sharing") basename = GLib.path_get_basename(self.server.shared_file) if self.server.archive_state == ArchiveState.PREPARING: self.sharing_label.set_text("Now preparing '%s' for sharing" % basename) elif self.server.download_count < 1: if self.server.download_finished_count == 0: text = "no downloads yet" elif self.server.download_finished_count == 1: text = "downloaded once" else: text = "%d downloads so far" % self.server.download_finished_count self.sharing_label.set_text("Sharing '%s'\n(%s)" % (basename, text)) else: if self.server.download_finished_count == 0: text = "download in progress" elif self.server.download_finished_count == 1: text = "download in progress, downloaded once already" else: text = "download in progress, %d downloads so far" % self.server.download_finished_count self.sharing_label.set_text("Sharing '%s'\n(%s)" % (basename, text))
def test_basic_argument(self): self.assertEqual(GLib.path_get_basename("/omg/foo/test"), "test") self.assertEqual(GLib.path_get_basename(u"/omg/foo/test"), "test")
def __maybe_set_window_title(window, basename): if (GLib.path_get_basename(window.filename) == basename): window.props.title = home_substitute(window.filename)
def __add2db(self, uri, info, mtime): """ Add new file to db with informations @param uri as string @param info as GstPbutils.DiscovererInfo @param mtime as int @return track id as int """ debug("CollectionScanner::add2db(): Read tags") path = GLib.filename_from_uri(uri)[0] tags = info.get_tags() title = self.get_title(tags, path) artists = self.get_artists(tags) composers = self.get_composers(tags) performers = self.get_performers(tags) a_sortnames = self.get_artist_sortnames(tags) aa_sortnames = self.get_album_artist_sortnames(tags) album_artists = self.get_album_artist(tags) album_name = self.get_album_name(tags) genres = self.get_genres(tags) discnumber = self.get_discnumber(tags) discname = self.get_discname(tags) tracknumber = self.get_tracknumber(tags, GLib.basename(path)) year = self.get_year(tags) duration = int(info.get_duration() / 1000000000) name = GLib.path_get_basename(path) # If no artists tag, use album artist if artists == '': artists = album_artists # if artists is always null, no album artists too, # use composer/performer if artists == '': artists = performers album_artists = composers if artists == '': artists = album_artists if artists == '': artists = _("Unknown") debug("CollectionScanner::add2db(): Restore stats") # Restore stats (track_pop, track_ltime, amtime, album_pop) = self.__history.get(name, duration) # If nothing in stats, set mtime if amtime == 0: amtime = mtime debug("CollectionScanner::add2db(): Add artists %s" % artists) (artist_ids, new_artist_ids) = self.add_artists(artists, album_artists, a_sortnames) debug("CollectionScanner::add2db(): " "Add album artists %s" % album_artists) (album_artist_ids, new_album_artist_ids) = self.add_album_artists( album_artists, aa_sortnames) new_artist_ids += new_album_artist_ids debug("CollectionScanner::add2db(): Add album: " "%s, %s" % (album_name, album_artist_ids)) (album_id, new_album) = self.add_album(album_name, album_artist_ids, path, album_pop, amtime) (genre_ids, new_genre_ids) = self.add_genres(genres, album_id) # Add track to db debug("CollectionScanner::add2db(): Add track") track_id = Lp().tracks.add(title, uri, duration, tracknumber, discnumber, discname, album_id, year, track_pop, track_ltime, mtime) debug("CollectionScanner::add2db(): Update tracks") self.update_track(track_id, artist_ids, genre_ids) self.update_album(album_id, album_artist_ids, genre_ids, year) # Notify about new artists/genres if new_genre_ids or new_artist_ids: with SqlCursor(Lp().db) as sql: sql.commit() for genre_id in new_genre_ids: GLib.idle_add(self.emit, 'genre-updated', genre_id, True) for artist_id in new_artist_ids: GLib.idle_add(self.emit, 'artist-updated', artist_id, album_id, True) return track_id
def __remove_from_device(self, playlists): """ Delete files not available in playlist """ track_uris = [] track_ids = [] # Get tracks if playlists and playlists[0] == Type.NONE: track_ids = [] album_ids = Lp().albums.get_synced_ids() for album_id in album_ids: track_ids += Lp().albums.get_track_ids(album_id) else: for playlist in playlists: track_ids += Lp().playlists.get_track_ids(playlist) # Get tracks uris for track_id in track_ids: if not self._syncing: self._fraction = 1.0 self.__in_thread = False return track = Track(track_id) if not track.uri.startswith('file:'): continue album_name = escape(track.album_name.lower()) if track.album.artist_ids[0] == Type.COMPILATIONS: on_device_album_uri = "%s/%s" % (self._uri, album_name) else: artists = escape(", ".join(track.album.artists).lower()) on_device_album_uri = "%s/%s_%s" % (self._uri, artists, album_name) filepath = GLib.filename_from_uri(track.uri)[0] track_name = escape(GLib.path_get_basename(filepath)) # Check extension, if not mp3, convert ext = os.path.splitext(filepath)[1] if ext != ".mp3" and self.__convert: track_name = track_name.replace(ext, ".mp3") on_disk = Gio.File.new_for_path(filepath) info = on_disk.query_info('time::modified', Gio.FileQueryInfoFlags.NONE, None) # Prefix track with mtime to make sure updating it later mtime = info.get_attribute_as_string('time::modified') dst_uri = "%s/%s_%s" % (on_device_album_uri, mtime, track_name) track_uris.append(dst_uri) on_mtp_files = self.__get_track_files() # Delete file on device and not in playlists for uri in on_mtp_files: if not self._syncing: self._fraction = 1.0 self.__in_thread = False return if uri not in track_uris and uri not in self.__copied_art_uris: to_delete = Gio.File.new_for_uri(uri) self.__retry(to_delete.delete, (None, )) self.__done += 1 self._fraction = self.__done / self.__total
def _add2db(self, filepath, infos, mtime): """ Add new file to db with informations @param filepath as string @param infos as GstPbutils.DiscovererInfo @param mtime as int @return track id as int """ tags = infos.get_tags() title = self.get_title(tags, filepath) artists = self.get_artists(tags) sortname = self.get_artist_sortname(tags) album_artist = self.get_album_artist(tags) album_name = self.get_album_name(tags) genres = self.get_genres(tags) discnumber = self.get_discnumber(tags) tracknumber = self.get_tracknumber(tags) year = self.get_year(tags) duration = int(infos.get_duration()/1000000000) name = GLib.path_get_basename(filepath) # Restore stats (track_pop, track_ltime, amtime, album_pop) = self._history.get( name, duration) # If nothing in stats, set mtime if amtime == 0: amtime = mtime (artist_ids, new_artist_ids) = self.add_artists(artists, album_artist, sortname) (album_artist_id, new) = self.add_album_artist(album_artist) if new: new_artist_ids.append(album_artist_id) # Check for album artist, if none, use first available artist no_album_artist = False if album_artist_id is None: album_artist_id = artist_ids[0] no_album_artist = True (album_id, new_album) = self.add_album(album_name, album_artist_id, no_album_artist, year, filepath, album_pop, amtime) (genre_ids, new_genre_ids) = self.add_genres(genres, album_id) # Add track to db track_id = Lp().tracks.add(title, filepath, duration, tracknumber, discnumber, album_id, year, track_pop, track_ltime, mtime) self.update_track(track_id, artist_ids, genre_ids) # Notify about new artists/genres if new_genre_ids or new_artist_ids: with SqlCursor(Lp().db) as sql: sql.commit() for genre_id in new_genre_ids: GLib.idle_add(self.emit, 'genre-added', genre_id) for artist_id in new_artist_ids: GLib.idle_add(self.emit, 'artist-added', artist_id, album_id) return track_id
def __copy_to_device(self, playlists): """ Copy file from playlist to device @param playlists as [str] """ for playlist in playlists: m3u = None stream = None if playlist != Type.NONE: try: playlist_name = Lp().playlists.get_name(playlist) # Create playlist m3u = Gio.File.new_for_path("/tmp/lollypop_%s.m3u" % (playlist_name, )) self.__retry( m3u.replace_contents, (b'#EXTM3U\n', None, False, Gio.FileCreateFlags.REPLACE_DESTINATION, None)) stream = m3u.open_readwrite(None) except Exception as e: print("DeviceWidget::_copy_to_device(): %s" % e) # Get tracks if playlist == Type.NONE: track_ids = [] album_ids = Lp().albums.get_synced_ids() for album_id in album_ids: track_ids += Lp().albums.get_track_ids(album_id) else: track_ids = Lp().playlists.get_track_ids(playlist) # Start copying for track_id in track_ids: if track_id is None: continue if not self._syncing: self._fraction = 1.0 self.__in_thread = False return track = Track(track_id) if not track.uri.startswith('file:'): continue album_name = escape(track.album_name.lower()) is_compilation = track.album.artist_ids[0] == Type.COMPILATIONS if is_compilation: on_device_album_uri = "%s/%s" %\ (self._uri, album_name) else: artists = escape(", ".join(track.album.artists).lower()) on_device_album_uri = "%s/%s_%s" %\ (self._uri, artists, album_name) d = Gio.File.new_for_uri(on_device_album_uri) if not d.query_exists(None): self.__retry(d.make_directory_with_parents, (None, )) # Copy album art art = Lp().art.get_album_artwork_path(track.album) if art is not None: src_art = Gio.File.new_for_path(art) art_uri = "%s/cover.jpg" % on_device_album_uri self.__copied_art_uris.append(art_uri) dst_art = Gio.File.new_for_uri(art_uri) if not dst_art.query_exists(None): self.__retry( src_art.copy, (dst_art, Gio.FileCopyFlags.OVERWRITE, None, None)) filepath = GLib.filename_from_uri(track.uri)[0] track_name = escape(GLib.path_get_basename(filepath)) # Check extension, if not mp3, convert ext = os.path.splitext(filepath)[1] if (ext != ".mp3" or self.__normalize) and self.__convert: convertion_needed = True track_name = track_name.replace(ext, ".mp3") else: convertion_needed = False src_track = Gio.File.new_for_uri(track.uri) info = src_track.query_info('time::modified', Gio.FileQueryInfoFlags.NONE, None) # Prefix track with mtime to make sure updating it later mtime = info.get_attribute_as_string('time::modified') dst_uri = "%s/%s_%s" % (on_device_album_uri, mtime, track_name) if stream is not None: if is_compilation: line = "%s/%s_%s\n" %\ (album_name, mtime, track_name) else: line = "%s_%s/%s_%s\n" %\ (artists, album_name, mtime, track_name) self.__retry(stream.get_output_stream().write, (line.encode(encoding='UTF-8'), None)) dst_track = Gio.File.new_for_uri(dst_uri) if not dst_track.query_exists(None): if convertion_needed: mp3_uri = "file:///tmp/%s" % track_name mp3_file = Gio.File.new_for_uri(mp3_uri) pipeline = self.__convert_to_mp3(src_track, mp3_file) # Check if encoding is finished if pipeline is not None: bus = pipeline.get_bus() bus.add_signal_watch() bus.connect('message::eos', self.__on_bus_eos) self.__encoding = True while self.__encoding and self._syncing: sleep(1) bus.disconnect_by_func(self.__on_bus_eos) pipeline.set_state(Gst.State.PAUSED) pipeline.set_state(Gst.State.READY) pipeline.set_state(Gst.State.NULL) self.__retry( mp3_file.move, (dst_track, Gio.FileCopyFlags.OVERWRITE, None, None)) # To be sure try: mp3_file.delete(None) except: pass else: self.__retry(src_track.copy, (dst_track, Gio.FileCopyFlags.OVERWRITE, None, None)) else: self.__done += 1 self.__done += 1 self._fraction = self.__done / self.__total if stream is not None: stream.close() if m3u is not None: playlist_name = escape(playlist_name) dst = Gio.File.new_for_uri(self._uri + '/' + playlist_name + '.m3u') self.__retry(m3u.move, (dst, Gio.FileCopyFlags.OVERWRITE, None, None))
def _add2db(self, filepath, infos, mtime): """ Add new file to db with informations @param filepath as string @param infos as GstPbutils.DiscovererInfo @param mtime as int @return track id as int """ debug("CollectionScanner::add2db(): Read tags") tags = infos.get_tags() title = self.get_title(tags, filepath) artists = self.get_artists(tags) composers = self.get_composers(tags) performers = self.get_performers(tags) sortnames = self.get_artist_sortnames(tags) album_artists = self.get_album_artist(tags) album_name = self.get_album_name(tags) genres = self.get_genres(tags) discnumber = self.get_discnumber(tags) tracknumber = self.get_tracknumber(tags) year = self.get_year(tags) duration = int(infos.get_duration() / 1000000000) name = GLib.path_get_basename(filepath) # If no artists tag, use album artist if artists == '': artists = album_artists # if artists is always null, no album artists too, # use composer/performer if artists == '': artists = performers album_artists = composers if artists == '': artists = album_artists debug("CollectionScanner::add2db(): Restore stats") # Restore stats (track_pop, track_ltime, amtime, album_pop) = self._history.get(name, duration) # If nothing in stats, set mtime if amtime == 0: amtime = mtime debug("CollectionScanner::add2db(): Add artists %s" % artists) (artist_ids, new_artist_ids) = self.add_artists(artists, album_artists, sortnames) debug("CollectionScanner::add2db(): " "Add album artists %s" % album_artists) (album_artist_ids, new_album_artist_ids) = self.add_album_artists(album_artists) new_artist_ids += new_album_artist_ids # Check for album artist, if none, use first available artist no_album_artist = False if not album_artist_ids: album_artist_ids = artist_ids no_album_artist = True debug("CollectionScanner::add2db(): Add album: " "%s, %s, %s" % (album_name, album_artist_ids, year)) (album_id, new_album) = self.add_album(album_name, album_artist_ids, no_album_artist, year, filepath, album_pop, amtime) (genre_ids, new_genre_ids) = self.add_genres(genres, album_id) # Add track to db debug("CollectionScanner::add2db(): Add track") track_id = Lp().tracks.add(title, filepath, duration, tracknumber, discnumber, album_id, year, track_pop, track_ltime, mtime) debug("CollectionScanner::add2db(): Update tracks") self.update_album(album_id, album_artist_ids, genre_ids) self.update_track(track_id, artist_ids, genre_ids) # Notify about new artists/genres if new_genre_ids or new_artist_ids: with SqlCursor(Lp().db) as sql: sql.commit() for genre_id in new_genre_ids: GLib.idle_add(self.emit, 'genre-added', genre_id) for artist_id in new_artist_ids: GLib.idle_add(self.emit, 'artist-added', artist_id, album_id) return track_id
def _add2db(self, filepath, infos, mtime): """ Add new file to db with informations @param filepath as string @param infos as GstPbutils.DiscovererInfo @param mtime as int @return track id as int """ debug("CollectionScanner::add2db(): Read tags") tags = infos.get_tags() title = self.get_title(tags, filepath) artists = self.get_artists(tags) composers = self.get_composers(tags) performers = self.get_performers(tags) a_sortnames = self.get_artist_sortnames(tags) aa_sortnames = self.get_album_artist_sortnames(tags) album_artists = self.get_album_artist(tags) album_name = self.get_album_name(tags) genres = self.get_genres(tags) discnumber = self.get_discnumber(tags) discname = self.get_discname(tags) tracknumber = self.get_tracknumber(tags) year = self.get_year(tags) duration = int(infos.get_duration()/1000000000) name = GLib.path_get_basename(filepath) # If no artists tag, use album artist if artists == '': artists = album_artists # if artists is always null, no album artists too, # use composer/performer if artists == '': artists = performers album_artists = composers if artists == '': artists = album_artists if artists == '': artists = _("Unknown") debug("CollectionScanner::add2db(): Restore stats") # Restore stats (track_pop, track_ltime, amtime, album_pop) = self._history.get( name, duration) # If nothing in stats, set mtime if amtime == 0: amtime = mtime debug("CollectionScanner::add2db(): Add artists %s" % artists) (artist_ids, new_artist_ids) = self.add_artists(artists, album_artists, a_sortnames) debug("CollectionScanner::add2db(): " "Add album artists %s" % album_artists) (album_artist_ids, new_album_artist_ids) = self.add_album_artists( album_artists, aa_sortnames) new_artist_ids += new_album_artist_ids debug("CollectionScanner::add2db(): Add album: " "%s, %s, %s" % (album_name, album_artist_ids, year)) (album_id, new_album) = self.add_album(album_name, album_artist_ids, year, filepath, album_pop, amtime) (genre_ids, new_genre_ids) = self.add_genres(genres, album_id) # Add track to db debug("CollectionScanner::add2db(): Add track") track_id = Lp().tracks.add(title, filepath, duration, tracknumber, discnumber, discname, album_id, year, track_pop, track_ltime, mtime) debug("CollectionScanner::add2db(): Update tracks") self.update_track(track_id, artist_ids, genre_ids) self.update_album(album_id, album_artist_ids, genre_ids) # Notify about new artists/genres if new_genre_ids or new_artist_ids: with SqlCursor(Lp().db) as sql: sql.commit() for genre_id in new_genre_ids: GLib.idle_add(self.emit, 'genre-added', genre_id) for artist_id in new_artist_ids: GLib.idle_add(self.emit, 'artist-added', artist_id, album_id) return track_id