Advertisement
bitetti

seek files

Nov 17th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.63 KB | None | 0 0
  1. #!/bin/pyton
  2.  
  3. import os
  4. import sys
  5. import string
  6. import re
  7. import time
  8. import stat
  9. import zlib
  10. import zipfile
  11. import sqlite3
  12.  
  13. def walk( base, parentId=0 ):
  14.     global cur
  15.    
  16.     mainId = 0
  17.     if base != '.':
  18.         dt = getDadosArquivo( base, parentId )
  19.         if dt == None:
  20.             mainId = makeArquivoReg( base, parentId, os.path.realpath(base) )
  21.         else:
  22.             mainId = dt[0]  #id do arquivo
  23.        
  24.     for f in os.listdir( base ):
  25.         pathname = os.path.join(base, f)
  26.         if not match(pathname):
  27.             isDir = os.path.isdir( pathname )
  28.             #print "%s - %s" % (base, pathname)
  29.             if isDir:
  30.                 #dt = getDadosArquivo( pathname, mainId )
  31.                 # se nao existe cria
  32.                 #if dt == None:
  33.                 #    makeArquivoReg
  34.                 walk( pathname, mainId )
  35.             else:
  36.                 #zip.write( pathname )
  37.                 dt = getDadosArquivo( pathname, mainId )
  38.                 if dt == None:
  39.                     makeArquivoReg( pathname, mainId, os.path.realpath(pathname) )
  40.                 else:
  41.                     #time_format = "%m/%d/%Y %I:%M:%S %p"
  42.                     file_stats = os.stat(pathname)
  43.                     modification_time = file_stats[stat.ST_MTIME] #time.strftime(time_format,time.localtime(file_stats[stat.ST_MTIME]))
  44.                     creation_time = file_stats[stat.ST_CTIME] #time.strftime(time_format,time.localtime(file_stats[stat.ST_CTIME]))
  45.                     if ("%s" % modification_time) != ("%s" %dt[2]):
  46.                         #print "%s %s %s" % (pathname, file_stats[stat.ST_MTIME], dt[2] )
  47.                         makeArquivoReg( '%s' % pathname, mainId, os.path.realpath(pathname), dt[0] )
  48.                    
  49.  
  50. def checkDeletes( ):
  51.     global cur
  52.     global commitId
  53.  
  54.     cur.execute("SELECT indexpath,idarquivos FROM arquivos WHERE isAtive=1")
  55.     for row in cur.fetchall():
  56.         if not os.path.exists( "./%s" % row[0] ):
  57.             deleteTrunk( row[1] )
  58.        
  59. def deleteTrunk( idArquivo ):
  60.     global commitId
  61.    
  62.     #hide
  63.     cur.execute("UPDATE arquivos SET isAtive=0 WHERE idarquivos=?", (idArquivo,) )
  64.     # history
  65.     cur.execute("""INSERT INTO mt_arquivos_history
  66.                (arquivo_idarquivos, operacao, commits_idcommits)
  67.                VALUES (?, 2,?)
  68.                """, (idArquivo, commitId) )
  69.     # filhos?
  70.     cur.execute("SELECT isFolder FROM arquivos WHERE idarquivos=?", (idArquivo,) )
  71.     df = cur.fetchone()
  72.     if ("%s" % df[0] ) == "1":
  73.         cur.execute("SELECT idarquivos FROM arquivos WHERE parent=? AND isAtive=1", (idArquivo,) )
  74.         for row in cur.fetchall():
  75.             deleteTrunk( row[0] )
  76.  
  77. def getDadosArquivo( path, pai ):
  78.     global cur
  79.     #print "SELECT idarquivos,data_insercao,data_atualizacao FROM arquivos WHERE parent=%s AND nome='%s'" % (pai, path[2:len(path)])
  80.     cur.execute("SELECT idarquivos,data_insercao,data_atualizacao FROM arquivos WHERE parent=? AND indexpath=? AND isAtive=1", (pai, path[2:len(path)],) )
  81.     dt = cur.fetchone()
  82.     return dt
  83.  
  84. def makeArquivoReg( base, parentId, path, toUpdate = -1 ):
  85.     global con
  86.     global cur
  87.     global commitId
  88.  
  89.     fpts = base.split( os.sep )
  90.     fNome = fpts[ len(fpts)-1 ]
  91.     basepath = ""
  92.     for  xp in fpts:
  93.         if xp != ".":
  94.             basepath += "%s%s" % (xp, os.sep )
  95.     basepath = basepath[0:len(basepath)-1]
  96.    
  97.     paiStr = "'%s'" % path
  98.     #base = base[2:len(base)]
  99.  
  100.     file_stats = os.stat(path)
  101.     modification_time = '%s' % file_stats[stat.ST_MTIME]
  102.     creation_time = '%s' %  file_stats[stat.ST_CTIME]
  103.     isFolder = 0
  104.     if os.path.isdir(path):
  105.         isFolder = 1
  106.  
  107.     binary = ""
  108.     print "Obtendo conteudo de: %s" % path
  109.     #print "Comprimir %s" % compress(fNome)
  110.     f = open(path, "r")
  111.     binary = f.read()
  112.     f.close()
  113.     if compress(fNome):
  114.         tBin = zlib.compress(binary,9)
  115.         binary = tBin
  116.     #binary = ''
  117.    
  118.     retId = toUpdate
  119.     workId = 0
  120.     operationStr = 'INSERT'
  121.  
  122.     if toUpdate == -1:
  123.         print "Add: %s" % path
  124.         cur.execute("""INSERT INTO arquivos
  125.        (nome,realpath,parent,data_atualizacao,indexpath,
  126.        dono,isbinary,
  127.        isfolder,
  128.        isagregate,
  129.        conteudo)
  130.        VALUES
  131.        ( ?,?,?,?,?,0,0,?,0,? )""", (fNome, paiStr, parentId, modification_time, basepath, isFolder, sqlite3.Binary(binary),)) #buffer(binary)), ) )
  132.         retId = cur.lastrowid
  133.         workId = retId
  134.         operationStr = 'INSERT'
  135.     else:
  136.         print "Atualizando: %s" % path
  137.         #cur.execute("""UPDATE arquivos
  138.         #SET  data_atualizacao=?,conteudo=?
  139.         #WHERE idarquivos=?;""", ( modification_time,sqlite3.Binary(binary),toUpdate,))
  140.         cur.execute("SELECT idarquivos,revisao FROM arquivos WHERE indexpath=? AND isAtive=1", (basepath,))
  141.         dtt = cur.fetchone()
  142.         print dtt is None
  143.         parentVersionId = dtt[0]
  144.         revisao = int(dtt[1]) + 1
  145.         cur.execute("""INSERT INTO arquivos
  146.        (nome,realpath,parent,data_atualizacao,indexpath,parent_version_id,revisao,
  147.        dono,isbinary,
  148.        isfolder,
  149.        isagregate,
  150.        conteudo)
  151.        VALUES
  152.        ( ?,?,?,?,?,?,?,0,0,?,0,? )""", (fNome, paiStr, parentId, modification_time, basepath, parentVersionId, revisao, isFolder, sqlite3.Binary(binary),)) #buffer(binary)), ) )
  153.         cur.execute("UPDATE arquivos SET isAtive=0 WHERE idarquivos=?",(parentVersionId,))
  154.         workId = toUpdate
  155.         operationStr = 'UPDATE'
  156.    
  157.     # history
  158.     cur.execute("""INSERT INTO mt_arquivos_history
  159.                (arquivo_idarquivos, operacao, commits_idcommits)
  160.                VALUES (?, (SELECT indice FROM mt_execucao_types WHERE descricao=?),?)
  161.                """, (workId, operationStr, commitId) )
  162.    
  163.     #con.commit()
  164.     return retId
  165.  
  166. def match( str ):
  167.     global matches
  168.     for rg in matches:
  169.         if rg.search(str) != None:
  170.             return True
  171.     return False
  172.  
  173. def compress( str ):
  174.     global noCompress
  175.     for rg in noCompress:
  176.         if rg.search(str) != None:
  177.             return False
  178.     return True
  179.  
  180. def getId( path ):
  181.     global cur
  182.     cur.execute("SELECT idarquivos FROM arquivos WHERE isAtive=1 AND indexpath=?", (path,))
  183.     dt = cur.fetchone()
  184.     return dt[0]
  185.  
  186. #matches
  187. matches = []
  188. with open('%s%s%s' %( os.curdir, os.sep, 'ignore.txt')) as f:
  189.     for line in f:
  190.         matches.append( re.compile( line[0:len(line)-1] ) )
  191. #nao comprimir
  192. noCompress = []
  193. with open('%s%s%s' %( os.curdir, os.sep, 'nocompress.txt')) as f:
  194.     for line in f:
  195.         noCompress.append( re.compile( line[0:len(line)-1] ) )
  196.  
  197. def ldz(str):
  198.     if (len('%s' % str)<2):
  199.         str = '0%s' % str
  200.     return str
  201.  
  202. #zip = zipfile.ZipFile('strut.zip','w')
  203. #walk( os.curdir )
  204. #zip.close()
  205.  
  206. con = sqlite3.connect('store.db')
  207. con.isolation_level = None
  208. cur = con.cursor()
  209.  
  210. # commit
  211. t = time.localtime()
  212. commitStr = "<update>"
  213. if len(sys.argv)>1:
  214.     commitStr = sys.argv[1]
  215. commitSQL = "[%s:%s:%s %s-%s-%s]) %s" % (ldz(t.tm_hour),ldz(t.tm_min),ldz(t.tm_sec), ldz(t.tm_year),ldz(t.tm_mon),ldz(t.tm_mday), commitStr)
  216. cur.execute("INSERT INTO commits (descricao,data_execucao) VALUES(?,?)", (commitSQL, int(time.mktime(t)),) )
  217. con.commit()
  218. commitId = cur.lastrowid
  219.  
  220. walk( os.curdir )
  221. checkDeletes()
  222.  
  223. #dados =  sqlite3.Binary( "mandioca frita e lazanha amarela" )
  224. f = open("7.png","rb")
  225. dados = f.read()
  226. f.close()
  227.  
  228. print len(dados)
  229.  
  230. compressed = zlib.compress(dados,9)
  231.  
  232. print len(compressed)
  233.  
  234. f = open("compressed.png","wb")
  235. f.write(zlib.decompress(compressed))
  236. f.flush()
  237. f.close()
  238. b = sqlite3.Binary(compressed)
  239. print b
  240. cur.execute("INSERT INTO tmp (dados) VALUES (?);", (b,) )
  241.  
  242.  
  243. #pf = ".\\fdf\\fdd\\ffd"
  244. #print os.sep
  245. #print pf.split( os.sep )
  246. con.commit()
  247. con.close()
  248.  
  249.  
  250. database= """
  251. DROP TABLE IF EXISTS "mt_execucao_types";
  252. DROP TRIGGER IF EXISTS "commits_insert";
  253. DROP TABLE IF EXISTS "commits";
  254. DROP TRIGGER IF EXISTS "arquivos_insert";
  255. DROP INDEX IF EXISTS "arquivos_indexpath";
  256. DROP INDEX IF EXISTS "arquivos_parent";
  257. DROP INDEX IF EXISTS "arquivos_done";
  258. DROP TABLE IF EXISTS "arquivos";
  259. DROP TRIGGER IF EXISTS "mt_arquivos_history";
  260. DROP INDEX IF EXISTS "mt_arquivos_history_idcommit";
  261. DROP TABLE IF EXISTS "mt_arquivos_history";
  262. DROP VIEW IF EXISTS "arquivos_from_commit";
  263.  
  264.  
  265. CREATE TABLE IF NOT EXISTS "mt_execucao_types" (
  266. indice INTEGER,
  267. descricao VARCHAR(32)
  268. );
  269. INSERT INTO mt_execucao_types VALUES( 0, "INSERT" );
  270. INSERT INTO mt_execucao_types VALUES( 1, "UPDATE" );
  271. INSERT INTO mt_execucao_types VALUES( 2, "DELETE" );
  272. INSERT INTO mt_execucao_types VALUES( 3, "MOVE" );
  273. INSERT INTO mt_execucao_types VALUES( 4, "RESTORE" );
  274. INSERT INTO mt_execucao_types VALUES( 5, "DISPOSE FROM DB" );
  275. INSERT INTO mt_execucao_types VALUES( 6, "COMPRESS DB" );
  276. INSERT INTO mt_execucao_types VALUES( 7, "CLEANUP DB" );
  277.  
  278. CREATE TABLE "commits" (
  279. idcommits INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  280. data_execucao VARCHAR(12) DEFAULT "0" NOT NULL,
  281. descricao TEXT
  282. );
  283.  
  284. CREATE TRIGGER IF NOT EXISTS commits_insert
  285. AFTER INSERT
  286. ON commits
  287. BEGIN
  288. UPDATE commits SET `data_execucao`=strftime('%s','NOW') WHERE `idcommits`=new.rowid;
  289. END
  290.  
  291. CREATE TABLE IF NOT EXISTS "arquivos" (
  292. idarquivos INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  293. nome VARCHAR(255) DEFAULT "erro" NOT NULL,
  294. indexpath VARCHAR(255),
  295. realpath VARCHAR(255),
  296. parent INTEGER,
  297. revisao INTEGER DEFAULT 1 NOT NULL,
  298. parent_version_id INTEGER,
  299. dono INTEGER DEFAULT 0 NOT NULL,
  300. data_insercao VARCHAR(12) DEFAULT "0" NOT NULL,
  301. data_atualizacao VARCHAR(12) DEFAULT "0" NOT NULL,
  302. isBinary INTEGER DEFAULT 0 NOT NULL,
  303. isFolder INTEGER NOT NULL DEFAULT 0,
  304. isAgregate INTEGER NOT NULL DEFAULT 0,
  305. isLink INTEGER NOT NULL DEFAULT 0,
  306. isAtive INTEGER NOT NULL DEFAULT 1,
  307. md5checksum VARCHAR(32),
  308. conteudo BLOB);
  309.  
  310. CREATE INDEX arquivos_indexpath ON arquivos (indexpath);
  311. CREATE INDEX arquivos_parent ON arquivos (parent);
  312. CREATE INDEX arquivos_done ON arquivos (dono);
  313.  
  314. CREATE TRIGGER IF NOT EXISTS arquivos_insert
  315. AFTER INSERT
  316. ON arquivos
  317. BEGIN
  318. UPDATE arquivos SET `data_insercao`=strftime('%s','NOW') WHERE `idarquivos`=new.rowid;
  319. END
  320.  
  321.  
  322.  
  323. CREATE TABLE IF NOT EXISTS "mt_arquivos_history" (
  324. idmt_arquivos_history INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  325. arquivo_idarquivos INTEGER DEFAULT 0 NOT NULL,
  326. operacao INTEGER DEFAULT 1 NOT NULL,
  327. data_execucao VARCHAR(12) DEFAULT "0" NOT NULL,
  328. commits_idcommits INTEGER
  329. );
  330.  
  331. CREATE INDEX mt_arquivos_history_idcommit ON mt_arquivos_history (commits_idcommits);
  332.  
  333. CREATE TRIGGER IF NOT EXISTS mt_arquivos_history_insert
  334. AFTER INSERT
  335. ON mt_arquivos_history
  336. BEGIN
  337. UPDATE mt_arquivos_history SET `data_execucao`=strftime('%s','NOW') WHERE `idmt_arquivos_history`=new.rowid;
  338. END
  339.  
  340. CREATE VIEW IF NOT EXISTS arquivos_from_commit AS
  341. SELECT arquivos.nome as nome, mt_arquivos_history.commits_idcommits as idcommits FROM arquivos INNER JOIN mt_arquivos_history ON  mt_arquivos_history.arquivo_idarquivos=arquivos.idarquivos;
  342.  
  343. ###############################3
  344.  
  345. INSERT INTO mt_arquivos_history
  346. (arquivo_idarquivos, executado, data_execucao,commits_idcommits)
  347. VALUES (1, (SELECT indice FROM mt_execucao_types WHERE descricao='INSERT'),strftime('%s','NOW'),1)
  348.  
  349. INSERT INTO mt_arquivos_history
  350. (arquivo_idarquivos, executado, commits_idcommits)
  351. VALUES (1, (SELECT indice FROM mt_execucao_types WHERE descricao='INSERT'),1)
  352.  
  353.  
  354. SELECT idcommits FROM mt_commits ORDER BY idcommits DESC LIMIT 1;
  355.  
  356. SELECT arquivo_idarquivos FROM mt_arquivos_history WHERE commits_idcommits=4;
  357.  
  358. SELECT nome FROM arquivos INNER JOIN mt_arquivos_history ON  mt_arquivos_history.arquivo_idarquivos=arquivos.idarquivos  WHERE commits_idcommits=4;
  359. """
  360.  
  361.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement