Last active
November 12, 2019 20:06
-
-
Save maxchehab/2c516aa7b1d0ade925cbc7941ccca83a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"encoding/json" | |
"fmt" | |
"log" | |
"os/user" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
type Message struct { | |
ID string `json:"id"` | |
Date int64 `json:"date"` | |
FromMe bool `json:"fromMe"` | |
From *Handle `json:"-"` | |
Text string `json:"text"` | |
} | |
type Handle struct { | |
ID int `json:"id"` | |
Name string `json:"name"` | |
} | |
var handlerMap = make(map[int]*Handle) | |
var database *sql.DB | |
func scanMessage(row *sql.Rows) Message { | |
var msg Message | |
var handleID int | |
row.Scan(&msg.ID, &msg.Date, &msg.FromMe, &handleID, &msg.Text) | |
msg.From = handleById(handleID) | |
return msg | |
} | |
func handleById(id int) *Handle { | |
if handlerMap[id] != nil { | |
return handlerMap[id] | |
} | |
query := fmt.Sprintf(`SELECT ROWID, id FROM handle WHERE ROWID = '%v'`, id) | |
rows, err := database.Query(query) | |
if err != nil { | |
log.Panic(err) | |
} | |
defer rows.Close() | |
var handle Handle | |
rows.Scan(&handle.ID, &handle.Name) | |
handlerMap[handle.ID] = &handle | |
return &handle | |
} | |
func getMessages() (messages []Message) { | |
query := fmt.Sprintln(`SELECT guid, date, is_from_me, handle_id, text FROM message ORDER BY date DESC LIMIT 5`) | |
rows, err := database.Query(query) | |
if err != nil { | |
log.Panic(err) | |
} | |
defer rows.Close() | |
for rows.Next() { | |
message := scanMessage(rows) | |
messages = append(messages, message) | |
} | |
return | |
} | |
func initDB(dir string) { | |
var err error | |
database, err = sql.Open("sqlite3", dir) | |
if err != nil { | |
log.Panic(err) | |
} | |
} | |
func homeDir() string { | |
usr, err := user.Current() | |
if err != nil { | |
log.Fatal(err) | |
} | |
return usr.HomeDir | |
} | |
func main() { | |
dir := fmt.Sprintf("%s/Library/Messages/chat.db", homeDir()) | |
initDB(dir) | |
messages := getMessages() | |
jsonb, _ := json.MarshalIndent(messages, "", " ") | |
fmt.Println(string(jsonb)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment