extraction.go 2.3 KB
package main

import (
	"io"
	"io/ioutil"
	"net/http"

	"github.com/jmoiron/sqlx"
)

func (app *App) PostExtractions(w http.ResponseWriter, r *http.Request) {
	userNo := r.Context().Value(PropUserNo).(uint64)
	r.ParseMultipartForm(32 << 20)

	form, _, err := r.FormFile("file")
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Unknown error")
		return
	}

	defer form.Close()

	file, err := ioutil.TempFile("", "db")
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Unknown error")
		return
	}
	defer file.Close()

	_, err = io.Copy(file, form)
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Unknown error")
		return
	}

	db, err := sqlx.Connect("sqlite3", file.Name())
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Could not open db file")
		return
	}
	defer db.Close()

	tx, err := app.db.Beginx()
	if err != nil {
		WriteError(w, http.StatusInternalServerError, "Unknown error")
		return
	}

	res, _ := tx.Exec("INSERT INTO extractions (`owner`) VALUES (?)", userNo)
	extNo, _ := res.LastInsertId()

	rows, err := db.Queryx("SELECT * FROM calllog")
	if err == nil {
		for rows.Next() {
			vals, _ := rows.SliceScan()
			tx.Exec("INSERT INTO calls VALUES (?, ?, ?, ?, ?, ?, ?)", append([]interface{}{extNo}, vals...)...)
		}
	}

	sql := `SELECT
		a.packagename, a.name, a.version, a.wifiusage, a.cellularusage,
		u.lasttimeused, u.totaltimeforeground
	FROM AppInfo a JOIN AppUsageYear u ON a.packagename=u.packagename`
	rows, err = db.Queryx(sql)
	if err == nil {
		for rows.Next() {
			vals, _ := rows.SliceScan()
			tx.Exec("INSERT INTO apps VALUES (?, ?, ?, ?, ?, ?, ?, ?)", append([]interface{}{extNo}, vals...)...)
		}
	}

	rows, err = db.Queryx("SELECT mid, type, address, body, date FROM sms")
	if err == nil {
		for rows.Next() {
			vals, _ := rows.SliceScan()
			tx.Exec("INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?)", append([]interface{}{extNo}, vals...)...)
		}
	}

	rows, err = db.Queryx("SELECT PID, UID, PPID, STIME, TIME, CMD FROM process")
	if err == nil {
		for rows.Next() {
			vals, _ := rows.SliceScan()
			tx.Exec("INSERT INTO processes VALUES (?, ?, ?, ?, ?, ?, ?)", append([]interface{}{extNo}, vals...)...)
		}
	}

	tx.Commit()

	w.Write([]byte("success"))
}