cli.py 14 KB

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