cli.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. import re
  19. strptime = datetime.strptime
  20. ARG_DATE_FMT = '%Y-%m-%d %H:%M:%S'
  21. simple_date = lambda s: strptime(s, ARG_DATE_FMT)
  22. re_station = re.compile(r'^/var/fourier/[^/]+/([^/]+)')
  23. def find_hash(hsh, db=None):
  24. cursor = db.cursor()
  25. cursor.execute("select * from file where hash = ?",
  26. (hsh, ),
  27. )
  28. return cursor.fetchone()
  29. def insert_file(hsh, filename, timestamp, db=None, uploaded=None):
  30. cursor = db.cursor()
  31. match = re_station.match(filename)
  32. station = match.group(1)
  33. was_uploaded = int(time.time()) if uploaded else None
  34. cursor.execute("""
  35. insert into file(hash, filename,
  36. timestamp, uploaded,
  37. station)
  38. values(?, ?, ?, ?, ?)
  39. """,
  40. (
  41. hsh,
  42. filename,
  43. int(time.mktime(timestamp.timetuple())),
  44. was_uploaded,
  45. station,
  46. )
  47. )
  48. def hash_file(filename):
  49. ahash = md5()
  50. with open(filename, 'rb') as fp:
  51. while True:
  52. data = fp.read(4096)
  53. if data:
  54. ahash.update(data)
  55. else:
  56. break
  57. return ahash.hexdigest()
  58. def parse_stations(string):
  59. return string.split(',')
  60. def main():
  61. parser = ArgumentParser()
  62. subparsers = parser.add_subparsers(dest='entity')
  63. dbparser = subparsers.add_parser('db')
  64. dbparser.add_argument('action')
  65. dbparser.add_argument('-from-date',
  66. dest='from_date',
  67. type=simple_date,
  68. )
  69. dbparser.add_argument('-to-date',
  70. dest='to_date',
  71. type=simple_date,
  72. )
  73. dbparser.add_argument('-station', dest='station')
  74. dbparser.add_argument('--dry-run', dest='dry_run',
  75. action='store_const',
  76. const=True,
  77. default=False
  78. )
  79. dbparser.add_argument('--uploaded', action='store_const',
  80. const=True, default=False,
  81. dest='uploaded',
  82. )
  83. dbparser.add_argument('-limit', type=int, dest='limit')
  84. stations_parser = subparsers.add_parser('station')
  85. stations_parser.add_argument('action')
  86. stations_parser.add_argument('stations', nargs='*', default=['98.5'])
  87. stations_parser.add_argument('--play-only', dest='play_only',
  88. action='store_const',
  89. const=True,
  90. default=False
  91. )
  92. stations_parser.add_argument('-output', dest='audio_output',
  93. type=int, default=0
  94. )
  95. args = parser.parse_args()
  96. action = args.action
  97. with open('/etc/fourier-config.json', 'r') as fp:
  98. config = json.loads(fp.read())
  99. device_id = config['device_id']
  100. dbpath = '/var/fourier/{}/files.db'.format(device_id)
  101. if args.entity == 'db':
  102. if action == 'stats':
  103. conn = sqlite3.connect(dbpath)
  104. cursor = conn.cursor()
  105. cursor.execute("select count(*), count(uploaded) from file")
  106. total, uploaded, = cursor.fetchone()
  107. print("total: {}".format(total))
  108. print("uploaded: {}".format(uploaded))
  109. print("pending: {}".format(total - uploaded))
  110. elif action == 'index-files':
  111. counter = 0
  112. already_indexed = 0
  113. multiplo_commit = 200
  114. conn = sqlite3.connect(dbpath)
  115. path = os.path.join('/var/fourier', device_id)
  116. if args.station:
  117. path = os.path.join(path, args.station)
  118. for folder, folders, files in os.walk(path):
  119. for file in files:
  120. if not file.endswith('.mp3'):
  121. continue
  122. filename = os.path.join(folder, file)
  123. dt = datetime.strptime(
  124. file[:19],
  125. '%Y-%m-%dT%H-%M-%S'
  126. )
  127. try:
  128. if args.from_date and args.to_date:
  129. do_insert = dt >= args.from_date\
  130. and dt <= args.to_date
  131. elif args.from_date:
  132. do_insert = dt >= args.from_date
  133. elif args.to_date:
  134. do_insert = dt <= args.to_date
  135. else:
  136. do_insert = True
  137. if do_insert:
  138. thehash = hash_file(filename)
  139. insert_file(thehash, filename, dt,
  140. db=conn,
  141. uploaded=args.uploaded,
  142. )
  143. counter += 1
  144. print(dt)
  145. if counter % multiplo_commit == 0:
  146. conn.commit()
  147. print('commited')
  148. except sqlite3.IntegrityError:
  149. already_indexed += 1
  150. print('already indexed: {}'.format(filename))
  151. if not args.dry_run:
  152. conn.commit()
  153. else:
  154. conn.rollback()
  155. print('\n[WARNING] DRY RUN FINISHED')
  156. print('----------------------------------')
  157. print('total files indexed: {}'.format(counter))
  158. print('total files in existence: {}'.format(already_indexed))
  159. print('----------------------------------')
  160. elif action == 'setup':
  161. if not os.path.isfile(dbpath):
  162. conn = sqlite3.connect(dbpath)
  163. cursor = conn.cursor()
  164. sentences = [
  165. """create table file(
  166. hash text primary key,
  167. station text,
  168. timestamp int,
  169. filename text,
  170. uploaded int
  171. )""",
  172. "create index timestamp_index_desc on file (timestamp desc)",
  173. "create index timestamp_index_asc on file (timestamp desc)",
  174. ]
  175. for query in sentences:
  176. cursor.execute(query)
  177. conn.commit()
  178. else:
  179. print('database already installed')
  180. sys.exit(1)
  181. elif action == 'migrate':
  182. conn = sqlite3.connect(dbpath)
  183. cursor = conn.cursor()
  184. try:
  185. cursor.execute(("select value "
  186. "from config "
  187. "where name = 'version'"))
  188. row = cursor.fetchone()
  189. min_version = row[0] if row else ''
  190. except sqlite3.OperationalError as err:
  191. strerr = str(err)
  192. if "table" in strerr and "config" in strerr:
  193. min_version = ''
  194. else:
  195. print(err)
  196. from fourier.migrations import versions
  197. cursor = conn.cursor()
  198. for v, qrs in versions:
  199. if v > min_version:
  200. try:
  201. for q in qrs:
  202. cursor.execute(q)
  203. cursor.execute()
  204. except Exception as ex:
  205. print('failed: {}'.format(ex))
  206. conn.rollback()
  207. elif action == 'connect':
  208. subprocess.call(['sqlite3', dbpath])
  209. elif action == 'add-missing-stations':
  210. conn = sqlite3.connect(dbpath)
  211. cursor = conn.cursor()
  212. query = ('select hash, filename '
  213. 'from file '
  214. 'where station is null ')
  215. if args.limit:
  216. query += ' limit {}'.format(args.limit)
  217. cursor.execute(query)
  218. curup = conn.cursor()
  219. for row in cursor:
  220. the_hash, filename, = row
  221. match = re_station.match(filename)
  222. if match:
  223. station_code = match.group(1)
  224. params = station_code, the_hash,
  225. curup.execute(('update "file" '
  226. 'set "station" = ? '
  227. 'where "hash" = ?'
  228. ), params
  229. )
  230. conn.commit()
  231. elif args.entity == 'station':
  232. if action == 'list':
  233. stations_path = os.path.join('/var/fourier', device_id)
  234. dirs = os.listdir(stations_path)
  235. for dr in dirs:
  236. if '.' not in dr:
  237. print(dr)
  238. elif action == 'record' or action == 'play':
  239. import pyaudio, wave
  240. if action == 'play':
  241. args.play_only = True
  242. audio = pyaudio.PyAudio()
  243. stream = audio.open(format=pyaudio.paInt16,
  244. output_device_index=args.audio_output,
  245. channels=1,
  246. rate=44100,
  247. output=True)
  248. processes = []
  249. transcoders = []
  250. totals = []
  251. basepath = '/var/fourier/tests'
  252. env = os.environ
  253. stream_index = 0
  254. stations = args.stations
  255. receivers_count = len(stations)
  256. if not os.path.isdir(basepath):
  257. os.mkdir(basepath)
  258. test_id = hexlify(os.urandom(4))
  259. for index in range(receivers_count):
  260. filename = os.path.join(basepath, "{}-{}.mp3"\
  261. .format(test_id, index)
  262. )
  263. if not args.play_only:
  264. ffmpeg = subprocess.Popen([
  265. 'ffmpeg', '-f', 's16le', '-i', 'pipe:0',
  266. '-ac', '1', '-ar', '24000',
  267. '-nostdin',
  268. '-f', 'mp3',
  269. filename,
  270. ],
  271. stdin=PIPE,
  272. stdout=PIPE,
  273. stderr=PIPE,
  274. env=env,
  275. preexec_fn=os.setpgrp,
  276. close_fds=True,
  277. )
  278. transcoders.append(ffmpeg)
  279. rtl = subprocess.Popen([
  280. 'rtl_fm', '-M', 'wbfm', '-g', '10',
  281. '-d', str(index),
  282. '-f', '{}M'.format(stations[index]),
  283. '-o', '4',
  284. '-F', '8',
  285. '-p', '200',
  286. '-s', '88200',
  287. '-r', '44100',
  288. ],
  289. stdout=PIPE,
  290. stdin=PIPE,
  291. stderr=PIPE,
  292. env=env,
  293. preexec_fn=os.setpgrp,
  294. close_fds=True,
  295. )
  296. processes.append(rtl)
  297. totals.append(0)
  298. scr = curses.initscr()
  299. scr.addstr(0, 0, 'Sintonizadores')
  300. scr.addstr(receivers_count + 2, 0,
  301. 'Presiona un número para escuchar'
  302. )
  303. if args.play_only:
  304. scr.addstr(receivers_count + 3, 0,
  305. 'Solo reproduciendo'
  306. )
  307. else:
  308. scr.addstr(receivers_count + 4, 0,
  309. 'Reproduciendo y grabando'
  310. )
  311. scr.addstr(receivers_count + 4, 0,
  312. 'ID de prueba: /var/fourier/tests/{}-x.mp3'\
  313. .format(test_id)
  314. )
  315. scr.addstr(receivers_count + 5, 0,
  316. 'Usar --play-only para solo reproducir'
  317. )
  318. scr.addstr(stream_index + 1, 0, '>')
  319. scr.refresh()
  320. scr.timeout(0)
  321. curses.noecho()
  322. curses.curs_set(0)
  323. try:
  324. while 1:
  325. refresh = False
  326. for index in range(receivers_count):
  327. data = processes[index].stdout.read(4096)
  328. if data:
  329. if index == stream_index:
  330. stream.write(data)
  331. if not args.play_only:
  332. transcoders[index].stdin.write(data)
  333. totals[index] += len(data)
  334. if totals[index] % 100 == 0:
  335. scr.addstr(index + 1, 5, '{:01x} {:>4} {}\n\n'\
  336. .format(index, stations[index], totals[index])
  337. )
  338. refresh = True
  339. else:
  340. errout = processes[index].stderr.read(4096)
  341. refresh = True
  342. k = scr.getch()
  343. if k > -1:
  344. key = int(chr(k), 16) if k > 0 else 0
  345. if key >= 0 and key < receivers_count:
  346. scr.addstr(stream_index + 1, 0, ' ')
  347. stream_index = key
  348. refresh = True
  349. if refresh:
  350. scr.addstr(stream_index + 1, 0, '>')
  351. scr.refresh()
  352. except KeyboardInterrupt:
  353. curses.endwin()
  354. for index in range(receivers_count):
  355. if not args.play_only:
  356. transcoders[index].send_signal(signal.SIGINT)
  357. processes[index].send_signal(signal.SIGINT)
  358. except Exception as ex:
  359. curses.endwin()
  360. print(ex)
  361. if __name__ == '__main__':
  362. main()