# Path: hashview/wordlists/forms.py
# class WordlistsForm(FlaskForm):
#     name = StringField('Name', validators=([DataRequired()]))
#     wordlist = FileField('Upload Wordlist')
#     submit = SubmitField('upload')      
# 
# Path: hashview/models.py
# class Tasks(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(100), nullable=False)
#     hc_attackmode = db.Column(db.String(25), nullable=False) # dictionary, mask, bruteforce, combinator
#     owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
#     wl_id = db.Column(db.Integer)
#     rule_id = db.Column(db.Integer)
#     hc_mask = db.Column(db.String(50))
# 
# class Wordlists(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(256), nullable=False)
#     last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
#     owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
#     type = db.Column(db.String(7))                          # Dynamic or Static
#     path = db.Column(db.String(245), nullable=False)
#     size = db.Column(db.BigInteger, nullable=False)
#     checksum = db.Column(db.String(64), nullable=False)
# 
# class Users(db.Model, UserMixin):
#     id = db.Column(db.Integer, primary_key=True)
#     first_name = db.Column(db.String(20), nullable=False)
#     last_name = db.Column(db.String(20), nullable=False)
#     email_address = db.Column(db.String(50), unique=True, nullable=False)
#     password = db.Column(db.String(60), nullable=False)
#     admin = db.Column(db.Boolean, nullable=False, default=False)
#     pushover_app_id = db.Column(db.String(50), nullable=True)
#     pushover_user_key = db.Column(db.String(50), nullable=True)
#     wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
#     rules = db.relationship('Rules', backref='owner', lazy=True)
#     jobs = db.relationship('Jobs', backref='owner', lazy=True)
#     tasks = db.relationship('Tasks', backref='owner', lazy=True)
#     taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
# 
#     def get_reset_token(self, expires_sec=1800):
#         s = Serializer(Config.SECRET_KEY, expires_sec)
#         return s.dumps({'user_id': self.id}).decode('utf-8')
# 
#     @staticmethod
#     def verify_reset_token(token):
#         s = Serializer(Config.SECRET_KEY)
#         try:
#             user_id = s.loads(token)['user_id']
#         except:
#             return None     
#         return Users.query.get(user_id)
# 
# Path: hashview.py
# def data_retention_cleanup():
# 
# Path: hashview/utils/utils.py
# def save_file(path, form_file):
#     random_hex = secrets.token_hex(8)
#     file_name = random_hex + os.path.split(form_file.filename)[0] + '.txt'
#     file_path = os.path.join(current_app.root_path, path, file_name)
#     form_file.save(file_path)
#     return file_path
# 
# def get_linecount(filepath):
#     
#     with open(filepath, 'rb') as fp:
#         c_generator = _count_generator(fp.raw.read)
#         count = sum(buffer.count(b'\n') for buffer in c_generator)
#         return count + 1
# 
# def get_filehash(filepath):
#     sha256_hash = hashlib.sha256()
#     with open(filepath,"rb") as f:
#         # Read and update hash string value in blocks of 4K
#         for byte_block in iter(lambda: f.read(4096),b""):
#             sha256_hash.update(byte_block)
#     return sha256_hash.hexdigest()
# 
# def update_dynamic_wordlist(wordlist_id):
#     wordlist = Wordlists.query.get(wordlist_id)
#     hashes = Hashes.query.filter_by(cracked=True).distinct('plaintext')
# 
#     # Do we delete the original file, or overwrite it?
#     # if we overwrite, what happens if the new content has fewer lines than the previous file.
#     # would this even happen? In most/all cases there will be new stuff to add.
#     # is there a file lock on a wordlist when in use by hashcat? Could we just create a temp file and replace after generation?
#     # Open file
#     file = open(wordlist.path, 'wt')
#     for entry in hashes:
#         file.write(str(bytes.fromhex(entry.plaintext).decode('latin-1')) + '\n')
#     file.close()
# 
#     # update line count
#     wordlist.size = get_linecount(wordlist.path)
#     # update file hash
#     wordlist.checksum = get_filehash(wordlist.path)
#     # update last update
#     wordlist.last_updated = datetime.today()
#     db.session.commit()


from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from hashview.wordlists.forms import WordlistsForm
from hashview.models import Tasks, Wordlists, Users
from hashview import db
from hashview.utils.utils import save_file, get_linecount, get_filehash, update_dynamic_wordlist

wordlists = Blueprint('wordlists', __name__)

@wordlists.route("/wordlists", methods=['GET'])
@login_required
def wordlists_list():
    static_wordlists = Wordlists.query.filter_by(type='static').all()
    dynamic_wordlists = Wordlists.query.filter_by(type='dynamic').all()
    wordlists = Wordlists.query.all()
    tasks = Tasks.query.all()

