dirnotes 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. import sys,os,argparse,stat
  15. #~ from dirWidget import DirWidget
  16. from PyQt4.QtGui import *
  17. from PyQt4 import QtGui, QtCore
  18. import xattr, sqlite3, time
  19. VERSION = "0.2"
  20. COMMENT_KEY = "user.xdg.comment"
  21. DATABASE_NAME = "~/.dirnotes.db"
  22. # convert the ~/ form to a fully qualified path
  23. DATABASE_NAME = os.path.expanduser(DATABASE_NAME)
  24. class DataBase:
  25. ''' the database is flat
  26. fileName: fully qualified name
  27. st_mtime: a float
  28. size: a long
  29. comment: a string
  30. comment_time: a float, the time of the comment save
  31. this is effectively a log file, as well as a resource for a restore
  32. (in case a file-move is done without comment)
  33. the database is associated with a user, in the $HOME dir
  34. '''
  35. def __init__(self):
  36. '''try to open the database; if not found, create it'''
  37. try:
  38. self.db = sqlite3.connect(DATABASE_NAME)
  39. except sqlite3.OperationalError:
  40. print("Database %s not found" % DATABASE_NAME)
  41. raise OperationalError
  42. c = self.db.cursor()
  43. try:
  44. c.execute("select * from dirnotes")
  45. except sqlite3.OperationalError:
  46. print("Table %s created" % ("dirnotes"))
  47. c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME)")
  48. def getData(self, fileName):
  49. c = self.db.cursor()
  50. c.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
  51. return c.fetchone()
  52. def setData(self, fileName, _date, _size, comment):
  53. c = self.db.cursor()
  54. c.execute("insert into dirnotes values (?,?,?,?,?)",
  55. (fileName, _date, _size, comment, time.time()))
  56. self.db.commit()
  57. return True
  58. def log(self, fileName, comment):
  59. ''' TODO: convert filename to canonical '''
  60. c = self.db.cursor()
  61. s = os.lstat(fileName)
  62. print "params: %s %s %d %s %s" % ((os.path.abspath(fileName),
  63. DataBase.epochToDb(s.st_mtime), s.st_size, comment,
  64. DataBase.epochToDb(time.time())))
  65. c.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'))",
  66. (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time()))
  67. self.db.commit()
  68. @staticmethod
  69. def epochToDb(epoch):
  70. return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(epoch))
  71. @staticmethod
  72. def DbToEpoch(dbTime):
  73. return time.mktime(time.strptime(dbTime,"%Y-%m-%d %H:%M:%S"))
  74. @staticmethod
  75. def getShortDate(longDate):
  76. e = DataBase.DbToEpoch(longDate)
  77. sd = time.strptime(longDate,"%Y-%m-%d %H:%M:%S")
  78. # check for this year, or today
  79. ty = time.mktime((time.localtime()[0],1,1,0,0,0,0,1,-1))
  80. today = time.mktime((time.localtime()[0:3]+(0,0,0,0,1,-1)))
  81. if e < ty:
  82. return time.strftime("%b %d %Y",sd)
  83. elif e < today:
  84. return time.strftime("%b %d",sd)
  85. else:
  86. return time.strftime("%X",sd)
  87. #~ test code for this routine
  88. #~ for i in range(int(time.time() - 370*24*3600),
  89. #~ int(time.time() + 48*3600),
  90. #~ 3599):
  91. #~ ds = DataBase.epochToDb(i)
  92. #~ print("%d\t%s\t%s" % (i,ds,DataBase.getShortDate(ds)))
  93. def parse():
  94. parser = argparse.ArgumentParser(description='dirnotes application')
  95. parser.add_argument('dirname',metavar='dirname',type=str,
  96. help='directory [default=current dir]',default=".",nargs='?')
  97. parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
  98. parser.add_argument('-n','--nogui',action="store_const",const="1",
  99. help='use text base interface')
  100. parser.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
  101. group = parser.add_mutually_exclusive_group()
  102. group.add_argument('-s','--sort-by-name',metavar='sort',action="store_const",const='n')
  103. group.add_argument('-m','--sort-by-date',metavar='sort',action='store_const',const='d')
  104. return parser.parse_args()
  105. #~ class FileObj(QtCore.QObject):
  106. class FileObj():
  107. FILE_IS_DIR = -1
  108. FILE_IS_LINK = -2
  109. def __init__(self, fileName):
  110. self.fileName = fileName
  111. s = os.lstat(fileName)
  112. self.date = DataBase.epochToDb(s.st_mtime)
  113. if stat.S_ISDIR(s.st_mode):
  114. self.size = FileObj.FILE_IS_DIR
  115. elif stat.S_ISLNK(s.st_mode):
  116. self.size = FileObj.FILE_IS_LINK
  117. else:
  118. self.size = s.st_size
  119. self.comment = ''
  120. try:
  121. self.comment = xattr.getxattr(fileName,COMMENT_KEY)
  122. except Exception as e:
  123. #print("comment read on %s failed, execption %s" % (self.fileName,e))
  124. pass
  125. def getName(self):
  126. return self.fileName
  127. def getComment(self):
  128. return self.comment
  129. def setComment(self,newComment):
  130. self.comment = newComment
  131. try:
  132. xattr.setxattr(self.fileName,COMMENT_KEY,self.comment)
  133. return True
  134. # we need to move these cases out to a handler
  135. except Exception as e:
  136. print("problem setting the comment on file %s" % (self.fileName,))
  137. print("error "+repr(e))
  138. ## todo: elif file.is_sym() the kernel won't allow comments on symlinks....stored in database
  139. if self.size == FileObj.FILE_IS_LINK:
  140. print("Linux does not allow comments on symlinks; comment is stored in database")
  141. elif os.access(self.fileName, os.W_OK)!=True:
  142. print("you don't appear to have write permissions on this file")
  143. # change the listbox background to yellow
  144. self.displayBox.notifyUnchanged()
  145. elif "Errno 95" in str(e):
  146. print("is this a VFAT or EXFAT volume? these don't allow comments")
  147. return False
  148. def getDate(self):
  149. return self.date
  150. def getSize(self):
  151. return self.size
  152. class HelpWidget(QDialog):
  153. def __init__(self, parent):
  154. super(QDialog, self).__init__(parent)
  155. self.layout = QVBoxLayout(self)
  156. self.tb = QLabel(self)
  157. self.tb.setWordWrap(True)
  158. msg = """<h1>Overview</h1>
  159. This app allows you to add comments to files. The comments are stored in
  160. a database, and where possible, saved in the xattr (hidden attributes)
  161. field of the file system.
  162. <p>
  163. You can sort the directory listing by clicking on the column heading.
  164. <p>
  165. The small box at the top left lets you navigate the directory listings.
  166. """
  167. self.tb.setText(msg)
  168. self.tb.setFixedWidth(600)
  169. self.pb = QPushButton('OK',self)
  170. self.pb.setFixedWidth(200)
  171. self.layout.addWidget(self.tb)
  172. self.layout.addWidget(self.pb)
  173. self.pb.pressed.connect(self.close)
  174. self.show()
  175. # sortable TableWidgetItem, based on idea by Aledsandar
  176. # http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
  177. # NOTE: the QTableWidgetItem has setData() and data() which may allow data bonding
  178. class SortableTableWidgetItem(QTableWidgetItem):
  179. def __init__(self, text, sortValue):
  180. QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
  181. self.sortValue = sortValue
  182. def __lt__(self, other):
  183. return self.sortValue < other.sortValue
  184. class DirNotes(QMainWindow):
  185. ''' the main window of the app
  186. has 3 list boxes: dir_left, dir_right (may be invisible) and files
  187. '''
  188. def __init__(self, argFilename, db, parent=None):
  189. super(DirNotes,self).__init__(parent)
  190. self.db = db
  191. self.refilling = False
  192. win = QWidget()
  193. self.setCentralWidget(win)
  194. lb = QTableWidget()
  195. self.lb = lb
  196. lb.setColumnCount(4)
  197. lb.horizontalHeader().setResizeMode( 3, QHeaderView.Stretch );
  198. lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
  199. lb.verticalHeader().setVisible(False)
  200. # resize the comments column
  201. # and resize the parent window to match the directory size
  202. # allow multiple entries on the line at this point
  203. #d = os.listdir(p.filename[0])
  204. #d.sort()
  205. longPathName = os.path.abspath(argFilename)
  206. print("longpathname is {}".format(longPathName))
  207. if os.path.isdir(longPathName):
  208. self.curPath = longPathName
  209. filename = ''
  210. else:
  211. self.curPath, filename = os.path.split(longPathName)
  212. print("working on <"+self.curPath+"> and <"+filename+">")
  213. lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
  214. lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
  215. lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
  216. lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
  217. lb.setSortingEnabled(True)
  218. self.refill()
  219. lb.resizeColumnsToContents()
  220. layout = QVBoxLayout()
  221. e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
  222. layout.addWidget(e)
  223. bup = QPushButton("up",win)
  224. bup.setIcon(QIcon.fromTheme('go-up')) # or go-previous
  225. bup.setFixedWidth(100)
  226. b1 = QPushButton("restore from database",win)
  227. upperLayout = QHBoxLayout()
  228. upperLayout.addWidget(bup)
  229. upperLayout.addWidget(b1)
  230. layout.addLayout(upperLayout)
  231. layout.addWidget(lb)
  232. win.setLayout(layout)
  233. lb.itemChanged.connect(self.change)
  234. lb.cellDoubleClicked.connect(self.double)
  235. b1.pressed.connect(self.restore_from_database)
  236. bup.pressed.connect(self.upOneLevel)
  237. mb = self.menuBar()
  238. mf = mb.addMenu('&File')
  239. mf.addAction("Sort by name", self.sbn, "Ctrl+N")
  240. mf.addAction("Sort by date", self.sbd, "Ctrl+D")
  241. mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
  242. mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
  243. mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
  244. mf.addSeparator()
  245. mf.addAction("Quit", self.close, "Ctrl+Q")
  246. mf.addAction("About", self.about, "Ctrl+H")
  247. #~ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
  248. self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
  249. self.setMinimumSize(600,700)
  250. lb.setFocus()
  251. def closeEvent(self,e):
  252. print("closing")
  253. def sbd(self):
  254. print("sort by date")
  255. self.lb.sortItems(1,QtCore.Qt.DescendingOrder)
  256. def sbs(self):
  257. print("sort by size")
  258. self.lb.sortItems(2)
  259. def sbn(self):
  260. print("sort by name")
  261. self.lb.sortItems(0)
  262. def about(self):
  263. HelpWidget(self)
  264. def sbc(self):
  265. print("sort by comment")
  266. self.lb.sortItems(3,QtCore.Qt.DescendingOrder)
  267. def newDir(self):
  268. print("change dir to "+self.dirLeft.currentPath())
  269. def double(self,row,col):
  270. print("double click {} {}".format(row, col))
  271. fo = self.lb.item(row,col).data(32).toPyObject()
  272. if col==0 and fo.getSize() == FileObj.FILE_IS_DIR:
  273. print("double click on {}".format(fo.getName()))
  274. self.curPath = fo.getName()
  275. self.refill()
  276. def upOneLevel(self):
  277. self.curPath = os.path.abspath(self.curPath + "/..")
  278. self.refill()
  279. def refill(self):
  280. self.refilling = True
  281. self.lb.sortingEnabled = False
  282. self.lb.clearContents()
  283. small_font = QFont("",8)
  284. dirIcon = QIcon.fromTheme('folder')
  285. fileIcon = QIcon.fromTheme('text-x-generic')
  286. linkIcon = QIcon.fromTheme('emblem-symbolic-link')
  287. current, dirs, files = os.walk(self.curPath,followlinks=True).next()
  288. dirs = map(lambda x:x+'/', dirs)
  289. dirs.sort()
  290. files.sort()
  291. d = dirs + files
  292. self.lb.setRowCount(len(d))
  293. #~ self.files = {}
  294. self.files = []
  295. # this is a list of all the file
  296. #~ print("insert {} items into cleared table {}".format(len(d),current))
  297. for i in range(len(d)):
  298. this_file = FileObj(current+'/'+d[i])
  299. #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
  300. #~ self.files.update({this_file.getName(),this_file})
  301. self.files = self.files + [this_file]
  302. if this_file.getSize() == FileObj.FILE_IS_DIR:
  303. item = SortableTableWidgetItem(d[i],' '+d[i]) # directories sort first
  304. else:
  305. item = SortableTableWidgetItem(d[i],d[i])
  306. item.setFlags(QtCore.Qt.ItemIsEnabled)
  307. item.setData(32,this_file) # keep a hidden copy of the file object
  308. self.lb.setItem(i,0,item)
  309. #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
  310. comment = this_file.getComment()
  311. self.lb.setItem(i,3,QTableWidgetItem(comment))
  312. dt = this_file.getDate()
  313. da = SortableTableWidgetItem(DataBase.getShortDate(dt),dt)
  314. #da.setFont(small_font)
  315. da.setFlags(QtCore.Qt.ItemIsEnabled)
  316. self.lb.setItem(i,1,da)
  317. si = this_file.getSize()
  318. if si==FileObj.FILE_IS_DIR:
  319. sa = SortableTableWidgetItem('',0)
  320. item.setIcon(dirIcon)
  321. elif si==FileObj.FILE_IS_LINK:
  322. sa = SortableTableWidgetItem('',0)
  323. item.setIcon(linkIcon)
  324. else:
  325. sa = SortableTableWidgetItem(str(si),si)
  326. item.setIcon(fileIcon)
  327. sa.setTextAlignment(QtCore.Qt.AlignRight)
  328. sa.setFlags(QtCore.Qt.ItemIsEnabled)
  329. self.lb.setItem(i,2,sa)
  330. self.refilling = False
  331. self.lb.sortingEnabled = True
  332. self.lb.resizeColumnToContents(1)
  333. def change(self,x):
  334. if self.refilling:
  335. return
  336. print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
  337. print(" selected file: "+self.lb.item(x.row(),0).data(32).toPyObject().getName())
  338. the_file = self.lb.item(x.row(),0).data(32).toPyObject()
  339. print(" and the row file is "+the_file.getName())
  340. r = the_file.setComment(str(x.text()))
  341. if r:
  342. self.db.log(the_file.getName(),x.text())
  343. def restore_from_database(self):
  344. print("restore from database")
  345. # retrieve the full path name
  346. fileName = str(self.lb.item(self.lb.currentRow(),0).data(32).toPyObject().getName())
  347. print("using filename: "+fileName)
  348. existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
  349. print("restore....existing="+existing_comment+"=")
  350. if len(existing_comment) > 0:
  351. m = QMessageBox()
  352. m.setText("This file already has a comment. Overwrite?")
  353. m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
  354. if m.exec_() != QMessageBox.Ok:
  355. return
  356. fo_row = self.db.getData(fileName)
  357. if fo_row and len(fo_row)>1:
  358. comment = fo_row[3]
  359. print(fileName,fo_row[0],comment)
  360. the_file = dn.files[self.lb.currentRow()]
  361. the_file.setComment(comment)
  362. self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
  363. if __name__=="__main__":
  364. p = parse()
  365. if len(p.dirname)>1 and p.dirname[-1]=='/':
  366. p.dirname = p.dirname[:-1]
  367. if os.path.isdir(p.dirname):
  368. p.dirname = p.dirname + '/'
  369. print(p.dirname)
  370. db = DataBase()
  371. a = QApplication([])
  372. dn = DirNotes(p.dirname,db)
  373. dn.show()
  374. a.exec_()
  375. #xattr.setxattr(filename,COMMENT_KEY,commentText)
  376. ''' files from directories
  377. use os.isfile()
  378. os.isdir()
  379. current, dirs, files = os.walk("path").next()
  380. possible set folllowLinks=True'''
  381. ''' notes from the wdrm project
  382. table showed
  383. filename, size, date size, date, desc
  384. at start, fills the list of all the files
  385. skip the . entry
  386. '''
  387. ''' should we also do user.xdg.tags="TagA,TagB" ?
  388. user.charset
  389. user.creator=application_name or user.xdg.creator
  390. user.xdg.origin.url
  391. user.xdg.language=[RFC3066/ISO639]
  392. user.xdg.publisher
  393. '''
  394. ''' TODO: add cut-copy-paste for comments '''
  395. ''' TODO: also need a way to display-&-restore comments from the database '''
  396. ''' commandline xattr
  397. getfattr -h (don't follow symlink) -d (dump all properties)
  398. '''
  399. ''' qt set color
  400. newitem.setData(Qt.BackgroundRole,QBrush(QColor("yellow")))
  401. '''
  402. ''' if the args line contains a file, jump to it '''