Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from xml.dom import minidom
- import shutil
- import datetime;
- # Search for m3u files
- # Read m3u Files
- # for line im m3u file
- # check if music file exists
- # create folder structure
- # link file
- # if file does not exist, ignore line (remove from target m3u)
- rhythmboxPath = '/home/keller/.local/share/rhythmbox/'
- musicPath = '/home/keller/Musik/'
- targetPath = '/home/keller/.musicsync'
- rhPlaylistsXML = minidom.parse(rhythmboxPath + 'playlists.xml')
- rhLibraryXML = minidom.parse(rhythmboxPath + 'rhythmdb.xml')
- def getParent(et):
- return et.parentNode
- fileList = set()
- if not os.path.isdir(targetPath):
- os.makedirs(targetPath)
- def create_link_song(m3uFile, source, target, song):
- """Make song Filename fitting to the database structure
- this ensures that duplicate songs don't clutter mp3 players'
- album views"""
- if not os.path.isfile(source):
- print(" ! File not Found: {}".format(source))
- return 0
- dest = "";
- songDir = target.split('/')
- songDir = '/'.join(songDir[0:len(songDir) - 1])
- try:
- try:
- os.makedirs(songDir)
- except OSError as err:
- pass
- os.link(source, target);
- except FileNotFoundError as err:
- raise err
- return 0
- except FileExistsError as err:
- pass
- except Exception as err:
- raise err
- return 0
- m3uFile.write(song)
- m3uFile.write('\n')
- fileList.add(song)
- print(" > Adding File: {}".format(song))
- return 1;
- # config['smartplaylist']['relative_to'] = False
- # config['smartplaylist']['playlist_dir'] = py3_path(dir)
- # config['smartplaylist']['playlists'].set([
- # {'name': 'my_playlist.m3u',
- # 'query': self.item.title},
- # {'name': 'all.m3u',
- # 'query': u''}
- # ])
- # spl = SmartPlaylistPlugin()
- # spl.build_queries()
- # spl.update_playlists()
- def export_playlist_static(playlist, m3uFile):
- i = 0
- for file in playlist.getElementsByTagName('location'):
- fullPath = file.firstChild.data
- if fullPath.startswith('file://' + musicPath):
- filePath = fullPath[len('file://' + musicPath):]
- i += create_link_song(
- m3uFile,
- fullPath[len('file://'):],
- targetPath + '/' + filePath,
- filePath
- )
- return i
- def export_playlist_automatic(playlist, m3uFile):
- search = ''
- ts = datetime.datetime.now().timestamp()
- rules = playlist.getElementsByTagName('conjunction')[0]
- rules = rules.getElementsByTagName('subquery')[0]
- rules = rules.getElementsByTagName('conjunction')[0]
- relevantEntries = rhLibraryXML.getElementsByTagName('entry')
- print("Rules:")
- for rule in rules.childNodes:
- if not rule.localName:
- continue
- comparator = rule.localName
- prop = rule.attributes['prop'].value
- value = rule.firstChild.data
- try:
- valueInt = int(float(("" + value).replace(',', '.')))
- except:
- valueInt = 0
- print(" " + prop + " " + comparator + " " + value)
- def compare(elm):
- songValue = elm.firstChild.nodeValue
- if comparator == 'current-time-within':
- return int(float(songValue.replace(',', '.'))) >= (ts - valueInt)
- if comparator == 'greater':
- return int(float(songValue.replace(',', '.'))) >= valueInt
- if comparator == 'less':
- return int(float(songValue.replace(',', '.'))) <= valueInt
- if comparator == 'equals':
- return int(float(songValue.replace(',', '.'))) == valueInt
- if comparator == 'like':
- return value in songValue
- if comparator == 'not-like':
- return value not in songValue
- currentEntries = rhLibraryXML.getElementsByTagName(prop)
- relevantEntries = [elm.parentNode for elm in currentEntries if elm.parentNode.attributes["type"].value == 'song' and compare(elm) and elm.parentNode in relevantEntries]
- if len(relevantEntries) < 1:
- print("\n=== No Results ===\n")
- return 0
- print("{} Entries matched".format(len(relevantEntries)))
- print("")
- i = 0
- for item in relevantEntries:
- file = item.getElementsByTagName('location')[0]
- fullPath = file.firstChild.data
- if fullPath.startswith('file://' + musicPath):
- filePath = fullPath[len('file://' + musicPath):]
- i += create_link_song(
- m3uFile,
- fullPath[len('file://'):],
- targetPath + '/' + filePath,
- filePath
- )
- return i
- rhPlaylists = rhPlaylistsXML.getElementsByTagName('playlist')
- for the_file in os.listdir(os.path.expanduser(targetPath)):
- file_path = os.path.join(os.path.expanduser(targetPath), the_file)
- try:
- if os.path.isfile(file_path):
- os.unlink(file_path)
- else:
- shutil
- except Exception as e:
- raise e
- for playlist in rhPlaylists:
- name = playlist.attributes["name"].value
- if playlist.attributes["type"].value not in ['static', 'automatic']:
- continue
- print("Exporting {}".format(name))
- print("===================================================")
- i = 0
- with open(targetPath + '/' + name + '.m3u', 'w+') as m3uFile:
- if playlist.attributes["type"].value == 'static':
- i = export_playlist_static(playlist, m3uFile)
- if playlist.attributes["type"].value == 'automatic':
- i = export_playlist_automatic(playlist, m3uFile)
- print("---------------------------------------------------")
- print("Exported {} Songs".format(i))
- print("")
- print("=== Total of {} Files were Linked".format(len(fileList)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement