dirnotes 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. #!/usr/bin/python
  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. depends on python-pyxattr
  9. some file systems don't allow xattr, and even linux
  10. doesn't allow xattr on symlinks, so the database is
  11. considered primary
  12. these comments stick to the symlink, not the deref
  13. """
  14. helpMsg = """<h1>Dirnotes</h1><h3>Overview</h3>
  15. This app allows you to add comments to files. The comments are stored in
  16. a database, and where possible, saved in the xattr (hidden attributes)
  17. field of the file system.
  18. <p>
  19. You can sort the directory listing by clicking on the column heading.
  20. <p>
  21. Double click on directory names to navigate the file system. Hover over
  22. fields for more information.
  23. <p>
  24. <h3>xattr extended attributes</h3>
  25. The xattr property is handy, but suffers from a few problems:
  26. <ul>
  27. <li>is not implemented on FAT/VFAT/EXFAT file systems (like USB sticks)
  28. <li>xattrs are not (by default) copied with the file when it's duplicated
  29. or backedup
  30. <li>xattrs are not available for symlinks
  31. <li>many programs which edit files do not preserve the xattrs during file-save
  32. </ul>
  33. When the database version of a comment differs from the xattr version, the
  34. comment box gets a light yellow background.
  35. """
  36. import sys,os,argparse,stat
  37. #~ from dirWidget import DirWidget
  38. from PyQt4.QtGui import *
  39. from PyQt4 import QtGui, QtCore
  40. import xattr, sqlite3, time
  41. VERSION = "0.2"
  42. COMMENT_KEY = "user.xdg.comment"
  43. DATABASE_NAME = "~/.dirnotes.db"
  44. # convert the ~/ form to a fully qualified path
  45. DATABASE_NAME = os.path.expanduser(DATABASE_NAME)
  46. class DataBase:
  47. ''' the database is flat
  48. fileName: fully qualified name
  49. st_mtime: a float
  50. size: a long
  51. comment: a string
  52. comment_time: a float, the time of the comment save
  53. this is effectively a log file, as well as a resource for a restore
  54. (in case a file-move is done without comment)
  55. the database is associated with a user, in the $HOME dir
  56. '''
  57. def __init__(self):
  58. '''try to open the database; if not found, create it'''
  59. try:
  60. self.db = sqlite3.connect(DATABASE_NAME)
  61. except sqlite3.OperationalError:
  62. print("Database %s not found" % DATABASE_NAME)
  63. raise OperationalError
  64. c = self.db.cursor()
  65. try:
  66. c.execute("select * from dirnotes")
  67. except sqlite3.OperationalError:
  68. print("Table %s created" % ("dirnotes"))
  69. c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME)")
  70. def getData(self, fileName):
  71. c = self.db.cursor()
  72. c.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
  73. return c.fetchone()
  74. def setData(self, fileName, _date, _size, comment):
  75. c = self.db.cursor()
  76. c.execute("insert into dirnotes values (?,?,?,?,?)",
  77. (fileName, _date, _size, comment, time.time()))
  78. self.db.commit()
  79. return True
  80. def log(self, fileName, comment):
  81. ''' TODO: convert filename to canonical '''
  82. c = self.db.cursor()
  83. s = os.lstat(fileName)
  84. print "params: %s %s %d %s %s" % ((os.path.abspath(fileName),
  85. DataBase.epochToDb(s.st_mtime), s.st_size, comment,
  86. DataBase.epochToDb(time.time())))
  87. c.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'))",
  88. (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time()))
  89. self.db.commit()
  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 = DataBase.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 = DataBase.epochToDb(i)
  114. #~ print("%d\t%s\t%s" % (i,ds,DataBase.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 = DataBase.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.comment = ''
  142. try:
  143. self.comment = xattr.get(fileName,COMMENT_KEY,nofollow=True)
  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 getComment(self):
  152. return self.comment
  153. def setComment(self,newComment):
  154. self.comment = newComment
  155. try:
  156. xattr.set(self.fileName,COMMENT_KEY,self.comment,nofollow=True)
  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 getDate(self):
  173. return self.date
  174. def getSize(self):
  175. return self.size
  176. class HelpWidget(QDialog):
  177. def __init__(self, parent):
  178. super(QDialog, self).__init__(parent)
  179. self.layout = QVBoxLayout(self)
  180. self.tb = QLabel(self)
  181. self.tb.setWordWrap(True)
  182. self.tb.setText(helpMsg)
  183. self.tb.setFixedWidth(500)
  184. self.pb = QPushButton('OK',self)
  185. self.pb.setFixedWidth(200)
  186. self.layout.addWidget(self.tb)
  187. self.layout.addWidget(self.pb)
  188. self.pb.pressed.connect(self.close)
  189. self.show()
  190. # sortable TableWidgetItem, based on idea by Aledsandar
  191. # http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
  192. # NOTE: the QTableWidgetItem has setData() and data() which may allow data bonding
  193. class SortableTableWidgetItem(QTableWidgetItem):
  194. def __init__(self, text, sortValue):
  195. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  196. self.sortValue = sortValue
  197. def __lt__(self, other):
  198. return self.sortValue < other.sortValue
  199. class DirNotes(QMainWindow):
  200. ''' the main window of the app
  201. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  202. '''
  203. def __init__(self, argFilename, db, parent=None):
  204. super(DirNotes,self).__init__(parent)
  205. self.db = db
  206. self.refilling = False
  207. win = QWidget()
  208. self.setCentralWidget(win)
  209. lb = QTableWidget()
  210. self.lb = lb
  211. lb.setColumnCount(4)
  212. lb.horizontalHeader().setResizeMode( 3, QHeaderView.Stretch );
  213. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  214. lb.verticalHeader().setVisible(False)
  215. # resize the comments column
  216. # and resize the parent window to match the directory size
  217. # allow multiple entries on the line at this point
  218. #d = os.listdir(p.filename[0])
  219. #d.sort()
  220. longPathName = os.path.abspath(argFilename)
  221. print("longpathname is {}".format(longPathName))
  222. if os.path.isdir(longPathName):
  223. self.curPath = longPathName
  224. filename = ''
  225. else:
  226. self.curPath, filename = os.path.split(longPathName)
  227. print("working on <"+self.curPath+"> and <"+filename+">")
  228. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  229. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  230. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  231. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  232. lb.setSortingEnabled(True)
  233. self.refill()
  234. lb.resizeColumnsToContents()
  235. if len(filename)>0:
  236. for i in range(lb.rowCount()):
  237. if filename == lb.item(i,0).data(32).toPyObject().getFileName():
  238. lb.setCurrentCell(i,3)
  239. break
  240. layout = QVBoxLayout()
  241. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  242. layout.addWidget(e)
  243. bup = QPushButton("up",win)
  244. bup.setIcon(QIcon.fromTheme('go-up')) # or go-previous
  245. bup.setFixedWidth(100)
  246. b1 = QPushButton("restore from database",win)
  247. upperLayout = QHBoxLayout()
  248. upperLayout.addWidget(bup)
  249. upperLayout.addWidget(b1)
  250. layout.addLayout(upperLayout)
  251. layout.addWidget(lb)
  252. win.setLayout(layout)
  253. lb.itemChanged.connect(self.change)
  254. lb.cellDoubleClicked.connect(self.double)
  255. b1.pressed.connect(self.restore_from_database)
  256. bup.pressed.connect(self.upOneLevel)
  257. mb = self.menuBar()
  258. mf = mb.addMenu('&File')
  259. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  260. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  261. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  262. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  263. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  264. mf.addSeparator()
  265. mf.addAction("Quit", self.close, "Ctrl+Q")
  266. mf.addAction("About", self.about, "Ctrl+H")
  267. #~ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  268. self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
  269. self.setMinimumSize(600,700)
  270. lb.setFocus()
  271. def closeEvent(self,e):
  272. print("closing")
  273. def sbd(self):
  274. print("sort by date")
  275. self.lb.sortItems(1,QtCore.Qt.DescendingOrder)
  276. def sbs(self):
  277. print("sort by size")
  278. self.lb.sortItems(2)
  279. def sbn(self):
  280. print("sort by name")
  281. self.lb.sortItems(0)
  282. def about(self):
  283. HelpWidget(self)
  284. def sbc(self):
  285. print("sort by comment")
  286. self.lb.sortItems(3,QtCore.Qt.DescendingOrder)
  287. def newDir(self):
  288. print("change dir to "+self.dirLeft.currentPath())
  289. def double(self,row,col):
  290. print("double click {} {}".format(row, col))
  291. fo = self.lb.item(row,0).data(32).toPyObject()
  292. if col==0 and fo.getSize() == FileObj.FILE_IS_DIR:
  293. print("double click on {}".format(fo.getName()))
  294. self.curPath = fo.getName()
  295. self.refill()
  296. def upOneLevel(self):
  297. self.curPath = os.path.abspath(self.curPath + "/..")
  298. self.refill()
  299. def refill(self):
  300. self.refilling = True
  301. self.lb.sortingEnabled = False
  302. self.lb.clearContents()
  303. small_font = QFont("",8)
  304. dirIcon = QIcon.fromTheme('folder')
  305. fileIcon = QIcon.fromTheme('text-x-generic')
  306. linkIcon = QIcon.fromTheme('emblem-symbolic-link')
  307. current, dirs, files = os.walk(self.curPath,followlinks=True).next()
  308. dirs = map(lambda x:x+'/', dirs)
  309. dirs.sort()
  310. files.sort()
  311. d = dirs + files
  312. self.lb.setRowCount(len(d))
  313. #~ self.files = {}
  314. self.files = []
  315. # this is a list of all the file
  316. #~ print("insert {} items into cleared table {}".format(len(d),current))
  317. for i in range(len(d)):
  318. this_file = FileObj(current+'/'+d[i])
  319. #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
  320. #~ self.files.update({this_file.getName(),this_file})
  321. self.files = self.files + [this_file]
  322. if this_file.getSize() == FileObj.FILE_IS_DIR:
  323. item = SortableTableWidgetItem(d[i],' '+d[i]) # directories sort first
  324. else:
  325. item = SortableTableWidgetItem(d[i],d[i])
  326. item.setFlags(QtCore.Qt.ItemIsEnabled)
  327. item.setData(32,this_file) # keep a hidden copy of the file object
  328. item.setToolTip(this_file.getName())
  329. self.lb.setItem(i,0,item)
  330. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  331. comment = this_file.getComment()
  332. self.lb.setItem(i,3,QTableWidgetItem(comment))
  333. dt = this_file.getDate()
  334. da = SortableTableWidgetItem(DataBase.getShortDate(dt),dt)
  335. #da.setFont(small_font)
  336. da.setToolTip(dt)
  337. da.setFlags(QtCore.Qt.ItemIsEnabled)
  338. self.lb.setItem(i,1,da)
  339. si = this_file.getSize()
  340. if si==FileObj.FILE_IS_DIR:
  341. sa = SortableTableWidgetItem('',0)
  342. item.setIcon(dirIcon)
  343. elif si==FileObj.FILE_IS_LINK:
  344. sa = SortableTableWidgetItem('symlink',-1)
  345. item.setIcon(linkIcon)
  346. dst = os.path.realpath(this_file.getName())
  347. sa.setToolTip("symlink: " + dst)
  348. else:
  349. sa = SortableTableWidgetItem(str(si),si)
  350. item.setIcon(fileIcon)
  351. sa.setTextAlignment(QtCore.Qt.AlignRight)
  352. sa.setFlags(QtCore.Qt.ItemIsEnabled)
  353. self.lb.setItem(i,2,sa)
  354. self.refilling = False
  355. self.lb.sortingEnabled = True
  356. self.lb.resizeColumnToContents(1)
  357. def change(self,x):
  358. if self.refilling:
  359. return
  360. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  361. print(" selected file: "+self.lb.item(x.row(),0).data(32).toPyObject().getName())
  362. the_file = self.lb.item(x.row(),0).data(32).toPyObject()
  363. print(" and the row file is "+the_file.getName())
  364. r = the_file.setComment(str(x.text())) # TODO: change priority
  365. if r:
  366. self.db.log(the_file.getName(),x.text())
  367. def restore_from_database(self):
  368. print("restore from database")
  369. # retrieve the full path name
  370. fileName = str(self.lb.item(self.lb.currentRow(),0).data(32).toPyObject().getName())
  371. print("using filename: "+fileName)
  372. existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
  373. print("restore....existing="+existing_comment+"=")
  374. if len(existing_comment) > 0:
  375. m = QMessageBox()
  376. m.setText("This file already has a comment. Overwrite?")
  377. m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
  378. if m.exec_() != QMessageBox.Ok:
  379. return
  380. fo_row = self.db.getData(fileName)
  381. if fo_row and len(fo_row)>1:
  382. comment = fo_row[3]
  383. print(fileName,fo_row[0],comment)
  384. the_file = dn.files[self.lb.currentRow()]
  385. the_file.setComment(comment)
  386. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  387. if __name__=="__main__":
  388. p = parse()
  389. if len(p.dirname)>1 and p.dirname[-1]=='/':
  390. p.dirname = p.dirname[:-1]
  391. if os.path.isdir(p.dirname):
  392. p.dirname = p.dirname + '/'
  393. print(p.dirname)
  394. db = DataBase()
  395. a = QApplication([])
  396. dn = DirNotes(p.dirname,db)
  397. dn.show()
  398. a.exec_()
  399. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  400. ''' files from directories
  401. use os.isfile()
  402. os.isdir()
  403. current, dirs, files = os.walk("path").next()
  404. possible set folllowLinks=True'''
  405. ''' notes from the wdrm project
  406. table showed
  407. filename, size, date size, date, desc
  408. at start, fills the list of all the files
  409. skip the . entry
  410. '''
  411. ''' should we also do user.xdg.tags="TagA,TagB" ?
  412. user.charset
  413. user.creator=application_name or user.xdg.creator
  414. user.xdg.origin.url
  415. user.xdg.language=[RFC3066/ISO639]
  416. user.xdg.publisher
  417. '''
  418. ''' TODO: add cut-copy-paste for comments '''
  419. ''' TODO: also need a way to display-&-restore comments from the database '''
  420. ''' commandline xattr
  421. getfattr -h (don't follow symlink) -d (dump all properties)
  422. '''
  423. ''' qt set color
  424. newitem.setData(Qt.BackgroundRole,QBrush(QColor("yellow")))
  425. '''
  426. ''' if the args line contains a file, jump to it '''