cli.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. from __future__ import print_function
  2. from argparse import ArgumentParser
  3. from hashlib import md5
  4. from datetime import datetime
  5. from binascii import hexlify
  6. from threading import Thread
  7. from StringIO import StringIO
  8. from io import BufferedWriter
  9. from subprocess import PIPE
  10. import subprocess
  11. import sqlite3
  12. import signal
  13. import curses
  14. import time
  15. import json
  16. import sys
  17. import os
  18. strptime = datetime.strptime
  19. ARG_DATE_FMT = '%Y-%m-%d %H:%M:%S'
  20. simple_date = lambda s: strptime(s, ARG_DATE_FMT)
  21. def find_hash(hsh, db=None):
  22. cursor = db.cursor()
  23. cursor.execute("select * from file where hash = ?",
  24. (hsh, ),
  25. )
  26. return cursor.fetchone()
  27. def insert_file(hsh, filename, timestamp, db=None):
  28. cursor = db.cursor()
  29. cursor.execute("""
  30. insert into file(hash, filename, timestamp)
  31. values(?, ?, ?)
  32. """,
  33. (hsh, filename, int(time.mktime(timestamp.timetuple())), )
  34. )
  35. def hash_file(filename):
  36. ahash = md5()
  37. with open(filename, 'rb') as fp:
  38. while True:
  39. data = fp.read(4096)
  40. if data:
  41. ahash.update(data)
  42. else:
  43. break
  44. return ahash.hexdigest()
  45. def parse_stations(string):
  46. return string.split(',')
  47. def main():
  48. parser = ArgumentParser()
  49. subparsers = parser.add_subparsers(dest='entity')
  50. dbparser = subparsers.add_parser('db')
  51. dbparser.add_argument('action')
  52. dbparser.add_argument('-from-date', dest='from_date',
  53. type=simple_date,
  54. )
  55. dbparser.add_argument('-station', dest='station')
  56. dbparser.add_argument('--dry-run', dest='dry_run',
  57. action='store_const',
  58. const=True,
  59. default=False
  60. )
  61. stations_parser = subparsers.add_parser('station')
  62. stations_parser.add_argument('action')
  63. stations_parser.add_argument('stations', nargs='*', default=['98.5'])
  64. stations_parser.add_argument('--play-only', dest='play_only',
  65. action='store_const',
  66. const=True,
  67. default=False
  68. )
  69. stations_parser.add_argument('-output', dest='audio_output',
  70. type=int, default=0
  71. )
  72. args = parser.parse_args()
  73. action = args.action
  74. with open('/etc/fourier-config.json', 'r') as fp:
  75. config = json.loads(fp.read())
  76. device_id = config['device_id']
  77. dbpath = '/var/fourier/{}/files.db'.format(device_id)
  78. if args.entity == 'db':
  79. if action == 'stats':
  80. conn = sqlite3.connect(dbpath)
  81. cursor = conn.cursor()
  82. cursor.execute("select count(*), count(uploaded) from file")
  83. total, uploaded, = cursor.fetchone()
  84. print("total: {}".format(total))
  85. print("uploaded: {}".format(uploaded))
  86. print("pending: {}".format(total - uploaded))
  87. elif action == 'index-files':
  88. counter = 0
  89. already_indexed = 0
  90. conn = sqlite3.connect(dbpath)
  91. path = os.path.join('/var/fourier', device_id)
  92. if args.station:
  93. path = os.path.join(path, args.station)
  94. for folder, folders, files in os.walk(path):
  95. for file in files:
  96. if not file.endswith('.mp3'):
  97. continue
  98. filename = os.path.join(folder, file)
  99. dt = datetime.strptime(
  100. file[:19],
  101. '%Y-%m-%dT%H-%M-%S'
  102. )
  103. try:
  104. if args.from_date:
  105. do_insert = dt >= args.from_date
  106. else:
  107. do_insert = True
  108. if do_insert:
  109. thehash = hash_file(filename)
  110. insert_file(thehash, filename, dt, db=conn)
  111. counter += 1
  112. print(dt)
  113. except sqlite3.IntegrityError:
  114. already_indexed += 1
  115. print('already indexed: {}'.format(filename))
  116. if not args.dry_run:
  117. conn.commit()
  118. else:
  119. conn.rollback()
  120. print('\n[WARNING] DRY RUN FINISHED')
  121. print('----------------------------------')
  122. print('total files indexed: {}'.format(counter))
  123. print('total files in existence: {}'.format(already_indexed))
  124. print('----------------------------------')
  125. elif action == 'setup':
  126. if not os.path.isfile(dbpath):
  127. conn = sqlite3.connect(dbpath)
  128. cursor = conn.cursor()
  129. sentences = [
  130. """create table file(
  131. hash text primary key,
  132. station text,
  133. timestamp int,
  134. filename text,
  135. uploaded int
  136. )""",
  137. "create index timestamp_index_desc on file (timestamp desc)",
  138. "create index timestamp_index_asc on file (timestamp desc)",
  139. ]
  140. for query in sentences:
  141. cursor.execute(query)
  142. conn.commit()
  143. else:
  144. print('database already installed')
  145. sys.exit(1)
  146. elif args.entity == 'station':
  147. if action == 'list':
  148. stations_path = os.path.join('/var/fourier', device_id)
  149. dirs = os.listdir(stations_path)
  150. for dr in dirs:
  151. if '.' not in dr:
  152. print(dr)
  153. elif action == 'record' or action == 'play':
  154. import pyaudio, wave
  155. if action == 'play':
  156. args.play_only = True
  157. audio = pyaudio.PyAudio()
  158. stream = audio.open(format=pyaudio.paInt16,
  159. output_device_index=args.audio_output,
  160. channels=1,
  161. rate=44100,
  162. output=True)
  163. processes = []
  164. transcoders = []
  165. totals = []
  166. basepath = '/var/fourier/tests'
  167. env = os.environ
  168. stream_index = 0
  169. stations = args.stations
  170. receivers_count = len(stations)
  171. if not os.path.isdir(basepath):
  172. os.mkdir(basepath)
  173. test_id = hexlify(os.urandom(4))
  174. for index in range(receivers_count):
  175. filename = os.path.join(basepath, "{}-{}.mp3"\
  176. .format(test_id, index)
  177. )
  178. if not args.play_only:
  179. ffmpeg = subprocess.Popen([
  180. 'ffmpeg', '-f', 's16le', '-i', 'pipe:0',
  181. '-ac', '1', '-ar', '24000',
  182. '-ab', '64k',
  183. '-nostdin',
  184. '-f', 'mp3',
  185. filename,
  186. ],
  187. stdin=PIPE,
  188. stdout=PIPE,
  189. stderr=PIPE,
  190. env=env,
  191. preexec_fn=os.setpgrp,
  192. close_fds=True,
  193. )
  194. transcoders.append(ffmpeg)
  195. rtl = subprocess.Popen([
  196. 'rtl_fm', '-M', 'wbfm', '-g', '10',
  197. '-d', str(index),
  198. '-f', '{}M'.format(stations[index]),
  199. '-o', '4',
  200. '-F', '8',
  201. '-p', '200',
  202. '-s', '88200',
  203. '-r', '44100',
  204. ],
  205. stdout=PIPE,
  206. stdin=PIPE,
  207. stderr=PIPE,
  208. env=env,
  209. preexec_fn=os.setpgrp,
  210. close_fds=True,
  211. )
  212. processes.append(rtl)
  213. totals.append(0)
  214. scr = curses.initscr()
  215. scr.addstr(0, 0, 'Sintonizadores')
  216. scr.addstr(receivers_count + 2, 0,
  217. 'Presiona un número para escuchar'
  218. )
  219. if args.play_only:
  220. scr.addstr(receivers_count + 3, 0,
  221. 'Solo reproduciendo'
  222. )
  223. else:
  224. scr.addstr(receivers_count + 4, 0,
  225. 'Reproduciendo y grabando'
  226. )
  227. scr.addstr(receivers_count + 4, 0,
  228. 'ID de prueba: /var/fourier/tests/{}-x.mp3'\
  229. .format(test_id)
  230. )
  231. scr.addstr(receivers_count + 5, 0,
  232. 'Usar --play-only para solo reproducir'
  233. )
  234. scr.addstr(stream_index + 1, 0, '>')
  235. scr.refresh()
  236. scr.timeout(0)
  237. curses.noecho()
  238. curses.curs_set(0)
  239. try:
  240. while 1:
  241. refresh = False
  242. for index in range(receivers_count):
  243. data = processes[index].stdout.read(4096)
  244. if data:
  245. if index == stream_index:
  246. stream.write(data)
  247. if not args.play_only:
  248. transcoders[index].stdin.write(data)
  249. totals[index] += len(data)
  250. if totals[index] % 10 == 0:
  251. scr.addstr(index + 1, 5, '{:01x} {:>4} {}\n\n'\
  252. .format(index, stations[index], totals[index])
  253. )
  254. refresh = True
  255. k = scr.getch()
  256. if k > -1:
  257. key = int(chr(k), 16) if k > 0 else 0
  258. if key >= 0 and key < receivers_count:
  259. scr.addstr(stream_index + 1, 0, ' ')
  260. stream_index = key
  261. refresh = True
  262. if refresh:
  263. scr.addstr(stream_index + 1, 0, '>')
  264. scr.refresh()
  265. except KeyboardInterrupt:
  266. curses.endwin()
  267. for index in range(receivers_count):
  268. if not args.play_only:
  269. transcoders[index].send_signal(signal.SIGINT)
  270. processes[index].send_signal(signal.SIGINT)
  271. except Exception as ex:
  272. curses.endwin()
  273. print(ex)
  274. if __name__ == '__main__':
  275. main()