Guest User

Untitled

a guest
Oct 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.47 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: iso-8859-1
  3.  
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17.  
  18. __title__="KeyJ's iPod shuffle Database Builder"
  19. __version__="1.0-rc1"
  20. __author__="Martin Fiedler"
  21. __email__="martin.fiedler@gmx.net"
  22.  
  23. """ VERSION HISTORY
  24. 1.0-rc1 (2006-04-26)
  25. * finally(!) added the often-requested auto-rename feature (-r option)
  26. 0.7-pre1 (2005-06-09)
  27. * 0.6-final was skipped because of the huge load of new (experimental)
  28. features in this version :)
  29. * rule files allow for nice and flexible fine tuning
  30. * fixed --nochdir and --nosmart bugs
  31. * numerical sorting (i.e. "track2.mp3" < "track10.mp3")
  32. * iTunesSD entries are now copied over from the old file if possible; this
  33. should preserve the keys for .aa files
  34. 0.6-pre2 (2005-05-02)
  35. * fixed file type bug (thanks to Nowhereman)
  36. * improved audio book support (thanks to Nowhereman)
  37. * files called $foo.book.$type (like example.book.mp3) are stored as
  38. audio books now
  39. * the subdirectories of /iPod_Control/Music are merged as if they were a
  40. single directory
  41. 0.6-pre1 (2005-04-23)
  42. * always starts from the directory of the executable now
  43. * output logging
  44. * generating iTunesPState and iTunesStats so that the iPod won't overwrite
  45. iTunesShuffle anymore
  46. * -> return of smart shuffle ;)
  47. * directory display order is identical to playback ordernow
  48. * command line options and help
  49. * interactive mode, configurable playback volume, directory limitation
  50. 0.5 (2005-04-15)
  51. * major code refactoring (thanks to Andre Kloss)
  52. * removed "smart shuffle" again -- the iPod deleted the file anyway :(
  53. * common errors are now reported more concisely
  54. * dot files (e.g. ".hidden_file") are now ignored while browsing the iPod
  55. 0.4 (2005-03-20)
  56. * fixed iPod crashes after playing the shuffle playlist to the end
  57. * fixed incorrect databse entries for non-MP3 files
  58. 0.3 (2005-03-18)
  59. * Python version now includes a "smart shuffle" feature
  60. 0.2 (2005-03-15)
  61. * added Python version
  62. 0.1 (2005-03-13)
  63. * initial public release, Win32 only
  64. """
  65.  
  66.  
  67. import sys,os,os.path,array,getopt,random,types,fnmatch,operator,string
  68.  
  69. KnownProps=('filename','size','ignore','type','shuffle','reuse','bookmark')
  70. Rules=[
  71. ([('filename','~','*.mp3')], {'type':1, 'shuffle':1, 'bookmark':0}),
  72. ([('filename','~','*.m4?')], {'type':2, 'shuffle':1, 'bookmark':0}),
  73. ([('filename','~','*.m4b')], { 'shuffle':0, 'bookmark':1}),
  74. ([('filename','~','*.aa')], {'type':1, 'shuffle':0, 'bookmark':1, 'reuse':1}),
  75. ([('filename','~','*.wav')], {'type':4, 'shuffle':0, 'bookmark':0}),
  76. ([('filename','~','*.book.???')], { 'shuffle':0, 'bookmark':1}),
  77. ([('filename','~','*.announce.???')], { 'shuffle':0, 'bookmark':0}),
  78. ([('filename','~','/recycled/*')], {'ignore':1}),
  79. ]
  80.  
  81. Options={
  82. "volume":None,
  83. "interactive":False,
  84. "smart":True,
  85. "home":True,
  86. "logging":True,
  87. "reuse":1,
  88. "logfile":"rebuild_db.log.txt",
  89. "rename":False
  90. }
  91. domains=[]
  92. total_count=0
  93. KnownEntries={}
  94.  
  95.  
  96. ################################################################################
  97.  
  98.  
  99. def open_log():
  100. global logfile
  101. if Options['logging']:
  102. try:
  103. logfile=file(Options['logfile'],"w")
  104. except IOError:
  105. logfile=None
  106. else:
  107. logfile=None
  108.  
  109.  
  110. def log(line="",newline=True):
  111. global logfile
  112. if newline:
  113. print line
  114. line+="\n"
  115. else:
  116. print line,
  117. line+=" "
  118. if logfile:
  119. try:
  120. logfile.write(line)
  121. except IOError:
  122. pass
  123.  
  124.  
  125. def close_log():
  126. global logfile
  127. if logfile:
  128. logfile.close()
  129.  
  130.  
  131. def go_home():
  132. if Options['home']:
  133. try:
  134. os.chdir(os.path.split(sys.argv[0])[0])
  135. except OSError:
  136. pass
  137.  
  138.  
  139. def filesize(filename):
  140. try:
  141. return os.stat(filename)[6]
  142. except OSError:
  143. return None
  144.  
  145.  
  146. ################################################################################
  147.  
  148.  
  149. def MatchRule(props,rule):
  150. try:
  151. prop,op,ref=props[rule[0]],rule[1],rule[2]
  152. except KeyError:
  153. return False
  154. if rule[1]=='~':
  155. return fnmatch.fnmatchcase(prop.lower(),ref.lower())
  156. elif rule[1]=='=':
  157. return cmp(prop,ref)==0
  158. elif rule[1]=='>':
  159. return cmp(prop,ref)>0
  160. elif rule[1]=='<':
  161. return cmp(prop,ref)<0
  162. else:
  163. return False
  164.  
  165.  
  166. def ParseValue(val):
  167. if len(val)>=2 and ((val[0]=="'" and val[-1]=="'") or (val[0]=='"' and val[-1]=='"')):
  168. return val[1:-1]
  169. try:
  170. return int(val)
  171. except ValueError:
  172. return val
  173.  
  174. def ParseRule(rule):
  175. sep_pos=min([rule.find(sep) for sep in "~=<>" if rule.find(sep)>0])
  176. prop=rule[:sep_pos].strip()
  177. if not prop in KnownProps:
  178. log("WARNING: unknown property `%s'"%prop)
  179. return (prop,rule[sep_pos],ParseValue(rule[sep_pos+1:].strip()))
  180.  
  181. def ParseAction(action):
  182. prop,value=map(string.strip,action.split('=',1))
  183. if not prop in KnownProps:
  184. log("WARNING: unknown property `%s'"%prop)
  185. return (prop,ParseValue(value))
  186.  
  187. def ParseRuleLine(line):
  188. line=line.strip()
  189. if not(line) or line[0]=="#":
  190. return None
  191. try:
  192. # split line into "ruleset: action"
  193. tmp=line.split(":")
  194. ruleset=map(string.strip,":".join(tmp[:-1]).split(","))
  195. actions=dict(map(ParseAction,tmp[-1].split(",")))
  196. if len(ruleset)==1 and not(ruleset[0]):
  197. return ([],actions)
  198. else:
  199. return (map(ParseRule,ruleset),actions)
  200. except OSError: #(ValueError,IndexError,KeyError):
  201. log("WARNING: rule `%s' is malformed, ignoring"%line)
  202. return None
  203. return None
  204.  
  205.  
  206. ################################################################################
  207.  
  208.  
  209. def safe_char(c):
  210. if c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_":
  211. return c
  212. return "_"
  213.  
  214. def rename_safely(path,name):
  215. base,ext=os.path.splitext(name)
  216. newname=''.join(map(safe_char,base))
  217. if name==newname+ext:
  218. return name
  219. if os.path.exists("%s/%s%s"%(path,newname,ext)):
  220. i=0
  221. while os.path.exists("%s/%s_%d%s"%(path,newname,i,ext)):
  222. i+=1
  223. newname+="_%d"%i
  224. newname+=ext
  225. try:
  226. os.rename("%s/%s"%(path,name),"%s/%s"%(path,newname))
  227. except OSError:
  228. pass # don't fail if the rename didn't work
  229. return newname
  230.  
  231.  
  232. def write_to_db(filename):
  233. global iTunesSD,domains,total_count,KnownEntries,Rules
  234.  
  235. # set default properties
  236. props={
  237. 'filename': filename,
  238. 'size': filesize(filename[1:]),
  239. 'ignore': 0,
  240. 'type': 1,
  241. 'shuffle': 1,
  242. 'reuse': Options['reuse'],
  243. 'bookmark': 0
  244. }
  245.  
  246. # check and apply rules
  247. for ruleset,action in Rules:
  248. if reduce(operator.__and__,[MatchRule(props,rule) for rule in ruleset],True):
  249. props.update(action)
  250. if props['ignore']: return 0
  251.  
  252. # retrieve entry from known entries or rebuild it
  253. entry=props['reuse'] and (filename in KnownEntries) and KnownEntries[filename]
  254. if not entry:
  255. header[29]=props['type']
  256. entry=header.tostring()+ \
  257. "".join([c+"\0" for c in filename[:261]])+ \
  258. "\0"*(525-2*len(filename))
  259.  
  260. # write entry, modifying shuffleflag and bookmarkflag at least
  261. iTunesSD.write(entry[:555]+chr(props['shuffle'])+chr(props['bookmark'])+entry[557])
  262. if props['shuffle']: domains[-1].append(total_count)
  263. total_count+=1
  264. return 1
  265.  
  266.  
  267. def make_key(s):
  268. if not s: return s
  269. s=s.lower()
  270. for i in xrange(len(s)):
  271. if s[i].isdigit(): break
  272. if not s[i].isdigit(): return s
  273. for j in xrange(i,len(s)):
  274. if not s[j].isdigit(): break
  275. if s[j].isdigit(): j+=1
  276. return (s[:i],int(s[i:j]),make_key(s[j:]))
  277.  
  278. def key_repr(x):
  279. if type(x)==types.TupleType:
  280. return "%s%d%s"%(x[0],x[1],key_repr(x[2]))
  281. else:
  282. return x
  283.  
  284. def cmp_key(a,b):
  285. if type(a)==types.TupleType and type(b)==types.TupleType:
  286. return cmp(a[0],b[0]) or cmp(a[1],b[1]) or cmp_key(a[2],b[2])
  287. else:
  288. return cmp(key_repr(a),key_repr(b))
  289.  
  290.  
  291. def file_entry(path,name,prefix=""):
  292. if not(name) or name[0]==".": return None
  293. fullname="%s/%s"%(path,name)
  294. may_rename=not(fullname.startswith("./iPod_Control")) and Options['rename']
  295. try:
  296. if os.path.islink(fullname):
  297. return None
  298. if os.path.isdir(fullname):
  299. if may_rename: name=rename_safely(path,name)
  300. return (0,make_key(name),prefix+name)
  301. if os.path.splitext(name)[1].lower() in (".mp3",".m4a",".m4b",".m4p",".aa",".wav"):
  302. if may_rename: name=rename_safely(path,name)
  303. return (1,make_key(name),prefix+name)
  304. except OSError:
  305. pass
  306. return None
  307.  
  308.  
  309. def browse(path, interactive):
  310. global domains
  311.  
  312. if path[-1]=="/": path=path[:-1]
  313. displaypath=path[1:]
  314. if not displaypath: displaypath="/"
  315.  
  316. if interactive:
  317. while 1:
  318. try:
  319. choice=raw_input("include `%s'? [(Y)es, (N)o, (A)ll] "%displaypath)[:1].lower()
  320. except EOFError:
  321. raise KeyboardInterrupt
  322. if not choice: continue
  323. if choice in "at": # all/alle/tous/<dontknow>
  324. interactive=0
  325. break
  326. if choice in "yjos": # yes/ja/oui/si
  327. break
  328. if choice in "n": # no/nein/non/non?
  329. return 0
  330.  
  331. try:
  332. files=filter(None,[file_entry(path,name) for name in os.listdir(path)])
  333. except OSError:
  334. return
  335.  
  336. if path=="./iPod_Control/Music":
  337. subdirs=[x[2] for x in files if not x[0]]
  338. files=filter(lambda x: x[0], files)
  339. for dir in subdirs:
  340. subpath="%s/%s"%(path,dir)
  341. try:
  342. files.extend(filter(lambda x: x and x[0],[file_entry(subpath,name,dir+"/") for name in os.listdir(subpath)]))
  343. except OSError:
  344. pass
  345.  
  346. files.sort(cmp_key)
  347. count=len([None for x in files if x[0]])
  348. if count: domains.append([])
  349.  
  350. real_count=0
  351. for item in files:
  352. fullname="%s/%s"%(path,item[2])
  353. if item[0]:
  354. real_count+=write_to_db(fullname[1:])
  355. else:
  356. browse(fullname,interactive)
  357.  
  358. if real_count==count:
  359. log("%s: %d files"%(displaypath,count))
  360. else:
  361. log("%s: %d files (out of %d)"%(displaypath,real_count,count))
  362.  
  363.  
  364. ################################################################################
  365.  
  366.  
  367. def stringval(i):
  368. if i<0: i+=0x1000000
  369. return "%c%c%c"%(i&0xFF,(i>>8)&0xFF,(i>>16)&0xFF)
  370.  
  371. def listval(i):
  372. if i<0: i+=0x1000000
  373. return [i&0xFF,(i>>8)&0xFF,(i>>16)&0xFF]
  374.  
  375.  
  376. def make_playback_state(volume=None):
  377. # I'm not at all proud of this function. Why can't stupid Python make strings
  378. # mutable?!
  379. log("Setting playback state ...",False)
  380. PState=[]
  381. try:
  382. f=file("iPod_Control/iTunes/iTunesPState","rb")
  383. a=array.array('B')
  384. a.fromstring(f.read())
  385. PState=a.tolist()
  386. f.close()
  387. except IOError,EOFError:
  388. del PState[:]
  389. if len(PState)!=21:
  390. PState=listval(29)+[0]*15+listval(1) # volume 29, FW ver 1.0
  391. PState[3:15]=[0]*6+[1]+[0]*5 # track 0, shuffle mode, start of track
  392. if volume is not None:
  393. PState[:3]=listval(volume)
  394. try:
  395. f=file("iPod_Control/iTunes/iTunesPState","wb")
  396. array.array('B',PState).tofile(f)
  397. f.close()
  398. except IOError:
  399. log("FAILED.")
  400. return 0
  401. log("OK.")
  402. return 1
  403.  
  404.  
  405. def make_stats(count):
  406. log("Creating statistics file ...",False)
  407. try:
  408. file("iPod_Control/iTunes/iTunesStats","wb").write(\
  409. stringval(count)+"\0"*3+(stringval(18)+"\xff"*3+"\0"*12)*count)
  410. except IOError:
  411. log("FAILED.")
  412. return 0
  413. log("OK.")
  414. return 1
  415.  
  416.  
  417. ################################################################################
  418.  
  419.  
  420. def smart_shuffle():
  421. try:
  422. slice_count=max(map(len,domains))
  423. except ValueError:
  424. return []
  425. slices=[[] for x in xrange(slice_count)]
  426. slice_fill=[0]*slice_count
  427.  
  428. for d in xrange(len(domains)):
  429. used=[]
  430. if not domains[d]: continue
  431. for n in domains[d]:
  432. # find slices where the nearest track of the same domain is far away
  433. metric=[min([slice_count]+[min(abs(s-u),abs(s-u+slice_count),abs(s-u-slice_count)) for u in used]) for s in xrange(slice_count)]
  434. thresh=(max(metric)+1)/2
  435. farthest=[s for s in xrange(slice_count) if metric[s]>=thresh]
  436.  
  437. # find emptiest slices
  438. thresh=(min(slice_fill)+max(slice_fill)+1)/2
  439. emptiest=[s for s in xrange(slice_count) if slice_fill[s]<=thresh if (s in farthest)]
  440.  
  441. # choose one of the remaining candidates and add the track to the chosen slice
  442. s=random.choice(emptiest or farthest)
  443. slices[s].append((n,d))
  444. slice_fill[s]+=1
  445. used.append(s)
  446.  
  447. # shuffle slices and avoid adjacent tracks of the same domain at slice boundaries
  448. seq=[]
  449. last_domain=-1
  450. for slice in slices:
  451. random.shuffle(slice)
  452. if len(slice)>2 and slice[0][1]==last_domain:
  453. slice.append(slice.pop(0))
  454. seq+=[x[0] for x in slice]
  455. last_domain=slice[-1][1]
  456. return seq
  457.  
  458.  
  459. def make_shuffle(count):
  460. random.seed()
  461. if Options['smart']:
  462. log("Generating smart shuffle sequence ...",False)
  463. seq=smart_shuffle()
  464. else:
  465. log("Generating shuffle sequence ...",False)
  466. seq=range(count)
  467. random.shuffle(seq)
  468. try:
  469. file("iPod_Control/iTunes/iTunesShuffle","wb").write("".join(map(stringval,seq)))
  470. except IOError:
  471. log("FAILED.")
  472. return 0
  473. log("OK.")
  474. return 1
  475.  
  476.  
  477. ################################################################################
  478.  
  479.  
  480. def main(dirs):
  481. global header,iTunesSD,total_count,KnownEntries,Rules
  482. log("Welcome to %s, version %s"%(__title__,__version__))
  483. log()
  484.  
  485. try:
  486. f=file("rebuild_db.rules","r")
  487. Rules+=filter(None,map(ParseRuleLine,f.read().split("\n")))
  488. f.close()
  489. except IOError:
  490. pass
  491.  
  492. if not os.path.isdir("iPod_Control/iTunes"):
  493. log("""ERROR: No iPod control directory found!
  494. Please make sure that:
  495. (*) this program's working directory is the iPod's root directory
  496. (*) the iPod was correctly initialized with iTunes""")
  497. sys.exit(1)
  498.  
  499. header=array.array('B')
  500. iTunesSD=None
  501. try:
  502. iTunesSD=file("iPod_Control/iTunes/iTunesSD","rb")
  503. header.fromfile(iTunesSD,51)
  504. if Options['reuse']:
  505. iTunesSD.seek(18)
  506. entry=iTunesSD.read(558)
  507. while len(entry)==558:
  508. filename=entry[33::2].split("\0",1)[0]
  509. KnownEntries[filename]=entry
  510. entry=iTunesSD.read(558)
  511. except (IOError,EOFError):
  512. pass
  513. if iTunesSD: iTunesSD.close()
  514.  
  515. if len(header)==51:
  516. log("Using iTunesSD headers from existing database.")
  517. if KnownEntries:
  518. log("Collected %d entries from existing database."%len(KnownEntries))
  519. else:
  520. del header[18:]
  521. if len(header)==18:
  522. log("Using iTunesSD main header from existing database.")
  523. else:
  524. del header[:]
  525. log("Rebuilding iTunesSD main header from scratch.")
  526. header.fromlist([0,0,0,1,6,0,0,0,18]+[0]*9)
  527. log("Rebuilding iTunesSD entry header from scratch.")
  528. header.fromlist([0,2,46,90,165,1]+[0]*20+[100,0,0,1,0,2,0])
  529.  
  530. log()
  531. try:
  532. iTunesSD=file("iPod_Control/iTunes/iTunesSD","wb")
  533. header[:18].tofile(iTunesSD)
  534. except IOError:
  535. log("""ERROR: Cannot write to the iPod database file (iTunesSD)!
  536. Please make sure that:
  537. (*) you have sufficient permissions to write to the iPod volume
  538. (*) you are actually using an iPod shuffle, and not some other iPod model :)""")
  539. sys.exit(1)
  540. del header[:18]
  541.  
  542. log("Searching for files on your iPod.")
  543. try:
  544. if dirs:
  545. for dir in dirs:
  546. browse("./"+dir,Options['interactive'])
  547. else:
  548. browse(".",Options['interactive'])
  549. log("%d playable files were found on your iPod."%total_count)
  550. log()
  551. log("Fixing iTunesSD header.")
  552. iTunesSD.seek(0)
  553. iTunesSD.write("\0%c%c"%(total_count>>8,total_count&0xFF))
  554. iTunesSD.close()
  555. except IOError:
  556. log("ERROR: Some strange errors occured while writing iTunesSD.")
  557. log(" You may have to re-initialize the iPod using iTunes.")
  558. sys.exit(1)
  559.  
  560. if make_playback_state(Options['volume'])* \
  561. make_stats(total_count)* \
  562. make_shuffle(total_count):
  563. log()
  564. log("The iPod shuffle database was rebuilt successfully.")
  565. log("Have fun listening to your music!")
  566. else:
  567. log()
  568. log("WARNING: The main database file was rebuilt successfully, but there were errors")
  569. log(" while resetting the other files. However, playback MAY work correctly.")
  570.  
  571.  
  572. ################################################################################
  573.  
  574.  
  575. def help():
  576. print "Usage: %s [OPTION]... [DIRECTORY]..."%sys.argv[0]
  577. print """Rebuild iPod shuffle database.
  578.  
  579. Mandatory arguments to long options are mandatory for short options too.
  580. -h, --help display this help text
  581. -i, --interactive prompt before browsing each directory
  582. -v, --volume=VOL set playback volume to a value between 0 and 38
  583. -s, --nosmart do not use smart shuffle
  584. -n, --nochdir do not change directory to this scripts directory first
  585. -l, --nolog do not create a log file
  586. -f, --force always rebuild database entries, do not re-use old ones
  587. -L, --logfile set log file name
  588.  
  589. Must be called from the iPod's root directory. By default, the whole iPod is
  590. searched for playable files, unless at least one DIRECTORY is specified."""
  591.  
  592.  
  593. def opterr(msg):
  594. print "parse error:",msg
  595. print "use `%s -h' to get help"%sys.argv[0]
  596. sys.exit(1)
  597.  
  598. def parse_options():
  599. try:
  600. opts,args=getopt.getopt(sys.argv[1:],"hiv:snlfL:r",\
  601. ["help","interactive","volume=","nosmart","nochdir","nolog","force","logfile=","rename"])
  602. except getopt.GetoptError, message:
  603. opterr(message)
  604. for opt,arg in opts:
  605. if opt in ("-h","--help"):
  606. help()
  607. sys.exit(0)
  608. elif opt in ("-i","--interactive"):
  609. Options['interactive']=True
  610. elif opt in ("-v","--volume"):
  611. try:
  612. Options['volume']=int(arg)
  613. except ValueError:
  614. opterr("invalid volume")
  615. elif opt in ("-s","--nosmart"):
  616. Options['smart']=False
  617. elif opt in ("-n","--nochdir"):
  618. Options['home']=False
  619. elif opt in ("-l","--nolog"):
  620. Options['logging']=False
  621. elif opt in ("-f","--force"):
  622. Options['reuse']=0
  623. elif opt in ("-L","--logfile"):
  624. Options['logfile']=arg
  625. elif opt in ("-r","--rename"):
  626. Options['rename']=True
  627. return args
  628.  
  629.  
  630. ################################################################################
  631.  
  632.  
  633. if __name__=="__main__":
  634. args=parse_options()
  635. go_home()
  636. open_log()
  637. try:
  638. main(args)
  639. except KeyboardInterrupt:
  640. log()
  641. log("You decided to cancel processing. This is OK, but please note that")
  642. log("the iPod database is now corrupt and the iPod won't play!")
  643. close_log()
Add Comment
Please, Sign In to add comment