dirnotes 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. #!/usr/bin/python3
  2. """ a simple gui or command line app
  3. to view and create/edit file comments
  4. comments are stored in an SQLite3 database
  5. default ~/.dirnotes.db
  6. where possible, comments are duplicated in
  7. xattr user.xdg.comment
  8. some file systems don't allow xattr, and even linux
  9. doesn't allow xattr on symlinks, so the database is
  10. considered primary
  11. these comments stick to the symlink, not the deref
  12. nav tools are enabled, so you can double-click to go into a dir, and
  13. there's an UP arrow to navigate back
  14. """
  15. helpMsg = """<h1>Dirnotes</h1><h3>Overview</h3>
  16. This app allows you to add comments to files. The comments are stored in
  17. a database, and where possible, saved in the xattr (hidden attributes)
  18. field of the file system.
  19. <p>
  20. You can sort the directory listing by clicking on the column heading.
  21. <p>
  22. Double click on directory names to navigate the file system. Hover over
  23. fields for more information.
  24. <p>
  25. <h3>xattr extended attributes</h3>
  26. The xattr property is handy, but suffers from a few problems:
  27. <ul>
  28. <li>is not implemented on FAT/VFAT/EXFAT file systems (like USB sticks)
  29. <li>xattrs are not (by default) copied with the file when it's duplicated
  30. or backedup
  31. <li>xattrs are not available for symlinks
  32. <li>many programs which edit files do not preserve the xattrs during file-save
  33. </ul>
  34. When the database version of a comment differs from the xattr version, the
  35. comment box gets a light yellow background.
  36. """
  37. import sys,os,argparse,stat
  38. #~ from dirWidget import DirWidget
  39. from PyQt5.QtGui import *
  40. from PyQt5.QtWidgets import *
  41. from PyQt5.QtCore import Qt, pyqtSignal
  42. import sqlite3, time
  43. VERSION = "0.3"
  44. COMMENT_KEY = "user.xdg.comment"
  45. DATABASE_NAME = "~/.dirnotes.db"
  46. # convert the ~/ form to a fully qualified path
  47. DATABASE_NAME = os.path.expanduser(DATABASE_NAME)
  48. class dnDataBase:
  49. ''' the database is flat
  50. fileName: fully qualified name
  51. st_mtime: a float
  52. size: a long
  53. comment: a string
  54. comment_time: a float, the time of the comment save
  55. this is effectively a log file, as well as a resource for a restore
  56. (in case a file-move is done without comment)
  57. the database is associated with a user, in the $HOME dir
  58. '''
  59. def __init__(self):
  60. '''try to open the database; if not found, create it'''
  61. try:
  62. self.db = sqlite3.connect(DATABASE_NAME)
  63. except sqlite3.OperationalError:
  64. print("Database %s not found" % DATABASE_NAME)
  65. raise OperationalError
  66. c = self.db.cursor()
  67. try:
  68. c.execute("select * from dirnotes")
  69. except sqlite3.OperationalError:
  70. print("Table %s created" % ("dirnotes"))
  71. c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME)")
  72. def getData(self, fileName):
  73. c = self.db.cursor()
  74. c.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
  75. return c.fetchone()
  76. def setData(self, fileName, comment):
  77. ''' TODO: convert filename to canonical '''
  78. c = self.db.cursor()
  79. s = os.lstat(fileName)
  80. print ("params: %s %s %d %s %s" % ((os.path.abspath(fileName),
  81. dnDataBase.epochToDb(s.st_mtime), s.st_size, comment,
  82. dnDataBase.epochToDb(time.time()))))
  83. try:
  84. c.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'))",
  85. (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time()))
  86. self.db.commit()
  87. except sqlite3.OperationalError:
  88. print("database is locked or unwriteable")
  89. #TODO: put up a message box for locked database
  90. @staticmethod
  91. def epochToDb(epoch):
  92. return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(epoch))
  93. @staticmethod
  94. def DbToEpoch(dbTime):
  95. return time.mktime(time.strptime(dbTime,"%Y-%m-%d %H:%M:%S"))
  96. @staticmethod
  97. def getShortDate(longDate):
  98. e = dnDataBase.DbToEpoch(longDate)
  99. sd = time.strptime(longDate,"%Y-%m-%d %H:%M:%S")
  100. # check for this year, or today
  101. ty = time.mktime((time.localtime()[0],1,1,0,0,0,0,1,-1))
  102. today = time.mktime((time.localtime()[0:3]+(0,0,0,0,1,-1)))
  103. if e < ty:
  104. return time.strftime("%b %d %Y",sd)
  105. elif e < today:
  106. return time.strftime("%b %d",sd)
  107. else:
  108. return time.strftime("%X",sd)
  109. #~ test code for this routine
  110. #~ for i in range(int(time.time() - 370*24*3600),
  111. #~ int(time.time() + 48*3600),
  112. #~ 3599):
  113. #~ ds = dnDataBase.epochToDb(i)
  114. #~ print("%d\t%s\t%s" % (i,ds,dnDataBase.getShortDate(ds)))
  115. def parse():
  116. parser = argparse.ArgumentParser(description='dirnotes application')
  117. parser.add_argument('dirname',metavar='dirname',type=str,
  118. help='directory [default=current dir]',default=".",nargs='?')
  119. parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
  120. parser.add_argument('-n','--nogui',action="store_const",const="1",
  121. help='use text base interface')
  122. parser.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
  123. group = parser.add_mutually_exclusive_group()
  124. group.add_argument('-s','--sort-by-name',metavar='sort',action="store_const",const='n')
  125. group.add_argument('-m','--sort-by-date',metavar='sort',action='store_const',const='d')
  126. return parser.parse_args()
  127. #~ class FileObj(QtCore.QObject):
  128. class FileObj():
  129. FILE_IS_DIR = -1
  130. FILE_IS_LINK = -2
  131. def __init__(self, fileName):
  132. self.fileName = fileName
  133. s = os.lstat(fileName)
  134. self.date = dnDataBase.epochToDb(s.st_mtime)
  135. if stat.S_ISDIR(s.st_mode):
  136. self.size = FileObj.FILE_IS_DIR
  137. elif stat.S_ISLNK(s.st_mode):
  138. self.size = FileObj.FILE_IS_LINK
  139. else:
  140. self.size = s.st_size
  141. self.xattrComment = ''
  142. try:
  143. self.xattrComment = os.getxattr(fileName,COMMENT_KEY,follow_symlinks=False).decode()
  144. except Exception as e:
  145. #print("comment read on %s failed, execption %s" % (self.fileName,e))
  146. pass
  147. def getName(self):
  148. return self.fileName
  149. def getFileName(self):
  150. return os.path.split(self.fileName)[1]
  151. def getXattrComment(self):
  152. return self.xattrComment
  153. def setXattrComment(self,newComment):
  154. self.xattrComment = newComment
  155. try:
  156. os.setxattr(self.fileName,COMMENT_KEY,bytes(self.xattrComment,'utf8'),follow_symlinks=False)
  157. return True
  158. # we need to move these cases out to a handler
  159. except Exception as e:
  160. print("problem setting the comment on file %s" % (self.fileName,))
  161. print("error "+repr(e))
  162. ## todo: elif file.is_sym() the kernel won't allow comments on symlinks....stored in database
  163. if self.size == FileObj.FILE_IS_LINK:
  164. print("Linux does not allow comments on symlinks; comment is stored in database")
  165. elif os.access(self.fileName, os.W_OK)!=True:
  166. print("you don't appear to have write permissions on this file")
  167. # change the listbox background to yellow
  168. self.displayBox.notifyUnchanged()
  169. elif "Errno 95" in str(e):
  170. print("is this a VFAT or EXFAT volume? these don't allow comments")
  171. return False
  172. def getDbComment(self,db):
  173. self.dbComment = ""
  174. row = db.getData(self.fileName)
  175. if row and len(row)>1:
  176. self.dbComment = row[3]
  177. def setDbComment(self,db,comment):
  178. db.setData(self.fileName,comment)
  179. def getDate(self):
  180. return self.date
  181. def getSize(self):
  182. return self.size
  183. class HelpWidget(QDialog):
  184. def __init__(self, parent):
  185. super(QDialog, self).__init__(parent)
  186. self.layout = QVBoxLayout(self)
  187. self.tb = QLabel(self)
  188. self.tb.setWordWrap(True)
  189. self.tb.setText(helpMsg)
  190. self.tb.setFixedWidth(500)
  191. self.pb = QPushButton('OK',self)
  192. self.pb.setFixedWidth(200)
  193. self.layout.addWidget(self.tb)
  194. self.layout.addWidget(self.pb)
  195. self.pb.pressed.connect(self.close)
  196. self.show()
  197. ''' a widget that shows only a dir listing
  198. '''
  199. #import sys,os,argparse
  200. #from PyQt4.QtGui import *
  201. #from PyQt4 import QtGui, QtCore
  202. class DirWidget(QListWidget):
  203. ''' a simple widget that shows a list of directories, staring
  204. at the directory passed into the constructor
  205. a mouse click or 'enter' key will send a 'selected' signal to
  206. anyone who connects to this.
  207. the .. parent directory is shown for all dirs except /
  208. the most interesting parts of the interface are:
  209. constructor - send in the directory to view
  210. method - currentPath() returns text of current path
  211. signal - selected calls a slot with a single arg: new path
  212. '''
  213. selected = pyqtSignal(str)
  214. def __init__(self, directory='.', parent=None):
  215. super(DirWidget,self).__init__(parent)
  216. self.directory = directory
  217. self.refill()
  218. self.itemActivated.connect(self.selectionByLWI)
  219. # it would be nice to pick up single-mouse-click for selection as well
  220. # but that seems to be a system-preferences global
  221. def selectionByLWI(self, li):
  222. self.directory = os.path.abspath(self.directory + '/' + str(li.text()))
  223. self.refill()
  224. self.selected.emit(self.directory)
  225. def refill(self):
  226. current,dirs,files = os.walk(self.directory,followlinks=True).next()
  227. dirs.sort()
  228. if '/' not in dirs:
  229. dirs = ['..'] + dirs
  230. self.clear()
  231. for d in dirs:
  232. li = QListWidgetItem(d,self)
  233. def currentPath(self):
  234. return self.directory
  235. # sortable TableWidgetItem, based on idea by Aledsandar
  236. # http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
  237. # NOTE: the QTableWidgetItem has setData() and data() which may allow data bonding
  238. # in Qt5, data() binding is more awkward, so do it here
  239. class SortableTableWidgetItem(QTableWidgetItem):
  240. def __init__(self, text, sortValue, file_object):
  241. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  242. self.sortValue = sortValue
  243. self.file_object = file_object
  244. def __lt__(self, other):
  245. return self.sortValue < other.sortValue
  246. class DirNotes(QMainWindow):
  247. ''' the main window of the app
  248. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  249. '''
  250. def __init__(self, argFilename, db, parent=None):
  251. super(DirNotes,self).__init__(parent)
  252. self.db = db
  253. self.refilling = False
  254. win = QWidget()
  255. self.setCentralWidget(win)
  256. lb = QTableWidget()
  257. self.lb = lb
  258. lb.setColumnCount(4)
  259. lb.horizontalHeader().setSectionResizeMode( 3, QHeaderView.Stretch );
  260. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  261. lb.verticalHeader().setVisible(False)
  262. # resize the comments column
  263. # and resize the parent window to match the directory size
  264. # allow multiple entries on the line at this point
  265. #d = os.listdir(p.filename[0])
  266. #d.sort()
  267. longPathName = os.path.abspath(argFilename)
  268. print("longpathname is {}".format(longPathName))
  269. if os.path.isdir(longPathName):
  270. self.curPath = longPathName
  271. filename = ''
  272. else:
  273. self.curPath, filename = os.path.split(longPathName)
  274. print("working on <"+self.curPath+"> and <"+filename+">")
  275. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  276. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  277. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  278. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  279. lb.setSortingEnabled(True)
  280. self.refill()
  281. lb.resizeColumnsToContents()
  282. if len(filename)>0:
  283. for i in range(lb.rowCount()):
  284. if filename == lb.item(i,0).data(32).toPyObject().getFileName():
  285. lb.setCurrentCell(i,3)
  286. break
  287. layout = QVBoxLayout()
  288. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  289. layout.addWidget(e)
  290. bup = QPushButton("up",win)
  291. bup.setIcon(QIcon.fromTheme('go-up')) # or go-previous
  292. bup.setFixedWidth(100)
  293. b1 = QPushButton("restore from database",win)
  294. upperLayout = QHBoxLayout()
  295. upperLayout.addWidget(bup)
  296. upperLayout.addWidget(b1)
  297. layout.addLayout(upperLayout)
  298. layout.addWidget(lb)
  299. win.setLayout(layout)
  300. lb.itemChanged.connect(self.change)
  301. lb.cellDoubleClicked.connect(self.double)
  302. b1.pressed.connect(self.restore_from_database)
  303. bup.pressed.connect(self.upOneLevel)
  304. mb = self.menuBar()
  305. mf = mb.addMenu('&File')
  306. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  307. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  308. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  309. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  310. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  311. mf.addSeparator()
  312. mf.addAction("Quit", self.close, "Ctrl+Q")
  313. mf.addAction("About", self.about, "Ctrl+H")
  314. #~ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  315. self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
  316. self.setMinimumSize(600,700)
  317. lb.setFocus()
  318. def closeEvent(self,e):
  319. print("closing")
  320. def sbd(self):
  321. print("sort by date")
  322. self.lb.sortItems(1,Qt.DescendingOrder)
  323. def sbs(self):
  324. print("sort by size")
  325. self.lb.sortItems(2)
  326. def sbn(self):
  327. print("sort by name")
  328. self.lb.sortItems(0)
  329. def about(self):
  330. HelpWidget(self)
  331. def sbc(self):
  332. print("sort by comment")
  333. self.lb.sortItems(3,Qt.DescendingOrder)
  334. def newDir(self):
  335. print("change dir to "+self.dirLeft.currentPath())
  336. def double(self,row,col):
  337. print("double click {} {}".format(row, col))
  338. fo = self.lb.item(row,0).file_object
  339. if col==0 and fo.getSize() == FileObj.FILE_IS_DIR:
  340. print("double click on {}".format(fo.getName()))
  341. self.curPath = fo.getName()
  342. self.refill()
  343. def upOneLevel(self):
  344. self.curPath = os.path.abspath(self.curPath + "/..")
  345. self.refill()
  346. def refill(self):
  347. self.refilling = True
  348. self.lb.sortingEnabled = False
  349. self.lb.clearContents()
  350. small_font = QFont("",8)
  351. dirIcon = QIcon.fromTheme('folder')
  352. fileIcon = QIcon.fromTheme('text-x-generic')
  353. linkIcon = QIcon.fromTheme('emblem-symbolic-link')
  354. current, dirs, files = next(os.walk(self.curPath,followlinks=True))
  355. dirs = list(map(lambda x:x+'/', dirs))
  356. dirs.sort()
  357. files.sort()
  358. d = dirs + files
  359. self.lb.setRowCount(len(d))
  360. #~ self.files = {}
  361. self.files = []
  362. # this is a list of all the file
  363. #~ print("insert {} items into cleared table {}".format(len(d),current))
  364. for i in range(len(d)):
  365. this_file = FileObj(current+'/'+d[i])
  366. this_file.getDbComment(self.db)
  367. print("FileObj created as {} and the db-comment is <{}>".format(this_file.fileName, this_file.dbComment))
  368. #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
  369. #~ self.files.update({this_file.getName(),this_file})
  370. self.files = self.files + [this_file]
  371. if this_file.getSize() == FileObj.FILE_IS_DIR:
  372. item = SortableTableWidgetItem(d[i],' '+d[i], this_file) # directories sort first
  373. else:
  374. item = SortableTableWidgetItem(d[i],d[i], this_file)
  375. item.setFlags(Qt.ItemIsEnabled)
  376. #item.setData(32,this_file) # keep a hidden copy of the file object
  377. item.setToolTip(this_file.getName())
  378. self.lb.setItem(i,0,item)
  379. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  380. # get the comment from database & xattrs, either can fail
  381. comment = ""
  382. row = self.db.getData(this_file.getName())
  383. if row and len(row)>0:
  384. comment = row[3]
  385. xattrComment = this_file.getXattrComment()
  386. self.lb.setItem(i,3,QTableWidgetItem(comment))
  387. if xattrComment != comment:
  388. self.lb.item(i,3).setBackground(QBrush(Qt.yellow))
  389. print("got two comments <{}> and <{}>".format(comment, xattrComment))
  390. dt = this_file.getDate()
  391. da = SortableTableWidgetItem(dnDataBase.getShortDate(dt),dt,this_file)
  392. #da.setFont(small_font)
  393. da.setToolTip(dt)
  394. da.setFlags(Qt.ItemIsEnabled)
  395. self.lb.setItem(i,1,da)
  396. si = this_file.getSize()
  397. if si==FileObj.FILE_IS_DIR:
  398. sa = SortableTableWidgetItem('',0,this_file)
  399. item.setIcon(dirIcon)
  400. elif si==FileObj.FILE_IS_LINK:
  401. sa = SortableTableWidgetItem('symlink',-1,this_file)
  402. item.setIcon(linkIcon)
  403. dst = os.path.realpath(this_file.getName())
  404. sa.setToolTip("symlink: " + dst)
  405. else:
  406. sa = SortableTableWidgetItem(str(si),si,this_file)
  407. item.setIcon(fileIcon)
  408. sa.setTextAlignment(Qt.AlignRight)
  409. sa.setFlags(Qt.ItemIsEnabled)
  410. self.lb.setItem(i,2,sa)
  411. self.refilling = False
  412. self.lb.sortingEnabled = True
  413. self.lb.resizeColumnToContents(1)
  414. def change(self,x):
  415. if self.refilling:
  416. return
  417. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  418. print(" selected file: "+self.lb.item(x.row(),0).file_object.getName())
  419. the_file = self.lb.item(x.row(),0).file_object
  420. print(" and the row file is "+the_file.getName())
  421. r = the_file.setXattrComment(str(x.text())) # TODO: change priority
  422. if r:
  423. self.db.setData(the_file.getName(),x.text())
  424. def restore_from_database(self):
  425. print("restore from database")
  426. # retrieve the full path name
  427. fileName = str(self.lb.item(self.lb.currentRow(),0).file_object.getName())
  428. print("using filename: "+fileName)
  429. existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
  430. print("restore....existing="+existing_comment+"=")
  431. if len(existing_comment) > 0:
  432. m = QMessageBox()
  433. m.setText("This file already has a comment. Overwrite?")
  434. m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
  435. if m.exec_() != QMessageBox.Ok:
  436. return
  437. fo_row = self.db.getData(fileName)
  438. if fo_row and len(fo_row)>1:
  439. comment = fo_row[3]
  440. print(fileName,fo_row[0],comment)
  441. the_file = dn.files[self.lb.currentRow()]
  442. the_file.setComment(comment)
  443. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  444. if __name__=="__main__":
  445. p = parse()
  446. if len(p.dirname)>1 and p.dirname[-1]=='/':
  447. p.dirname = p.dirname[:-1]
  448. if os.path.isdir(p.dirname):
  449. p.dirname = p.dirname + '/'
  450. print(p.dirname)
  451. db = dnDataBase()
  452. # TODO: if there's a file specified, jump to it
  453. a = QApplication([])
  454. dn = DirNotes(p.dirname,db)
  455. dn.show()
  456. a.exec_()
  457. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  458. ''' files from directories
  459. use os.isfile()
  460. os.isdir()
  461. current, dirs, files = os.walk("path").next()
  462. possible set folllowLinks=True'''
  463. ''' notes from the wdrm project
  464. table showed
  465. filename, size, date size, date, desc
  466. at start, fills the list of all the files
  467. skip the . entry
  468. '''
  469. ''' should we also do user.xdg.tags="TagA,TagB" ?
  470. user.charset
  471. user.creator=application_name or user.xdg.creator
  472. user.xdg.origin.url
  473. user.xdg.language=[RFC3066/ISO639]
  474. user.xdg.publisher
  475. '''
  476. ''' TODO: add cut-copy-paste for comments '''
  477. ''' TODO: also need a way to display-&-restore comments from the database '''
  478. ''' TODO: implement startup -s and -m for size and date '''
  479. ''' TODO: add an icon for the app '''
  480. ''' TODO: create 'show comment history' popup '''
  481. ''' TODO: add dual-pane for file-move, file-copy '''
  482. ''' commandline xattr
  483. getfattr -h (don't follow symlink) -d (dump all properties)
  484. '''
  485. ''' if the args line contains a file, jump to it '''