cli.py 11 KB

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