# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# 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 sqlite3
import mobius

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

  # create data object
  data = pymobius.Data ()
  data.cookies = []
  
  # decode
  db = sqlite3.connect (path)
  db.text_factory = str
  decode_cookies (db, data)
  db.close ()

  # return data object
  return data

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Retrieve data from cookies.sqlite table
# Tested versions: 14.0.1, 45.0.1, 50.0.2, 53.0.2, 59.0.2
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode_cookies (db, data):
  cursor = db.cursor ()

  # check if column "basedomain" exists
  column_names = set ([row[1].lower () for row in cursor.execute ('PRAGMA table_info (moz_cookies)')])

  if 'basedomain' in column_names:
    stmt = '''
       SELECT id,
              basedomain,
              name,
              value,
              lastaccessed,
              creationtime
         FROM moz_cookies'''
         
  else:
    stmt = '''
       SELECT id,
              NULL,
              name,
              value,
              lastaccessed,
              0
         FROM moz_cookies'''

  # do query
  cursor = db.cursor ()

  # process rows
  for row in cursor.execute (stmt):
    entry = pymobius.Data ()
    entry.id = row[0]
    entry.domain = row[1]
    entry.name = row[2]
    entry.value = row[3]
    entry.last_accessed_time = mobius.datetime.new_datetime_from_unix_timestamp (row[4] // 1000000)
    entry.creation_time = mobius.datetime.new_datetime_from_unix_timestamp (row[5] // 1000000)

    data.cookies.append (entry)
