2022-11-22 18:34:32 +01:00
#!/bin/python3
2022-11-24 14:54:41 +01:00
import hashlib,os,random,re,shutil,subprocess,sys
2022-11-22 18:34:32 +01:00
from pathlib import Path
from uuid import uuid4
import sqlite3 as sql
2022-11-23 23:00:08 +01:00
ROOT_DIR=os.getcwd() # The directory where all directories and files of the index are located
CONFIG_DIR=ROOT_DIR # The directory where the file 'index.db' is located
LINUX_APP_STARTER="xdg-open" # The command which opens the files in the default applications
2022-11-22 18:34:32 +01:00
class database():
2022-11-23 23:00:08 +01:00
def __init__(self,filepath = CONFIG_DIR + "/index.db"):
2022-11-22 18:34:32 +01:00
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):
# compile the options into a command for the SQLite database
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):
# create the database and tables
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 CATEGORY(
NAME TEXT PRIMARY KEY NOT NULL,
2022-12-02 11:58:11 +01:00
ALIAS TEXT
2022-11-22 18:34:32 +01:00
); """
self.crsr.execute(sqlcommand)
sqlcommand = """CREATE TABLE TAGS(
NAME TEXT PRIMARY KEY NOT NULL,
2022-12-02 11:58:11 +01:00
ALIAS TEXT
2022-11-22 18:34:32 +01:00
); """
self.crsr.execute(sqlcommand)
def delete_index(self,typ,item):
self.crsr.execute("DELETE FROM {} WHERE {}='{}'".format(self.name,typ,item))
self.connection.commit()
return
def get_col(self,column = "*"):
# get the column of some table. If no options given, return all columns
self.crsr.execute("SELECT {} FROM {}".format(column,self.name))
tres=self.crsr.fetchall()
res=[]
for i in tres:
res.append(i)
# if the table is empty, return ".".
if not res:
res="."
return res
2022-11-23 23:00:08 +01:00
def get_item(self,column,where,specific=False):
2022-11-22 18:34:32 +01:00
tres=[]
if column == "*":
for col in self.collist:
temp_list=[]
2022-11-23 23:00:08 +01:00
if specific:
self.crsr.execute("SELECT * FROM {} WHERE {}='{}'".format(self.name,col,where))
else:
self.crsr.execute("SELECT * FROM {} WHERE {} GLOB '*{}*'".format(self.name,col,where))
2022-11-22 18:34:32 +01:00
temp_list=self.crsr.fetchall()
if temp_list:
for i in temp_list:
if not i in tres:
tres.append(i)
else:
2022-11-23 23:00:08 +01:00
if specific:
self.crsr.execute("SELECT * FROM {} WHERE {}='{}'".format(self.name,column,where))
else:
self.crsr.execute("SELECT * FROM {} WHERE {} GLOB '*{}*'".format(self.name,column,where))
2022-11-22 18:34:32 +01:00
tres=self.crsr.fetchall()
n=0
res=[]
for i in tres:
m=0
for j in tres:
if i in j and n!=m:
continue
else:
res.append(i)
m+=1
n+=1
# if the table is empty, return ".".
if not res:
return ["."]
return res
def select_index(self,sel_list,quiet=False):
if quiet == "strict":
return sel_list
if sel_list:
res=[]
if len(sel_list) > 1:
n=0
print("Found several matches:")
for tup in sel_list:
temp_list=[]
for j in tup:
temp_list.append(j)
print("Match [{}]".format(n))
if self.name == "FILES":
print("\tTitle:\t ",temp_list[2])
name=ctb.get_alias(temp_list[4])
if name != ".":
category=name
else:
category=temp_list[4]
print("\tCategory:",category)
tags_list=[]
for tag in temp_list[5].split(","):
name=ttb.get_alias(tag)
if name != ".":
tag=name
tags_list.append(tag)
print("\tTags:\t ",",".join(tags_list))
else:
print("\tName:\t ",temp_list[0])
print("\tAlias:\t ",temp_list[1])
print("\tDescription: ",temp_list[2])
n+=1
eingabe=input("Enter number(s) (0-{}; '*' for all entries): ".format(n-1))
if not eingabe:
return ["."]
num_list=[]
if re.match('[*]',eingabe):
for i in range(0,n):
num_list.append(i)
else:
num_list=eingabe.split(' ')
nminus=0
for i in num_list:
if int(i) >= n:
print("The number {} is too big!".format(i))
nminus+=1
continue
res.append(sel_list[int(i)])
if not quiet:
print("\nFinal match{}:".format("es" if len(num_list)-nminus > 1 else ""))
else:
if sel_list[0] == ".":
if not quiet == "strict":
print("No matching entry found!")
return ["."]
res=sel_list
if not quiet == "strict":
print("\nMatch found!")
return res
return 1
2022-11-23 23:00:08 +01:00
def sql_compare_list(self,typ,firstlist,secondlist,specific=False):
2022-11-22 18:34:32 +01:00
if isinstance(firstlist, str):
firstlist=firstlist.split(" ")
if firstlist:
n=0
temp_list=[]
if not secondlist:
n=0
for i in self.get_col(typ):
2022-11-24 14:54:41 +01:00
aliases=[]
2022-11-29 10:17:44 +01:00
if i == "." and self.name == "FILES":
print("NO ENTRIES IN THE INDEX!")
return "."
2022-11-24 14:54:41 +01:00
# get aliases for the checks, but only for unspecific search!
if self.name == "FILES":
if typ == "*":
for tag in i[5].split(","):
aliases.append(ttb.get_alias(tag))
aliases.append(ctb.get_alias(i[4]))
elif typ == "TAGS":
for tag in i[0].split(","):
aliases.append(ttb.get_alias(tag))
elif typ == "CATEGORY":
aliases.append(ctb.get_alias(i[0]))
istr=" ".join(i).lower() + " " + " ".join(aliases).lower()
2022-11-22 18:34:32 +01:00
success=0
for j in firstlist:
j=j.lower()
2022-11-23 23:00:08 +01:00
if specific:
for part in i:
part=part.lower()
if j == part:
if not success == -1:
success=1
if success == 0:
success=-1
2022-11-22 18:34:32 +01:00
else:
2022-11-23 23:00:08 +01:00
if j in istr:
if not success == -1:
success=1
else:
success=-1
2022-11-22 18:34:32 +01:00
if success > 0:
if typ == "*":
2022-11-23 23:00:08 +01:00
temp_list.append(self.get_item("*",i[0],specific)[0])
2022-11-22 18:34:32 +01:00
else:
2022-11-23 23:00:08 +01:00
for k in self.get_item(typ,i[0],specific):
2022-11-22 18:34:32 +01:00
if not k in temp_list:
temp_list.append(k)
n+=1
else:
if not secondlist[0] == ".":
for i in secondlist:
for j in firstlist:
if j in i:
temp_list.append(secondlist[n])
n+=1
else:
return secondlist
if not temp_list:
return ["."]
return temp_list
return secondlist
def update_index(self,typ,update,where,val):
self.crsr.execute("UPDATE {} SET {}='{}' WHERE {}='{}'".format(self.name,typ,update,where,val))
self.connection.commit()
return True
class metatable(database):
def __init__(self,typ,filepath = CONFIG_DIR + "/index.db"):
self.name=typ.upper()
2022-12-02 11:58:11 +01:00
self.collist=["NAME","ALIAS"]
2022-11-22 18:34:32 +01:00
super().__init__(filepath)
2022-12-02 16:42:40 +01:00
def add_index(self,val,alias,randhex=None):
if not randhex:
randhex=get_randhex()
val=re.sub('[ ,?!/\\:!*"<>|]', '', val)
2022-12-02 11:58:11 +01:00
super().add_index([val[:8] + "-" + randhex,alias])
2022-11-22 18:34:32 +01:00
def check_index(self,typ):
res=[]
for i in tb.get_col(typ):
success=0
for j in self.get_col("NAME"):
2022-12-01 18:20:05 +01:00
if j[0] in i[0]:
2022-11-22 18:34:32 +01:00
success=1
if not i[0] in res and success == 0:
res.append(i[0])
return res
def get_alias(self,arg):
2022-12-01 18:20:05 +01:00
if not arg:
return "."
2022-11-22 18:34:32 +01:00
selection=self.search_index(arg,"strict")
item=selection[0]
2022-11-23 23:00:08 +01:00
if item[0] != ".":
alias=item[1]
else:
alias = "."
2022-11-22 18:34:32 +01:00
return alias
def get_name(self,arg):
2022-12-01 18:20:05 +01:00
if not arg:
return "."
2022-11-22 18:34:32 +01:00
selection=self.search_index(arg,"strict")
item=selection[0]
name=item[0]
return name
def search_index(self,args,quiet=True):
selection=[]
2022-11-24 14:54:41 +01:00
selection=self.sql_compare_list("*", [args], selection,True)
2022-12-02 16:42:40 +01:00
if selection[0] == ".":
slist=args.split(" ")
selection=self.sql_compare_list("*", slist, [],False)
if len(selection) > 1:
print("Please enter a more specific search query!")
return "."
2022-11-22 18:34:32 +01:00
selection=self.select_index(selection,quiet)
return selection
2022-11-29 10:17:44 +01:00
def update_index(self, typ, update, where, val):
selection=self.search_index(update,"strict")
if selection[0] != "." and len(selection) >= 1:
print("One entry is already called {}!".format(update))
return False
else:
super().update_index(typ, update, where, val)
return True
2022-11-22 18:34:32 +01:00
class filestable(database):
def __init__(self,filepath = CONFIG_DIR + "/index.db"):
self.name="FILES"
self.collist=["FILE","HASH","TITLE","SOURCE","CATEGORY","TAGS","CONTENT"]
super().__init__(filepath)
2022-11-23 23:00:08 +01:00
def add_index(self,filepath,category="default",title="",source="",tags="",content=""):
2022-11-22 18:34:32 +01:00
filehash=self.get_hash(filepath) # make hash of file before copy
if filehash in str(self.get_col("HASH")):
print("This file already exists!")
2022-12-01 18:20:05 +01:00
return False
2022-11-22 18:34:32 +01:00
n=0
# get the name of the category from the meta table
2022-11-23 23:00:08 +01:00
if not category:
2022-11-22 18:34:32 +01:00
category="default"
2022-11-23 23:00:08 +01:00
name=ctb.get_name(category)
if name != ".":
category=name
else:
2022-12-02 11:58:11 +01:00
ctb.add_index(category.lower(),category)
2022-11-24 14:54:41 +01:00
category=ctb.get_name(category)
2022-11-22 18:34:32 +01:00
# get the name of the tags from the meta table
tags_list=[]
for tag in tags.split(','):
name=ttb.get_name(tag)
if name != ".":
tag=name
else:
2022-12-02 11:58:11 +01:00
ttb.add_index(tag.lower(),tag)
2022-11-24 14:54:41 +01:00
tags_list.append(ttb.get_name(tag))
2022-11-22 18:34:32 +01:00
tags=",".join(tags_list)
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 to copy the file, return if error.
try:
shutil.copy(filepath,"{}/{}/{}".format(ROOT_DIR,category,filename))
except Exception as e:
print(e)
print("COULDN'T COPY FILE TO DESTINATION!")
2022-12-01 18:20:05 +01:00
return False
2022-11-22 18:34:32 +01:00
vallist=[filename,filehash,title,source,category,tags,content]
super().add_index(vallist)
2022-12-01 18:20:05 +01:00
return True
2022-11-22 18:34:32 +01:00
def check_index(self):
hash_list=[]
path_list=[]
for i in self.get_col():
filename=i[0]
category=i[4]
filehash1=i[1]
filepath="{}/{}/{}".format(ROOT_DIR,category,filename)
if not os.path.exists(filepath):
path_list.append(i)
try:
filehash2=self.get_hash(filepath)
if not filehash1 == filehash2:
hash_list.append(i)
except Exception:
path_list.append(i)
return hash_list,path_list
def delete_index(self,sel_list):
self.get_item("HASH",sel_list[1])
super().delete_index("HASH",sel_list[1])
2022-12-01 18:20:05 +01:00
return True
2022-11-22 18:34:32 +01:00
def update_index(self,typ,update,sel_list):
typ=typ.upper()
if typ in ["FILE","HASH"]:
print("This type can't be changed!")
return 1
category=sel_list[4]
filehash=sel_list[1]
filename=sel_list[0]
if typ in ["CATEGORY"]:
# get alias of category
name=ctb.get_name(update)
if name != ".":
update=name
2022-11-24 14:54:41 +01:00
else:
2022-12-02 11:58:11 +01:00
ctb.add_index(update.lower(),update)
2022-11-24 14:54:41 +01:00
update=ctb.get_name(update)
2022-11-22 18:34:32 +01:00
if not os.path.exists("{}/{}".format(ROOT_DIR,update)):
os.makedirs("{}/{}".format(ROOT_DIR,update))
shutil.move("{}/{}/{}".format(ROOT_DIR,category,filename), "{}/{}/{}".format(ROOT_DIR,update,filename))
if typ in ["TAGS"]:
2022-11-24 14:54:41 +01:00
tags_list=[]
2022-11-29 10:54:21 +01:00
if update[0][0] == "+":
for tag in sel_list[5].split(","):
tags_list.append(tag)
for tag in update[1:].split(","):
name=ttb.get_name(tag)
if name == ".":
2022-12-02 11:58:11 +01:00
ttb.add_index(tag.lower(), tag)
2022-11-29 10:54:21 +01:00
name=ttb.get_name(tag)
2022-11-24 14:54:41 +01:00
tags_list.append(name)
2022-11-29 10:54:21 +01:00
elif update[0][0] == "-":
for tag in sel_list[5].split(","):
success=0
for i in update[1:].split(","):
name=ttb.get_name(i)
if name == ".":
ttb.add_index(tag.lower(), tag)
name=ttb.get_name(tag)
if name == tag:
success = -1
if success >= 0:
tags_list.append(tag)
else:
for tag in update.split(","):
name=ttb.get_name(tag)
if name != ".":
tags_list.append(name)
else:
2022-12-02 11:58:11 +01:00
ttb.add_index(tag.lower(), tag)
2022-11-29 10:54:21 +01:00
tags_list.append(ttb.get_name(tag))
2022-11-24 14:54:41 +01:00
update=",".join(tags_list)
2022-11-22 18:34:32 +01:00
super().update_index(typ, update, "HASH", filehash)
def get_hash(self,filepath):
2022-11-23 23:00:08 +01:00
# https://www.quickprogrammingtips.com/python/how-to-calculate-md5-hash-of-a-file-in-python.html
2022-11-22 18:34:32 +01:00
md5_hash = hashlib.md5()
# hash selected file in chunks of 4KiB, read the link above if you ask why.
with open(filepath,"rb") as f:
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,quiet=False):
snext="all"
shash=[]
alle=[]
category=[]
sfile=[]
content=[]
source=[]
title=[]
tags=[]
for arg in args:
arg=arg.lower()
if re.match('^[-]\w{1}$', arg):
if arg == "-h":
snext="hash"
elif arg == "-a": # technically unneeded because of else at the end
snext="all"
elif arg == "-c":
snext="category"
elif arg == "-f":
snext="file"
elif arg == "-i": # Inhalt
snext="content"
elif arg == "-s":
snext="source"
elif arg == "-t":
snext="title"
elif arg == "-g": # Gruppe
snext="tags"
else:
snext="all"
continue
if snext == "hash":
shash.append(arg)
elif snext == "all":
alle.append(arg)
elif snext == "category":
name=ctb.get_name(arg)
if name != ".":
arg=name
category.append(arg)
elif snext == "file":
sfile.append(arg)
elif snext == "content":
content.append(arg)
elif snext == "source":
source.append(arg)
elif snext == "title":
title.append(arg)
elif snext == "tags":
2022-11-24 14:54:41 +01:00
'''if "," in arg:
2022-11-22 18:34:32 +01:00
for tag in arg.split(","):
name=ttb.get_name(arg)
if name != ".":
arg=name
tags.append(arg)
else:
name=ttb.get_name(arg)
2022-11-24 14:54:41 +01:00
print("name",name)
2022-11-22 18:34:32 +01:00
if name != ".":
2022-11-24 14:54:41 +01:00
arg=name'''
tags.append(arg)
2022-11-22 18:34:32 +01:00
else:
alle.append(arg)
# search for the right items
selection=[]
selection=self.sql_compare_list("*",alle,selection)
selection=self.sql_compare_list("HASH",shash,selection)
selection=self.sql_compare_list("CATEGORY",category,selection)
selection=self.sql_compare_list("FILE",sfile,selection)
selection=self.sql_compare_list("CONTENT",content,selection)
selection=self.sql_compare_list("SOURCE",source,selection)
selection=self.sql_compare_list("TITLE",title,selection)
selection=self.sql_compare_list("TAGS",tags,selection)
return self.select_index(selection,quiet)
2022-11-29 10:17:44 +01:00
def get_randhex(count=5):
2022-11-28 10:56:33 +01:00
randhex=""
for i in range(count):
randhex+=random.choice("0123456789abcdef")
return randhex
2022-11-23 23:00:08 +01:00
def add(args):
if len(args) >= 6:
tb.add_index(args[0],args[1],args[2],args[3],args[4],args[5])
return
n=0
2022-11-22 18:34:32 +01:00
for i in ["Filepath","Category","Title","Source","Tags","Content"]:
2022-11-23 23:00:08 +01:00
try:
print("{}: {}".format(i,args[n]))
except Exception:
if i == "Tags":
extra=" (Separate with ',')"
else:
extra=""
eingabe = input("Enter {}{}: ".format(i,extra))
if i in ["Category"] and not eingabe:
print("{} set to 'default'".format(i))
eingabe="default"
args.append(eingabe)
2022-11-22 18:34:32 +01:00
if i in ["Filepath"]:
2022-11-23 23:00:08 +01:00
if not args[n]:
2022-11-22 18:34:32 +01:00
print("{} must not be empty!".format(i))
return 1
else:
2022-11-23 23:00:08 +01:00
if not Path(args[n]).is_file():
2022-12-02 11:58:11 +01:00
print(" The file '{}' doesn't exist or is not a file!".format(args[n]))
2022-11-22 18:34:32 +01:00
return 1
2022-11-23 23:00:08 +01:00
n+=1
2022-12-01 18:20:05 +01:00
success=tb.add_index(args[0],args[1],args[2],args[3],args[4],args[5])
if success:
print("Added '{}'!".format(args[2]))
2022-11-22 18:34:32 +01:00
def check(args):
success=0
hash_list,temp_list=tb.check_index()
path_list=[]
hashcheck=pathcheck=True
verbose=False
for arg in args:
if arg == "-v":
verbose=True
elif arg == "-f":
hashcheck=False
elif arg == "-h":
pathcheck=False
if hash_list:
print("{} file{} faulty!".format(len(hash_list),"s are" if len(hash_list) > 1 else " is"))
success=-1
if verbose:
for tup in hash_list:
print("Title: ",tup[2])
print("\tCategory:",tup[4])
print("\tFilename:",tup[0])
for i in temp_list:
if not i in path_list:
path_list.append(i)
if path_list:
print("{} file{} missing!".format(len(path_list),"s are" if len(path_list) > 1 else " is"))
success=-1
if verbose:
for tup in path_list:
print("Title: ",tup[2])
print("\tCategory:",tup[4])
print("\tFilename:",tup[0])
if success >= 0:
print("Everything is good!")
if hash_list and hashcheck:
eingabe=input("Do you want to remove the faulty files? [y/N]: ")
if re.match('[yY]',eingabe):
print("Removing faulty files...")
repair(hash_list)
if path_list and pathcheck:
eingabe=input("Do you want to remove the orphaned entries? [Y/n]: ")
if not re.match('[nN]',eingabe):
print("Removing orphaned entries...")
repair(path_list)
def delete(args):
selection=search(args,True)
for sel in selection:
if sel[0] != ".":
try:
category=sel[4]
filename=sel[0]
os.remove("{}/{}/{}".format(ROOT_DIR,category,filename))
except Exception as e:
print(e)
print("Couldn't delete a file!")
return 1
tb.delete_index(sel)
2022-12-01 18:20:05 +01:00
print("Deleted '{}'!".format(sel[2]))
2022-11-22 18:34:32 +01:00
2022-11-24 23:40:18 +01:00
def help(args):
syntax=False
for arg in args:
if not syntax and not re.match('[mM]',arg):
2022-11-22 18:34:32 +01:00
print("SYNTAX: image-index <option> [args]")
2022-11-24 23:40:18 +01:00
syntax=True
if re.match('[aA].*',arg):
print("add:\tadds a new entry;\n\tInstant: image-index add <filepath> <category> <title> <source> <tags> <content>")
print("\tPrompt: image-index add")
print('EXAMPLES:\nimage-index add ~/Pictures/example.jpg "A Category" "Example file" "https://example.org" "Tag,Example,Some thing" "This is an example for the add option."')
print("image-index add ~/Videos/movie.mp4 (This will ask for the other options in a prompt)\n")
elif re.match('[mM].*',arg):
meta_help()
elif re.match('[cC].*',arg):
print("check:\tchecks the existence and correctness of all files in the index;\n\tSyntax: image-index check [options]")
print("\tOptions: -v: show every faulty/orphaned entry")
print("\t\t -f: check only if files exist (disables the other check)")
print("\t\t -h: check only if hashes are correct (disables the other check)\n")
elif re.match('[dD].*',arg):
print("delete:\tdeletes a file and entry based on a search query;\n\tInstant: image-index delete <words/filters>")
print("\tPrompt: image-index delete")
print("EXAMPLE:\nimage-index delete -t Example -g Tag Example -a .mp4 add\n")
elif re.match('[oO].*',arg):
print("open:\topens a file based on a search query in the standard app;\n\tInstant: image-index open <words/filters>")
print("\tPrompt: image-index open")
print("EXAMPLE:\nimage-index open example -s example.org -i an example\n")
elif re.match('[sS].*',arg):
2022-11-24 23:50:14 +01:00
print("show:\tsearches through the index and shows the matches;\n\tInstant: image-index show <words/filters>")
2022-11-24 23:40:18 +01:00
print("\tPrompt: image-index show")
2022-11-24 23:50:14 +01:00
print("FILTERS: -a: All types\n\t -c: Category\n\t -f: Filename\n\t -g: Tags")
print("\t -h: Hash\n\t -i: Content\n\t -s: Source\n\t -t: Title")
2022-11-24 23:40:18 +01:00
print("EXAMPLE:\nimage-index show example -c category\n")
elif re.match('[uU].*',arg):
print("update:\tchanges specific column based on a search query;\n\tInstant: image-index update <column> <updated_value> <words/filters>")
print("\tPrompt: image-index update")
print('EXAMPLES:\nimage-index update category "New Category" -t example')
print('image-index update Tags "Tag,Example,Test" -s https:// -a example')
2022-11-29 10:54:21 +01:00
print('image-index update title "Some new title" -g "some thing" -a an example')
print('SPECIAL EXAMPLES TAGS:\nimage-index update tags +New_tag,hello -g "some thing" (adds the tags "New_tag" and "hello")')
print('image-index update tags -Tag -t Example (removes the tag "Tag")\n')
2022-11-24 23:40:18 +01:00
if not args:
2022-11-29 10:54:21 +01:00
print("SYNTAX: image-index <option> [args]")
2022-11-22 18:34:32 +01:00
print("OPTIONS:\n\thelp:\tdisplays this text")
2022-11-29 11:04:42 +01:00
print("\t\tSyntax: image-index help [commands]")
2022-11-22 18:34:32 +01:00
print("\tmeta:\tdisplays help for the metadata tables")
2022-11-24 23:40:18 +01:00
print("\tadd:\tadds a new entry;\n\t\tSyntax: image-index add <filepath> <category> <title> <source> <tags> <content>")
2022-11-22 18:34:32 +01:00
print("\tcheck:\tchecks the existence and correctness of all files in the index;\n\t\tSyntax: image-index check [options]")
2022-11-24 23:40:18 +01:00
print("\tdelete:\tdeletes a file and entry based on a search query;\n\t\tSyntax: image-index delete <words/filters>")
print("\topen:\topens a file based on a search query in the standard app;\n\t\tSyntax: image-index open <words/filters>")
print("\tshow:\tsearches through the index and shows the matches;\n\t\tSyntax: image-index show <words/filters>")
print("\tupdate:\tchanges specific column based on a search query;\n\t\tSyntax: image-index update <column> <updated_value> <words/filters>")
2022-11-22 18:34:32 +01:00
def meta(args):
if len(args) == 0 or re.match('[hH].*',args[0]):
meta_help()
else:
if len(args) <= 1:
print("Options: Category, Tags")
args.append(input("Input one type to check from the list above: "))
command=args[0]
typ=args[1]
args=args[2:]
if re.match('[cC].*',command):
meta_check(typ,args)
elif re.match('[uU].*',command):
meta_update(typ,args)
def meta_check(typ,args):
if re.match('[cC].*',typ):
tres=ctb.check_index("CATEGORY")
elif re.match('[tT].*',typ):
tres=ttb.check_index("TAGS")
else:
print("No valid type specified!")
2022-12-01 18:20:05 +01:00
return False
2022-11-22 18:34:32 +01:00
if tres:
yas=True
print("Missing items:",','.join(tres))
eingabe=input("Do you want to add aliases to them?[Y/n]: ")
if re.match('[nN]',eingabe):
yas=False
print("yo")
for val in tres:
if yas:
eingabe=input("Enter Alias for {}: ".format(val.upper()))
else:
eingabe=""
if re.match('[cC].*',typ):
2022-12-02 11:58:11 +01:00
ctb.add_index(val,eingabe)
2022-11-22 18:34:32 +01:00
elif re.match('[tT].*',typ):
2022-12-02 11:58:11 +01:00
ttb.add_index(val,eingabe)
2022-12-01 18:20:05 +01:00
else:
print("Everything is good!")
2022-11-22 18:34:32 +01:00
def meta_update(typ,args):
if len(args) == 0:
args.append(input("Enter the alias to update: "))
args.append(input("Enter the updated alias: "))
elif len(args) == 1:
args.append(input("Enter the updated alias: "))
search=args[0]
update=args[1]
if re.match('[cC].*',typ):
sel_list=ctb.search_index(search)
for item in sel_list:
2022-11-24 14:54:41 +01:00
alias=ctb.get_alias(item[0])
2022-11-29 10:17:44 +01:00
success=ctb.update_index("ALIAS", update, "NAME", item[0])
2022-11-22 18:34:32 +01:00
elif re.match('[tT].*',typ):
sel_list=ttb.search_index(search)
for item in sel_list:
2022-11-24 14:54:41 +01:00
alias=ttb.get_alias(item[0])
2022-11-29 10:17:44 +01:00
success=ttb.update_index("ALIAS", update, "NAME", item[0])
2022-11-22 18:34:32 +01:00
else:
2022-11-24 14:54:41 +01:00
print("The first argument needs to be either 'Category' or 'Tags'!")
2022-11-22 18:34:32 +01:00
return 1
2022-11-29 10:17:44 +01:00
if item[0] != "." and success:
2022-11-24 14:54:41 +01:00
print("Updated {} to {}".format(alias,update))
2022-11-22 18:34:32 +01:00
def meta_help():
print("SYNTAX: image-index meta <option> [args]")
2022-11-23 23:00:08 +01:00
print("OPTIONS:\n\thelp:\tdisplays this text")
2022-11-22 18:34:32 +01:00
print("\tcheck:\tcheck which items don't have an entry yet;\n\t\tSyntax: image-index meta check <Category/Tags>")
print("\tupdate:\tchange an alias of one entry based on a search query;\n\t\tSyntax: image-index update <Category/Tags> [entry] [alias]")
2022-11-24 23:50:14 +01:00
print('\t\tExamples: image-index meta update tags Example "New alias"')
print('\t\t\t image-index meta update category "A Category" "Example Category"\n')
2022-11-22 18:34:32 +01:00
def sopen(args):
plat=sys.platform
selection=search(args,True)
for sel in selection:
if not sel[0] == ".":
filename=sel[0]
category=sel[4]
filepath="{}/{}/{}".format(ROOT_DIR,category,filename)
else:
continue
if plat.startswith('linux'):
subprocess.Popen([LINUX_APP_STARTER, filepath])
else:
os.startfile(filepath)
2022-11-23 23:00:08 +01:00
def update(args):
n=0
for i in ["column","updated string"]:
try:
2022-11-24 14:54:41 +01:00
trash=args[n]
2022-11-23 23:00:08 +01:00
except Exception as e:
eingabe=input("Enter {}: ".format(i))
args.append(eingabe)
n+=1
selection=search(args[n:],True)
typ=args[0]
update=args[1]
2022-11-22 18:34:32 +01:00
for sel in selection:
if sel[0] != ".":
2022-12-01 18:20:05 +01:00
n=0
for i in tb.collist:
if i.lower() == typ.lower():
old=sel[n]
else:
n+=1
2022-11-22 18:34:32 +01:00
tb.update_index(typ,update,sel)
2022-12-01 18:20:05 +01:00
if re.match('[tT][aA].*', typ) and re.match('[-+]', update[0]):
tags_list=[]
for tag in update[1:].split(","):
tags_list.append(tag)
tagstr=", ".join(tags_list)
if update[0] == "-":
print("Removed {}!".format(tagstr))
elif update[0] == "+":
print("Added {}!".format(tagstr))
else:
print("Updated {} to {}!".format(old,update))
2022-11-22 18:34:32 +01:00
def repair(err_list):
sel_list=[]
for i in err_list:
if not i in sel_list:
sel_list.append(i)
for tup in sel_list:
filename=tup[0]
category=tup[4]
filepath="{}/{}/{}".format(ROOT_DIR,category,filename)
if os.path.exists(filepath):
os.remove(filepath)
tb.delete_index(tup)
def search(args,quiet=False):
if len(args) == 0:
2022-11-24 23:50:14 +01:00
print("Separate the items with spaces.")
print("FILTERS: -a: All types\n\t -c: Category\n\t -f: Filename\n\t -g: Tags")
print("\t -h: Hash\n\t -i: Content\n\t -s: Source\n\t -t: Title")
2022-11-22 18:34:32 +01:00
args=input("Query: ")
if len(args) > 0:
res=tb.search_index(args.split(' '),quiet)
else:
print("\nQuery empty!")
return ["."]
else:
res=tb.search_index(args,quiet)
return res
def show(args):
tres=search(args,False)
if not tres[0] == ".":
for res in tres:
print("Title: ",res[2])
print("\tSource:\t ",res[3])
2022-11-24 14:54:41 +01:00
alias=ctb.get_alias(res[4])
if alias != ".":
print("\tCategory: {} ({})".format(alias,res[4]))
2022-11-22 18:34:32 +01:00
else:
print("\tCategory:",res[4])
print("\tFilename:",res[0])
print("\tHash:\t ",res[1])
tags_list=[]
for tag in res[5].split(","):
2022-12-01 18:20:05 +01:00
alias=ttb.get_alias(tag)
if alias != ".":
tags_list.append(alias)
2022-11-22 18:34:32 +01:00
print("\tTags:\t ",",".join(tags_list))
print("\tContent: ",res[6])
def main():
if len(sys.argv) <= 1 or re.match('[hH].*',sys.argv[1]):
2022-11-24 23:40:18 +01:00
help(sys.argv[2:])
2022-11-22 18:34:32 +01:00
else:
command=sys.argv[1]
args=[]
for i in sys.argv[2:]:
args.append(i)
if re.match('[aA].*',command):
2022-11-23 23:00:08 +01:00
add(args)
2022-11-22 18:34:32 +01:00
elif re.match('[mM].*',command):
meta(args)
elif re.match('[cC].*',command):
check(args)
elif re.match('[dD].*',command):
delete(args)
elif re.match('[oO].*',command):
sopen(args)
elif re.match('[sS].*',command):
show(args)
elif re.match('[uU].*',command):
update(args)
else:
print("No such option!")
tb.connection.close()
ctb.connection.close()
ttb.connection.close()
#input("Press return...")
if __name__ == "__main__":
filepath=CONFIG_DIR + '/index.db'
tb = filestable(filepath)
ctb = metatable("CATEGORY",filepath)
ttb = metatable("TAGS",filepath)
main()