image-index-py/main.py

221 lines
7.5 KiB
Python
Executable file

#!/bin/python3
import sys,os,re,subprocess
from func import *
from config import *
def add():
args=[]
for i in ["Filepath","Category","Title","Source","Tags","Content"]:
eingabe = input("Enter {}: ".format(i))
if i in ["Filepath"] and not eingabe:
print("{} has to not be empty!".format(i))
return 1
if i in ["Category"] and not eingabe:
print("{} set to 'default'".format(i))
eingabe="default"
args.append(eingabe)
tb.add_index(args[0],args[1],args[2],args[3],args[4],args[5])
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)
def help():
print("SYNTAX:\n\t'image-index <option> [args]' executes the command")
print("\nOPTIONS:\n\thelp:\tdisplays this prompt")
#print("\tmeta:\tdisplays help for the metadata thing")
print("\tadd:\tadds a new entry;\n\t\tInstant: image-index add <filepath> <category> <title> <source> <tags> <content>")
print("\t\tPrompt: image-index add")
print("\tcheck:\tchecks the existence and correctness of all files in the index;\n\t\tSyntax: image-index check [options]")
print("\t\tOptions: -v: show every faulty/orphaned entry")
print("\t\t\t -f: check only if files exist (disables the other check)")
print("\t\t\t -h: check only if hashes are correct (disables the other check)")
print("\tdelete:\tdeletes a file and entry based on a search query;\n\t\tInstant: image-index delete <words/filters>")
print("\t\tPrompt: image-index delete")
print("\topen:\topens a file based on a search query in the standard app;\n\t\tInstant: image-index open <words/filters>")
print("\t\tPrompt: image-index open")
print("\tshow:\tsearches through the index and shows the matches (use prompt for list of filters);\n\t\tInstant: image-index show <words/filters>")
print("\t\tPrompt: image-index show")
print("\tupdate:\tchanges specific column based on a search query;\n\t\tInstant: image-index update <column> <updated_value> <words/filters>")
print("\t\tPrompt: image-index update")
def meta(args):
command=args[0]
args=args[1:]
def open(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)
def update(args):
if len(args) > 2:
typ=args[0]
update=args[1]
args=args[2:]
selection=search(args,True)
elif len(args) == 2:
typ=args[0]
update=args[1]
selection=search([],True)
elif len(args) == 1:
typ=args[0]
update=input("Enter the updated string: ")
selection=search([],True)
elif len(args) < 1:
typ=input("Enter the column: ")
update=input("Enter the update: ")
selection=search([],True)
for sel in selection:
if sel[0] != ".":
tb.update_index(typ,update,sel)
def repair(err_list):
sel_list=[]
for i in err_list:
print(i)
if not i in sel_list:
sel_list.append(i)
for tup in sel_list:
filepath="{}/{}/{}".format(ROOT_DIR,tup[4],tup[0])
if os.path.exists(filepath):
os.remove(filepath)
tb.delete_index(tup)
def search(args,quiet=False):
if len(args) == 0:
print("Separate the items with spaces ( )")
print("FILTERS: -a: All types")
print("\t -c: Category")
print("\t -f: Filename")
print("\t -g: Tags")
print("\t -h: Hash")
print("\t -i: Content")
print("\t -s: Source")
print("\t -t: Title")
args=input("Query: ")
if len(args) > 0:
res=tb.search_index(args.split(' '),quiet)
else:
print("\nQuery empty!")
return ["."]
else:
tres=tb.search_index(args,quiet)
return tres
def show(args):
tres=search(args,False)
if not tres[0] == ".":
for res in tres:
print("Title: ",res[2])
print("\tSource:\t ",res[3])
print("\tCategory:",res[4])
print("\tFilename:",res[0])
print("\tHash:\t ",res[1])
print("\tTags:\t ",res[5])
print("\tContent: ",res[6])
def main():
if len(sys.argv) <= 1 or re.match('[hH].*',sys.argv[1]):
help()
else:
command=sys.argv[1]
args=[]
for i in sys.argv[2:]:
args.append(i)
if re.match('[aA].*',command):
if len(sys.argv) == 2:
add()
elif len(sys.argv) >= 8:
tb.add_index(args[0],args[1],args[2],args[3],args[4],args[5])
else:
print("Not enough arguments!")
return
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):
open(args)
elif re.match('[sS].*',command):
show(args)
elif re.match('[uU].*',command):
update(args)
else:
print("No such option!")
tb.connection.close()
mtb.connection.close()
#input("Press return...")
if __name__ == "__main__":
filepath=CONFIG_DIR + '/index.db'
tb = filestable()
mtb = metatable()
main()