Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.44 KB | None | 0 0
  1. import os
  2. from xml.dom import minidom
  3. import shutil
  4.  
  5. import datetime;
  6.  
  7.  
  8. # Search for m3u files
  9. # Read m3u Files
  10. # for line im m3u file
  11. # check if music file exists
  12. # create folder structure
  13. # link file
  14. # if file does not exist, ignore line (remove from target m3u)
  15.  
  16. rhythmboxPath = '/home/keller/.local/share/rhythmbox/'
  17. musicPath = '/home/keller/Musik/'
  18. targetPath = '/home/keller/.musicsync'
  19.  
  20. rhPlaylistsXML = minidom.parse(rhythmboxPath + 'playlists.xml')
  21. rhLibraryXML = minidom.parse(rhythmboxPath + 'rhythmdb.xml')
  22.  
  23. def getParent(et):
  24. return et.parentNode
  25.  
  26. fileList = set()
  27.  
  28. if not os.path.isdir(targetPath):
  29. os.makedirs(targetPath)
  30.  
  31. def create_link_song(m3uFile, source, target, song):
  32. """Make song Filename fitting to the database structure
  33.  
  34. this ensures that duplicate songs don't clutter mp3 players'
  35. album views"""
  36.  
  37. if not os.path.isfile(source):
  38. print(" ! File not Found: {}".format(source))
  39. return 0
  40.  
  41. dest = "";
  42. songDir = target.split('/')
  43. songDir = '/'.join(songDir[0:len(songDir) - 1])
  44. try:
  45. try:
  46. os.makedirs(songDir)
  47. except OSError as err:
  48. pass
  49.  
  50. os.link(source, target);
  51.  
  52. except FileNotFoundError as err:
  53. raise err
  54. return 0
  55. except FileExistsError as err:
  56. pass
  57. except Exception as err:
  58. raise err
  59. return 0
  60.  
  61. m3uFile.write(song)
  62. m3uFile.write('\n')
  63. fileList.add(song)
  64. print(" > Adding File: {}".format(song))
  65. return 1;
  66.  
  67. # config['smartplaylist']['relative_to'] = False
  68. # config['smartplaylist']['playlist_dir'] = py3_path(dir)
  69. # config['smartplaylist']['playlists'].set([
  70. # {'name': 'my_playlist.m3u',
  71. # 'query': self.item.title},
  72. # {'name': 'all.m3u',
  73. # 'query': u''}
  74. # ])
  75.  
  76. # spl = SmartPlaylistPlugin()
  77. # spl.build_queries()
  78. # spl.update_playlists()
  79.  
  80. def export_playlist_static(playlist, m3uFile):
  81. i = 0
  82. for file in playlist.getElementsByTagName('location'):
  83. fullPath = file.firstChild.data
  84. if fullPath.startswith('file://' + musicPath):
  85. filePath = fullPath[len('file://' + musicPath):]
  86. i += create_link_song(
  87. m3uFile,
  88. fullPath[len('file://'):],
  89. targetPath + '/' + filePath,
  90. filePath
  91. )
  92.  
  93. return i
  94.  
  95.  
  96. def export_playlist_automatic(playlist, m3uFile):
  97. search = ''
  98. ts = datetime.datetime.now().timestamp()
  99. rules = playlist.getElementsByTagName('conjunction')[0]
  100. rules = rules.getElementsByTagName('subquery')[0]
  101. rules = rules.getElementsByTagName('conjunction')[0]
  102.  
  103. relevantEntries = rhLibraryXML.getElementsByTagName('entry')
  104. print("Rules:")
  105. for rule in rules.childNodes:
  106. if not rule.localName:
  107. continue
  108.  
  109. comparator = rule.localName
  110. prop = rule.attributes['prop'].value
  111. value = rule.firstChild.data
  112. try:
  113. valueInt = int(float(("" + value).replace(',', '.')))
  114. except:
  115. valueInt = 0
  116.  
  117. print(" " + prop + " " + comparator + " " + value)
  118. def compare(elm):
  119. songValue = elm.firstChild.nodeValue
  120. if comparator == 'current-time-within':
  121. return int(float(songValue.replace(',', '.'))) >= (ts - valueInt)
  122.  
  123. if comparator == 'greater':
  124. return int(float(songValue.replace(',', '.'))) >= valueInt
  125.  
  126. if comparator == 'less':
  127. return int(float(songValue.replace(',', '.'))) <= valueInt
  128.  
  129. if comparator == 'equals':
  130. return int(float(songValue.replace(',', '.'))) == valueInt
  131.  
  132. if comparator == 'like':
  133. return value in songValue
  134.  
  135. if comparator == 'not-like':
  136. return value not in songValue
  137.  
  138.  
  139. currentEntries = rhLibraryXML.getElementsByTagName(prop)
  140. relevantEntries = [elm.parentNode for elm in currentEntries if elm.parentNode.attributes["type"].value == 'song' and compare(elm) and elm.parentNode in relevantEntries]
  141.  
  142. if len(relevantEntries) < 1:
  143. print("\n=== No Results ===\n")
  144. return 0
  145.  
  146. print("{} Entries matched".format(len(relevantEntries)))
  147. print("")
  148. i = 0
  149. for item in relevantEntries:
  150. file = item.getElementsByTagName('location')[0]
  151. fullPath = file.firstChild.data
  152. if fullPath.startswith('file://' + musicPath):
  153. filePath = fullPath[len('file://' + musicPath):]
  154. i += create_link_song(
  155. m3uFile,
  156. fullPath[len('file://'):],
  157. targetPath + '/' + filePath,
  158. filePath
  159. )
  160.  
  161. return i
  162.  
  163.  
  164. rhPlaylists = rhPlaylistsXML.getElementsByTagName('playlist')
  165.  
  166. for the_file in os.listdir(os.path.expanduser(targetPath)):
  167. file_path = os.path.join(os.path.expanduser(targetPath), the_file)
  168. try:
  169. if os.path.isfile(file_path):
  170. os.unlink(file_path)
  171. else:
  172. shutil
  173. except Exception as e:
  174. raise e
  175.  
  176. for playlist in rhPlaylists:
  177. name = playlist.attributes["name"].value
  178. if playlist.attributes["type"].value not in ['static', 'automatic']:
  179. continue
  180.  
  181. print("Exporting {}".format(name))
  182. print("===================================================")
  183. i = 0
  184. with open(targetPath + '/' + name + '.m3u', 'w+') as m3uFile:
  185. if playlist.attributes["type"].value == 'static':
  186. i = export_playlist_static(playlist, m3uFile)
  187.  
  188. if playlist.attributes["type"].value == 'automatic':
  189. i = export_playlist_automatic(playlist, m3uFile)
  190. print("---------------------------------------------------")
  191. print("Exported {} Songs".format(i))
  192. print("")
  193.  
  194. print("=== Total of {} Files were Linked".format(len(fileList)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement