PageRenderTime 680ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/bin/alarm.py

https://github.com/mogga/mogga-dotfiles
Python | 191 lines | 142 code | 28 blank | 21 comment | 19 complexity | f5d657de2e4f4bac1b13c1c684713961 MD5 | raw file
  1. #!/usr/bin/env python
  2. """
  3. Alarm script
  4. ============
  5. Author: Laszlo Szathmary, 2011 (jabba.laci@gmail.com)
  6. Website: https://ubuntuincident.wordpress.com/2011/04/17/alarm-script/
  7. GitHub: https://github.com/jabbalaci/Bash-Utils
  8. A simple alarm script that plays a list of MP3s at a given time.
  9. Very useful if you leave your computer switched on during the night.
  10. Usage:
  11. ------
  12. ./alarm.py -p
  13. Play music. First do this to adjust volume! If the volume is low,
  14. you won't hear it in the morning.
  15. ./alarm.py -t 7h15
  16. Set alarm time. The format is HhM, where H is the hour (24-hour system),
  17. M is the minute, 'h' is the separator.
  18. ./alarm.py
  19. Set alarm with the default time. In my case it's 6h55.
  20. """
  21. import os
  22. import sys
  23. from optparse import OptionParser
  24. from datetime import datetime
  25. from time import sleep
  26. from random import shuffle
  27. MUSIC_DIR = '/media/jabba/JIVE/mp3/sfa_scifi'
  28. TRAVERSE_RECURSIVELY = True
  29. MPLAYER = '/usr/bin/mplayer'
  30. MPLAYER_OPTIONS = '-endpos 00:00:60' # play first 60 seconds; disabled when -p is used
  31. DEFAULT_TIME = '6h55'
  32. class CollectMp3:
  33. """Collect music files recursively in a given directory."""
  34. def __init__(self, music_dir):
  35. self.music_dir = music_dir
  36. self.songs = []
  37. def traverse(self, directory):
  38. """Traverse directory recursively. Symlinks are skipped."""
  39. content = [os.path.join(directory, x) for x in os.listdir(directory)]
  40. dirs = sorted([x for x in content if os.path.isdir(x)])
  41. files = sorted([x for x in content if os.path.isfile(x)])
  42. for f in files:
  43. if os.path.islink(f):
  44. continue
  45. ext = os.path.splitext(f)[1]
  46. if ext in ('.mp3', '.flac', '.ogg', '.flv'):
  47. self.songs.append(f)
  48. if TRAVERSE_RECURSIVELY:
  49. for d in dirs:
  50. if os.path.islink(d):
  51. continue
  52. self.traverse(d)
  53. def collect(self):
  54. """Collect songs, shuffle order, and print a little statistics."""
  55. self.traverse(self.music_dir)
  56. if self.get_number_of_songs() == 0:
  57. print "Error: there are no songs available."
  58. sys.exit(-1)
  59. # else
  60. shuffle(self.songs)
  61. header = "number of songs: {0}".format(self.get_number_of_songs())
  62. sep = '#' * (len(header) + 2 + 2)
  63. print sep
  64. print '# ' + header + ' #'
  65. print sep
  66. print
  67. def get_number_of_songs(self):
  68. return len(self.songs)
  69. def get_songs(self):
  70. return self.songs
  71. collector = CollectMp3(MUSIC_DIR)
  72. #############################################################################
  73. def play_music():
  74. songs = collector.get_songs()
  75. for f in songs:
  76. val = os.system("{mplayer} {options} \"{song}\"".format(mplayer=MPLAYER, options=MPLAYER_OPTIONS, song=f))
  77. if val == 2: # interrupted with CTRL-C
  78. sys.exit(val)
  79. def set_alarm(hour, minute):
  80. # autoflush
  81. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
  82. sep = "=" * 19
  83. print sep
  84. print "| Alarm at {0:2}h{1:02}. |".format(hour, minute)
  85. print sep
  86. alarm_time = hour * 100 + minute
  87. while True:
  88. now = datetime.now()
  89. time = datetime.time(now)
  90. current_time = time.hour * 100 + time.minute
  91. if (current_time >= alarm_time) and (current_time - alarm_time <= 100):
  92. play_music()
  93. sys.exit(0)
  94. else:
  95. sys.stdout.write('.')
  96. try:
  97. sleep(10)
  98. except KeyboardInterrupt:
  99. print
  100. break # break out of 'while True'
  101. def check_alarm(alarm_time):
  102. msg = "{0} error: there is a problem with the alarm time.".format(sys.argv[0])
  103. try:
  104. alarm_time = alarm_time.lower()
  105. if 'h' not in alarm_time:
  106. alarm_time += 'h'
  107. hour, minute = alarm_time.split('h')
  108. if not minute:
  109. minute = '0'
  110. hour = int(hour)
  111. minute = int(minute)
  112. if not ((0 <= hour <= 23) and (0 <= minute <= 59)):
  113. print >>sys.stderr, msg
  114. sys.exit(1)
  115. except ValueError:
  116. print >>sys.stderr, msg
  117. sys.exit(1)
  118. return hour, minute
  119. def main(default=DEFAULT_TIME):
  120. parser = OptionParser(usage='%prog [options]')
  121. #[options]
  122. parser.add_option('-t',
  123. '--time',
  124. action='store',
  125. default=default,
  126. type='string',
  127. dest='alarm_time',
  128. help='Alarm time, ex.: 6h55.')
  129. parser.add_option('-p',
  130. '--play',
  131. action='store_true',
  132. default=False,
  133. dest='is_play',
  134. help='Play music. Useful for adjusting the volume.')
  135. options, arguments = parser.parse_args()
  136. if options.is_play:
  137. global MPLAYER_OPTIONS
  138. MPLAYER_OPTIONS = ''
  139. print '# MPLAYER_OPTIONS is disabled'
  140. collector.collect()
  141. if options.is_play:
  142. play_music() # play and
  143. sys.exit(0) # quit
  144. # else
  145. if options.alarm_time:
  146. hour, minute = check_alarm(options.alarm_time)
  147. set_alarm(hour, minute)
  148. if __name__ == "__main__":
  149. main()