# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# 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.util
import pymobius.app.gecko
import sqlite3
import mobius
import os

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Load data from places.sqlite file
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode (f):

  data = pymobius.Data ()
  data.history = []

  path = pymobius.app.gecko.retrieve_db_file (f)

  if path:
    db = sqlite3.connect (path)
    decode_places (db, data)
    db.close ()

    os.remove (path)
    f.set_handled ()

  # return data object
  return data

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Retrieve data from places.sqlite table
# Tested versions: 14.0.1, 45.0.1, 53.0.2, 59.0.2
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode_places (db, data):
  cursor = db.cursor ()
  
  stmt = '''
       SELECT p.id,
              p.url,
              p.title,
              p.typed,
              h.visit_date,
              h.visit_type
         FROM moz_places p, moz_historyvisits h
        WHERE h.place_id = p.id
     ORDER BY h.visit_date'''

  for row in cursor.execute (stmt):
    entry = pymobius.Data ()
    entry.id = row[0]
    entry.url = row[1]
    entry.title = row[2]
    entry.typed = row[3] == 1
    entry.timestamp = mobius.datetime.new_datetime_from_unix_timestamp (row[4] // 1000000)
    entry.visit_type = row[5]

    data.history.append (entry)
