19 "go.mau.fi/whatsmeow/store/sqlstore"
20 waLog "go.mau.fi/whatsmeow/util/log"
24 // whatsappImportMark marks history in the first line of a batch.
25 whatsappImportMark = " (imported)"
27 // whatsappImportBytes limits one export's uncompressed chat text.
28 whatsappImportBytes = 64 << 20
32 whatsappImportStart = regexp.MustCompile(`^\[(\d{2}/\d{2}/\d{4}, \d{2}:\d{2}:\d{2})\] ([^\r\n]+?): ?(.*)$`)
33 whatsappImportHeader = regexp.MustCompile(`^\[WhatsApp\] (.*), (?:group|private chat) ([^ ,]+), [A-Za-z]+ (\d{4}-\d{2}-\d{2})$`)
34 whatsappImportUnknown = regexp.MustCompile(`^\[WhatsApp\] (.*), [A-Za-z]+ (\d{4}-\d{2}-\d{2})$`)
37 // whatsappImport runs the offline import command. It holds the same token lock
38 // as the daemon and probe, even for a plan. The plan reads no credentials for a
39 // model and makes no network call. Only a completed rebuild replaces the agent
40 // directory. Unfinished subagents and pending target deliveries prevent either
42 func whatsappImport(ctx context.Context, args []string, out io.Writer) (err error) {
43 options, err := whatsappImportParse(args)
45 return fmt.Errorf("parse import arguments: %w", err)
50 return fmt.Errorf("find import data directory: %w", err)
53 tokens, err := lockTokens(dir)
55 return fmt.Errorf("lock import tokens: %w", err)
59 closeErr := tokens.Close()
61 err = errors.Join(err, fmt.Errorf("close import token lock: %w", closeErr))
65 root := filepath.Join(dir, "agent")
66 agent, err := whatsappImportAgent(root, options.agent)
68 return fmt.Errorf("select import agent: %w", err)
71 err = whatsappImportIdle(root, agent)
73 return fmt.Errorf("check import work: %w", err)
76 old, err := rebuildReadLog(ctx, agent.dir)
78 return fmt.Errorf("read import log: %w", err)
81 var rootLog []DatedMessage
83 if agent.dir != root {
84 rootLog, err = rebuildReadLog(ctx, root)
86 return fmt.Errorf("read root import history: %w", err)
90 names, owner, err := whatsappImportNames(ctx, dir)
92 return fmt.Errorf("read import names: %w", err)
95 plan, err := whatsappImportPlan(ctx, options.paths, old, rootLog, names, owner, time.Local)
97 return fmt.Errorf("plan import: %w", err)
100 plan.agent = agent.config.Name
101 err = plan.Write(out)
103 return fmt.Errorf("write import plan: %w", err)
106 if options.planOnly || len(plan.added) == 0 {
110 // An existing agent is required so that a failed import never creates
111 // or changes the original agent's configuration.
112 _, err = os.Stat(filepath.Join(agent.dir, "config.json"))
114 return fmt.Errorf("read agent config: %w", err)
117 config, err := loadConfig(dir)
119 return fmt.Errorf("load import configuration: %w", err)
122 address, auth, err := modelEndpoint(config, dir)
124 return fmt.Errorf("select import endpoint: %w", err)
127 usage, err := os.CreateTemp(dir, ".import-usage-*.jsonl")
129 return fmt.Errorf("create import usage: %w", err)
132 usagePath := usage.Name()
134 closeErr := os.Remove(usagePath)
136 err = errors.Join(err, fmt.Errorf("remove import usage: %w", closeErr))
142 return fmt.Errorf("close import usage: %w", err)
145 client := newModelClient(address, auth, agent.CacheKey(), usagePath)
146 backup, err := rebuild(ctx, agent, plan.added, client, newCompactor(client, agent.Prompt, config.Compactor, agent.Tools()), out)
148 return fmt.Errorf("rebuild imported memory: %w", err)
151 _, err = fmt.Fprintf(out, "import complete: backup %s\n", backup)
153 return fmt.Errorf("write import result: %w", err)
159 // WhatsAppImportPlan holds the new chat-day batches and the size of the merged
160 // log. Its estimate uses the measured cost of 1.3 calls per message, not a
161 // promise about a particular export or compaction retry.
162 type WhatsAppImportPlan struct {
164 cutoffs map[string]time.Time
176 // Write prints the plan without chat text or the owner's profile name.
177 func (p WhatsAppImportPlan) Write(out io.Writer) error {
178 cutoff := "none (no live WhatsApp batch)"
179 if !p.cutoff.IsZero() {
180 cutoff = p.cutoff.Format(time.RFC3339)
184 if !p.first.IsZero() {
185 dateRange = p.first.Format(time.RFC3339) + " to " + p.last.Format(time.RFC3339)
188 owner := "known (mapped to You)"
190 owner = "unknown (sender names kept as written)"
193 _, err := fmt.Fprintf(out, "agent: %s\nchats: %d\n", p.agent, len(p.chats))
195 return fmt.Errorf("write import plan: %w", err)
198 for _, chat := range p.chats {
200 cutoff, found := p.cutoffs[chat]
202 line += " (cutoff: " + cutoff.Format(time.RFC3339) + ")"
205 _, err = fmt.Fprintln(out, line)
207 return fmt.Errorf("write import plan: %w", err)
211 estimate := 1.3 * float64(p.messages)
212 if len(p.added) == 0 {
217 fmt.Sprintf("batches: %d (%d chat-days skipped)", len(p.added), p.skipped),
218 "dates: " + dateRange,
221 fmt.Sprintf("bytes: %d (new batch text)", p.bytes),
222 fmt.Sprintf("messages: %d (merged log)", p.messages),
223 fmt.Sprintf("estimated calls: %.0f (about 1.3 per message, limit %d)", estimate, rebuildCallLimit),
226 _, err = io.WriteString(out, strings.Join(lines, "\n")+"\n")
228 return fmt.Errorf("write import plan: %w", err)
234 // WhatsAppImportOptions selects the target, exports, and plan-only mode.
235 type WhatsAppImportOptions struct {
241 // whatsappImportParse accepts GNU-style flags, including --agent=NAME and --
242 // before paths that start with a dash.
243 func whatsappImportParse(args []string) (WhatsAppImportOptions, error) {
244 var options WhatsAppImportOptions
247 for i := 0; i < len(args); i++ {
250 case flags && arg == "--":
252 case flags && arg == "-n":
253 options.planOnly = true
254 case flags && (arg == "--agent" || strings.HasPrefix(arg, "--agent=")):
255 _, name, found := strings.Cut(arg, "=")
259 return options, errors.New("--agent needs a child name")
266 return options, errors.New("--agent needs a child name")
270 case flags && strings.HasPrefix(arg, "-"):
271 return options, fmt.Errorf("unknown import flag %q", arg)
273 options.paths = append(options.paths, arg)
277 if len(options.paths) == 0 {
278 return options, errors.New("usage: onechat import [-n] [--agent NAME] ZIP [ZIP...]")
284 // whatsappImportAgent selects the root or an existing direct child without
285 // creating a directory or config. A root without a config can have a plan,
286 // using the default name.
287 func whatsappImportAgent(root, name string) (*Agent, error) {
288 _, err := os.Stat(filepath.Join(root, "config.json"))
289 if errors.Is(err, os.ErrNotExist) && name == "" {
290 var config AgentConfig
292 config, err = defaultAgentConfig()
294 return nil, fmt.Errorf("read default import agent: %w", err)
304 return nil, fmt.Errorf("read root agent config: %w", err)
307 agent, err := openAgent(root)
309 return nil, fmt.Errorf("open root agent: %w", err)
316 if agent.config.Parent != "" {
317 return nil, errors.New("import root cannot have a parent")
320 children, err := agent.Children()
322 return nil, fmt.Errorf("read import children: %w", err)
325 for _, child := range children {
326 if child.config.Name == name {
331 return nil, fmt.Errorf("child %q does not exist", name)
334 // whatsappImportIdle refuses unfinished subagents and pending deliveries to the
335 // target. Rebuilding renumbers its log, so saved delivery IDs must not refer to
336 // it until their turns finish. The caller holds the token lock.
337 func whatsappImportIdle(root string, agent *Agent) error {
338 err := rebuildIdle(agent.dir)
340 return fmt.Errorf("check target work: %w", err)
343 data, err := os.ReadFile(filepath.Join(root, "messages.json"))
344 if errors.Is(err, os.ErrNotExist) {
349 return fmt.Errorf("read agent deliveries: %w", err)
352 var queue DaemonMessageFile
354 err = json.Unmarshal(data, &queue)
356 return fmt.Errorf("decode agent deliveries: %w", err)
359 for _, message := range queue.Pending {
360 if message.Target == agent.config.Name {
361 return fmt.Errorf("import refused: agent %q has pending deliveries", agent.config.Name)
368 // whatsappImportNames reads only local session data. Group names that the
369 // library keeps only in memory can also come from logged or pending batches.
370 // Ambiguous names have no ID. A missing session keeps sender names unchanged.
371 func whatsappImportNames(ctx context.Context, dir string) (names map[string]WhatsAppChat, owner string, err error) {
372 names = make(map[string]WhatsAppChat)
373 path := filepath.Join(dir, whatsappDirName, whatsappSessionFileName)
374 _, err = os.Stat(path)
375 if errors.Is(err, os.ErrNotExist) {
376 return names, "", nil
380 return nil, "", fmt.Errorf("read import session: %w", err)
383 address, err := whatsappSessionAddress(path)
385 return nil, "", fmt.Errorf("find import session address: %w", err)
388 container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop)
390 return nil, "", fmt.Errorf("open import session: %w", err)
394 closeErr := container.Close()
396 err = errors.Join(err, fmt.Errorf("close import session: %w", closeErr))
400 device, err := container.GetFirstDevice(ctx)
402 return nil, "", fmt.Errorf("read import device: %w", err)
405 if device.ID == nil {
406 return names, "", nil
409 owner = device.PushName
410 own := whatsappOwnIDs(device.ID.User, device.LID.User)
411 contacts, err := device.Contacts.GetAllContacts(ctx)
413 return nil, "", fmt.Errorf("read import contacts: %w", err)
416 for jid, contact := range contacts {
417 if slices.Contains(own, jid.User) {
421 for _, name := range []string{contact.FirstName, contact.FullName, contact.PushName, contact.BusinessName} {
423 whatsappImportName(names, WhatsAppChat{
424 ID: jid.ToNonAD().String(),
426 Group: jid.Server == "g.us",
432 data, err := os.ReadFile(filepath.Join(dir, whatsappDirName, whatsappStateFileName))
433 if errors.Is(err, os.ErrNotExist) {
434 return names, owner, nil
438 return nil, "", fmt.Errorf("read pending import names: %w", err)
441 var state WhatsAppStateFile
443 err = json.Unmarshal(data, &state)
445 return nil, "", fmt.Errorf("decode pending import names: %w", err)
448 for _, batch := range state.Batches {
449 whatsappImportName(names, batch.Chat)
452 return names, owner, nil
455 // whatsappImportName adds an exact match unless distinct IDs share its name.
456 func whatsappImportName(names map[string]WhatsAppChat, chat WhatsAppChat) {
457 old, found := names[chat.Name]
458 if found && old.ID != chat.ID {
462 names[chat.Name] = chat
465 // whatsappImportPlan filters each chat at its earliest live message across the
466 // target and root logs. Only imported days in the target are skipped. Each
467 // remaining chat-day becomes a work message dated at its last exported message.
468 // Overlapping input chat-days are refused.
469 func whatsappImportPlan(ctx context.Context, paths []string, old, rootLog []DatedMessage, names map[string]WhatsAppChat, owner string, location *time.Location) (WhatsAppImportPlan, error) {
470 plan := WhatsAppImportPlan{
471 ownerKnown: owner != "",
472 cutoffs: make(map[string]time.Time),
475 names = maps.Clone(names)
477 names = make(map[string]WhatsAppChat)
480 imported, err := whatsappImportHistory(old, rootLog, names, plan.cutoffs, location)
482 return plan, fmt.Errorf("read import history: %w", err)
485 seen := make(map[string]bool)
486 for _, path := range paths {
487 if ctx.Err() != nil {
488 return plan, ctx.Err()
491 chat, messages, err := whatsappImportRead(path, owner, location)
493 return plan, fmt.Errorf("read import export: %w", err)
496 known, found := names[chat.Name]
501 if !slices.Contains(plan.chats, chat.Name) {
502 plan.chats = append(plan.chats, chat.Name)
505 cutoff := plan.cutoffs[chat.Name]
506 if !cutoff.IsZero() && (plan.cutoff.IsZero() || cutoff.Before(plan.cutoff)) {
510 days := make(map[string][]WhatsAppMessage)
511 for _, message := range messages {
512 if !cutoff.IsZero() && !message.Time.Before(cutoff) {
516 day := message.Time.In(location).Format(time.DateOnly)
517 days[day] = append(days[day], message)
520 for _, day := range slices.Sorted(maps.Keys(days)) {
521 key := chat.Name + "\n" + day
528 return plan, errors.New("import inputs overlap: give only one export for each chat and day")
532 batch := WhatsAppBatch{
537 text := batch.Text(location)
538 first, body, _ := strings.Cut(text, "\n")
540 first = "[WhatsApp] " + chat.Name + ", " + batch.Messages[0].Time.In(location).Format(whatsappBatchDayLayout)
543 text = first + whatsappImportMark + "\n" + body
544 plan.added = append(plan.added, DatedMessage{
547 Date: batch.Messages[len(batch.Messages)-1].Time.Format(time.RFC3339Nano),
550 plan.bytes += len(text)
551 firstDate, lastDate := batch.Messages[0].Time, batch.Messages[len(batch.Messages)-1].Time
552 if plan.first.IsZero() || firstDate.Before(plan.first) {
553 plan.first = firstDate
556 if plan.last.IsZero() || lastDate.After(plan.last) {
562 plan.added, err = rebuildMerge(nil, plan.added)
564 return plan, fmt.Errorf("order import batches: %w", err)
567 plan.messages = len(old) + len(plan.added)
568 slices.Sort(plan.chats)
573 // whatsappImportHistory reads batch names and live cutoffs from both logs.
574 // Imported chat-days belong only to the target log, which is first.
575 func whatsappImportHistory(target, root []DatedMessage, names map[string]WhatsAppChat, cutoffs map[string]time.Time, location *time.Location) (map[string]bool, error) {
576 imported := make(map[string]bool)
577 for source, entries := range [][]DatedMessage{target, root} {
578 for _, entry := range entries {
579 if entry.Kind != "work" || !strings.HasPrefix(entry.Text, "[WhatsApp] ") {
583 first, _, _ := strings.Cut(entry.Text, "\n")
584 marked := strings.HasSuffix(first, whatsappImportMark)
585 first = strings.TrimSuffix(first, whatsappImportMark)
586 match := whatsappImportHeader.FindStringSubmatch(first)
589 name, day = match[1], match[3]
590 whatsappImportName(names, WhatsAppChat{
593 Group: strings.Contains(first, ", group "+match[2]+","),
596 match = whatsappImportUnknown.FindStringSubmatch(first)
598 name, day = match[1], match[2]
603 return nil, errors.New("invalid WhatsApp batch header")
608 imported[name+"\n"+day] = true
614 _, body, found := strings.Cut(entry.Text, "\n")
615 if !found || len(body) < len("15:04 ") {
616 return nil, errors.New("missing first WhatsApp message time")
619 date, err := time.ParseInLocation("2006-01-02 15:04", day+" "+body[:5], location)
621 return nil, fmt.Errorf("parse first live message time: %w", err)
624 if cutoffs[name].IsZero() || date.Before(cutoffs[name]) {
633 // whatsappImportRead reads the single _chat.txt in an export without extracting
634 // archive paths. Non-start lines continue the preceding message, and all
635 // invisible left-to-right marks are removed. Dates use location. Media and
636 // system messages remain text, including the written sender.
637 func whatsappImportRead(path, owner string, location *time.Location) (chat WhatsAppChat, messages []WhatsAppMessage, err error) {
638 chat.Name = strings.TrimPrefix(strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)), "WhatsApp Chat - ")
639 if chat.Name == "" || strings.ContainsAny(chat.Name, "\r\n") {
640 return chat, nil, errors.New("read export: chat name must be one nonempty line")
643 archive, err := zip.OpenReader(path)
645 return chat, nil, fmt.Errorf("open export: %w", err)
649 closeErr := archive.Close()
651 err = errors.Join(err, fmt.Errorf("close export: %w", closeErr))
657 for _, entry := range archive.File {
658 if filepath.Base(entry.Name) == "_chat.txt" && !entry.FileInfo().IsDir() {
660 return chat, nil, errors.New("read export: more than one _chat.txt")
668 return chat, nil, errors.New("read export: _chat.txt is missing")
671 if file.UncompressedSize64 > whatsappImportBytes {
672 return chat, nil, errors.New("read export: chat text exceeds 64 MiB")
675 reader, err := file.Open()
677 return chat, nil, fmt.Errorf("open chat text: %w", err)
681 closeErr := reader.Close()
683 err = errors.Join(err, fmt.Errorf("close export chat text: %w", closeErr))
687 scanner := bufio.NewScanner(io.LimitReader(reader, whatsappImportBytes+1))
688 scanner.Buffer(make([]byte, 64*1024), buildLineBytes)
691 line := strings.ReplaceAll(scanner.Text(), "\u200e", "")
692 match := whatsappImportStart.FindStringSubmatch(line)
694 if len(messages) == 0 {
699 return chat, nil, errors.New("read export: text before the first dated message")
702 messages[len(messages)-1].Text += "\n" + line
709 date, err = time.ParseInLocation("02/01/2006, 15:04:05", match[1], location)
711 return chat, nil, fmt.Errorf("parse export local date: %w", err)
714 messages = append(messages, WhatsAppMessage{
718 Mine: owner != "" && match[2] == owner && match[2] != chat.Name,
721 if match[2] == chat.Name {
726 if scanner.Err() != nil {
727 return chat, nil, fmt.Errorf("read chat text: %w", scanner.Err())
730 if len(messages) == 0 {
731 return chat, nil, errors.New("read export: no dated messages")
734 slices.SortStableFunc(messages, func(a, b WhatsAppMessage) int {
735 return a.Time.Compare(b.Time)
738 return chat, messages, nil