# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mobius Forensic Toolkit
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019 Eduardo Aguiar
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import os
import os.path
import urlparse
import urllib
import mobius

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Convert URL to path
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def url_to_path (url):
  path = urllib.unquote_plus (urlparse.urlsplit (url)[2])

  if isinstance (path, str):
    try:
      path = unicode (path, 'utf-8')
    except UnicodeDecodeError:
      path = unicode (path, 'cp1252', 'ignore')

  return path.encode ('utf-8')

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Set file handled
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def file_set_handled (item, f):

  # create file reader
  if not f:
    return

  reader = f.new_reader ()
  if not reader:
    return

  # calculate hash sha2-512
  h = mobius.crypt.hash ('sha2_512')
  data = reader.read (65536)

  while data:
    h.update (data)
    data = reader.read (65536)

  # add to kff file
  case = item.case
  path = case.create_path (os.path.join ('hashset', '%04d-handled.ignore' % item.uid))

  fp = open (path, 'a')
  fp.write ('%s\n' % h.get_hex_digest ())
  fp.close ()
  
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Clear list of handled files
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def file_clear_handled (item):
  path = item.case.get_path (os.path.join ('hashset', '%04d-handled.ignore' % item.uid))

  if os.path.exists (path):
    os.remove (path)
    
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Get folder's children
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def folder_get_children (folder):
  children = []
  
  try:
    children = folder.get_children ()
  except Exception, e:
    mobius.core.log ('pymobius.util.folder_get_children (%s): %s' % (folder.path, e))

  return children
