dirnotes 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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
  42. import sqlite3, time
  43. VERSION = "0.2"
  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. # sortable TableWidgetItem, based on idea by Aledsandar
  198. # http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
  199. # NOTE: the QTableWidgetItem has setData() and data() which may allow data bonding
  200. # in Qt5, data() binding is more awkward, so do it here
  201. class SortableTableWidgetItem(QTableWidgetItem):
  202. def __init__(self, text, sortValue, file_object):
  203. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  204. self.sortValue = sortValue
  205. self.file_object = file_object
  206. def __lt__(self, other):
  207. return self.sortValue < other.sortValue
  208. class DirNotes(QMainWindow):
  209. ''' the main window of the app
  210. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  211. '''
  212. def __init__(self, argFilename, db, parent=None):
  213. super(DirNotes,self).__init__(parent)
  214. self.db = db
  215. self.refilling = False
  216. win = QWidget()
  217. self.setCentralWidget(win)
  218. lb = QTableWidget()
  219. self.lb = lb
  220. lb.setColumnCount(4)
  221. lb.horizontalHeader().setSectionResizeMode( 3, QHeaderView.Stretch );
  222. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  223. lb.verticalHeader().setVisible(False)
  224. # resize the comments column
  225. # and resize the parent window to match the directory size
  226. # allow multiple entries on the line at this point
  227. #d = os.listdir(p.filename[0])
  228. #d.sort()
  229. longPathName = os.path.abspath(argFilename)
  230. print("longpathname is {}".format(longPathName))
  231. if os.path.isdir(longPathName):
  232. self.curPath = longPathName
  233. filename = ''
  234. else:
  235. self.curPath, filename = os.path.split(longPathName)
  236. print("working on <"+self.curPath+"> and <"+filename+">")
  237. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  238. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  239. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  240. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  241. lb.setSortingEnabled(True)
  242. self.refill()
  243. lb.resizeColumnsToContents()
  244. if len(filename)>0:
  245. for i in range(lb.rowCount()):
  246. if filename == lb.item(i,0).data(32).toPyObject().getFileName():
  247. lb.setCurrentCell(i,3)
  248. break
  249. layout = QVBoxLayout()
  250. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  251. layout.addWidget(e)
  252. bup = QPushButton("up",win)
  253. bup.setIcon(QIcon.fromTheme('go-up')) # or go-previous
  254. bup.setFixedWidth(100)
  255. b1 = QPushButton("restore from database",win)
  256. upperLayout = QHBoxLayout()
  257. upperLayout.addWidget(bup)
  258. upperLayout.addWidget(b1)
  259. layout.addLayout(upperLayout)
  260. layout.addWidget(lb)
  261. win.setLayout(layout)
  262. lb.itemChanged.connect(self.change)
  263. lb.cellDoubleClicked.connect(self.double)
  264. b1.pressed.connect(self.restore_from_database)
  265. bup.pressed.connect(self.upOneLevel)
  266. mb = self.menuBar()
  267. mf = mb.addMenu('&File')
  268. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  269. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  270. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  271. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  272. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  273. mf.addSeparator()
  274. mf.addAction("Quit", self.close, "Ctrl+Q")
  275. mf.addAction("About", self.about, "Ctrl+H")
  276. #~ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  277. self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
  278. self.setMinimumSize(600,700)
  279. lb.setFocus()
  280. def closeEvent(self,e):
  281. print("closing")
  282. def sbd(self):
  283. print("sort by date")
  284. self.lb.sortItems(1,Qt.DescendingOrder)
  285. def sbs(self):
  286. print("sort by size")
  287. self.lb.sortItems(2)
  288. def sbn(self):
  289. print("sort by name")
  290. self.lb.sortItems(0)
  291. def about(self):
  292. HelpWidget(self)
  293. def sbc(self):
  294. print("sort by comment")
  295. self.lb.sortItems(3,Qt.DescendingOrder)
  296. def newDir(self):
  297. print("change dir to "+self.dirLeft.currentPath())
  298. def double(self,row,col):
  299. print("double click {} {}".format(row, col))
  300. fo = self.lb.item(row,0).file_object
  301. if col==0 and fo.getSize() == FileObj.FILE_IS_DIR:
  302. print("double click on {}".format(fo.getName()))
  303. self.curPath = fo.getName()
  304. self.refill()
  305. def upOneLevel(self):
  306. self.curPath = os.path.abspath(self.curPath + "/..")
  307. self.refill()
  308. def refill(self):
  309. self.refilling = True
  310. self.lb.sortingEnabled = False
  311. self.lb.clearContents()
  312. small_font = QFont("",8)
  313. dirIcon = QIcon.fromTheme('folder')
  314. fileIcon = QIcon.fromTheme('text-x-generic')
  315. linkIcon = QIcon.fromTheme('emblem-symbolic-link')
  316. current, dirs, files = next(os.walk(self.curPath,followlinks=True))
  317. dirs = list(map(lambda x:x+'/', dirs))
  318. dirs.sort()
  319. files.sort()
  320. d = dirs + files
  321. self.lb.setRowCount(len(d))
  322. #~ self.files = {}
  323. self.files = []
  324. # this is a list of all the file
  325. #~ print("insert {} items into cleared table {}".format(len(d),current))
  326. for i in range(len(d)):
  327. this_file = FileObj(current+'/'+d[i])
  328. this_file.getDbComment(self.db)
  329. print("FileObj created as {} and the db-comment is <{}>".format(this_file.fileName, this_file.dbComment))
  330. #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
  331. #~ self.files.update({this_file.getName(),this_file})
  332. self.files = self.files + [this_file]
  333. if this_file.getSize() == FileObj.FILE_IS_DIR:
  334. item = SortableTableWidgetItem(d[i],' '+d[i], this_file) # directories sort first
  335. else:
  336. item = SortableTableWidgetItem(d[i],d[i], this_file)
  337. item.setFlags(Qt.ItemIsEnabled)
  338. #item.setData(32,this_file) # keep a hidden copy of the file object
  339. item.setToolTip(this_file.getName())
  340. self.lb.setItem(i,0,item)
  341. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  342. # get the comment from database & xattrs, either can fail
  343. comment = ""
  344. row = self.db.getData(this_file.getName())
  345. if row and len(row)>0:
  346. comment = row[3]
  347. xattrComment = this_file.getXattrComment()
  348. self.lb.setItem(i,3,QTableWidgetItem(comment))
  349. if xattrComment != comment:
  350. self.lb.item(i,3).setBackground(QBrush(Qt.yellow))
  351. print("got two comments <{}> and <{}>".format(comment, xattrComment))
  352. dt = this_file.getDate()
  353. da = SortableTableWidgetItem(dnDataBase.getShortDate(dt),dt,this_file)
  354. #da.setFont(small_font)
  355. da.setToolTip(dt)
  356. da.setFlags(Qt.ItemIsEnabled)
  357. self.lb.setItem(i,1,da)
  358. si = this_file.getSize()
  359. if si==FileObj.FILE_IS_DIR:
  360. sa = SortableTableWidgetItem('',0,this_file)
  361. item.setIcon(dirIcon)
  362. elif si==FileObj.FILE_IS_LINK:
  363. sa = SortableTableWidgetItem('symlink',-1,this_file)
  364. item.setIcon(linkIcon)
  365. dst = os.path.realpath(this_file.getName())
  366. sa.setToolTip("symlink: " + dst)
  367. else:
  368. sa = SortableTableWidgetItem(str(si),si,this_file)
  369. item.setIcon(fileIcon)
  370. sa.setTextAlignment(Qt.AlignRight)
  371. sa.setFlags(Qt.ItemIsEnabled)
  372. self.lb.setItem(i,2,sa)
  373. self.refilling = False
  374. self.lb.sortingEnabled = True
  375. self.lb.resizeColumnToContents(1)
  376. def change(self,x):
  377. if self.refilling:
  378. return
  379. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  380. print(" selected file: "+self.lb.item(x.row(),0).file_object.getName())
  381. the_file = self.lb.item(x.row(),0).file_object
  382. print(" and the row file is "+the_file.getName())
  383. r = the_file.setXattrComment(str(x.text())) # TODO: change priority
  384. if r:
  385. self.db.setData(the_file.getName(),x.text())
  386. def restore_from_database(self):
  387. print("restore from database")
  388. # retrieve the full path name
  389. fileName = str(self.lb.item(self.lb.currentRow(),0).file_object.getName())
  390. print("using filename: "+fileName)
  391. existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
  392. print("restore....existing="+existing_comment+"=")
  393. if len(existing_comment) > 0:
  394. m = QMessageBox()
  395. m.setText("This file already has a comment. Overwrite?")
  396. m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
  397. if m.exec_() != QMessageBox.Ok:
  398. return
  399. fo_row = self.db.getData(fileName)
  400. if fo_row and len(fo_row)>1:
  401. comment = fo_row[3]
  402. print(fileName,fo_row[0],comment)
  403. the_file = dn.files[self.lb.currentRow()]
  404. the_file.setComment(comment)
  405. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  406. if __name__=="__main__":
  407. p = parse()
  408. if len(p.dirname)>1 and p.dirname[-1]=='/':
  409. p.dirname = p.dirname[:-1]
  410. if os.path.isdir(p.dirname):
  411. p.dirname = p.dirname + '/'
  412. print(p.dirname)
  413. db = dnDataBase()
  414. # TODO: if there's a file specified, jump to it
  415. a = QApplication([])
  416. dn = DirNotes(p.dirname,db)
  417. dn.show()
  418. a.exec_()
  419. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  420. ''' files from directories
  421. use os.isfile()
  422. os.isdir()
  423. current, dirs, files = os.walk("path").next()
  424. possible set folllowLinks=True'''
  425. ''' notes from the wdrm project
  426. table showed
  427. filename, size, date size, date, desc
  428. at start, fills the list of all the files
  429. skip the . entry
  430. '''
  431. ''' should we also do user.xdg.tags="TagA,TagB" ?
  432. user.charset
  433. user.creator=application_name or user.xdg.creator
  434. user.xdg.origin.url
  435. user.xdg.language=[RFC3066/ISO639]
  436. user.xdg.publisher
  437. '''
  438. ''' TODO: add cut-copy-paste for comments '''
  439. ''' TODO: also need a way to display-&-restore comments from the database '''
  440. ''' TODO: implement startup -s and -m for size and date '''
  441. ''' TODO: add an icon for the app '''
  442. ''' TODO: create 'show comment history' popup '''
  443. ''' TODO: add dual-pane for file-move, file-copy '''
  444. ''' commandline xattr
  445. getfattr -h (don't follow symlink) -d (dump all properties)
  446. '''
  447. ''' if the args line contains a file, jump to it '''