# Path: hashview/wordlists/forms.py
# class WordlistsForm(FlaskForm):
#     name = StringField('Name', validators=([DataRequired()]))
#     wordlist = FileField('Upload Wordlist')
#     submit = SubmitField('upload')      
# 
# Path: hashview/models.py
# class Tasks(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(100), nullable=False)
#     hc_attackmode = db.Column(db.String(25), nullable=False) # dictionary, mask, bruteforce, combinator
#     owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
#     wl_id = db.Column(db.Integer)
#     rule_id = db.Column(db.Integer)
#     hc_mask = db.Column(db.String(50))
# 
# class Wordlists(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(256), nullable=False)
#     last_updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
#     owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
#     type = db.Column(db.String(7))                          # Dynamic or Static
#     path = db.Column(db.String(245), nullable=False)
#     size = db.Column(db.BigInteger, nullable=False)
#     checksum = db.Column(db.String(64), nullable=False)
# 
# class Users(db.Model, UserMixin):
#     id = db.Column(db.Integer, primary_key=True)
#     first_name = db.Column(db.String(20), nullable=False)
#     last_name = db.Column(db.String(20), nullable=False)
#     email_address = db.Column(db.String(50), unique=True, nullable=False)
#     password = db.Column(db.String(60), nullable=False)
#     admin = db.Column(db.Boolean, nullable=False, default=False)
#     pushover_app_id = db.Column(db.String(50), nullable=True)
#     pushover_user_key = db.Column(db.String(50), nullable=True)
#     wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
#     rules = db.relationship('Rules', backref='owner', lazy=True)
#     jobs = db.relationship('Jobs', backref='owner', lazy=True)
#     tasks = db.relationship('Tasks', backref='owner', lazy=True)
#     taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
# 
#     def get_reset_token(self, expires_sec=1800):
#         s = Serializer(Config.SECRET_KEY, expires_sec)
#         return s.dumps({'user_id': self.id}).decode('utf-8')
# 
#     @staticmethod
#     def verify_reset_token(token):
#         s = Serializer(Config.SECRET_KEY)
#         try:
#             user_id = s.loads(token)['user_id']
#         except:
#             return None     
#         return Users.query.get(user_id)
# 
# Path: hashview.py
# def data_retention_cleanup():
# 
# Path: hashview/utils/utils.py
# def save_file(path, form_file):
#     random_hex = secrets.token_hex(8)
#     file_name = random_hex + os.path.split(form_file.filename)[0] + '.txt'
#     file_path = os.path.join(current_app.root_path, path, file_name)
#     form_file.save(file_path)
#     return file_path
# 
# def get_linecount(filepath):
#     
#     with open(filepath, 'rb') as fp:
#         c_generator = _count_generator(fp.raw.read)
#         count = sum(buffer.count(b'\n') for buffer in c_generator)
#         return count + 1
# 
# def get_filehash(filepath):
#     sha256_hash = hashlib.sha256()
#     with open(filepath,"rb") as f:
#         # Read and update hash string value in blocks of 4K
#         for byte_block in iter(lambda: f.read(4096),b""):
#             sha256_hash.update(byte_block)
#     return sha256_hash.hexdigest()
# 
# def update_dynamic_wordlist(wordlist_id):
#     wordlist = Wordlists.query.get(wordlist_id)
#     hashes = Hashes.query.filter_by(cracked=True).distinct('plaintext')
# 
#     # Do we delete the original file, or overwrite it?
#     # if we overwrite, what happens if the new content has fewer lines than the previous file.
#     # would this even happen? In most/all cases there will be new stuff to add.
#     # is there a file lock on a wordlist when in use by hashcat? Could we just create a temp file and replace after generation?
#     # Open file
#     file = open(wordlist.path, 'wt')
#     for entry in hashes:
#         file.write(str(bytes.fromhex(entry.plaintext).decode('latin-1')) + '\n')
#     file.close()
# 
#     # update line count
#     wordlist.size = get_linecount(wordlist.path)
#     # update file hash
#     wordlist.checksum = get_filehash(wordlist.path)
#     # update last update
#     wordlist.last_updated = datetime.today()
#     db.session.commit()


# Path: hashview/wordlists/routes.py
from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from hashview.wordlists.forms import WordlistsForm
from hashview.models import Tasks, Wordlists, Users
from hashview import db
from hashview.utils.utils import save_file, get_linecount, get_filehash, update_dynamic_wordlist


wordlists = Blueprint('wordlists', __name__)

@wordlists.route("/wordlists", methods=['GET'])
@login_required
def wordlists_list():
    static_wordlists = Wordlists.query.filter_by(type='static').all()
    dynamic_wordlists = Wordlists.query.filter_by(type='dynamic').all()
    wordlists = Wordlists.query.all()
    tasks = Tasks.query.all()

    users = Users.query.all()