cli.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from __future__ import print_function
  2. from argparse import ArgumentParser
  3. from hashlib import md5
  4. from datetime import datetime
  5. import sqlite3
  6. import time
  7. import json
  8. import os
  9. strptime = datetime.strptime
  10. ARG_DATE_FMT = '%Y-%m-%d %H:%M:%S'
  11. simple_date = lambda s: strptime(s, ARG_DATE_FMT)
  12. def find_hash(hsh, db=None):
  13. cursor = db.cursor()
  14. cursor.execute("select * from file where hash = ?",
  15. (hsh, ),
  16. )
  17. return cursor.fetchone()
  18. def insert_file(hsh, filename, timestamp, db=None):
  19. cursor = db.cursor()
  20. cursor.execute("""
  21. insert into file(hash, filename, timestamp)
  22. values(?, ?, ?)
  23. """,
  24. (hsh, filename, int(time.mktime(timestamp.timetuple())), )
  25. )
  26. def main():
  27. parser = ArgumentParser()
  28. subparsers = parser.add_subparsers(dest='entity')
  29. dbparser = subparsers.add_parser('db')
  30. dbparser.add_argument('action')
  31. dbparser.add_argument('-from-date', dest='from_date',
  32. type=simple_date,
  33. )
  34. dbparser.add_argument('--dry-run', dest='dry_run',
  35. action='store_const',
  36. const=True,
  37. default=False
  38. )
  39. args = parser.parse_args()
  40. action = args.action
  41. with open('/etc/fourier-config.json', 'r') as fp:
  42. config = json.loads(fp.read())
  43. device_id = config['device_id']
  44. dbpath = '/var/fourier/{}/files.db'.format(device_id)
  45. if action == 'stats':
  46. conn = sqlite3.connect(dbpath)
  47. cursor = conn.cursor()
  48. cursor.execute("select count(*), count(uploaded) from file")
  49. total, uploaded, = cursor.fetchone()
  50. print("total: {}".format(total))
  51. print("uploaded: {}".format(uploaded))
  52. print("pending: {}".format(total - uploaded))
  53. elif action == 'index-files':
  54. counter = 0
  55. already_indexed = 0
  56. conn = sqlite3.connect(dbpath)
  57. path = os.path.join('/var/fourier', device_id)
  58. for folder, folders, files in os.walk(path):
  59. for file in files:
  60. if file.endswith('.mp3'):
  61. filename = os.path.join(folder, file)
  62. ahash = md5()
  63. with open(filename, 'rb') as fp:
  64. while True:
  65. data = fp.read(4096)
  66. if data:
  67. ahash.update(data)
  68. else:
  69. break
  70. thehash = ahash.hexdigest()
  71. exists = find_hash(thehash, db=conn)
  72. if not exists:
  73. if args.from_date:
  74. dt = datetime.strptime(
  75. file[:19],
  76. '%Y-%m-%dT%H-%M-%S'
  77. )
  78. if dt >= args.from_date:
  79. counter += 1
  80. insert_file(thehash, filename, dt, db=conn)
  81. print(dt)
  82. else:
  83. counter += 1
  84. insert_file(thehash, filename, dt, db=conn)
  85. print(dt)
  86. else:
  87. already_indexed += 1
  88. print('already indexed: {}'.format(filename))
  89. if not args.dry_run:
  90. conn.commit()
  91. else:
  92. conn.rollback()
  93. print('\n[WARNING] DRY RUN FINISHED')
  94. print('----------------------------------')
  95. print('total files indexed: {}'.format(counter))
  96. print('total files in existence: {}'.format(already_indexed))
  97. print('----------------------------------')
  98. if __name__ == '__main__':
  99. main()