From ed3df6b81a8c224e7a550c5c3fa8d2d761309f11 Mon Sep 17 00:00:00 2001
From: Michael Rodin <rodinmi@corvinianum.de>
Date: Sat, 12 Nov 2022 21:35:50 +0100
Subject: [PATCH] Initial commit

---
 .gitignore |  6 ++++
 func.py    | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 main.py    | 22 +++++++++++++
 3 files changed, 122 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 func.py
 create mode 100755 main.py

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e3e0132
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+/**
+
+!/.gitignore
+!/func.py
+!/index.db
+!/main.py
\ No newline at end of file
diff --git a/func.py b/func.py
new file mode 100644
index 0000000..fcd654f
--- /dev/null
+++ b/func.py
@@ -0,0 +1,94 @@
+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)
\ No newline at end of file
diff --git a/main.py b/main.py
new file mode 100755
index 0000000..cb95dbd
--- /dev/null
+++ b/main.py
@@ -0,0 +1,22 @@
+#!/bin/python3
+import sys,os
+os.chdir("ii-py")
+from func import *
+from vars import *
+
+def main():
+    if len(sys.argv) > 1:
+        for i in sys.argv:
+            print("Arg:" + i)
+
+    #tb.add_index("/home/marcel/Downloads/froggy.jpg","Tiere","Fifel","https://youtu.be","Tier,Meme_template","Ein sitzender Frosch. Ist er nicht süß?")
+    tb.search_index()
+
+
+if __name__ == "__main__":
+    filepath=CONFIG_DIR + '/index.db'
+    tb = filestable(filepath)
+    mtb = metatable(filepath)
+    main()
+    print("Stopping")
+    tb.connection.close()