# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mobius Forensic Toolkit
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022 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 struct
import traceback
import mobius
from . import decoder_share_metadata

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Entry
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Entry (object):

  # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  # @brief initialize object
  # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  def __init__ (self):
    self.path = None
    self.size = None
    self.title = None
    self.artist = None
    self.album = None
    self.category = None
    self.year = None
    self.vidinfo = None
    self.language = None
    self.url = None
    self.comment = None
    self.download_completed_time = None
    self.flag_shared = True
    self.flag_corrupted = False
    self.flag_completed = False

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief decrypt data
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decrypt (data, seed):
  out = b''
  for c in data:
    out += bytes ([c ^ (seed >> 8)])
    seed = ((c + seed) * 23219 + 36126) & 0xffff
  return out

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief get file type according to amime field
# @see const_ares.pas and helper_mimetypes.pas
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def get_file_type (mime):
  return {
      1 : 'Audio',
      2 : 'Audio',
      3 : 'Software',
      4 : 'Audio',
      5 : 'Video',
      6 : 'Document',
      7 : 'Image'}.get (mime, 'Other')

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Decode file
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode (f):
  try:
    return decode_file (f) 
  except Exception as e:
    mobius.core.logf ('WRN %s %s' % (str (e), traceback.format_exc ()))

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Decode data from ShareL.dat
# @see get_cached_metas (helper_library_db.pas)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode_file (f):

  # try to open file
  reader = f.new_reader ()
  if not reader:
    return

  # decode header
  decoder = mobius.decoder.data_decoder (reader)
  signature = decoder.get_string_by_size (14)

  if signature != '__ARESDB1.04L_':
    return

  # get ShareL.dat metadata
  sharel_path = f.path.replace ('/', '\\')
  sharel_creation_time = f.creation_time
  sharel_last_modification_time = f.modification_time

  # decode entries
  pos = decoder.tell ()
  size = decoder.get_size ()
  entries = []

  while pos < size:

    # entry header
    enc_data = decoder.get_bytearray_by_size (47)
    pos += 47
    data = decrypt (enc_data, 13871)

    hash_sha1, mime, e_size, param1, param2, param3, data_size = struct.unpack ('<20sB4xQIIIH', data)

    entry = Entry ()
    entry.sharel_path = sharel_path
    entry.sharel_creation_time = sharel_creation_time
    entry.sharel_last_modification_time = sharel_last_modification_time
    entry.filetype = get_file_type (mime)
    entry.size = e_size
    entry.hash_sha1 = mobius.encoder.hexstring (hash_sha1)

    # entry metadata
    if data_size > 0:
      enc_data = decoder.get_bytearray_by_size (data_size)
      data = decrypt (enc_data, 13872)
      pos += data_size

      metadata = decoder_share_metadata.decode (data)
      for var, value in metadata.items ():
        setattr (entry, var, value)

      # entry is downloaded if download completed time is set
      entry.flag_downloaded = bool (entry.download_completed_time)

      # ShareL.dat entries are completed
      entry.flag_completed = True

      # set name
      entry.name = entry.path.rsplit ('\\')[-1]

    # add entry
    entries.append (entry)

  return entries
