image-index-py/func.py
2022-11-12 21:35:50 +01:00

94 lines
3.4 KiB
Python

import os,shutil,hashlib,re
from uuid import uuid4
import sqlite3 as sql
from vars import *
class database():
def __init__(self,filepath):
self.connection=None
self.crsr=None
if not os.path.exists(filepath) :
self.create_database(filepath)
else:
self.connection = sql.connect(filepath)
self.crsr = self.connection.cursor()
def add_index(self,vallist):
print("Parent method!")
colstring=",".join(self.collist)
valstring="'{}'".format("','".join(vallist))
self.crsr.execute("""INSERT INTO {table} ({cols})
VALUES ({vals});
""".format(table=self.name,cols=colstring,vals=valstring))
self.connection.commit()
def create_database(self, filepath):
self.connection = sql.connect(filepath)
self.crsr = self.connection.cursor()
sqlcommand = """CREATE TABLE FILES(
FILE TEXT PRIMARY KEY NOT NULL,
HASH TEXT NOT NULL,
TITLE TEXT ,
SOURCE TEXT ,
CATEGORY TEXT NOT NULL,
TAGS TEXT ,
CONTENT TEXT
); """
self.crsr.execute(sqlcommand)
'''sqlcommand = """CREATE TABLE META(
TAGS TEXT PRIMARY KEY NOT NULL
); """
self.crsr.execute(sqlcommand)'''
def get_col(self,column = "*"):
self.crsr.execute("SELECT {} FROM {}".format(column,self.name))
res=self.crsr.fetchall()
if not res:
res="."
return res
class metatable(database):
def __init__(self,filepath = os.getcwd() + "/index.db"):
self.name="META"
self.collist=["TAGS"]
super().__init__(filepath)
def add_index(self):
super().add_index(vallist)
class filestable(database):
def __init__(self,filepath = os.getcwd() + "/index.db"):
self.name="FILES"
self.collist=["FILE","HASH","TITLE","SOURCE","CATEGORY","TAGS","CONTENT"]
super().__init__(filepath)
def add_index(self,filepath,category="default",title="",source="",tags="",content=""):
filehash=self.get_hash(filepath)
for i in self.get_col("HASH"):
print(i[0])
if filehash in self.get_col("HASH")[0]:
print("This file already exists!")
return
filetype=os.path.splitext(filepath)[1]
filename=str(uuid4()) + filetype
if not os.path.exists("{}/{}".format(ROOT_DIR,category)):
os.makedirs("{}/{}".format(ROOT_DIR,category))
try:
shutil.copy(filepath,"{}/{}/{}".format(ROOT_DIR,category,filename))
except Exception as e:
print(e)
print("COULDN'T COPY FILE TO DESTINATION!")
print("Executing")
vallist=[filename,filehash,title,source,category,tags,content]
super().add_index(vallist)
def get_hash(self,filepath):
#https://www.quickprogrammingtips.com/python/how-to-calculate-md5-hash-of-a-file-in-python.html
md5_hash = hashlib.md5()
with open(filepath,"rb") as f:
# Read and update hash in chunks of 4K
for byte_block in iter(lambda: f.read(4096),b""):
md5_hash.update(byte_block)
f.close()
return str(md5_hash.hexdigest())
def search_index(self,*args):
for arg in args:
if not re.match('^[-]\w{1}$', arg) == None:
print("Heureka!")
print(args)