#!/usr/bin/env python
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# 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 pymobius.p2p.bittorrent.decoder_btencode
import datetime

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Generic dataholder
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class dataholder (object):
  pass

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief get data as UNIX datetime
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def get_unix_datetime (timestamp):

  if timestamp > 0:
    delta = datetime.timedelta (seconds=timestamp)
    date = datetime.datetime (1970, 1, 1, 0, 0, 0) + delta
  else:
    date = None

  return date

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Decode data from BT *.fastresume file
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode (f):

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

  # decode BTEncode data
  bt_data = reader.read ()
  metadata = pymobius.p2p.bittorrent.decoder_btencode.decode (bt_data)

  # create data object
  data = dataholder ()
  data.metadata = metadata
  
  # attributes
  data.added_time = get_unix_datetime (metadata.pop ('added_time', 0))
  data.completed_time = get_unix_datetime (metadata.pop ('completed_time', 0))
  data.last_seen_complete = get_unix_datetime (metadata.pop ('last_seen_complete', 0))
  
  # files
  data.files = []
  file_sizes = metadata.pop ('file sizes', [])

  for idx, name in enumerate (metadata.pop ('mapped_files', [])):
    f = dataholder ()
    f.name = name
    
    if idx < len (file_sizes):
      f.size = file_sizes[idx][0]
      f.last_modification_time = get_unix_datetime (file_sizes[idx][1])
    else:
      f.size = -1
      f.last_modification_time = None
      
    data.files.append (f)

  # peers
  data.peers = []

  return data
