cli.py 13 KB

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