cli.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 action == 'migrate':
  147. conn = sqlite3.connect(dbpath)
  148. cursor = conn.cursor()
  149. try:
  150. cursor.execute(("select value "
  151. "from config "
  152. "where name = 'version'"))
  153. row = cursor.fetchone()
  154. min_version = row[0] if row else ''
  155. except sqlite3.OperationalError as err:
  156. strerr = str(err)
  157. if "table" in strerr and "config" in strerr:
  158. min_version = ''
  159. else:
  160. print(err)
  161. from fourier.migrations import versions
  162. cursor = conn.cursor()
  163. for v, qrs in versions:
  164. if v > min_version:
  165. try:
  166. for q in qrs:
  167. cursor.execute(q)
  168. cursor.execute()
  169. except Exception as ex:
  170. print('failed: {}'.format(ex))
  171. conn.rollback()
  172. elif action == 'connect':
  173. subprocess.call(['sqlite3', dbpath])
  174. elif args.entity == 'station':
  175. if action == 'list':
  176. stations_path = os.path.join('/var/fourier', device_id)
  177. dirs = os.listdir(stations_path)
  178. for dr in dirs:
  179. if '.' not in dr:
  180. print(dr)
  181. elif action == 'record' or action == 'play':
  182. import pyaudio, wave
  183. if action == 'play':
  184. args.play_only = True
  185. audio = pyaudio.PyAudio()
  186. stream = audio.open(format=pyaudio.paInt16,
  187. output_device_index=args.audio_output,
  188. channels=1,
  189. rate=44100,
  190. output=True)
  191. processes = []
  192. transcoders = []
  193. totals = []
  194. basepath = '/var/fourier/tests'
  195. env = os.environ
  196. stream_index = 0
  197. stations = args.stations
  198. receivers_count = len(stations)
  199. if not os.path.isdir(basepath):
  200. os.mkdir(basepath)
  201. test_id = hexlify(os.urandom(4))
  202. for index in range(receivers_count):
  203. filename = os.path.join(basepath, "{}-{}.mp3"\
  204. .format(test_id, index)
  205. )
  206. if not args.play_only:
  207. ffmpeg = subprocess.Popen([
  208. 'ffmpeg', '-f', 's16le', '-i', 'pipe:0',
  209. '-ac', '1', '-ar', '24000',
  210. '-nostdin',
  211. '-f', 'mp3',
  212. filename,
  213. ],
  214. stdin=PIPE,
  215. stdout=PIPE,
  216. stderr=PIPE,
  217. env=env,
  218. preexec_fn=os.setpgrp,
  219. close_fds=True,
  220. )
  221. transcoders.append(ffmpeg)
  222. rtl = subprocess.Popen([
  223. 'rtl_fm', '-M', 'wbfm', '-g', '10',
  224. '-d', str(index),
  225. '-f', '{}M'.format(stations[index]),
  226. '-o', '4',
  227. '-F', '8',
  228. '-p', '200',
  229. '-s', '88200',
  230. '-r', '44100',
  231. ],
  232. stdout=PIPE,
  233. stdin=PIPE,
  234. stderr=PIPE,
  235. env=env,
  236. preexec_fn=os.setpgrp,
  237. close_fds=True,
  238. )
  239. processes.append(rtl)
  240. totals.append(0)
  241. scr = curses.initscr()
  242. scr.addstr(0, 0, 'Sintonizadores')
  243. scr.addstr(receivers_count + 2, 0,
  244. 'Presiona un número para escuchar'
  245. )
  246. if args.play_only:
  247. scr.addstr(receivers_count + 3, 0,
  248. 'Solo reproduciendo'
  249. )
  250. else:
  251. scr.addstr(receivers_count + 4, 0,
  252. 'Reproduciendo y grabando'
  253. )
  254. scr.addstr(receivers_count + 4, 0,
  255. 'ID de prueba: /var/fourier/tests/{}-x.mp3'\
  256. .format(test_id)
  257. )
  258. scr.addstr(receivers_count + 5, 0,
  259. 'Usar --play-only para solo reproducir'
  260. )
  261. scr.addstr(stream_index + 1, 0, '>')
  262. scr.refresh()
  263. scr.timeout(0)
  264. curses.noecho()
  265. curses.curs_set(0)
  266. try:
  267. while 1:
  268. refresh = False
  269. for index in range(receivers_count):
  270. data = processes[index].stdout.read(4096)
  271. if data:
  272. if index == stream_index:
  273. stream.write(data)
  274. if not args.play_only:
  275. transcoders[index].stdin.write(data)
  276. totals[index] += len(data)
  277. if totals[index] % 100 == 0:
  278. scr.addstr(index + 1, 5, '{:01x} {:>4} {}\n\n'\
  279. .format(index, stations[index], totals[index])
  280. )
  281. refresh = True
  282. else:
  283. errout = processes[index].stderr.read(4096)
  284. scr.addstr(0, 0, 'ALL FUCKED')
  285. refresh = True
  286. k = scr.getch()
  287. if k > -1:
  288. key = int(chr(k), 16) if k > 0 else 0
  289. if key >= 0 and key < receivers_count:
  290. scr.addstr(stream_index + 1, 0, ' ')
  291. stream_index = key
  292. refresh = True
  293. if refresh:
  294. scr.addstr(stream_index + 1, 0, '>')
  295. scr.refresh()
  296. except KeyboardInterrupt:
  297. curses.endwin()
  298. for index in range(receivers_count):
  299. if not args.play_only:
  300. transcoders[index].send_signal(signal.SIGINT)
  301. processes[index].send_signal(signal.SIGINT)
  302. except Exception as ex:
  303. curses.endwin()
  304. print(ex)
  305. if __name__ == '__main__':
  306. main()